func
stringlengths
0
484k
target
int64
0
1
cwe
sequencelengths
0
4
project
stringclasses
799 values
commit_id
stringlengths
40
40
hash
float64
1,215,700,430,453,689,100,000,000B
340,281,914,521,452,260,000,000,000,000B
size
int64
1
24k
message
stringlengths
0
13.3k
flatpak_dir_get_deploy_data (FlatpakDir *self, FlatpakDecomposed *ref, int required_version, GCancellable *cancellable, GError **error) { g_autoptr(GFile) deploy_dir = NULL; deploy_dir = flatpak_dir_get_if_deployed (self, ref, NULL, cancellable); if (deploy_dir == NULL) { g_set_error (error, FLATPAK_ERROR, FLATPAK_ERROR_NOT_INSTALLED, _("%s not installed"), flatpak_decomposed_get_ref (ref)); return NULL; } if (!flatpak_dir_ensure_repo (self, cancellable, error)) return NULL; return flatpak_load_deploy_data (deploy_dir, ref, self->repo, required_version, cancellable, error); }
0
[ "CWE-74" ]
flatpak
fb473cad801c6b61706353256cab32330557374a
95,020,266,041,625,050,000,000,000,000,000,000,000
26
dir: Pass environment via bwrap --setenv when running apply_extra This means we can systematically pass the environment variables through bwrap(1), even if it is setuid and thus is filtering out security-sensitive environment variables. bwrap ends up being run with an empty environment instead. As with the previous commit, this regressed while fixing CVE-2021-21261. Fixes: 6d1773d2 "run: Convert all environment variables into bwrap arguments" Signed-off-by: Simon McVittie <[email protected]>
static int ZEND_FASTCALL ZEND_IS_NOT_IDENTICAL_SPEC_CV_TMP_HANDLER(ZEND_OPCODE_HANDLER_ARGS) { zend_op *opline = EX(opline); zend_free_op free_op2; zval *result = &EX_T(opline->result.u.var).tmp_var; is_identical_function(result, _get_zval_ptr_cv(&opline->op1, EX(Ts), BP_VAR_R TSRMLS_CC), _get_zval_ptr_tmp(&opline->op2, EX(Ts), &free_op2 TSRMLS_CC) TSRMLS_CC); Z_LVAL_P(result) = !Z_LVAL_P(result); zval_dtor(free_op2.var); ZEND_VM_NEXT_OPCODE(); }
0
[]
php-src
ce96fd6b0761d98353761bf78d5bfb55291179fd
82,777,369,596,093,180,000,000,000,000,000,000,000
14
- fix #39863, do not accept paths with NULL in them. See http://news.php.net/php.internals/50191, trunk will have the patch later (adding a macro and/or changing (some) APIs. Patch by Rasmus
copy_banner(cupsd_client_t *con, /* I - Client connection */ cupsd_job_t *job, /* I - Job information */ const char *name) /* I - Name of banner */ { int i; /* Looping var */ int kbytes; /* Size of banner file in kbytes */ char filename[1024]; /* Job filename */ cupsd_banner_t *banner; /* Pointer to banner */ cups_file_t *in; /* Input file */ cups_file_t *out; /* Output file */ int ch; /* Character from file */ char attrname[255], /* Name of attribute */ *s; /* Pointer into name */ ipp_attribute_t *attr; /* Attribute */ cupsdLogMessage(CUPSD_LOG_DEBUG2, "copy_banner(con=%p[%d], job=%p[%d], name=\"%s\")", con, con ? con->number : -1, job, job->id, name ? name : "(null)"); /* * Find the banner; return if not found or "none"... */ if (!name || !strcmp(name, "none") || (banner = cupsdFindBanner(name)) == NULL) return (0); /* * Open the banner and job files... */ if (add_file(con, job, banner->filetype, 0)) return (-1); snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot, job->id, job->num_files); if ((out = cupsFileOpen(filename, "w")) == NULL) { cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create banner job file %s - %s", filename, strerror(errno)); job->num_files --; return (0); } fchmod(cupsFileNumber(out), 0640); fchown(cupsFileNumber(out), RunUser, Group); /* * Try the localized banner file under the subdirectory... */ strlcpy(attrname, job->attrs->attrs->next->values[0].string.text, sizeof(attrname)); if (strlen(attrname) > 2 && attrname[2] == '-') { /* * Convert ll-cc to ll_CC... */ attrname[2] = '_'; attrname[3] = (char)toupper(attrname[3] & 255); attrname[4] = (char)toupper(attrname[4] & 255); } snprintf(filename, sizeof(filename), "%s/banners/%s/%s", DataDir, attrname, name); if (access(filename, 0) && strlen(attrname) > 2) { /* * Wasn't able to find "ll_CC" locale file; try the non-national * localization banner directory. */ attrname[2] = '\0'; snprintf(filename, sizeof(filename), "%s/banners/%s/%s", DataDir, attrname, name); } if (access(filename, 0)) { /* * Use the non-localized banner file. */ snprintf(filename, sizeof(filename), "%s/banners/%s", DataDir, name); } if ((in = cupsFileOpen(filename, "r")) == NULL) { cupsFileClose(out); unlink(filename); cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open banner template file %s - %s", filename, strerror(errno)); job->num_files --; return (0); } /* * Parse the file to the end... */ while ((ch = cupsFileGetChar(in)) != EOF) if (ch == '{') { /* * Get an attribute name... */ for (s = attrname; (ch = cupsFileGetChar(in)) != EOF;) if (!isalpha(ch & 255) && ch != '-' && ch != '?') break; else if (s < (attrname + sizeof(attrname) - 1)) *s++ = (char)ch; else break; *s = '\0'; if (ch != '}') { /* * Ignore { followed by stuff that is not an attribute name... */ cupsFilePrintf(out, "{%s%c", attrname, ch); continue; } /* * See if it is defined... */ if (attrname[0] == '?') s = attrname + 1; else s = attrname; if (!strcmp(s, "printer-name")) { cupsFilePuts(out, job->dest); continue; } else if ((attr = ippFindAttribute(job->attrs, s, IPP_TAG_ZERO)) == NULL) { /* * See if we have a leading question mark... */ if (attrname[0] != '?') { /* * Nope, write to file as-is; probably a PostScript procedure... */ cupsFilePrintf(out, "{%s}", attrname); } continue; } /* * Output value(s)... */ for (i = 0; i < attr->num_values; i ++) { if (i) cupsFilePutChar(out, ','); switch (attr->value_tag) { case IPP_TAG_INTEGER : case IPP_TAG_ENUM : if (!strncmp(s, "time-at-", 8)) { struct timeval tv; /* Time value */ tv.tv_sec = attr->values[i].integer; tv.tv_usec = 0; cupsFilePuts(out, cupsdGetDateTime(&tv, CUPSD_TIME_STANDARD)); } else cupsFilePrintf(out, "%d", attr->values[i].integer); break; case IPP_TAG_BOOLEAN : cupsFilePrintf(out, "%d", attr->values[i].boolean); break; case IPP_TAG_NOVALUE : cupsFilePuts(out, "novalue"); break; case IPP_TAG_RANGE : cupsFilePrintf(out, "%d-%d", attr->values[i].range.lower, attr->values[i].range.upper); break; case IPP_TAG_RESOLUTION : cupsFilePrintf(out, "%dx%d%s", attr->values[i].resolution.xres, attr->values[i].resolution.yres, attr->values[i].resolution.units == IPP_RES_PER_INCH ? "dpi" : "dpcm"); break; case IPP_TAG_URI : case IPP_TAG_STRING : case IPP_TAG_TEXT : case IPP_TAG_NAME : case IPP_TAG_KEYWORD : case IPP_TAG_CHARSET : case IPP_TAG_LANGUAGE : if (!_cups_strcasecmp(banner->filetype->type, "postscript")) { /* * Need to quote strings for PS banners... */ const char *p; for (p = attr->values[i].string.text; *p; p ++) { if (*p == '(' || *p == ')' || *p == '\\') { cupsFilePutChar(out, '\\'); cupsFilePutChar(out, *p); } else if (*p < 32 || *p > 126) cupsFilePrintf(out, "\\%03o", *p & 255); else cupsFilePutChar(out, *p); } } else cupsFilePuts(out, attr->values[i].string.text); break; default : break; /* anti-compiler-warning-code */ } } } else if (ch == '\\') /* Quoted char */ { ch = cupsFileGetChar(in); if (ch != '{') /* Only do special handling for \{ */ cupsFilePutChar(out, '\\'); cupsFilePutChar(out, ch); } else cupsFilePutChar(out, ch); cupsFileClose(in); kbytes = (cupsFileTell(out) + 1023) / 1024; job->koctets += kbytes; if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL) attr->values[0].integer += kbytes; cupsFileClose(out); return (kbytes); }
0
[ "CWE-20" ]
cups
49fa4983f25b64ec29d548ffa3b9782426007df3
322,181,251,822,044,650,000,000,000,000,000,000,000
274
DBUS notifications could crash the scheduler (Issue #5143) - scheduler/ipp.c: Make sure requesting-user-name string is valid UTF-8.
static bool fdc_reset_sensei_needed(void *opaque) { FDCtrl *s = opaque; return s->reset_sensei != 0; }
0
[ "CWE-119" ]
qemu
e907746266721f305d67bc0718795fedee2e824c
41,198,656,724,018,570,000,000,000,000,000,000,000
6
fdc: force the fifo access to be in bounds of the allocated buffer During processing of certain commands such as FD_CMD_READ_ID and FD_CMD_DRIVE_SPECIFICATION_COMMAND the fifo memory access could get out of bounds leading to memory corruption with values coming from the guest. Fix this by making sure that the index is always bounded by the allocated memory. This is CVE-2015-3456. Signed-off-by: Petr Matousek <[email protected]> Reviewed-by: John Snow <[email protected]> Signed-off-by: John Snow <[email protected]>
static void ebus_class_init(ObjectClass *klass, void *data) { PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); DeviceClass *dc = DEVICE_CLASS(klass); k->realize = ebus_realize; k->vendor_id = PCI_VENDOR_ID_SUN; k->device_id = PCI_DEVICE_ID_SUN_EBUS; k->revision = 0x01; k->class_id = PCI_CLASS_BRIDGE_OTHER; dc->props = ebus_properties; }
0
[ "CWE-476" ]
qemu
ad280559c68360c9f1cd7be063857853759e6a73
193,340,463,885,000,630,000,000,000,000,000,000,000
12
sun4u: add power_mem_read routine Define skeleton 'power_mem_read' routine. Avoid NULL dereference. Reported-by: Fakhri Zulkifli <[email protected]> Signed-off-by: Prasad J Pandit <[email protected]> Signed-off-by: Mark Cave-Ayland <[email protected]>
int key_link(struct key *keyring, struct key *key) { struct assoc_array_edit *edit; int ret; kenter("{%d,%d}", keyring->serial, refcount_read(&keyring->usage)); key_check(keyring); key_check(key); ret = __key_link_begin(keyring, &key->index_key, &edit); if (ret == 0) { kdebug("begun {%d,%d}", keyring->serial, refcount_read(&keyring->usage)); ret = __key_link_check_restriction(keyring, key); if (ret == 0) ret = __key_link_check_live_key(keyring, key); if (ret == 0) __key_link(key, &edit); __key_link_end(keyring, &key->index_key, edit); } kleave(" = %d {%d,%d}", ret, keyring->serial, refcount_read(&keyring->usage)); return ret; }
0
[ "CWE-20" ]
linux
363b02dab09b3226f3bd1420dad9c72b79a42a76
169,031,159,518,106,400,000,000,000,000,000,000,000
24
KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]>
R_API void r_bin_java_get_field_json_definitions(RBinJavaObj *bin, PJ *pj) { r_return_if_fail (pj); RBinJavaField *fm_type = NULL; RListIter *iter = NULL; pj_ka (pj, "fields"); if (!bin) { pj_end (pj); return; } r_list_foreach (bin->fields_list, iter, fm_type) { r_bin_java_get_field_json_definition (bin, fm_type, pj); } pj_end (pj); }
0
[ "CWE-125" ]
radare2
0927ed3ae99444e7b47b84e43118deb10fe37529
94,705,517,506,402,320,000,000,000,000,000,000,000
16
Fix oobread crash in java parser ##crash * Reported by @bet4it via @huntrdev * BountyID: 229a2e0d-9e5c-402f-9a24-57fa2eb1aaa7 * Reproducer: poc4java
ecb_ews_verify_changes (ECalCache *cal_cache, icalcomponent_kind kind, GSList *in_items, /* EEwsItem * */ GCancellable *cancellable) { GSList *items = NULL, *link; g_return_val_if_fail (E_IS_CAL_CACHE (cal_cache), in_items); for (link = in_items; link; link = g_slist_next (link)) { EEwsItem *item = link->data; const EwsId *id = e_ews_item_get_id (item); EEwsItemType type = e_ews_item_get_item_type (item); if (!g_cancellable_is_cancelled (cancellable) && ( (type == E_EWS_ITEM_TYPE_EVENT && kind == ICAL_VEVENT_COMPONENT) || (type == E_EWS_ITEM_TYPE_MEMO && kind == ICAL_VJOURNAL_COMPONENT) || (type == E_EWS_ITEM_TYPE_TASK && kind == ICAL_VTODO_COMPONENT) )) { ECalComponent *existing = NULL; if (e_cal_cache_get_component (cal_cache, id->id, NULL, &existing, cancellable, NULL) && existing && g_strcmp0 (e_cal_util_get_x_property (e_cal_component_get_icalcomponent (existing), "X-EVOLUTION-CHANGEKEY"), id->change_key) == 0) { g_object_unref (item); } else { items = g_slist_prepend (items, item); } g_clear_object (&existing); } else if (type == E_EWS_ITEM_TYPE_EVENT || type == E_EWS_ITEM_TYPE_MEMO || type == E_EWS_ITEM_TYPE_TASK) { g_object_unref (item); } else { items = g_slist_prepend (items, item); } } g_slist_free (in_items); return items; }
0
[ "CWE-295" ]
evolution-ews
915226eca9454b8b3e5adb6f2fff9698451778de
151,202,402,477,009,900,000,000,000,000,000,000,000
42
I#27 - SSL Certificates are not validated This depends on https://gitlab.gnome.org/GNOME/evolution-data-server/commit/6672b8236139bd6ef41ecb915f4c72e2a052dba5 too. Closes https://gitlab.gnome.org/GNOME/evolution-ews/issues/27
bool cleanup_excluding_fields_processor(void *arg) { return field ? 0 : cleanup_processor(arg); }
0
[ "CWE-617" ]
server
2e7891080667c59ac80f788eef4d59d447595772
182,831,662,563,165,450,000,000,000,000,000,000,000
2
MDEV-25635 Assertion failure when pushing from HAVING into WHERE of view This bug could manifest itself after pushing a where condition over a mergeable derived table / view / CTE DT into a grouping view / derived table / CTE V whose item list contained set functions with constant arguments such as MIN(2), SUM(1) etc. In such cases the field references used in the condition pushed into the view V that correspond set functions are wrapped into Item_direct_view_ref wrappers. Due to a wrong implementation of the virtual method const_item() for the class Item_direct_view_ref the wrapped set functions with constant arguments could be erroneously taken for constant items. This could lead to a wrong result set returned by the main select query in 10.2. In 10.4 where a possibility of pushing condition from HAVING into WHERE had been added this could cause a crash. Approved by Sergey Petrunya <[email protected]>
const envoy::config::listener::v3::Listener& config() const { return config_; }
0
[ "CWE-400" ]
envoy
dfddb529e914d794ac552e906b13d71233609bf7
38,965,085,341,738,280,000,000,000,000,000,000,000
1
listener: Add configurable accepted connection limits (#153) Add support for per-listener limits on accepted connections. Signed-off-by: Tony Allen <[email protected]>
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; i<number_opaque; i++) { if (opaque[i].red == image->background_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; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_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; i<image_colors; i++) image->colormap[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; i<image_colors; i++) { LBR04PacketRGB(image->colormap[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; i<image_colors; i++) { LBR03PacketRGB(image->colormap[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; i<image_colors; i++) { LBR02PacketBlue(image->colormap[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; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[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; i<image_colors; i++) if (image->colormap[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 */ }
0
[ "CWE-416" ]
ImageMagick
916d7bbd2c66a286d379dbd94bc6035c8fab937c
229,387,549,869,980,600,000,000,000,000,000,000,000
3,547
Removed invalid free reported in #1791.
int machine_check_generic(struct pt_regs *regs) { unsigned long reason = get_mc_reason(regs); printk("Machine check in kernel mode.\n"); printk("Caused by (from SRR1=%lx): ", reason); switch (reason & 0x601F0000) { case 0x80000: printk("Machine check signal\n"); break; case 0: /* for 601 */ case 0x40000: case 0x140000: /* 7450 MSS error and TEA */ printk("Transfer error ack signal\n"); break; case 0x20000: printk("Data parity error signal\n"); break; case 0x10000: printk("Address parity error signal\n"); break; case 0x20000000: printk("L1 Data Cache error\n"); break; case 0x40000000: printk("L1 Instruction Cache error\n"); break; case 0x00100000: printk("L2 data cache parity error\n"); break; default: printk("Unknown values in msr\n"); } return 0; }
0
[]
linux
5d176f751ee3c6eededd984ad409bff201f436a7
177,445,355,386,278,600,000,000,000,000,000,000,000
35
powerpc: tm: Enable transactional memory (TM) lazily for userspace Currently the MSR TM bit is always set if the hardware is TM capable. This adds extra overhead as it means the TM SPRS (TFHAR, TEXASR and TFAIR) must be swapped for each process regardless of if they use TM. For processes that don't use TM the TM MSR bit can be turned off allowing the kernel to avoid the expensive swap of the TM registers. A TM unavailable exception will occur if a thread does use TM and the kernel will enable MSR_TM and leave it so for some time afterwards. Signed-off-by: Cyril Bur <[email protected]> Signed-off-by: Michael Ellerman <[email protected]>
nf_ct_frag6_reasm(struct frag_queue *fq, struct sk_buff *prev, struct net_device *dev) { struct sk_buff *fp, *head = fq->q.fragments; int payload_len; u8 ecn; inet_frag_kill(&fq->q); WARN_ON(head == NULL); WARN_ON(head->ip_defrag_offset != 0); ecn = ip_frag_ecn_table[fq->ecn]; if (unlikely(ecn == 0xff)) return false; /* Unfragmented part is taken from the first segment. */ payload_len = ((head->data - skb_network_header(head)) - sizeof(struct ipv6hdr) + fq->q.len - sizeof(struct frag_hdr)); if (payload_len > IPV6_MAXPLEN) { net_dbg_ratelimited("nf_ct_frag6_reasm: payload len = %d\n", payload_len); return false; } /* Head of list must not be cloned. */ if (skb_unclone(head, GFP_ATOMIC)) return false; /* If the first fragment is fragmented itself, we split * it to two chunks: the first with data and paged part * and the second, holding only fragments. */ if (skb_has_frag_list(head)) { struct sk_buff *clone; int i, plen = 0; clone = alloc_skb(0, GFP_ATOMIC); if (clone == NULL) return false; clone->next = head->next; head->next = clone; skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list; skb_frag_list_init(head); for (i = 0; i < skb_shinfo(head)->nr_frags; i++) plen += skb_frag_size(&skb_shinfo(head)->frags[i]); clone->len = clone->data_len = head->data_len - plen; head->data_len -= clone->len; head->len -= clone->len; clone->csum = 0; clone->ip_summed = head->ip_summed; add_frag_mem_limit(fq->q.net, clone->truesize); } /* morph head into last received skb: prev. * * This allows callers of ipv6 conntrack defrag to continue * to use the last skb(frag) passed into the reasm engine. * The last skb frag 'silently' turns into the full reassembled skb. * * Since prev is also part of q->fragments we have to clone it first. */ if (head != prev) { struct sk_buff *iter; fp = skb_clone(prev, GFP_ATOMIC); if (!fp) return false; fp->next = prev->next; iter = head; while (iter) { if (iter->next == prev) { iter->next = fp; break; } iter = iter->next; } skb_morph(prev, head); prev->next = head->next; consume_skb(head); head = prev; } /* We have to remove fragment header from datagram and to relocate * header in order to calculate ICV correctly. */ skb_network_header(head)[fq->nhoffset] = skb_transport_header(head)[0]; memmove(head->head + sizeof(struct frag_hdr), head->head, (head->data - head->head) - sizeof(struct frag_hdr)); head->mac_header += sizeof(struct frag_hdr); head->network_header += sizeof(struct frag_hdr); skb_shinfo(head)->frag_list = head->next; skb_reset_transport_header(head); skb_push(head, head->data - skb_network_header(head)); for (fp = head->next; fp; fp = fp->next) { head->data_len += fp->len; head->len += fp->len; if (head->ip_summed != fp->ip_summed) head->ip_summed = CHECKSUM_NONE; else if (head->ip_summed == CHECKSUM_COMPLETE) head->csum = csum_add(head->csum, fp->csum); head->truesize += fp->truesize; fp->sk = NULL; } sub_frag_mem_limit(fq->q.net, head->truesize); head->ignore_df = 1; head->next = NULL; head->dev = dev; head->tstamp = fq->q.stamp; ipv6_hdr(head)->payload_len = htons(payload_len); ipv6_change_dsfield(ipv6_hdr(head), 0xff, ecn); IP6CB(head)->frag_max_size = sizeof(struct ipv6hdr) + fq->q.max_size; /* Yes, and fold redundant checksum back. 8) */ if (head->ip_summed == CHECKSUM_COMPLETE) head->csum = csum_partial(skb_network_header(head), skb_network_header_len(head), head->csum); fq->q.fragments = NULL; fq->q.rb_fragments = RB_ROOT; fq->q.fragments_tail = NULL; return true; }
0
[ "CWE-20" ]
linux
5d407b071dc369c26a38398326ee2be53651cfe4
300,446,202,847,744,080,000,000,000,000,000,000,000
131
ip: frags: fix crash in ip_do_fragment() A kernel crash occurrs when defragmented packet is fragmented in ip_do_fragment(). In defragment routine, skb_orphan() is called and skb->ip_defrag_offset is set. but skb->sk and skb->ip_defrag_offset are same union member. so that frag->sk is not NULL. Hence crash occurrs in skb->sk check routine in ip_do_fragment() when defragmented packet is fragmented. test commands: %iptables -t nat -I POSTROUTING -j MASQUERADE %hping3 192.168.4.2 -s 1000 -p 2000 -d 60000 splat looks like: [ 261.069429] kernel BUG at net/ipv4/ip_output.c:636! [ 261.075753] invalid opcode: 0000 [#1] SMP DEBUG_PAGEALLOC KASAN PTI [ 261.083854] CPU: 1 PID: 1349 Comm: hping3 Not tainted 4.19.0-rc2+ #3 [ 261.100977] RIP: 0010:ip_do_fragment+0x1613/0x2600 [ 261.106945] Code: e8 e2 38 e3 fe 4c 8b 44 24 18 48 8b 74 24 08 e9 92 f6 ff ff 80 3c 02 00 0f 85 da 07 00 00 48 8b b5 d0 00 00 00 e9 25 f6 ff ff <0f> 0b 0f 0b 44 8b 54 24 58 4c 8b 4c 24 18 4c 8b 5c 24 60 4c 8b 6c [ 261.127015] RSP: 0018:ffff8801031cf2c0 EFLAGS: 00010202 [ 261.134156] RAX: 1ffff1002297537b RBX: ffffed0020639e6e RCX: 0000000000000004 [ 261.142156] RDX: 0000000000000000 RSI: 0000000000000000 RDI: ffff880114ba9bd8 [ 261.150157] RBP: ffff880114ba8a40 R08: ffffed0022975395 R09: ffffed0022975395 [ 261.158157] R10: 0000000000000001 R11: ffffed0022975394 R12: ffff880114ba9ca4 [ 261.166159] R13: 0000000000000010 R14: ffff880114ba9bc0 R15: dffffc0000000000 [ 261.174169] FS: 00007fbae2199700(0000) GS:ffff88011b400000(0000) knlGS:0000000000000000 [ 261.183012] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 261.189013] CR2: 00005579244fe000 CR3: 0000000119bf4000 CR4: 00000000001006e0 [ 261.198158] Call Trace: [ 261.199018] ? dst_output+0x180/0x180 [ 261.205011] ? save_trace+0x300/0x300 [ 261.209018] ? ip_copy_metadata+0xb00/0xb00 [ 261.213034] ? sched_clock_local+0xd4/0x140 [ 261.218158] ? kill_l4proto+0x120/0x120 [nf_conntrack] [ 261.223014] ? rt_cpu_seq_stop+0x10/0x10 [ 261.227014] ? find_held_lock+0x39/0x1c0 [ 261.233008] ip_finish_output+0x51d/0xb50 [ 261.237006] ? ip_fragment.constprop.56+0x220/0x220 [ 261.243011] ? nf_ct_l4proto_register_one+0x5b0/0x5b0 [nf_conntrack] [ 261.250152] ? rcu_is_watching+0x77/0x120 [ 261.255010] ? nf_nat_ipv4_out+0x1e/0x2b0 [nf_nat_ipv4] [ 261.261033] ? nf_hook_slow+0xb1/0x160 [ 261.265007] ip_output+0x1c7/0x710 [ 261.269005] ? ip_mc_output+0x13f0/0x13f0 [ 261.273002] ? __local_bh_enable_ip+0xe9/0x1b0 [ 261.278152] ? ip_fragment.constprop.56+0x220/0x220 [ 261.282996] ? nf_hook_slow+0xb1/0x160 [ 261.287007] raw_sendmsg+0x21f9/0x4420 [ 261.291008] ? dst_output+0x180/0x180 [ 261.297003] ? sched_clock_cpu+0x126/0x170 [ 261.301003] ? find_held_lock+0x39/0x1c0 [ 261.306155] ? stop_critical_timings+0x420/0x420 [ 261.311004] ? check_flags.part.36+0x450/0x450 [ 261.315005] ? _raw_spin_unlock_irq+0x29/0x40 [ 261.320995] ? _raw_spin_unlock_irq+0x29/0x40 [ 261.326142] ? cyc2ns_read_end+0x10/0x10 [ 261.330139] ? raw_bind+0x280/0x280 [ 261.334138] ? sched_clock_cpu+0x126/0x170 [ 261.338995] ? check_flags.part.36+0x450/0x450 [ 261.342991] ? __lock_acquire+0x4500/0x4500 [ 261.348994] ? inet_sendmsg+0x11c/0x500 [ 261.352989] ? dst_output+0x180/0x180 [ 261.357012] inet_sendmsg+0x11c/0x500 [ ... ] v2: - clear skb->sk at reassembly routine.(Eric Dumarzet) Fixes: fa0f527358bd ("ip: use rb trees for IP frag queue.") Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Taehee Yoo <[email protected]> Reviewed-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]>
static int pptp_getname(struct socket *sock, struct sockaddr *uaddr, int *usockaddr_len, int peer) { int len = sizeof(struct sockaddr_pppox); struct sockaddr_pppox sp; memset(&sp.sa_addr, 0, sizeof(sp.sa_addr)); sp.sa_family = AF_PPPOX; sp.sa_protocol = PX_PROTO_PPTP; sp.sa_addr.pptp = pppox_sk(sock->sk)->proto.pptp.src_addr; memcpy(uaddr, &sp, len); *usockaddr_len = len; return 0; }
0
[ "CWE-200" ]
net
09ccfd238e5a0e670d8178cf50180ea81ae09ae1
50,653,068,883,499,220,000,000,000,000,000,000,000
18
pptp: verify sockaddr_len in pptp_bind() and pptp_connect() Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]>
static int opmul(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0x48; } switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_WORD ) { data[l++] = 0x66; } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xf6; } else { data[l++] = 0xf7; } if (op->operands[0].type & OT_MEMORY) { data[l++] = 0x20 | op->operands[0].regs[0]; } else { data[l++] = 0xe0 | op->operands[0].reg; } break; default: return -1; } return l; }
0
[ "CWE-119", "CWE-125", "CWE-787" ]
radare2
9b46d38dd3c4de6048a488b655c7319f845af185
174,334,805,396,817,300,000,000,000,000,000,000,000
27
Fix #12372 and #12373 - Crash in x86 assembler (#12380) 0 ,0,[bP-bL-bP-bL-bL-r-bL-bP-bL-bL- mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx-- leA ,0,[bP-bL-bL-bP-bL-bP-bL-60@bL- leA ,0,[bP-bL-r-bP-bL-bP-bL-60@bL- mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx--
int ff_set_ref_count(H264Context *h) { int ref_count[2], list_count; int num_ref_idx_active_override_flag; // set defaults, might be overridden a few lines later ref_count[0] = h->pps.ref_count[0]; ref_count[1] = h->pps.ref_count[1]; if (h->slice_type_nos != AV_PICTURE_TYPE_I) { unsigned max[2]; max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31; if (h->slice_type_nos == AV_PICTURE_TYPE_B) h->direct_spatial_mv_pred = get_bits1(&h->gb); num_ref_idx_active_override_flag = get_bits1(&h->gb); if (num_ref_idx_active_override_flag) { ref_count[0] = get_ue_golomb(&h->gb) + 1; if (h->slice_type_nos == AV_PICTURE_TYPE_B) { ref_count[1] = get_ue_golomb(&h->gb) + 1; } else // full range is spec-ok in this case, even for frames ref_count[1] = 1; } if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){ av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", ref_count[0]-1, max[0], ref_count[1]-1, max[1]); h->ref_count[0] = h->ref_count[1] = 0; h->list_count = 0; return AVERROR_INVALIDDATA; } if (h->slice_type_nos == AV_PICTURE_TYPE_B) list_count = 2; else list_count = 1; } else { list_count = 0; ref_count[0] = ref_count[1] = 0; } if (list_count != h->list_count || ref_count[0] != h->ref_count[0] || ref_count[1] != h->ref_count[1]) { h->ref_count[0] = ref_count[0]; h->ref_count[1] = ref_count[1]; h->list_count = list_count; return 1; } return 0; }
0
[ "CWE-703" ]
FFmpeg
8a3b85f3a7952c54a2c36ba1797f7e0cde9f85aa
177,789,967,204,296,500,000,000,000,000,000,000,000
53
avcodec/h264: update current_sps & sps->new only after the whole slice header decoder and init code finished This avoids them being cleared before the full initialization finished Fixes out of array read Fixes: asan_heap-oob_f0c5e6_7071_cov_1605985132_mov_h264_aac__Demo_FlagOfOurFathers.mov Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind Signed-off-by: Michael Niedermayer <[email protected]>
gimp_channel_init (GimpChannel *channel) { gimp_rgba_set (&channel->color, 0.0, 0.0, 0.0, GIMP_OPACITY_OPAQUE); channel->show_masked = FALSE; /* Selection mask variables */ channel->boundary_known = FALSE; channel->segs_in = NULL; channel->segs_out = NULL; channel->num_segs_in = 0; channel->num_segs_out = 0; channel->empty = FALSE; channel->bounds_known = FALSE; channel->x1 = 0; channel->y1 = 0; channel->x2 = 0; channel->y2 = 0; }
0
[ "CWE-703" ]
gimp
6ab90ecbbd7cc95901933f62227fd140c0576d55
108,765,075,406,516,030,000,000,000,000,000,000,000
19
app: fix #8230 crash in gimp_layer_invalidate_boundary when channel is NULL gimp_channel_is_empty returns FALSE if channel is NULL. This causes gimp_layer_invalidate_boundary to crash if the mask channel is NULL. With a NULL channel gimp_channel_is_empty should return TRUE, just like the similar gimp_image_is_empty does, because returning FALSE here suggests we have a non empty channel. (cherry picked from commit 22af0bcfe67c1c86381f33975ca7fdbde6b36b39)
int qcow2_mark_consistent(BlockDriverState *bs) { BDRVQcowState *s = bs->opaque; if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) { int ret = bdrv_flush(bs); if (ret < 0) { return ret; } s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT; return qcow2_update_header(bs); } return 0; }
0
[ "CWE-476" ]
qemu
11b128f4062dd7f89b14abc8877ff20d41b28be9
6,826,081,122,312,479,000,000,000,000,000,000,000
15
qcow2: Fix NULL dereference in qcow2_open() error path (CVE-2014-0146) The qcow2 code assumes that s->snapshots is non-NULL if s->nb_snapshots != 0. By having the initialisation of both fields separated in qcow2_open(), any error occuring in between would cause the error path to dereference NULL in qcow2_free_snapshots() if the image had any snapshots. Signed-off-by: Kevin Wolf <[email protected]> Reviewed-by: Max Reitz <[email protected]> Signed-off-by: Stefan Hajnoczi <[email protected]>
static inline int get_amv(Mpeg4DecContext *ctx, int n) { MpegEncContext *s = &ctx->m; int x, y, mb_v, sum, dx, dy, shift; int len = 1 << (s->f_code + 4); const int a = s->sprite_warping_accuracy; if (s->workaround_bugs & FF_BUG_AMV) len >>= s->quarter_sample; if (s->real_sprite_warping_points == 1) { if (ctx->divx_version == 500 && ctx->divx_build == 413) sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample)); else sum = RSHIFT(s->sprite_offset[0][n] << s->quarter_sample, a); } else { dx = s->sprite_delta[n][0]; dy = s->sprite_delta[n][1]; shift = ctx->sprite_shift[0]; if (n) dy -= 1 << (shift + a + 1); else dx -= 1 << (shift + a + 1); mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16; sum = 0; for (y = 0; y < 16; y++) { int v; v = mb_v + dy * y; // FIXME optimize for (x = 0; x < 16; x++) { sum += v >> shift; v += dx; } } sum = RSHIFT(sum, a + 8 - s->quarter_sample); } if (sum < -len) sum = -len; else if (sum >= len) sum = len - 1; return sum; }
0
[ "CWE-703" ]
FFmpeg
3edc3b159503d512c919b3d5902f7026e961823a
50,219,869,252,177,640,000,000,000,000,000,000,000
46
avcodec/mpeg4videodec: Check for bitstream overread in decode_vol_header() Fixes out of array read Fixes: 08e48e9daae7d8f8ab6dbe3919e797e5-asan_heap-oob_157461c_5295_cov_1266798650_firefing.mpg Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind Signed-off-by: Michael Niedermayer <[email protected]>
u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx) { return 0; }
0
[ "CWE-362" ]
linux
17743798d81238ab13050e8e2833699b54e15467
253,168,988,228,444,950,000,000,000,000,000,000,000
4
mm/hugetlb: fix a race between hugetlb sysctl handlers There is a race between the assignment of `table->data` and write value to the pointer of `table->data` in the __do_proc_doulongvec_minmax() on the other thread. CPU0: CPU1: proc_sys_write hugetlb_sysctl_handler proc_sys_call_handler hugetlb_sysctl_handler_common hugetlb_sysctl_handler table->data = &tmp; hugetlb_sysctl_handler_common table->data = &tmp; proc_doulongvec_minmax do_proc_doulongvec_minmax sysctl_head_finish __do_proc_doulongvec_minmax unuse_table i = table->data; *i = val; // corrupt CPU1's stack Fix this by duplicating the `table`, and only update the duplicate of it. And introduce a helper of proc_hugetlb_doulongvec_minmax() to simplify the code. The following oops was seen: BUG: kernel NULL pointer dereference, address: 0000000000000000 #PF: supervisor instruction fetch in kernel mode #PF: error_code(0x0010) - not-present page Code: Bad RIP value. ... Call Trace: ? set_max_huge_pages+0x3da/0x4f0 ? alloc_pool_huge_page+0x150/0x150 ? proc_doulongvec_minmax+0x46/0x60 ? hugetlb_sysctl_handler_common+0x1c7/0x200 ? nr_hugepages_store+0x20/0x20 ? copy_fd_bitmaps+0x170/0x170 ? hugetlb_sysctl_handler+0x1e/0x20 ? proc_sys_call_handler+0x2f1/0x300 ? unregister_sysctl_table+0xb0/0xb0 ? __fd_install+0x78/0x100 ? proc_sys_write+0x14/0x20 ? __vfs_write+0x4d/0x90 ? vfs_write+0xef/0x240 ? ksys_write+0xc0/0x160 ? __ia32_sys_read+0x50/0x50 ? __close_fd+0x129/0x150 ? __x64_sys_write+0x43/0x50 ? do_syscall_64+0x6c/0x200 ? entry_SYSCALL_64_after_hwframe+0x44/0xa9 Fixes: e5ff215941d5 ("hugetlb: multiple hstates for multiple page sizes") Signed-off-by: Muchun Song <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Reviewed-by: Mike Kravetz <[email protected]> Cc: Andi Kleen <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Linus Torvalds <[email protected]>
ecma_bigint_or (ecma_value_t left_value, /**< left BigInt value */ ecma_value_t right_value) /**< right BigInt value */ { if (left_value == ECMA_BIGINT_ZERO) { return ecma_copy_value (right_value); } if (right_value == ECMA_BIGINT_ZERO) { return ecma_copy_value (left_value); } ecma_extended_primitive_t *left_p = ecma_get_extended_primitive_from_value (left_value); ecma_extended_primitive_t *right_p = ecma_get_extended_primitive_from_value (right_value); if (!(left_p->u.bigint_sign_and_size & ECMA_BIGINT_SIGN)) { if (!(right_p->u.bigint_sign_and_size & ECMA_BIGINT_SIGN)) { return ecma_bigint_bitwise_op (ECMA_BIG_UINT_BITWISE_OR, left_p, right_p); } /* x | (-y) == x | ~(y-1) == ~((y-1) &~ x) == -(((y-1) &~ x) + 1) */ uint32_t operation_and_options = (ECMA_BIG_UINT_BITWISE_AND_NOT | ECMA_BIG_UINT_BITWISE_DECREASE_LEFT | ECMA_BIG_UINT_BITWISE_INCREASE_RESULT); return ecma_bigint_bitwise_op (operation_and_options, right_p, left_p); } if (!(right_p->u.bigint_sign_and_size & ECMA_BIGINT_SIGN)) { /* (-x) | y == ~(x-1) | y == ~((x-1) &~ y) == -(((x-1) &~ y) + 1) */ uint32_t operation_and_options = (ECMA_BIG_UINT_BITWISE_AND_NOT | ECMA_BIG_UINT_BITWISE_DECREASE_LEFT | ECMA_BIG_UINT_BITWISE_INCREASE_RESULT); return ecma_bigint_bitwise_op (operation_and_options, left_p, right_p); } /* (-x) | (-y) == ~(x-1) | ~(y-1) == ~((x-1) & (y-1)) = -(((x-1) & (y-1)) + 1) */ uint32_t operation_and_options = (ECMA_BIG_UINT_BITWISE_AND | ECMA_BIG_UINT_BITWISE_DECREASE_BOTH | ECMA_BIG_UINT_BITWISE_INCREASE_RESULT); return ecma_bigint_bitwise_op (operation_and_options, left_p, right_p); } /* ecma_bigint_or */
0
[ "CWE-416" ]
jerryscript
3bcd48f72d4af01d1304b754ef19fe1a02c96049
144,707,969,585,332,630,000,000,000,000,000,000,000
45
Improve parse_identifier (#4691) Ascii string length is no longer computed during string allocation. JerryScript-DCO-1.0-Signed-off-by: Daniel Batiz [email protected]
format_SET_MPLS_LABEL(const struct ofpact_mpls_label *a, struct ds *s) { ds_put_format(s, "%sset_mpls_label(%s%"PRIu32"%s)%s", colors.paren, colors.end, ntohl(a->label), colors.paren, colors.end); }
0
[ "CWE-125" ]
ovs
9237a63c47bd314b807cda0bd2216264e82edbe8
169,486,781,114,149,670,000,000,000,000,000,000,000
6
ofp-actions: Avoid buffer overread in BUNDLE action decoding. Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9052 Signed-off-by: Ben Pfaff <[email protected]> Acked-by: Justin Pettit <[email protected]>
static __cold void io_free_req(struct io_kiocb *req) { struct io_ring_ctx *ctx = req->ctx; io_req_put_rsrc(req); io_dismantle_req(req); io_put_task(req->task, 1); spin_lock(&ctx->completion_lock); wq_list_add_head(&req->comp_list, &ctx->locked_free_list); ctx->locked_free_nr++; spin_unlock(&ctx->completion_lock); }
0
[ "CWE-416" ]
linux
9cae36a094e7e9d6e5fe8b6dcd4642138b3eb0c7
323,974,319,708,730,770,000,000,000,000,000,000,000
13
io_uring: reinstate the inflight tracking After some debugging, it was realized that we really do still need the old inflight tracking for any file type that has io_uring_fops assigned. If we don't, then trivial circular references will mean that we never get the ctx cleaned up and hence it'll leak. Just bring back the inflight tracking, which then also means we can eliminate the conditional dropping of the file when task_work is queued. Fixes: d5361233e9ab ("io_uring: drop the old style inflight file tracking") Signed-off-by: Jens Axboe <[email protected]>
AP_DECLARE(void) ap_destroy_sub_req(request_rec *r) { /* Reclaim the space */ apr_pool_destroy(r->pool); }
0
[]
httpd
eb986059aa5aa0b6c1d52714ea83e3dd758afdd1
186,741,465,041,478,140,000,000,000,000,000,000,000
5
Merge r1889036 from trunk: legacy default slash-matching behavior w/ 'MergeSlashes OFF' Submitted By: Ruediger Pluem Reviewed By: covener, rpluem, ylavic git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1889038 13f79535-47bb-0310-9956-ffa450edef68
static void __attribute__((__noreturn__)) usage(FILE *out) { fputs(USAGE_HEADER, out); fprintf(out, _( " %1$s [-lhV]\n" " %1$s -a [options]\n" " %1$s [options] [--source] <source> | [--target] <directory>\n" " %1$s [options] <source> <directory>\n" " %1$s <operation> <mountpoint> [<target>]\n"), program_invocation_short_name); fputs(USAGE_OPTIONS, out); fprintf(out, _( " -a, --all mount all filesystems mentioned in fstab\n" " -c, --no-canonicalize don't canonicalize paths\n" " -f, --fake dry run; skip the mount(2) syscall\n" " -F, --fork fork off for each device (use with -a)\n" " -T, --fstab <path> alternative file to /etc/fstab\n")); fprintf(out, _( " -h, --help display this help text and exit\n" " -i, --internal-only don't call the mount.<type> helpers\n" " -l, --show-labels lists all mounts with LABELs\n" " -n, --no-mtab don't write to /etc/mtab\n")); fprintf(out, _( " -o, --options <list> comma-separated list of mount options\n" " -O, --test-opts <list> limit the set of filesystems (use with -a)\n" " -r, --read-only mount the filesystem read-only (same as -o ro)\n" " -t, --types <list> limit the set of filesystem types\n")); fprintf(out, _( " --source <src> explicitly specifies source (path, label, uuid)\n" " --target <target> explicitly specifies mountpoint\n")); fprintf(out, _( " -v, --verbose say what is being done\n" " -V, --version display version information and exit\n" " -w, --read-write mount the filesystem read-write (default)\n")); fputs(USAGE_SEPARATOR, out); fputs(USAGE_HELP, out); fputs(USAGE_VERSION, out); fprintf(out, _( "\nSource:\n" " -L, --label <label> synonym for LABEL=<label>\n" " -U, --uuid <uuid> synonym for UUID=<uuid>\n" " LABEL=<label> specifies device by filesystem label\n" " UUID=<uuid> specifies device by filesystem UUID\n" " PARTLABEL=<label> specifies device by partition label\n" " PARTUUID=<uuid> specifies device by partition UUID\n")); fprintf(out, _( " <device> specifies device by path\n" " <directory> mountpoint for bind mounts (see --bind/rbind)\n" " <file> regular file for loopdev setup\n")); fprintf(out, _( "\nOperations:\n" " -B, --bind mount a subtree somewhere else (same as -o bind)\n" " -M, --move move a subtree to some other place\n" " -R, --rbind mount a subtree and all submounts somewhere else\n")); fprintf(out, _( " --make-shared mark a subtree as shared\n" " --make-slave mark a subtree as slave\n" " --make-private mark a subtree as private\n" " --make-unbindable mark a subtree as unbindable\n")); fprintf(out, _( " --make-rshared recursively mark a whole subtree as shared\n" " --make-rslave recursively mark a whole subtree as slave\n" " --make-rprivate recursively mark a whole subtree as private\n" " --make-runbindable recursively mark a whole subtree as unbindable\n")); fprintf(out, USAGE_MAN_TAIL("mount(8)")); exit(out == stderr ? MOUNT_EX_USAGE : MOUNT_EX_SUCCESS); }
0
[ "CWE-200" ]
util-linux
5ebbc3865d1e53ef42e5f121c41faab23dd59075
69,397,083,812,479,330,000,000,000,000,000,000,000
74
mount: sanitize paths from non-root users $ mount /root/.ssh/../../dev/sda2 mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot this is too promiscuous. It seems better to ignore on command line specified paths which are not resolve-able for non-root users. Fixed version: $ mount /root/.ssh/../../dev/sda2 mount: /root/.ssh/../../dev/sda2: Permission denied $ mount /dev/sda2 mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot Note that this bug has no relation to mount(2) permissions evaluation in suid mode. The way how non-root user specifies paths on command line is completely irrelevant for comparison with fstab entries. Signed-off-by: Karel Zak <[email protected]>
ecma_bigint_to_bigint (ecma_value_t value, /**< any value */ bool allow_numbers) /**< converting ecma numbers is allowed */ { bool free_value = false; if (ecma_is_value_object (value)) { value = ecma_op_object_default_value (ecma_get_object_from_value (value), ECMA_PREFERRED_TYPE_NUMBER); free_value = true; if (ECMA_IS_VALUE_ERROR (value)) { return value; } } ecma_value_t result; if (ecma_is_value_string (value)) { result = ecma_bigint_parse_string_value (value, ECMA_BIGINT_PARSE_NO_OPTIONS); } else if (ecma_is_value_bigint (value)) { result = value; if (!free_value && value != ECMA_BIGINT_ZERO) { ecma_ref_extended_primitive (ecma_get_extended_primitive_from_value (value)); } else { free_value = false; } } else if (allow_numbers && ecma_is_value_number (value)) { result = ecma_bigint_number_to_bigint (ecma_get_number_from_value (value)); } else if (ecma_is_value_false (value)) { result = ECMA_BIGINT_ZERO; } else if (ecma_is_value_true (value)) { result = ecma_bigint_create_from_digit (1, false); } else { result = ecma_raise_type_error (ECMA_ERR_MSG ("Value cannot be converted to BigInt")); } if (free_value) { ecma_free_value (value); } return result; } /* ecma_bigint_to_bigint */
0
[ "CWE-416" ]
jerryscript
3bcd48f72d4af01d1304b754ef19fe1a02c96049
12,707,787,153,286,784,000,000,000,000,000,000,000
59
Improve parse_identifier (#4691) Ascii string length is no longer computed during string allocation. JerryScript-DCO-1.0-Signed-off-by: Daniel Batiz [email protected]
void reset_render_context(ASS_Renderer *render_priv, ASS_Style *style) { style = handle_selective_style_overrides(render_priv, style); init_font_scale(render_priv); render_priv->state.c[0] = style->PrimaryColour; render_priv->state.c[1] = style->SecondaryColour; render_priv->state.c[2] = style->OutlineColour; render_priv->state.c[3] = style->BackColour; render_priv->state.flags = (style->Underline ? DECO_UNDERLINE : 0) | (style->StrikeOut ? DECO_STRIKETHROUGH : 0); render_priv->state.font_size = style->FontSize; free(render_priv->state.family); render_priv->state.family = NULL; render_priv->state.family = strdup(style->FontName); render_priv->state.treat_family_as_pattern = style->treat_fontname_as_pattern; render_priv->state.bold = style->Bold; render_priv->state.italic = style->Italic; update_font(render_priv); render_priv->state.border_style = style->BorderStyle; render_priv->state.border_x = style->Outline; render_priv->state.border_y = style->Outline; change_border(render_priv, render_priv->state.border_x, render_priv->state.border_y); render_priv->state.scale_x = style->ScaleX; render_priv->state.scale_y = style->ScaleY; render_priv->state.hspacing = style->Spacing; render_priv->state.be = 0; render_priv->state.blur = style->Blur; render_priv->state.shadow_x = style->Shadow; render_priv->state.shadow_y = style->Shadow; render_priv->state.frx = render_priv->state.fry = 0.; render_priv->state.frz = M_PI * style->Angle / 180.; render_priv->state.fax = render_priv->state.fay = 0.; render_priv->state.font_encoding = style->Encoding; }
0
[ "CWE-125" ]
libass
f4f48950788b91c6a30029cc28a240b834713ea7
255,807,743,377,498,030,000,000,000,000,000,000,000
40
Fix line wrapping mode 0/3 bugs This fixes two separate bugs: a) Don't move a linebreak into the first symbol. This results in a empty line at the front, which does not help to equalize line lengths at all. Instead, merge line with the second one. b) When moving a linebreak into a symbol that already is a break, the number of lines must be decremented. Otherwise, uninitialized memory is possibly used for later layout operations. Found by fuzzer test case id:000085,sig:11,src:003377+003350,op:splice,rep:8. This might also affect and hopefully fix libass#229. v2: change semantics according to review
static double mp_bitwise_right_shift(_cimg_math_parser& mp) { return (double)((longT)_mp_arg(2)>>(unsigned int)_mp_arg(3)); }
0
[ "CWE-770" ]
cimg
619cb58dd90b4e03ac68286c70ed98acbefd1c90
65,643,724,799,307,240,000,000,000,000,000,000,000
3
CImg<>::load_bmp() and CImg<>::load_pandore(): Check that dimensions encoded in file does not exceed file size.
static int piv_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); int r; piv_private_data_t * priv = PIV_DATA(card); /* may be called before piv_init has allocated priv */ if (priv) { /* need to save sw1 and sw2 if trying to determine card_state from pin_cmd */ if (priv->pin_cmd_verify) { priv->pin_cmd_verify_sw1 = sw1; priv->pin_cmd_verify_sw2 = sw2; } else { /* a command has completed and it is not verify */ /* If we are in a context_specific sequence, unlock */ if (priv->context_specific) { sc_log(card->ctx,"Clearing CONTEXT_SPECIFIC lock"); priv->context_specific = 0; sc_unlock(card); } } if (priv->card_issues & CI_VERIFY_630X) { /* Handle the Yubikey NEO or any other PIV card which returns in response to a verify * 63 0X rather than 63 CX indicate the number of remaining PIN retries. * Perhaps they misread the spec and thought 0xCX meant "clear" or "don't care", not a literal 0xC! */ if (priv->pin_cmd_verify && sw1 == 0x63U) { priv->pin_cmd_verify_sw2 |= 0xC0U; /* make it easier to test in other code */ if ((sw2 & ~0x0fU) == 0x00U) { sc_log(card->ctx, "Verification failed (remaining tries: %d)", (sw2 & 0x0f)); return SC_ERROR_PIN_CODE_INCORRECT; /* this is what the iso_check_sw returns for 63 C0 */ } } } } r = iso_drv->ops->check_sw(card, sw1, sw2); return r; }
0
[ "CWE-125" ]
OpenSC
8fe377e93b4b56060e5bbfb6f3142ceaeca744fa
326,725,020,700,923,800,000,000,000,000,000,000,000
42
fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes.
GF_Err gf_isom_set_high_dynamic_range_info(GF_ISOFile* movie, u32 trackNumber, u32 StreamDescriptionIndex, GF_MasteringDisplayColourVolumeInfo* mdcv, GF_ContentLightLevelInfo* clli) { GF_Err e; GF_TrackBox* trak; GF_SampleEntryBox* entry; GF_SampleDescriptionBox* stsd; e = CanAccessMovie(movie, GF_ISOM_OPEN_WRITE); if (e) return e; trak = gf_isom_get_track_from_file(movie, trackNumber); if (!trak) return GF_BAD_PARAM; stsd = trak->Media->information->sampleTable->SampleDescription; if (!stsd) return movie->LastError = GF_ISOM_INVALID_FILE; if (!StreamDescriptionIndex || StreamDescriptionIndex > gf_list_count(stsd->child_boxes)) { return movie->LastError = GF_BAD_PARAM; } entry = (GF_SampleEntryBox*)gf_list_get(stsd->child_boxes, StreamDescriptionIndex - 1); //no support for generic sample entries (eg, no MPEG4 descriptor) if (entry == NULL) return GF_BAD_PARAM; if (!movie->keep_utc) trak->Media->mediaHeader->modificationTime = gf_isom_get_mp4time(); if (entry->internal_type != GF_ISOM_SAMPLE_ENTRY_VIDEO) return GF_BAD_PARAM; GF_MasteringDisplayColourVolumeBox *mdcvb = (GF_MasteringDisplayColourVolumeBox *) gf_isom_box_find_child(entry->child_boxes, GF_ISOM_BOX_TYPE_MDCV); if (!mdcvb) { mdcvb = (GF_MasteringDisplayColourVolumeBox*)gf_isom_box_new_parent(&entry->child_boxes, GF_ISOM_BOX_TYPE_MDCV); if (!mdcvb) return GF_OUT_OF_MEM; } mdcvb->mdcv = *mdcv; /*clli*/ GF_ContentLightLevelBox *cllib = (GF_ContentLightLevelBox *)gf_isom_box_find_child(entry->child_boxes, GF_ISOM_BOX_TYPE_CLLI); if (!cllib) { cllib = (GF_ContentLightLevelBox*)gf_isom_box_new_parent(&entry->child_boxes, GF_ISOM_BOX_TYPE_CLLI); if (!cllib) return GF_OUT_OF_MEM; } cllib->clli = *clli; return GF_OK; }
0
[ "CWE-476" ]
gpac
ebfa346eff05049718f7b80041093b4c5581c24e
28,882,893,277,403,320,000,000,000,000,000,000,000
42
fixed #1706
static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx) { u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl; if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm)) exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; if (vmx->vpid == 0) exec_control &= ~SECONDARY_EXEC_ENABLE_VPID; if (!enable_ept) { exec_control &= ~SECONDARY_EXEC_ENABLE_EPT; enable_unrestricted_guest = 0; /* Enable INVPCID for non-ept guests may cause performance regression. */ exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID; } if (!enable_unrestricted_guest) exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST; if (!ple_gap) exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING; if (!vmx_vm_has_apicv(vmx->vcpu.kvm)) exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT | SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY); exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE; /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD (handle_vmptrld). We can NOT enable shadow_vmcs here because we don't have yet a current VMCS12 */ exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS; return exec_control; }
0
[]
kvm
a642fc305053cc1c6e47e4f4df327895747ab485
205,510,616,168,061,750,000,000,000,000,000,000,000
29
kvm: vmx: handle invvpid vm exit gracefully On systems with invvpid instruction support (corresponding bit in IA32_VMX_EPT_VPID_CAP MSR is set) guest invocation of invvpid causes vm exit, which is currently not handled and results in propagation of unknown exit to userspace. Fix this by installing an invvpid vm exit handler. This is CVE-2014-3646. Cc: [email protected] Signed-off-by: Petr Matousek <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>
gpk_erase_card(sc_card_t *card) { struct gpk_private_data *priv = DRVDATA(card); sc_apdu_t apdu; u8 offset; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); switch (card->type) { case SC_CARD_TYPE_GPK_GPK4000_su256: case SC_CARD_TYPE_GPK_GPK4000_sdo: offset = 0x6B; /* courtesy gemplus hotline */ break; case SC_CARD_TYPE_GPK_GPK4000_s: offset = 7; break; case SC_CARD_TYPE_GPK_GPK8000: case SC_CARD_TYPE_GPK_GPK8000_8K: case SC_CARD_TYPE_GPK_GPK8000_16K: case SC_CARD_TYPE_GPK_GPK16000: offset = 0; break; default: return SC_ERROR_NOT_SUPPORTED; } memset(&apdu, 0, sizeof(apdu)); apdu.cse = SC_APDU_CASE_1; apdu.cla = 0xDB; apdu.ins = 0xDE; apdu.p2 = offset; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error"); priv->key_set = 0; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); }
0
[ "CWE-125" ]
OpenSC
8fe377e93b4b56060e5bbfb6f3142ceaeca744fa
100,206,811,748,177,500,000,000,000,000,000,000,000
43
fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes.
static int ethtool_self_test(struct net_device *dev, char __user *useraddr) { struct ethtool_test test; struct ethtool_ops *ops = dev->ethtool_ops; u64 *data; int ret; if (!ops->self_test || !ops->self_test_count) return -EOPNOTSUPP; if (copy_from_user(&test, useraddr, sizeof(test))) return -EFAULT; test.len = ops->self_test_count(dev); data = kmalloc(test.len * sizeof(u64), GFP_USER); if (!data) return -ENOMEM; ops->self_test(dev, &test, data); ret = -EFAULT; if (copy_to_user(useraddr, &test, sizeof(test))) goto out; useraddr += sizeof(test); if (copy_to_user(useraddr, data, test.len * sizeof(u64))) goto out; ret = 0; out: kfree(data); return ret; }
0
[]
linux
e89e9cf539a28df7d0eb1d0a545368e9920b34ac
287,975,874,044,632,200,000,000,000,000,000,000,000
32
[IPv4/IPv6]: UFO Scatter-gather approach Attached is kernel patch for UDP Fragmentation Offload (UFO) feature. 1. This patch incorporate the review comments by Jeff Garzik. 2. Renamed USO as UFO (UDP Fragmentation Offload) 3. udp sendfile support with UFO This patches uses scatter-gather feature of skb to generate large UDP datagram. Below is a "how-to" on changes required in network device driver to use the UFO interface. UDP Fragmentation Offload (UFO) Interface: ------------------------------------------- UFO is a feature wherein the Linux kernel network stack will offload the IP fragmentation functionality of large UDP datagram to hardware. This will reduce the overhead of stack in fragmenting the large UDP datagram to MTU sized packets 1) Drivers indicate their capability of UFO using dev->features |= NETIF_F_UFO | NETIF_F_HW_CSUM | NETIF_F_SG NETIF_F_HW_CSUM is required for UFO over ipv6. 2) UFO packet will be submitted for transmission using driver xmit routine. UFO packet will have a non-zero value for "skb_shinfo(skb)->ufo_size" skb_shinfo(skb)->ufo_size will indicate the length of data part in each IP fragment going out of the adapter after IP fragmentation by hardware. skb->data will contain MAC/IP/UDP header and skb_shinfo(skb)->frags[] contains the data payload. The skb->ip_summed will be set to CHECKSUM_HW indicating that hardware has to do checksum calculation. Hardware should compute the UDP checksum of complete datagram and also ip header checksum of each fragmented IP packet. For IPV6 the UFO provides the fragment identification-id in skb_shinfo(skb)->ip6_frag_id. The adapter should use this ID for generating IPv6 fragments. Signed-off-by: Ananda Raju <[email protected]> Signed-off-by: Rusty Russell <[email protected]> (forwarded) Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define ThrowTIFFException(severity,message) \ { \ if (tiff_pixels != (unsigned char *) NULL) \ tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); \ if (quantum_info != (QuantumInfo *) NULL) \ quantum_info=DestroyQuantumInfo(quantum_info); \ TIFFClose(tiff); \ ThrowReaderException(severity,message); \ } const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType more_frames, status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *tiff_pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } more_frames=MagickTrue; do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning photometric=PHOTOMETRIC_RGB; if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point", exception); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black", exception); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white", exception); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette",exception); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB",exception); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB",exception); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)", exception); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV",exception); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK",exception); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated",exception); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR",exception); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown",exception); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric", exception)); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb",exception); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb",exception); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace,exception); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace,exception); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace,exception); TIFFGetProfiles(tiff,image,exception); TIFFGetProperties(tiff,image,exception); option=GetImageOption(image_info,"tiff:exif-properties"); if (IsStringFalse(option) == MagickFalse) /* enabled by default */ TIFFGetEXIFProperties(tiff,image,exception); (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->resolution.x=x_resolution; image->resolution.y=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5); image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MagickPathExtent]; uint16 horizontal, vertical; tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal, &vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MagickPathExtent, "%dx%d",horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor,exception); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } quantum_info=(QuantumInfo *) NULL; if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors,exception) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } value=(unsigned short) image->scene; if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { TIFFClose(tiff); return(DestroyImageList(image)); } status=ResetImagePixels(image,exception); if (status == MagickFalse) { TIFFClose(tiff); return(DestroyImageList(image)); } /* Allocate memory for the image and pixel buffer. */ tiff_pixels=(unsigned char *) NULL; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified",exception); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->alpha_trait=BlendPixelTrait; } else for (i=0; i < extra_samples; i++) { image->alpha_trait=BlendPixelTrait; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated", exception); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated", exception); } } if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); method=ReadGenericMethod; rows_per_strip=(uint32) image->rows; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char buffer[MagickPathExtent]; method=ReadStripMethod; (void) FormatLocaleString(buffer,MagickPathExtent,"%u", (unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",buffer,exception); } if (rows_per_strip > (uint32) image->rows) rows_per_strip=(uint32) image->rows; if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG)) if ((image->alpha_trait == UndefinedPixelTrait) || (samples_per_pixel >= 4)) method=ReadRGBAMethod; if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE)) if ((image->alpha_trait == UndefinedPixelTrait) || (samples_per_pixel >= 5)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; if (TIFFScanlineSize(tiff) <= 0) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (((MagickSizeType) TIFFScanlineSize(tiff)) > GetBlobSize(image)) ThrowTIFFException(CorruptImageError,"InsufficientImageDataInFile"); number_pixels=MagickMax(TIFFScanlineSize(tiff),MagickMax((ssize_t) image->columns*samples_per_pixel*pow(2.0,ceil(log(bits_per_sample)/ log(2.0))),image->columns*rows_per_strip)*sizeof(uint32)); tiff_pixels=(unsigned char *) AcquireMagickMemory(number_pixels); if (tiff_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(tiff_pixels,0,number_pixels); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); if (image->alpha_trait != UndefinedPixelTrait) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; tiff_status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels); if (tiff_status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; tiff_status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels); if (tiff_status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; tiff_status=TIFFReadPixels(tiff,(tsample_t) i,y,(char *) tiff_pixels); if (tiff_status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; unsigned char *p; tiff_status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels); if (tiff_status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=tiff_pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456)),q); SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984)),q); SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816)),q); SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q); q+=GetPixelChannels(image); p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) tiff_pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) tiff_pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p))),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p))),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p))),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) ThrowTIFFException(CoderError,"ImageIsNotTiled"); if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) || (AcquireMagickResource(HeightResource,rows) == MagickFalse)) ThrowTIFFException(ImageError,"WidthOrHeightExceedsLimit"); (void) SetImageStorageClass(image,DirectClass,exception); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows* sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y+=rows) { register ssize_t x; register Quantum *magick_restrict q, *magick_restrict tile; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+ x); for (row=rows_remaining; row > 0; row--) { if (image->alpha_trait != UndefinedPixelTrait) for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p++; q+=GetPixelChannels(image); } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); p++; q+=GetPixelChannels(image); } p+=columns-columns_remaining; q-=GetPixelChannels(image)*(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; q+=GetPixelChannels(image)*(image->columns-1); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p--; q-=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (more_frames != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while ((status != MagickFalse) && (more_frames != MagickFalse)); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if ((image_info->number_scenes != 0) && (image_info->scene >= GetImageListLength(image))) status=MagickFalse; if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }
0
[ "CWE-399", "CWE-772" ]
ImageMagick
256825d4eb33dc301496710d15cf5a7ae924088b
255,127,043,394,063,760,000,000,000,000,000,000,000
1,042
Fixed possible memory leak reported in #1206
call_start(struct rpc_task *task) { struct rpc_clnt *clnt = task->tk_client; dprintk("RPC: %5u call_start %s%d proc %s (%s)\n", task->tk_pid, clnt->cl_protname, clnt->cl_vers, rpc_proc_name(task), (RPC_IS_ASYNC(task) ? "async" : "sync")); /* Increment call count */ task->tk_msg.rpc_proc->p_count++; clnt->cl_stats->rpccnt++; task->tk_action = call_reserve; }
0
[ "CWE-400", "CWE-399", "CWE-703" ]
linux
0b760113a3a155269a3fba93a409c640031dd68f
195,270,841,327,294,760,000,000,000,000,000,000,000
14
NLM: Don't hang forever on NLM unlock requests If the NLM daemon is killed on the NFS server, we can currently end up hanging forever on an 'unlock' request, instead of aborting. Basically, if the rpcbind request fails, or the server keeps returning garbage, we really want to quit instead of retrying. Tested-by: Vasily Averin <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> Cc: [email protected]
int ha_partition::rnd_pos(uchar * buf, uchar *pos) { uint part_id; handler *file; DBUG_ENTER("ha_partition::rnd_pos"); part_id= uint2korr((const uchar *) pos); DBUG_ASSERT(part_id < m_tot_parts); file= m_file[part_id]; m_last_part= part_id; DBUG_RETURN(file->rnd_pos(buf, (pos + PARTITION_BYTES_IN_POS))); }
0
[]
mysql-server
be901b60ae59c93848c829d1b0b2cb523ab8692e
199,311,237,589,461,140,000,000,000,000,000,000,000
12
Bug#26390632: CREATE TABLE CAN CAUSE MYSQL TO EXIT. Analysis ======== CREATE TABLE of InnoDB table with a partition name which exceeds the path limit can cause the server to exit. During the preparation of the partition name, there was no check to identify whether the complete path name for partition exceeds the max supported path length, causing the server to exit during subsequent processing. Fix === During the preparation of partition name, check and report an error if the partition path name exceeds the maximum path name limit. This is a 5.5 patch.
add_keyserver_modify (PKT_signature *sig,int enabled) { const byte *s; size_t n; int i; char *buf; /* The keyserver modify flag is a negative flag (i.e. no-modify) */ enabled=!enabled; s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n ); /* Already set or cleared */ if (s && n && ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80)))) return; if (!s || !n) { /* create a new one */ n = 1; buf = xmalloc_clear (n); } else { buf = xmalloc (n); memcpy (buf, s, n); } if(enabled) buf[0] |= 0x80; /* no-modify flag */ else buf[0] &= ~0x80; /* Are there any bits set? */ for(i=0;i<n;i++) if(buf[i]!=0) break; if(i==n) delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS); else build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n); xfree (buf); }
0
[ "CWE-20" ]
gnupg
2183683bd633818dd031b090b5530951de76f392
184,336,627,152,437,370,000,000,000,000,000,000,000
42
Use inline functions to convert buffer data to scalars. * common/host2net.h (buf16_to_ulong, buf16_to_uint): New. (buf16_to_ushort, buf16_to_u16): New. (buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New. -- Commit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to avoid all sign extension on shift problems. Hanno Böck found a case with an invalid read due to this problem. To fix that once and for all almost all uses of "<< 24" and "<< 8" are changed by this patch to use an inline function from host2net.h. Signed-off-by: Werner Koch <[email protected]>
static int io_shutdown_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) { if (unlikely(sqe->off || sqe->addr || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)) return -EINVAL; req->shutdown.how = READ_ONCE(sqe->len); return 0; }
0
[ "CWE-416" ]
linux
9cae36a094e7e9d6e5fe8b6dcd4642138b3eb0c7
127,913,931,299,329,850,000,000,000,000,000,000,000
10
io_uring: reinstate the inflight tracking After some debugging, it was realized that we really do still need the old inflight tracking for any file type that has io_uring_fops assigned. If we don't, then trivial circular references will mean that we never get the ctx cleaned up and hence it'll leak. Just bring back the inflight tracking, which then also means we can eliminate the conditional dropping of the file when task_work is queued. Fixes: d5361233e9ab ("io_uring: drop the old style inflight file tracking") Signed-off-by: Jens Axboe <[email protected]>
void WebContents::ResetManagedWebContents(bool async) { if (async) { // Browser context should be destroyed only after the WebContents, // this is guaranteed in the sync mode by the order of declaration, // in the async version we maintain a reference until the WebContents // is destroyed. // //electron/patches/chromium/content_browser_main_loop.patch // is required to get the right quit closure for the main message loop. base::ThreadTaskRunnerHandle::Get()->DeleteSoon( FROM_HERE, inspectable_web_contents_.release()); } else { inspectable_web_contents_.reset(); } }
0
[ "CWE-200", "CWE-668" ]
electron
07a1c2a3e5845901f7e2eda9506695be58edc73c
43,829,519,097,569,840,000,000,000,000,000,000,000
14
fix: restrict sendToFrame to same-process frames by default (#26875)
JBIG2Bitmap *JBIG2Bitmap::getSlice(unsigned int x, unsigned int y, unsigned int wA, unsigned int hA) { JBIG2Bitmap *slice; unsigned int xx, yy; if (!data) { return nullptr; } slice = new JBIG2Bitmap(0, wA, hA); if (slice->isOk()) { slice->clearToZero(); for (yy = 0; yy < hA; ++yy) { for (xx = 0; xx < wA; ++xx) { if (getPixel(x + xx, y + yy)) { slice->setPixel(xx, yy); } } } } else { delete slice; slice = nullptr; } return slice; }
0
[ "CWE-476", "CWE-190" ]
poppler
27354e9d9696ee2bc063910a6c9a6b27c5184a52
222,193,585,535,460,820,000,000,000,000,000,000,000
25
JBIG2Stream: Fix crash on broken file https://github.com/jeffssh/CVE-2021-30860 Thanks to David Warren for the heads up
static int raw_setsockopt(struct socket *sock, int level, int optname, char __user *optval, int optlen) { struct sock *sk = sock->sk; struct raw_sock *ro = raw_sk(sk); struct can_filter *filter = NULL; /* dyn. alloc'ed filters */ struct can_filter sfilter; /* single filter */ struct net_device *dev = NULL; can_err_mask_t err_mask = 0; int count = 0; int err = 0; if (level != SOL_CAN_RAW) return -EINVAL; if (optlen < 0) return -EINVAL; switch (optname) { case CAN_RAW_FILTER: if (optlen % sizeof(struct can_filter) != 0) return -EINVAL; count = optlen / sizeof(struct can_filter); if (count > 1) { /* filter does not fit into dfilter => alloc space */ filter = kmalloc(optlen, GFP_KERNEL); if (!filter) return -ENOMEM; if (copy_from_user(filter, optval, optlen)) { kfree(filter); return -EFAULT; } } else if (count == 1) { if (copy_from_user(&sfilter, optval, optlen)) return -EFAULT; } lock_sock(sk); if (ro->bound && ro->ifindex) dev = dev_get_by_index(&init_net, ro->ifindex); if (ro->bound) { /* (try to) register the new filters */ if (count == 1) err = raw_enable_filters(dev, sk, &sfilter, 1); else err = raw_enable_filters(dev, sk, filter, count); if (err) { if (count > 1) kfree(filter); goto out_fil; } /* remove old filter registrations */ raw_disable_filters(dev, sk, ro->filter, ro->count); } /* remove old filter space */ if (ro->count > 1) kfree(ro->filter); /* link new filters to the socket */ if (count == 1) { /* copy filter data for single filter */ ro->dfilter = sfilter; filter = &ro->dfilter; } ro->filter = filter; ro->count = count; out_fil: if (dev) dev_put(dev); release_sock(sk); break; case CAN_RAW_ERR_FILTER: if (optlen != sizeof(err_mask)) return -EINVAL; if (copy_from_user(&err_mask, optval, optlen)) return -EFAULT; err_mask &= CAN_ERR_MASK; lock_sock(sk); if (ro->bound && ro->ifindex) dev = dev_get_by_index(&init_net, ro->ifindex); /* remove current error mask */ if (ro->bound) { /* (try to) register the new err_mask */ err = raw_enable_errfilter(dev, sk, err_mask); if (err) goto out_err; /* remove old err_mask registration */ raw_disable_errfilter(dev, sk, ro->err_mask); } /* link new err_mask to the socket */ ro->err_mask = err_mask; out_err: if (dev) dev_put(dev); release_sock(sk); break; case CAN_RAW_LOOPBACK: if (optlen != sizeof(ro->loopback)) return -EINVAL; if (copy_from_user(&ro->loopback, optval, optlen)) return -EFAULT; break; case CAN_RAW_RECV_OWN_MSGS: if (optlen != sizeof(ro->recv_own_msgs)) return -EINVAL; if (copy_from_user(&ro->recv_own_msgs, optval, optlen)) return -EFAULT; break; default: return -ENOPROTOOPT; } return err; }
0
[ "CWE-200" ]
linux-2.6
e84b90ae5eb3c112d1f208964df1d8156a538289
151,661,969,498,324,420,000,000,000,000,000,000,000
143
can: Fix raw_getname() leak raw_getname() can leak 10 bytes of kernel memory to user (two bytes hole between can_family and can_ifindex, 8 bytes at the end of sockaddr_can structure) Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Oliver Hartkopp <[email protected]> Signed-off-by: David S. Miller <[email protected]>
unsigned int scalar7(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3, const unsigned int arg4, const unsigned int arg5, const unsigned int arg6, const unsigned int arg7) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2: arg3!=~0U && arg3>_cimg_mp_slot_c && _cimg_mp_is_comp(arg3)?arg3: arg4!=~0U && arg4>_cimg_mp_slot_c && _cimg_mp_is_comp(arg4)?arg4: arg5!=~0U && arg5>_cimg_mp_slot_c && _cimg_mp_is_comp(arg5)?arg5: arg6!=~0U && arg6>_cimg_mp_slot_c && _cimg_mp_is_comp(arg6)?arg6: arg7!=~0U && arg7>_cimg_mp_slot_c && _cimg_mp_is_comp(arg7)?arg7: ((return_new_comp = true), scalar()); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2,arg3,arg4,arg5,arg6,arg7).move_to(code); return pos; }
0
[ "CWE-770" ]
cimg
619cb58dd90b4e03ac68286c70ed98acbefd1c90
255,076,793,394,432,230,000,000,000,000,000,000,000
16
CImg<>::load_bmp() and CImg<>::load_pandore(): Check that dimensions encoded in file does not exceed file size.
static void MapToLabels(const string& subscript, Labels* labels, absl::flat_hash_map<char, int>* label_mapping) { for (int i = 0; i < subscript.size(); ++i) { const char label_char = subscript[i]; if (label_char == '.') { labels->push_back(kEllipsisLabel); i += 2; // Skip next 2 characters as well. continue; } if (!label_mapping->contains(label_char)) { const int next_label = label_mapping->size(); (*label_mapping)[label_char] = next_label; } const int mapped_label = (*label_mapping)[label_char]; labels->push_back(mapped_label); } }
0
[ "CWE-703", "CWE-824" ]
tensorflow
f09caa532b6e1ac8d2aa61b7832c78c5b79300c6
269,972,592,379,462,180,000,000,000,000,000,000,000
17
Fix EinsumHelper::ParseEquation to avoid uninitialized accesses. EinsumHelper::ParseEquation is supposed to return true or false in input_has_ellipsis and output_has_ellipsis to indicate whether there is ellipsis in the inputs and output. Previously, when there is no ellipsis in the inputs or output, the routine doesn't assign false to the variables. This change initializes the two variables with false to fix the problem. PiperOrigin-RevId: 391772004 Change-Id: I17b6c88aadef4131470378e48cced054bf252e86
int security_socket_post_create(struct socket *sock, int family, int type, int protocol, int kern) { return security_ops->socket_post_create(sock, family, type, protocol, kern); }
0
[]
linux-2.6
ee18d64c1f632043a02e6f5ba5e045bb26a5465f
136,252,895,632,536,370,000,000,000,000,000,000,000
6
KEYS: Add a keyctl to install a process's session keyring on its parent [try #6] Add a keyctl to install a process's session keyring onto its parent. This replaces the parent's session keyring. Because the COW credential code does not permit one process to change another process's credentials directly, the change is deferred until userspace next starts executing again. Normally this will be after a wait*() syscall. To support this, three new security hooks have been provided: cred_alloc_blank() to allocate unset security creds, cred_transfer() to fill in the blank security creds and key_session_to_parent() - which asks the LSM if the process may replace its parent's session keyring. The replacement may only happen if the process has the same ownership details as its parent, and the process has LINK permission on the session keyring, and the session keyring is owned by the process, and the LSM permits it. Note that this requires alteration to each architecture's notify_resume path. This has been done for all arches barring blackfin, m68k* and xtensa, all of which need assembly alteration to support TIF_NOTIFY_RESUME. This allows the replacement to be performed at the point the parent process resumes userspace execution. This allows the userspace AFS pioctl emulation to fully emulate newpag() and the VIOCSETTOK and VIOCSETTOK2 pioctls, all of which require the ability to alter the parent process's PAG membership. However, since kAFS doesn't use PAGs per se, but rather dumps the keys into the session keyring, the session keyring of the parent must be replaced if, for example, VIOCSETTOK is passed the newpag flag. This can be tested with the following program: #include <stdio.h> #include <stdlib.h> #include <keyutils.h> #define KEYCTL_SESSION_TO_PARENT 18 #define OSERROR(X, S) do { if ((long)(X) == -1) { perror(S); exit(1); } } while(0) int main(int argc, char **argv) { key_serial_t keyring, key; long ret; keyring = keyctl_join_session_keyring(argv[1]); OSERROR(keyring, "keyctl_join_session_keyring"); key = add_key("user", "a", "b", 1, keyring); OSERROR(key, "add_key"); ret = keyctl(KEYCTL_SESSION_TO_PARENT); OSERROR(ret, "KEYCTL_SESSION_TO_PARENT"); return 0; } Compiled and linked with -lkeyutils, you should see something like: [dhowells@andromeda ~]$ keyctl show Session Keyring -3 --alswrv 4043 4043 keyring: _ses 355907932 --alswrv 4043 -1 \_ keyring: _uid.4043 [dhowells@andromeda ~]$ /tmp/newpag [dhowells@andromeda ~]$ keyctl show Session Keyring -3 --alswrv 4043 4043 keyring: _ses 1055658746 --alswrv 4043 4043 \_ user: a [dhowells@andromeda ~]$ /tmp/newpag hello [dhowells@andromeda ~]$ keyctl show Session Keyring -3 --alswrv 4043 4043 keyring: hello 340417692 --alswrv 4043 4043 \_ user: a Where the test program creates a new session keyring, sticks a user key named 'a' into it and then installs it on its parent. Signed-off-by: David Howells <[email protected]> Signed-off-by: James Morris <[email protected]>
read_vhost_message(struct virtio_net *dev, int sockfd, struct vhu_msg_context *ctx) { int ret; ret = read_fd_message(dev->ifname, sockfd, (char *)&ctx->msg, VHOST_USER_HDR_SIZE, ctx->fds, VHOST_MEMORY_MAX_NREGIONS, &ctx->fd_num); if (ret <= 0) { return ret; } else if (ret != VHOST_USER_HDR_SIZE) { VHOST_LOG_CONFIG(ERR, "(%s) Unexpected header size read\n", dev->ifname); close_msg_fds(ctx); return -1; } if (ctx->msg.size) { if (ctx->msg.size > sizeof(ctx->msg.payload)) { VHOST_LOG_CONFIG(ERR, "(%s) invalid msg size: %d\n", dev->ifname, ctx->msg.size); return -1; } ret = read(sockfd, &ctx->msg.payload, ctx->msg.size); if (ret <= 0) return ret; if (ret != (int)ctx->msg.size) { VHOST_LOG_CONFIG(ERR, "(%s) read control message failed\n", dev->ifname); return -1; } } return ret; }
0
[ "CWE-125", "CWE-787" ]
dpdk
6442c329b9d2ded0f44b27d2016aaba8ba5844c5
180,722,638,425,687,300,000,000,000,000,000,000,000
31
vhost: fix queue number check when setting inflight FD In function vhost_user_set_inflight_fd, queue number in inflight message is used to access virtqueue. However, queue number could be larger than VHOST_MAX_VRING and cause write OOB as this number will be used to write inflight info in virtqueue structure. This patch checks the queue number to avoid the issue and also make sure virtqueues are allocated before setting inflight information. Fixes: ad0a4ae491fe ("vhost: checkout resubmit inflight information") Cc: [email protected] Reported-by: Wenxiang Qian <[email protected]> Signed-off-by: Chenbo Xia <[email protected]> Reviewed-by: Maxime Coquelin <[email protected]>
MemoryRegion *flatview_translate(struct uc_struct *uc, FlatView *fv, hwaddr addr, hwaddr *xlat, hwaddr *plen, bool is_write, MemTxAttrs attrs) { MemoryRegion *mr; MemoryRegionSection section; AddressSpace *as = NULL; /* This can be MMIO, so setup MMIO bit. */ section = flatview_do_translate(uc, fv, addr, xlat, plen, NULL, is_write, true, &as, attrs); mr = section.mr; return mr; }
0
[ "CWE-476" ]
unicorn
3d3deac5e6d38602b689c4fef5dac004f07a2e63
274,723,237,617,755,350,000,000,000,000,000,000,000
15
Fix crash when mapping a big memory and calling uc_close
static void sctp_generate_autoclose_event(unsigned long data) { struct sctp_association *asoc = (struct sctp_association *) data; sctp_generate_timeout_event(asoc, SCTP_EVENT_TIMEOUT_AUTOCLOSE); }
0
[]
linux
196d67593439b03088913227093e374235596e33
230,581,908,655,443,400,000,000,000,000,000,000,000
5
sctp: Add support to per-association statistics via a new SCTP_GET_ASSOC_STATS call The current SCTP stack is lacking a mechanism to have per association statistics. This is an implementation modeled after OpenSolaris' SCTP_GET_ASSOC_STATS. Userspace part will follow on lksctp if/when there is a general ACK on this. V4: - Move ipackets++ before q->immediate.func() for consistency reasons - Move sctp_max_rto() at the end of sctp_transport_update_rto() to avoid returning bogus RTO values - return asoc->rto_min when max_obs_rto value has not changed V3: - Increase ictrlchunks in sctp_assoc_bh_rcv() as well - Move ipackets++ to sctp_inq_push() - return 0 when no rto updates took place since the last call V2: - Implement partial retrieval of stat struct to cope for future expansion - Kill the rtxpackets counter as it cannot be precise anyway - Rename outseqtsns to outofseqtsns to make it clearer that these are out of sequence unexpected TSNs - Move asoc->ipackets++ under a lock to avoid potential miscounts - Fold asoc->opackets++ into the already existing asoc check - Kill unneeded (q->asoc) test when increasing rtxchunks - Do not count octrlchunks if sending failed (SCTP_XMIT_OK != 0) - Don't count SHUTDOWNs as SACKs - Move SCTP_GET_ASSOC_STATS to the private space API - Adjust the len check in sctp_getsockopt_assoc_stats() to allow for future struct growth - Move association statistics in their own struct - Update idupchunks when we send a SACK with dup TSNs - return min_rto in max_rto when RTO has not changed. Also return the transport when max_rto last changed. Signed-off: Michele Baldessari <[email protected]> Acked-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]>
int brcmf_net_attach(struct brcmf_if *ifp, bool rtnl_locked) { struct brcmf_pub *drvr = ifp->drvr; struct net_device *ndev; s32 err; brcmf_dbg(TRACE, "Enter, bsscfgidx=%d mac=%pM\n", ifp->bsscfgidx, ifp->mac_addr); ndev = ifp->ndev; /* set appropriate operations */ ndev->netdev_ops = &brcmf_netdev_ops_pri; ndev->needed_headroom += drvr->hdrlen; ndev->ethtool_ops = &brcmf_ethtool_ops; /* set the mac address & netns */ memcpy(ndev->dev_addr, ifp->mac_addr, ETH_ALEN); dev_net_set(ndev, wiphy_net(cfg_to_wiphy(drvr->config))); INIT_WORK(&ifp->multicast_work, _brcmf_set_multicast_list); INIT_WORK(&ifp->ndoffload_work, _brcmf_update_ndtable); if (rtnl_locked) err = register_netdevice(ndev); else err = register_netdev(ndev); if (err != 0) { brcmf_err("couldn't register the net device\n"); goto fail; } ndev->priv_destructor = brcmf_cfg80211_free_netdev; brcmf_dbg(INFO, "%s: Broadcom Dongle Host Driver\n", ndev->name); return 0; fail: drvr->iflist[ifp->bsscfgidx] = NULL; ndev->netdev_ops = NULL; return -EBADE; }
0
[ "CWE-20" ]
linux
a4176ec356c73a46c07c181c6d04039fafa34a9f
324,458,815,384,539,400,000,000,000,000,000,000,000
41
brcmfmac: add subtype check for event handling in data path For USB there is no separate channel being used to pass events from firmware to the host driver and as such are passed over the data path. In order to detect mock event messages an additional check is needed on event subtype. This check is added conditionally using unlikely() keyword. Reviewed-by: Hante Meuleman <[email protected]> Reviewed-by: Pieter-Paul Giesberts <[email protected]> Reviewed-by: Franky Lin <[email protected]> Signed-off-by: Arend van Spriel <[email protected]> Signed-off-by: Kalle Valo <[email protected]>
static const char *cmd_debug_log(cmd_parms *cmd, void *_dcfg, const char *p1) { directory_config *dcfg = (directory_config *)_dcfg; apr_status_t rc; dcfg->debuglog_name = ap_server_root_relative(cmd->pool, p1); rc = apr_file_open(&dcfg->debuglog_fd, dcfg->debuglog_name, APR_WRITE | APR_APPEND | APR_CREATE | APR_BINARY, CREATEMODE, cmd->pool); if (rc != APR_SUCCESS) { return apr_psprintf(cmd->pool, "ModSecurity: Failed to open debug log file: %s", dcfg->debuglog_name); } return NULL; }
0
[ "CWE-20", "CWE-611" ]
ModSecurity
d4d80b38aa85eccb26e3c61b04d16e8ca5de76fe
245,056,294,977,400,360,000,000,000,000,000,000,000
18
Added SecXmlExternalEntity
int mingw_rmdir(const char *pathname) { int ret, tries = 0; wchar_t wpathname[MAX_PATH]; if (xutftowcs_path(wpathname, pathname) < 0) return -1; while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) { if (!is_file_in_use_error(GetLastError())) errno = err_win_to_posix(GetLastError()); if (errno != EACCES) break; if (!is_dir_empty(wpathname)) { errno = ENOTEMPTY; break; } /* * We assume that some other process had the source or * destination file open at the wrong moment and retry. * In order to give the other process a higher chance to * complete its operation, we give up our time slice now. * If we have to retry again, we do sleep a bit. */ Sleep(delay[tries]); tries++; } while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) && ask_yes_no_if_possible("Deletion of directory '%s' failed. " "Should I try again?", pathname)) ret = _wrmdir(wpathname); if (!ret) invalidate_lstat_cache(); return ret; }
0
[ "CWE-59", "CWE-61" ]
git
684dd4c2b414bcf648505e74498a608f28de4592
290,526,033,117,860,850,000,000,000,000,000,000,000
34
checkout: fix bug that makes checkout follow symlinks in leading path Before checking out a file, we have to confirm that all of its leading components are real existing directories. And to reduce the number of lstat() calls in this process, we cache the last leading path known to contain only directories. However, when a path collision occurs (e.g. when checking out case-sensitive files in case-insensitive file systems), a cached path might have its file type changed on disk, leaving the cache on an invalid state. Normally, this doesn't bring any bad consequences as we usually check out files in index order, and therefore, by the time the cached path becomes outdated, we no longer need it anyway (because all files in that directory would have already been written). But, there are some users of the checkout machinery that do not always follow the index order. In particular: checkout-index writes the paths in the same order that they appear on the CLI (or stdin); and the delayed checkout feature -- used when a long-running filter process replies with "status=delayed" -- postpones the checkout of some entries, thus modifying the checkout order. When we have to check out an out-of-order entry and the lstat() cache is invalid (due to a previous path collision), checkout_entry() may end up using the invalid data and thrusting that the leading components are real directories when, in reality, they are not. In the best case scenario, where the directory was replaced by a regular file, the user will get an error: "fatal: unable to create file 'foo/bar': Not a directory". But if the directory was replaced by a symlink, checkout could actually end up following the symlink and writing the file at a wrong place, even outside the repository. Since delayed checkout is affected by this bug, it could be used by an attacker to write arbitrary files during the clone of a maliciously crafted repository. Some candidate solutions considered were to disable the lstat() cache during unordered checkouts or sort the entries before passing them to the checkout machinery. But both ideas include some performance penalty and they don't future-proof the code against new unordered use cases. Instead, we now manually reset the lstat cache whenever we successfully remove a directory. Note: We are not even checking whether the directory was the same as the lstat cache points to because we might face a scenario where the paths refer to the same location but differ due to case folding, precomposed UTF-8 issues, or the presence of `..` components in the path. Two regression tests, with case-collisions and utf8-collisions, are also added for both checkout-index and delayed checkout. Note: to make the previously mentioned clone attack unfeasible, it would be sufficient to reset the lstat cache only after the remove_subtree() call inside checkout_entry(). This is the place where we would remove a directory whose path collides with the path of another entry that we are currently trying to check out (possibly a symlink). However, in the interest of a thorough fix that does not leave Git open to similar-but-not-identical attack vectors, we decided to intercept all `rmdir()` calls in one fell swoop. This addresses CVE-2021-21300. Co-authored-by: Johannes Schindelin <[email protected]> Signed-off-by: Matheus Tavares <[email protected]>
mt_copy(mrb_state *mrb, mt_tbl *t) { mt_tbl *t2; size_t i; if (t == NULL) return NULL; if (t->alloc == 0) return NULL; if (t->size == 0) return NULL; t2 = mt_new(mrb); for (i=0; i<t->alloc; i++) { struct mt_elem *slot = &t->table[i]; if (slot->key) { mt_put(mrb, t2, slot->key, slot->func_p, slot->noarg_p, slot->ptr); } } return t2; }
0
[ "CWE-476", "CWE-190" ]
mruby
f5e10c5a79a17939af763b1dcf5232ce47e24a34
232,484,388,817,422,060,000,000,000,000,000,000,000
19
proc.c: add `mrb_state` argument to `mrb_proc_copy()`. The function may invoke the garbage collection and it requires `mrb_state` to run.
static struct ldb_message *ldb_msg_copy_shallow_impl(TALLOC_CTX *mem_ctx, const struct ldb_message *msg) { struct ldb_message *msg2; unsigned int i; msg2 = talloc(mem_ctx, struct ldb_message); if (msg2 == NULL) return NULL; *msg2 = *msg; msg2->elements = talloc_array(msg2, struct ldb_message_element, msg2->num_elements); if (msg2->elements == NULL) goto failed; for (i=0;i<msg2->num_elements;i++) { msg2->elements[i] = msg->elements[i]; } return msg2; failed: talloc_free(msg2); return NULL; }
0
[ "CWE-200" ]
samba
7efe8182c165fbf17d2f88c173527a7a554e214b
8,074,455,010,544,177,000,000,000,000,000,000,000
25
CVE-2022-32746 ldb: Add flag to mark message element values as shared When making a shallow copy of an ldb message, mark the message elements of the copy as sharing their values with the message elements in the original message. This flag value will be heeded in the next commit. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton <[email protected]>
Luv24toRGB(LogLuvState* sp, uint8* op, tmsize_t n) { uint32* luv = (uint32*) sp->tbuf; uint8* rgb = (uint8*) op; while (n-- > 0) { float xyz[3]; LogLuv24toXYZ(*luv++, xyz); XYZtoRGB24(xyz, rgb); rgb += 3; } }
0
[ "CWE-787" ]
libtiff
aaab5c3c9d2a2c6984f23ccbc79702610439bc65
77,236,954,705,133,750,000,000,000,000,000,000,000
13
* libtiff/tif_luv.c: fix potential out-of-bound writes in decode functions in non debug builds by replacing assert()s by regular if checks (bugzilla #2522). Fix potential out-of-bound reads in case of short input data.
static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_NAME *nm, STACK_OF(X509_CRL) *crls) { int i; X509_CRL *crl, *best_crl = NULL; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); if (X509_NAME_cmp(nm, X509_CRL_get_issuer(crl))) continue; if (check_crl_time(ctx, crl, 0)) { *pcrl = crl; CRYPTO_add(&crl->references, 1, CRYPTO_LOCK_X509); return 1; } best_crl = crl; } if (best_crl) { *pcrl = best_crl; CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509); } return 0; }
0
[ "CWE-119" ]
openssl
fa57f74a3941db6b2efb2f43c6add914ec83db20
69,931,342,185,485,510,000,000,000,000,000,000,000
23
Fix length checks in X509_cmp_time to avoid out-of-bounds reads. Also tighten X509_cmp_time to reject more than three fractional seconds in the time; and to reject trailing garbage after the offset. CVE-2015-1789 Reviewed-by: Viktor Dukhovni <[email protected]> Reviewed-by: Richard Levitte <[email protected]>
evalfun(struct funcnode *func, int argc, char **argv, int flags) { volatile struct shparam saveparam; struct jmploc *volatile savehandler; struct jmploc jmploc; int e; int savefuncline; int saveloopnest; saveparam = shellparam; savefuncline = funcline; saveloopnest = loopnest; savehandler = handler; if ((e = setjmp(jmploc.loc))) { goto funcdone; } INTOFF; handler = &jmploc; shellparam.malloc = 0; func->count++; funcline = func->n.ndefun.linno; loopnest = 0; INTON; shellparam.nparam = argc - 1; shellparam.p = argv + 1; shellparam.optind = 1; shellparam.optoff = -1; evaltree(func->n.ndefun.body, flags & EV_TESTED); funcdone: INTOFF; loopnest = saveloopnest; funcline = savefuncline; freefunc(func); freeparam(&shellparam); shellparam = saveparam; handler = savehandler; INTON; evalskip &= ~(SKIPFUNC | SKIPFUNCDEF); return e; }
0
[]
dash
29d6f2148f10213de4e904d515e792d2cf8c968e
122,046,087,746,783,330,000,000,000,000,000,000,000
40
eval: Check nflag in evaltree instead of cmdloop This patch moves the nflag check from cmdloop into evaltree. This is so that nflag will be in force even if we enter the shell via a path other than cmdloop, e.g., through sh -c. Reported-by: Joey Hess <[email protected]> Signed-off-by: Herbert Xu <[email protected]>
void __khugepaged_exit(struct mm_struct *mm) { struct mm_slot *mm_slot; int free = 0; spin_lock(&khugepaged_mm_lock); mm_slot = get_mm_slot(mm); if (mm_slot && khugepaged_scan.mm_slot != mm_slot) { hlist_del(&mm_slot->hash); list_del(&mm_slot->mm_node); free = 1; } if (free) { spin_unlock(&khugepaged_mm_lock); clear_bit(MMF_VM_HUGEPAGE, &mm->flags); free_mm_slot(mm_slot); mmdrop(mm); } else if (mm_slot) { spin_unlock(&khugepaged_mm_lock); /* * This is required to serialize against * khugepaged_test_exit() (which is guaranteed to run * under mmap sem read mode). Stop here (after we * return all pagetables will be destroyed) until * khugepaged has finished working on the pagetables * under the mmap_sem. */ down_write(&mm->mmap_sem); up_write(&mm->mmap_sem); } else spin_unlock(&khugepaged_mm_lock); }
0
[ "CWE-399" ]
linux
78f11a255749d09025f54d4e2df4fbcb031530e2
249,714,507,788,414,800,000,000,000,000,000,000,000
33
mm: thp: fix /dev/zero MAP_PRIVATE and vm_flags cleanups The huge_memory.c THP page fault was allowed to run if vm_ops was null (which would succeed for /dev/zero MAP_PRIVATE, as the f_op->mmap wouldn't setup a special vma->vm_ops and it would fallback to regular anonymous memory) but other THP logics weren't fully activated for vmas with vm_file not NULL (/dev/zero has a not NULL vma->vm_file). So this removes the vm_file checks so that /dev/zero also can safely use THP (the other albeit safer approach to fix this bug would have been to prevent the THP initial page fault to run if vm_file was set). After removing the vm_file checks, this also makes huge_memory.c stricter in khugepaged for the DEBUG_VM=y case. It doesn't replace the vm_file check with a is_pfn_mapping check (but it keeps checking for VM_PFNMAP under VM_BUG_ON) because for a is_cow_mapping() mapping VM_PFNMAP should only be allowed to exist before the first page fault, and in turn when vma->anon_vma is null (so preventing khugepaged registration). So I tend to think the previous comment saying if vm_file was set, VM_PFNMAP might have been set and we could still be registered in khugepaged (despite anon_vma was not NULL to be registered in khugepaged) was too paranoid. The is_linear_pfn_mapping check is also I think superfluous (as described by comment) but under DEBUG_VM it is safe to stay. Addresses https://bugzilla.kernel.org/show_bug.cgi?id=33682 Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Caspar Zhang <[email protected]> Acked-by: Mel Gorman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: <[email protected]> [2.6.38.x] Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
int MYSQL_BIN_LOG::close_purge_index_file() { int error= 0; DBUG_ENTER("MYSQL_BIN_LOG::close_purge_index_file"); if (my_b_inited(&purge_index_file)) { end_io_cache(&purge_index_file); error= my_close(purge_index_file.file, MYF(0)); } my_delete(purge_index_file_name, MYF(0)); bzero((char*) &purge_index_file, sizeof(purge_index_file)); DBUG_RETURN(error); }
0
[ "CWE-264" ]
mysql-server
48bd8b16fe382be302c6f0b45931be5aa6f29a0e
313,417,511,008,017,550,000,000,000,000,000,000,000
16
Bug#24388753: PRIVILEGE ESCALATION USING MYSQLD_SAFE [This is the 5.5/5.6 version of the bugfix]. The problem was that it was possible to write log files ending in .ini/.cnf that later could be parsed as an options file. This made it possible for users to specify startup options without the permissions to do so. This patch fixes the problem by disallowing general query log and slow query log to be written to files ending in .ini and .cnf.
bdecode_node bdecode_node::non_owning() const { // if we're not a root, just return a copy of ourself if (m_tokens.empty()) return *this; // otherwise, return a reference to this node, but without // being an owning root node return bdecode_node(&m_tokens[0], m_buffer, m_buffer_size, m_token_idx); }
0
[ "CWE-125" ]
libtorrent
ec30a5e9ec703afb8abefba757c6d401303b53db
337,234,345,495,649,200,000,000,000,000,000,000,000
9
fix out-of-bounds read in bdecode Fixes #2099
static struct bio *bio_copy_kern(struct request_queue *q, void *data, unsigned int len, gfp_t gfp_mask, int reading) { unsigned long kaddr = (unsigned long)data; unsigned long end = (kaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = kaddr >> PAGE_SHIFT; struct bio *bio; void *p = data; int nr_pages = 0; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages = end - start; bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); while (len) { struct page *page; unsigned int bytes = PAGE_SIZE; if (bytes > len) bytes = len; page = alloc_page(GFP_NOIO | __GFP_ZERO | gfp_mask); if (!page) goto cleanup; if (!reading) memcpy(page_address(page), p, bytes); if (bio_add_pc_page(q, bio, page, bytes, 0) < bytes) break; len -= bytes; p += bytes; } if (reading) { bio->bi_end_io = bio_copy_kern_endio_read; bio->bi_private = data; } else { bio->bi_end_io = bio_copy_kern_endio; } return bio; cleanup: bio_free_pages(bio); bio_put(bio); return ERR_PTR(-ENOMEM); }
0
[ "CWE-200" ]
linux
cc8f7fe1f5eab010191aa4570f27641876fa1267
303,855,384,279,556,270,000,000,000,000,000,000,000
56
block-map: add __GFP_ZERO flag for alloc_page in function bio_copy_kern Add __GFP_ZERO flag for alloc_page in function bio_copy_kern to initialize the buffer of a bio. Signed-off-by: Haimin Zhang <[email protected]> Reviewed-by: Chaitanya Kulkarni <[email protected]> Reviewed-by: Christoph Hellwig <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Jens Axboe <[email protected]>
isis_print_mt_capability_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len, tmp; while (len > 2) { ND_TCHECK2(*tptr, 2); stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); len = len - 2; /* Make sure the subTLV fits within the space left */ if (len < stlv_len) goto trunc; /* Make sure the entire subTLV is in the captured data */ ND_TCHECK2(*(tptr), stlv_len); switch (stlv_type) { case ISIS_SUBTLV_SPB_INSTANCE: if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN) goto trunc; ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr))); tptr = tptr + 2; ND_PRINT((ndo, "\n\t RES: %d", EXTRACT_16BITS(tptr) >> 5)); ND_PRINT((ndo, ", V: %d", (EXTRACT_16BITS(tptr) >> 4) & 0x0001)); ND_PRINT((ndo, ", SPSource-ID: %d", (EXTRACT_32BITS(tptr) & 0x000fffff))); tptr = tptr+4; ND_PRINT((ndo, ", No of Trees: %x", *(tptr))); tmp = *(tptr++); len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN; while (tmp) { if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN) goto trunc; ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d", *(tptr) >> 7, (*(tptr) >> 6) & 0x01, (*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f))); tptr++; ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr + 4; ND_PRINT((ndo, ", BVID: %d, SPVID: %d", (EXTRACT_24BITS(tptr) >> 12) & 0x000fff, EXTRACT_24BITS(tptr) & 0x000fff)); tptr = tptr + 3; len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN; tmp--; } break; case ISIS_SUBTLV_SPBM_SI: if (stlv_len < 8) goto trunc; ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr))); tptr = tptr+2; ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12, (EXTRACT_16BITS(tptr)) & 0x0fff)); tptr = tptr+2; len = len - 8; stlv_len = stlv_len - 8; while (stlv_len >= 4) { ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d", (EXTRACT_32BITS(tptr) >> 31), (EXTRACT_32BITS(tptr) >> 30) & 0x01, (EXTRACT_32BITS(tptr) >> 24) & 0x03f, (EXTRACT_32BITS(tptr)) & 0x0ffffff)); tptr = tptr + 4; len = len - 4; stlv_len = stlv_len - 4; } break; default: break; } tptr += stlv_len; len -= stlv_len; } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); }
0
[ "CWE-125", "CWE-787" ]
tcpdump
b20e1639dbac84b3fcb393858521c13ad47a9d70
118,527,614,125,380,520,000,000,000,000,000,000,000
124
CVE-2017-13026/IS-IS: Clean up processing of subTLVs. Add bounds checks, do a common check to make sure we captured the entire subTLV, add checks to make sure the subTLV fits within the TLV. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add tests using the capture files supplied by the reporter(s), modified so the capture files won't be rejected as an invalid capture. Update existing tests for changes to IS-IS dissector.
static UINT rdpei_recv_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s) { UINT16 eventId; UINT32 pduLength; UINT error; Stream_Read_UINT16(s, eventId); /* eventId (2 bytes) */ Stream_Read_UINT32(s, pduLength); /* pduLength (4 bytes) */ #ifdef WITH_DEBUG_RDPEI WLog_DBG(TAG, "rdpei_recv_pdu: eventId: %" PRIu16 " (%s) length: %" PRIu32 "", eventId, rdpei_eventid_string(eventId), pduLength); #endif switch (eventId) { case EVENTID_SC_READY: if ((error = rdpei_recv_sc_ready_pdu(callback, s))) { WLog_ERR(TAG, "rdpei_recv_sc_ready_pdu failed with error %" PRIu32 "!", error); return error; } if ((error = rdpei_send_cs_ready_pdu(callback))) { WLog_ERR(TAG, "rdpei_send_cs_ready_pdu failed with error %" PRIu32 "!", error); return error; } break; case EVENTID_SUSPEND_TOUCH: if ((error = rdpei_recv_suspend_touch_pdu(callback, s))) { WLog_ERR(TAG, "rdpei_recv_suspend_touch_pdu failed with error %" PRIu32 "!", error); return error; } break; case EVENTID_RESUME_TOUCH: if ((error = rdpei_recv_resume_touch_pdu(callback, s))) { WLog_ERR(TAG, "rdpei_recv_resume_touch_pdu failed with error %" PRIu32 "!", error); return error; } break; default: break; } return CHANNEL_RC_OK; }
1
[ "CWE-125" ]
FreeRDP
6b485b146a1b9d6ce72dfd7b5f36456c166e7a16
50,489,604,797,886,400,000,000,000,000,000,000,000
53
Fixed oob read in irp_write and similar
static void opj_tcd_code_block_dec_deallocate(opj_tcd_precinct_t * p_precinct) { OPJ_UINT32 cblkno, l_nb_code_blocks; opj_tcd_cblk_dec_t * l_code_block = p_precinct->cblks.dec; if (l_code_block) { /*fprintf(stderr,"deallocate codeblock:{\n");*/ /*fprintf(stderr,"\t x0=%d, y0=%d, x1=%d, y1=%d\n",l_code_block->x0, l_code_block->y0, l_code_block->x1, l_code_block->y1);*/ /*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ", l_code_block->numbps, l_code_block->numlenbits, l_code_block->len, l_code_block->numnewpasses, l_code_block->real_num_segs, l_code_block->m_current_max_segs );*/ l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_dec_t); /*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/ for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { if (l_code_block->data) { opj_free(l_code_block->data); l_code_block->data = 00; } if (l_code_block->segs) { opj_free(l_code_block->segs); l_code_block->segs = 00; } ++l_code_block; } opj_free(p_precinct->cblks.dec); p_precinct->cblks.dec = 00; } }
0
[ "CWE-119", "CWE-787" ]
openjpeg
397f62c0a838e15d667ef50e27d5d011d2c79c04
297,714,395,684,474,750,000,000,000,000,000,000,000
34
Fix write heap buffer overflow in opj_mqc_byteout(). Discovered by Ke Liu of Tencent's Xuanwu LAB (#835)
int ssl3_get_cert_status(SSL *s) { int ok, al; unsigned long resplen, n; const unsigned char *p; n = s->method->ssl_get_message(s, SSL3_ST_CR_CERT_STATUS_A, SSL3_ST_CR_CERT_STATUS_B, SSL3_MT_CERTIFICATE_STATUS, 16384, &ok); if (!ok) return ((int)n); if (n < 4) { /* need at least status type + length */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_LENGTH_MISMATCH); goto f_err; } p = (unsigned char *)s->init_msg; if (*p++ != TLSEXT_STATUSTYPE_ocsp) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE); goto f_err; } n2l3(p, resplen); if (resplen + 4 != n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_LENGTH_MISMATCH); goto f_err; } OPENSSL_free(s->tlsext_ocsp_resp); s->tlsext_ocsp_resp = BUF_memdup(p, resplen); if (!s->tlsext_ocsp_resp) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS, ERR_R_MALLOC_FAILURE); goto f_err; } s->tlsext_ocsp_resplen = resplen; if (s->ctx->tlsext_status_cb) { int ret; ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg); if (ret == 0) { al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE; SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_INVALID_STATUS_RESPONSE); goto f_err; } if (ret < 0) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS, ERR_R_MALLOC_FAILURE); goto f_err; } } return 1; f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); s->state = SSL_ST_ERR; return (-1); }
0
[ "CWE-362" ]
openssl
98ece4eebfb6cd45cc8d550c6ac0022965071afc
13,314,422,574,417,710,000,000,000,000,000,000,000
59
Fix race condition in NewSessionTicket If a NewSessionTicket is received by a multi-threaded client when attempting to reuse a previous ticket then a race condition can occur potentially leading to a double free of the ticket data. CVE-2015-1791 This also fixes RT#3808 where a session ID is changed for a session already in the client session cache. Since the session ID is the key to the cache this breaks the cache access. Parts of this patch were inspired by this Akamai change: https://github.com/akamai/openssl/commit/c0bf69a791239ceec64509f9f19fcafb2461b0d3 Reviewed-by: Rich Salz <[email protected]>
int ExpressionRegex::execute(RegexExecutionState* regexState) const { invariant(regexState); invariant(!regexState->nullish()); invariant(regexState->pcrePtr); int execResult = pcre_exec(regexState->pcrePtr.get(), nullptr, regexState->input->c_str(), regexState->input->size(), regexState->startBytePos, 0, // No need to overwrite the options set during pcre_compile. &(regexState->capturesBuffer.front()), regexState->capturesBuffer.size()); // The 'execResult' will be (numCaptures + 1) if there is a match, -1 if there is no match, // negative (other than -1) if there is an error during execution, and zero if capturesBuffer's // capacity is not sufficient to hold all the results. The latter scenario should never occur. uassert(51156, str::stream() << "Error occurred while executing the regular expression in " << _opName << ". Result code: " << execResult, execResult == -1 || execResult == (regexState->numCaptures + 1)); return execResult; }
0
[ "CWE-190" ]
mongo
21d8699ed6c517b45e1613e20231cd8eba894985
209,031,738,197,493,760,000,000,000,000,000,000,000
22
SERVER-43699 $mod should not overflow for large negative values
static OPJ_BOOL opj_j2k_exec ( opj_j2k_t * p_j2k, opj_procedure_list_t * p_procedure_list, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_BOOL (** l_procedure) (opj_j2k_t * ,opj_stream_private_t *,opj_event_mgr_t *) = 00; OPJ_BOOL l_result = OPJ_TRUE; OPJ_UINT32 l_nb_proc, i; /* preconditions*/ assert(p_procedure_list != 00); assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list); l_procedure = (OPJ_BOOL (**) (opj_j2k_t * ,opj_stream_private_t *,opj_event_mgr_t *)) opj_procedure_list_get_first_procedure(p_procedure_list); for (i=0;i<l_nb_proc;++i) { l_result = l_result && ((*l_procedure) (p_j2k,p_stream,p_manager)); ++l_procedure; } /* and clear the procedure list at the end.*/ opj_procedure_list_clear(p_procedure_list); return l_result; }
0
[ "CWE-416" ]
openjpeg
940100c28ae28931722290794889cf84a92c5f6f
251,980,492,157,794,430,000,000,000,000,000,000,000
27
Fix potential use-after-free in opj_j2k_write_mco function Fixes #563
static int __vxlan_fdb_delete(struct vxlan_dev *vxlan, const unsigned char *addr, union vxlan_addr ip, __be16 port, __be32 src_vni, __be32 vni, u32 ifindex, bool swdev_notify) { struct vxlan_fdb *f; struct vxlan_rdst *rd = NULL; int err = -ENOENT; f = vxlan_find_mac(vxlan, addr, src_vni); if (!f) return err; if (!vxlan_addr_any(&ip)) { rd = vxlan_fdb_find_rdst(f, &ip, port, vni, ifindex); if (!rd) goto out; } /* remove a destination if it's not the only one on the list, * otherwise destroy the fdb entry */ if (rd && !list_is_singular(&f->remotes)) { vxlan_fdb_dst_destroy(vxlan, f, rd, swdev_notify); goto out; } vxlan_fdb_destroy(vxlan, f, true, swdev_notify); out: return 0; }
0
[]
net
6c8991f41546c3c472503dff1ea9daaddf9331c2
156,796,629,330,474,630,000,000,000,000,000,000,000
32
net: ipv6_stub: use ip6_dst_lookup_flow instead of ip6_dst_lookup ipv6_stub uses the ip6_dst_lookup function to allow other modules to perform IPv6 lookups. However, this function skips the XFRM layer entirely. All users of ipv6_stub->ip6_dst_lookup use ip_route_output_flow (via the ip_route_output_key and ip_route_output helpers) for their IPv4 lookups, which calls xfrm_lookup_route(). This patch fixes this inconsistent behavior by switching the stub to ip6_dst_lookup_flow, which also calls xfrm_lookup_route(). This requires some changes in all the callers, as these two functions take different arguments and have different return types. Fixes: 5f81bd2e5d80 ("ipv6: export a stub for IPv6 symbols used by vxlan") Reported-by: Xiumei Mu <[email protected]> Signed-off-by: Sabrina Dubroca <[email protected]> Signed-off-by: David S. Miller <[email protected]>
static int pfkey_process(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr) { void *ext_hdrs[SADB_EXT_MAX]; int err; /* Non-zero return value of pfkey_broadcast() does not always signal * an error and even on an actual error we may still want to process * the message so rather ignore the return value. */ pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL, BROADCAST_PROMISC_ONLY, NULL, sock_net(sk)); memset(ext_hdrs, 0, sizeof(ext_hdrs)); err = parse_exthdrs(skb, hdr, ext_hdrs); if (!err) { err = -EOPNOTSUPP; if (pfkey_funcs[hdr->sadb_msg_type]) err = pfkey_funcs[hdr->sadb_msg_type](sk, skb, hdr, ext_hdrs); } return err; }
0
[ "CWE-362" ]
linux
ba953a9d89a00c078b85f4b190bc1dde66fe16b5
114,365,429,316,846,140,000,000,000,000,000,000,000
21
af_key: Do not call xfrm_probe_algs in parallel When namespace support was added to xfrm/afkey, it caused the previously single-threaded call to xfrm_probe_algs to become multi-threaded. This is buggy and needs to be fixed with a mutex. Reported-by: Abhishek Shah <[email protected]> Fixes: 283bc9f35bbb ("xfrm: Namespacify xfrm state/policy locks") Signed-off-by: Herbert Xu <[email protected]> Signed-off-by: Steffen Klassert <[email protected]>
static void vnc_client_write_locked(VncState *vs) { #ifdef CONFIG_VNC_SASL if (vs->sasl.conn && vs->sasl.runSSF && !vs->sasl.waitWriteSSF) { vnc_client_write_sasl(vs); } else #endif /* CONFIG_VNC_SASL */ { vnc_client_write_plain(vs); } }
0
[ "CWE-401" ]
qemu
6bf21f3d83e95bcc4ba35a7a07cc6655e8b010b0
153,238,091,471,603,430,000,000,000,000,000,000,000
13
vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <[email protected]> Signed-off-by: Li Qiang <[email protected]> Message-id: [email protected] Signed-off-by: Gerd Hoffmann <[email protected]>
cnt_recv_prep(struct req *req, const char *ci) { const char *xff; if (req->restarts == 0) { /* * This really should be done earlier, but we want to capture * it in the VSL log. */ http_CollectHdr(req->http, H_X_Forwarded_For); if (http_GetHdr(req->http, H_X_Forwarded_For, &xff)) { http_Unset(req->http, H_X_Forwarded_For); http_PrintfHeader(req->http, "X-Forwarded-For: %s, %s", xff, ci); } else { http_PrintfHeader(req->http, "X-Forwarded-For: %s", ci); } http_CollectHdr(req->http, H_Cache_Control); /* By default we use the first backend */ req->director_hint = VCL_DefaultDirector(req->vcl); req->d_ttl = -1; req->d_grace = -1; req->disable_esi = 0; req->hash_always_miss = 0; req->hash_ignore_busy = 0; req->client_identity = NULL; req->storage = NULL; } req->vdc->retval = 0; req->is_hit = 0; req->is_hitmiss = 0; req->is_hitpass = 0; }
1
[ "CWE-212" ]
varnish-cache
bd7b3d6d47ccbb5e1747126f8e2a297f38e56b8c
11,672,790,114,875,600,000,000,000,000,000,000,000
36
Clear err_code and err_reason at start of request handling req->err_code and req->err_reason are set when going to synthetic handling. From there the resp.reason HTTP field is set from req->err_reason if set, or the generic code based on req->err_code is used if it was NULL. This patch clears these members so that a value from the handling of a previous request doesn't linger. Fixes: VSV00004
void crypto_remove_final(struct list_head *list) { struct crypto_alg *alg; struct crypto_alg *n; list_for_each_entry_safe(alg, n, list, cra_list) { list_del_init(&alg->cra_list); crypto_alg_put(alg); } }
0
[ "CWE-284", "CWE-264", "CWE-269" ]
linux
4943ba16bbc2db05115707b3ff7b4874e9e3c560
265,491,001,249,372,670,000,000,000,000,000,000,000
10
crypto: include crypto- module prefix in template This adds the module loading prefix "crypto-" to the template lookup as well. For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly includes the "crypto-" prefix at every level, correctly rejecting "vfat": net-pf-38 algif-hash crypto-vfat(blowfish) crypto-vfat(blowfish)-all crypto-vfat Reported-by: Mathias Krause <[email protected]> Signed-off-by: Kees Cook <[email protected]> Acked-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[email protected]>
gnome_desktop_thumbnail_script_exec (const char *cmd, int size, const char *uri, GError **error) { g_autofree char *error_out = NULL; g_auto(GStrv) expanded_script = NULL; int exit_status; gboolean ret; GBytes *image = NULL; ScriptExec *exec; exec = script_exec_new (uri, error); if (!exec) goto out; expanded_script = expand_thumbnailing_cmd (cmd, exec, size, error); if (expanded_script == NULL) goto out; print_script_debug (expanded_script); ret = g_spawn_sync (NULL, expanded_script, NULL, G_SPAWN_SEARCH_PATH, child_setup, exec->fd_array, NULL, &error_out, &exit_status, error); if (ret && g_spawn_check_exit_status (exit_status, error)) { char *contents; gsize length; if (g_file_get_contents (exec->outfile, &contents, &length, error)) image = g_bytes_new_take (contents, length); } else { g_debug ("Failed to launch script: %s", !ret ? (*error)->message : error_out); } out: script_exec_free (exec); return image; }
0
[]
nautilus
2ddba428ef2b13d0620bd599c3635b9c11044659
165,652,418,179,901,460,000,000,000,000,000,000,000
41
Update gnome-desktop code Closes https://gitlab.gnome.org/GNOME/nautilus/issues/987
static int nft_basechain_init(struct nft_base_chain *basechain, u8 family, struct nft_chain_hook *hook, u32 flags) { struct nft_chain *chain; struct nft_hook *h; basechain->type = hook->type; INIT_LIST_HEAD(&basechain->hook_list); chain = &basechain->chain; if (nft_base_chain_netdev(family, hook->num)) { list_splice_init(&hook->list, &basechain->hook_list); list_for_each_entry(h, &basechain->hook_list, list) nft_basechain_hook_init(&h->ops, family, hook, chain); basechain->ops.hooknum = hook->num; basechain->ops.priority = hook->priority; } else { nft_basechain_hook_init(&basechain->ops, family, hook, chain); } chain->flags |= NFT_CHAIN_BASE | flags; basechain->policy = NF_ACCEPT; if (chain->flags & NFT_CHAIN_HW_OFFLOAD && !nft_chain_offload_support(basechain)) return -EOPNOTSUPP; flow_block_init(&basechain->flow_block); return 0; }
0
[ "CWE-400", "CWE-703" ]
linux
e02f0d3970404bfea385b6edb86f2d936db0ea2b
331,175,646,678,084,700,000,000,000,000,000,000,000
31
netfilter: nf_tables: disallow binding to already bound chain Update nft_data_init() to report EINVAL if chain is already bound. Fixes: d0e2c7de92c7 ("netfilter: nf_tables: add NFT_CHAIN_BINDING") Reported-by: Gwangun Jung <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>
static int verify_policy_type(u8 type) { switch (type) { case XFRM_POLICY_TYPE_MAIN: #ifdef CONFIG_XFRM_SUB_POLICY case XFRM_POLICY_TYPE_SUB: #endif break; default: return -EINVAL; } return 0; }
0
[ "CWE-264" ]
net
90f62cf30a78721641e08737bda787552428061e
44,457,221,366,198,300,000,000,000,000,000,000,000
15
net: Use netlink_ns_capable to verify the permisions of netlink messages It is possible by passing a netlink socket to a more privileged executable and then to fool that executable into writing to the socket data that happens to be valid netlink message to do something that privileged executable did not intend to do. To keep this from happening replace bare capable and ns_capable calls with netlink_capable, netlink_net_calls and netlink_ns_capable calls. Which act the same as the previous calls except they verify that the opener of the socket had the desired permissions as well. Reported-by: Andy Lutomirski <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> Signed-off-by: David S. Miller <[email protected]>
bgp_attr_default_intern (u_char origin) { struct attr attr; struct attr *new; memset (&attr, 0, sizeof (struct attr)); bgp_attr_extra_get (&attr); bgp_attr_default_set(&attr, origin); new = bgp_attr_intern (&attr); bgp_attr_extra_free (&attr); aspath_unintern (&new->aspath); return new; }
0
[]
quagga
8794e8d229dc9fe29ea31424883433d4880ef408
47,438,454,302,229,060,000,000,000,000,000,000,000
16
bgpd: Fix regression in args consolidation, total should be inited from args * bgp_attr.c: (bgp_attr_unknown) total should be initialised from the args.
static void sp_node_init(struct sp_node *node, unsigned long start, unsigned long end, struct mempolicy *pol) { node->start = start; node->end = end; node->policy = pol; }
0
[ "CWE-388" ]
linux
cf01fb9985e8deb25ccf0ea54d916b8871ae0e62
177,219,190,065,642,900,000,000,000,000,000,000,000
7
mm/mempolicy.c: fix error handling in set_mempolicy and mbind. In the case that compat_get_bitmap fails we do not want to copy the bitmap to the user as it will contain uninitialized stack data and leak sensitive data. Signed-off-by: Chris Salls <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
static void squashfs_stat(char *source) { time_t mkfs_time = (time_t) sBlk.s.mkfs_time; struct tm *t = use_localtime ? localtime(&mkfs_time) : gmtime(&mkfs_time); char *mkfs_str = asctime(t); #if __BYTE_ORDER == __BIG_ENDIAN printf("Found a valid %sSQUASHFS %d:%d superblock on %s.\n", swap ? "little endian " : "big endian ", sBlk.s.s_major, sBlk.s.s_minor, source); #else printf("Found a valid %sSQUASHFS %d:%d superblock on %s.\n", swap ? "big endian " : "little endian ", sBlk.s.s_major, sBlk.s.s_minor, source); #endif printf("Creation or last append time %s", mkfs_str ? mkfs_str : "failed to get time\n"); printf("Filesystem size %llu bytes (%.2f Kbytes / %.2f Mbytes)\n", sBlk.s.bytes_used, sBlk.s.bytes_used / 1024.0, sBlk.s.bytes_used / (1024.0 * 1024.0)); printf("Block size %d\n", sBlk.s.block_size); printf("Filesystem is %sexportable via NFS\n", SQUASHFS_EXPORTABLE(sBlk.s.flags) ? "" : "not "); printf("Inodes are %scompressed\n", SQUASHFS_UNCOMPRESSED_INODES(sBlk.s.flags) ? "un" : ""); printf("Data is %scompressed\n", SQUASHFS_UNCOMPRESSED_DATA(sBlk.s.flags) ? "un" : ""); printf("Check data is %spresent in the filesystem\n", SQUASHFS_CHECK_DATA(sBlk.s.flags) ? "" : "not "); printf("Duplicates are removed\n"); printf("Number of inodes %d\n", sBlk.s.inodes); printf("Number of uids %d\n", sBlk.no_uids); printf("Number of gids %d\n", sBlk.no_guids); TRACE("sBlk.s.inode_table_start 0x%llx\n", sBlk.s.inode_table_start); TRACE("sBlk.s.directory_table_start 0x%llx\n", sBlk.s.directory_table_start); TRACE("sBlk.uid_start 0x%llx\n", sBlk.uid_start); TRACE("sBlk.guid_start 0x%llx\n", sBlk.guid_start); }
0
[ "CWE-200", "CWE-59", "CWE-22" ]
squashfs-tools
e0485802ec72996c20026da320650d8362f555bd
261,229,164,687,668,760,000,000,000,000,000,000,000
41
Unsquashfs: additional write outside destination directory exploit fix An issue on github (https://github.com/plougher/squashfs-tools/issues/72) showed how some specially crafted Squashfs filesystems containing invalid file names (with '/' and '..') can cause Unsquashfs to write files outside of the destination directory. Since then it has been shown that specially crafted Squashfs filesystems that contain a symbolic link pointing outside of the destination directory, coupled with an identically named file within the same directory, can cause Unsquashfs to write files outside of the destination directory. Specifically the symbolic link produces a pathname pointing outside of the destination directory, which is then followed when writing the duplicate identically named file within the directory. This commit fixes this exploit by explictly checking for duplicate filenames within a directory. As directories in v2.1, v3.x, and v4.0 filesystems are sorted, this is achieved by checking for consecutively identical filenames. Additionally directories are checked to ensure they are sorted, to avoid attempts to evade the duplicate check. Version 1.x and 2.0 filesystems (where the directories were unsorted) are sorted and then the above duplicate filename check is applied. Signed-off-by: Phillip Lougher <[email protected]>
static inline struct frag_queue *fq_find(struct net *net, __be32 id, u32 user, struct in6_addr *src, struct in6_addr *dst) { struct inet_frag_queue *q; struct ip6_create_arg arg; unsigned int hash; arg.id = id; arg.user = user; arg.src = src; arg.dst = dst; read_lock_bh(&nf_frags.lock); hash = inet6_hash_frag(id, src, dst, nf_frags.rnd); q = inet_frag_find(&net->nf_frag.frags, &nf_frags, &arg, hash); local_bh_enable(); if (q == NULL) goto oom; return container_of(q, struct frag_queue, q); oom: return NULL; }
0
[]
linux
3ef0eb0db4bf92c6d2510fe5c4dc51852746f206
222,325,954,294,138,500,000,000,000,000,000,000,000
26
net: frag, move LRU list maintenance outside of rwlock Updating the fragmentation queues LRU (Least-Recently-Used) list, required taking the hash writer lock. However, the LRU list isn't tied to the hash at all, so we can use a separate lock for it. Original-idea-by: Florian Westphal <[email protected]> Signed-off-by: Jesper Dangaard Brouer <[email protected]> Signed-off-by: David S. Miller <[email protected]>
in_csum(const uint16_t *addr, size_t len, uint32_t csum, uint32_t *acc) { register size_t nleft = len; const uint16_t *w = addr; register uint16_t answer; register uint32_t sum = csum; /* * Our algorithm is simple, using a 32 bit accumulator (sum), * we add sequential 16 bit words to it, and at the end, fold * back all the carry bits from the top 16 bits into the lower * 16 bits. */ while (nleft > 1) { sum += *w++; nleft -= 2; } /* mop up an odd byte, if necessary */ if (nleft == 1) sum += htons(*(u_char *) w << 8); if (acc) *acc = sum; /* * add back carry outs from top 16 bits to low 16 bits */ sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ sum += (sum >> 16); /* add carry */ answer = (~sum & 0xffff); /* truncate to 16 bits */ return (answer); }
0
[ "CWE-59", "CWE-61" ]
keepalived
04f2d32871bb3b11d7dc024039952f2fe2750306
152,953,414,475,488,440,000,000,000,000,000,000,000
33
When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]>
explicit BoostedTreesCalculateBestFeatureSplitV2( OpKernelConstruction* const context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("logits_dimension", &logits_dim_)); OP_REQUIRES_OK(context, context->GetAttr("num_features", &num_features_)); }
0
[ "CWE-125", "CWE-369" ]
tensorflow
e84c975313e8e8e38bb2ea118196369c45c51378
108,780,669,935,181,480,000,000,000,000,000,000,000
6
In tf.raw_ops.BoostedTreesSparseCalculateBestFeatureSplit, limit stat_dim in stats_summary_indices to under stats_dims in stats_summary_shape PiperOrigin-RevId: 387171191 Change-Id: I83ca8a75b22aa78c037e8b98779da6cced16bfaa
int unit_deserialize_skip(FILE *f) { int r; assert(f); /* Skip serialized data for this unit. We don't know what it is. */ for (;;) { _cleanup_free_ char *line = NULL; char *l; r = read_line(f, LONG_LINE_MAX, &line); if (r < 0) return log_error_errno(r, "Failed to read serialization line: %m"); if (r == 0) return 0; l = strstrip(line); /* End marker */ if (isempty(l)) return 1; } }
0
[ "CWE-269" ]
systemd
bf65b7e0c9fc215897b676ab9a7c9d1c688143ba
151,466,329,413,560,950,000,000,000,000,000,000,000
23
core: imply NNP and SUID/SGID restriction for DynamicUser=yes service Let's be safe, rather than sorry. This way DynamicUser=yes services can neither take benefit of, nor create SUID/SGID binaries. Given that DynamicUser= is a recent addition only we should be able to get away with turning this on, even though this is strictly speaking a binary compatibility breakage.
xmlTextReaderXmlLang(xmlTextReaderPtr reader) { if (reader == NULL) return(NULL); if (reader->node == NULL) return(NULL); return(xmlNodeGetLang(reader->node)); }
0
[ "CWE-399" ]
libxml2
213f1fe0d76d30eaed6e5853057defc43e6df2c9
97,427,362,784,597,340,000,000,000,000,000,000,000
7
CVE-2015-1819 Enforce the reader to run in constant memory One of the operation on the reader could resolve entities leading to the classic expansion issue. Make sure the buffer used for xmlreader operation is bounded. Introduce a new allocation type for the buffers for this effect.
static void ioport_write(void *opaque, uint32_t addr, uint32_t val) { PCIQXLDevice *d = opaque; uint32_t io_port = addr - d->io_base; switch (io_port) { case QXL_IO_RESET: case QXL_IO_SET_MODE: case QXL_IO_MEMSLOT_ADD: case QXL_IO_MEMSLOT_DEL: case QXL_IO_CREATE_PRIMARY: case QXL_IO_UPDATE_IRQ: case QXL_IO_LOG: break; default: if (d->mode != QXL_MODE_VGA) { break; } dprint(d, 1, "%s: unexpected port 0x%x (%s) in vga mode\n", __func__, io_port, io_port_to_string(io_port)); return; } switch (io_port) { case QXL_IO_UPDATE_AREA: { QXLRect update = d->ram->update_area; qxl_spice_update_area(d, d->ram->update_surface, &update, NULL, 0, 0); break; } case QXL_IO_NOTIFY_CMD: qemu_spice_wakeup(&d->ssd); break; case QXL_IO_NOTIFY_CURSOR: qemu_spice_wakeup(&d->ssd); break; case QXL_IO_UPDATE_IRQ: qxl_set_irq(d); break; case QXL_IO_NOTIFY_OOM: if (!SPICE_RING_IS_EMPTY(&d->ram->release_ring)) { break; } pthread_yield(); if (!SPICE_RING_IS_EMPTY(&d->ram->release_ring)) { break; } d->oom_running = 1; qxl_spice_oom(d); d->oom_running = 0; break; case QXL_IO_SET_MODE: dprint(d, 1, "QXL_SET_MODE %d\n", val); qxl_set_mode(d, val, 0); break; case QXL_IO_LOG: if (d->guestdebug) { fprintf(stderr, "qxl/guest-%d: %ld: %s", d->id, qemu_get_clock_ns(vm_clock), d->ram->log_buf); } break; case QXL_IO_RESET: dprint(d, 1, "QXL_IO_RESET\n"); qxl_hard_reset(d, 0); break; case QXL_IO_MEMSLOT_ADD: if (val >= NUM_MEMSLOTS) { qxl_guest_bug(d, "QXL_IO_MEMSLOT_ADD: val out of range"); break; } if (d->guest_slots[val].active) { qxl_guest_bug(d, "QXL_IO_MEMSLOT_ADD: memory slot already active"); break; } d->guest_slots[val].slot = d->ram->mem_slot; qxl_add_memslot(d, val, 0); break; case QXL_IO_MEMSLOT_DEL: if (val >= NUM_MEMSLOTS) { qxl_guest_bug(d, "QXL_IO_MEMSLOT_DEL: val out of range"); break; } qxl_del_memslot(d, val); break; case QXL_IO_CREATE_PRIMARY: if (val != 0) { qxl_guest_bug(d, "QXL_IO_CREATE_PRIMARY: val != 0"); break; } dprint(d, 1, "QXL_IO_CREATE_PRIMARY\n"); d->guest_primary.surface = d->ram->create_surface; qxl_create_guest_primary(d, 0); break; case QXL_IO_DESTROY_PRIMARY: if (val != 0) { qxl_guest_bug(d, "QXL_IO_DESTROY_PRIMARY: val != 0"); break; } dprint(d, 1, "QXL_IO_DESTROY_PRIMARY (%s)\n", qxl_mode_to_string(d->mode)); qxl_destroy_primary(d); break; case QXL_IO_DESTROY_SURFACE_WAIT: qxl_spice_destroy_surface_wait(d, val); break; case QXL_IO_DESTROY_ALL_SURFACES: qxl_spice_destroy_surfaces(d); break; default: fprintf(stderr, "%s: ioport=0x%x, abort()\n", __FUNCTION__, io_port); abort(); } }
1
[]
qemu-kvm
5ff4e36c804157bd84af43c139f8cd3a59722db9
316,514,169,486,879,240,000,000,000,000,000,000,000
113
qxl: async io support using new spice api Some of the QXL port i/o commands are waiting for the spice server to complete certain actions. Add async versions for these commands, so we don't block the vcpu while the spice server processses the command. Instead the qxl device will raise an IRQ when done. The async command processing relies on an added QXLInterface::async_complete and added QXLWorker::*_async additions, in spice server qxl >= 3.1 Signed-off-by: Gerd Hoffmann <[email protected]> Signed-off-by: Alon Levy <[email protected]>
HeaderMapImpl::HeaderEntryImpl& HeaderMapImpl::maybeCreateInline(HeaderEntryImpl** entry, const LowerCaseString& key, HeaderString&& value) { if (*entry) { value.clear(); return **entry; } addSize(key.get().size() + value.size()); std::list<HeaderEntryImpl>::iterator i = headers_.insert(key, std::move(value)); i->entry_ = i; *entry = &(*i); return **entry; }
0
[ "CWE-400", "CWE-703" ]
envoy
afc39bea36fd436e54262f150c009e8d72db5014
50,691,742,735,470,530,000,000,000,000,000,000,000
14
Track byteSize of HeaderMap internally. Introduces a cached byte size updated internally in HeaderMap. The value is stored as an optional, and is cleared whenever a non-const pointer or reference to a HeaderEntry is accessed. The cached value can be set with refreshByteSize() which performs an iteration over the HeaderMap to sum the size of each key and value in the HeaderMap. Signed-off-by: Asra Ali <[email protected]>
static void load_vmcs12_host_state(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) { struct kvm_segment seg; if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) vcpu->arch.efer = vmcs12->host_ia32_efer; else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) vcpu->arch.efer |= (EFER_LMA | EFER_LME); else vcpu->arch.efer &= ~(EFER_LMA | EFER_LME); vmx_set_efer(vcpu, vcpu->arch.efer); kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp); kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip); vmx_set_rflags(vcpu, X86_EFLAGS_FIXED); /* * Note that calling vmx_set_cr0 is important, even if cr0 hasn't * actually changed, because it depends on the current state of * fpu_active (which may have changed). * Note that vmx_set_cr0 refers to efer set above. */ vmx_set_cr0(vcpu, vmcs12->host_cr0); /* * If we did fpu_activate()/fpu_deactivate() during L2's run, we need * to apply the same changes to L1's vmcs. We just set cr0 correctly, * but we also need to update cr0_guest_host_mask and exception_bitmap. */ update_exception_bitmap(vcpu); vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0); vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits); /* * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01 * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask(); */ vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK); kvm_set_cr4(vcpu, vmcs12->host_cr4); nested_ept_uninit_mmu_context(vcpu); kvm_set_cr3(vcpu, vmcs12->host_cr3); kvm_mmu_reset_context(vcpu); if (!enable_ept) vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault; if (enable_vpid) { /* * Trivially support vpid by letting L2s share their parent * L1's vpid. TODO: move to a more elaborate solution, giving * each L2 its own vpid and exposing the vpid feature to L1. */ vmx_flush_tlb(vcpu); } vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs); vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp); vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip); vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base); vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base); /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1. */ if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS) vmcs_write64(GUEST_BNDCFGS, 0); if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) { vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat); vcpu->arch.pat = vmcs12->host_ia32_pat; } if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL, vmcs12->host_ia32_perf_global_ctrl); /* Set L1 segment info according to Intel SDM 27.5.2 Loading Host Segment and Descriptor-Table Registers */ seg = (struct kvm_segment) { .base = 0, .limit = 0xFFFFFFFF, .selector = vmcs12->host_cs_selector, .type = 11, .present = 1, .s = 1, .g = 1 }; if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) seg.l = 1; else seg.db = 1; vmx_set_segment(vcpu, &seg, VCPU_SREG_CS); seg = (struct kvm_segment) { .base = 0, .limit = 0xFFFFFFFF, .type = 3, .present = 1, .s = 1, .db = 1, .g = 1 }; seg.selector = vmcs12->host_ds_selector; vmx_set_segment(vcpu, &seg, VCPU_SREG_DS); seg.selector = vmcs12->host_es_selector; vmx_set_segment(vcpu, &seg, VCPU_SREG_ES); seg.selector = vmcs12->host_ss_selector; vmx_set_segment(vcpu, &seg, VCPU_SREG_SS); seg.selector = vmcs12->host_fs_selector; seg.base = vmcs12->host_fs_base; vmx_set_segment(vcpu, &seg, VCPU_SREG_FS); seg.selector = vmcs12->host_gs_selector; seg.base = vmcs12->host_gs_base; vmx_set_segment(vcpu, &seg, VCPU_SREG_GS); seg = (struct kvm_segment) { .base = vmcs12->host_tr_base, .limit = 0x67, .selector = vmcs12->host_tr_selector, .type = 11, .present = 1 }; vmx_set_segment(vcpu, &seg, VCPU_SREG_TR); kvm_set_dr(vcpu, 7, 0x400); vmcs_write64(GUEST_IA32_DEBUGCTL, 0); }
0
[]
kvm
a642fc305053cc1c6e47e4f4df327895747ab485
211,079,946,111,516,530,000,000,000,000,000,000,000
124
kvm: vmx: handle invvpid vm exit gracefully On systems with invvpid instruction support (corresponding bit in IA32_VMX_EPT_VPID_CAP MSR is set) guest invocation of invvpid causes vm exit, which is currently not handled and results in propagation of unknown exit to userspace. Fix this by installing an invvpid vm exit handler. This is CVE-2014-3646. Cc: [email protected] Signed-off-by: Petr Matousek <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>
size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize) { return ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dct_rawContent); }
0
[ "CWE-362" ]
zstd
3e5cdf1b6a85843e991d7d10f6a2567c15580da0
223,457,181,447,601,470,000,000,000,000,000,000,000
4
fixed T36302429
cifs_get_tcp_session(struct smb_vol *volume_info) { struct TCP_Server_Info *tcp_ses = NULL; struct sockaddr_storage addr; struct sockaddr_in *sin_server = (struct sockaddr_in *) &addr; struct sockaddr_in6 *sin_server6 = (struct sockaddr_in6 *) &addr; int rc; memset(&addr, 0, sizeof(struct sockaddr_storage)); cFYI(1, "UNC: %s ip: %s", volume_info->UNC, volume_info->UNCip); if (volume_info->UNCip && volume_info->UNC) { rc = cifs_fill_sockaddr((struct sockaddr *)&addr, volume_info->UNCip, strlen(volume_info->UNCip), volume_info->port); if (!rc) { /* we failed translating address */ rc = -EINVAL; goto out_err; } } else if (volume_info->UNCip) { /* BB using ip addr as tcp_ses name to connect to the DFS root below */ cERROR(1, "Connecting to DFS root not implemented yet"); rc = -EINVAL; goto out_err; } else /* which tcp_sess DFS root would we conect to */ { cERROR(1, "CIFS mount error: No UNC path (e.g. -o " "unc=//192.168.1.100/public) specified"); rc = -EINVAL; goto out_err; } /* see if we already have a matching tcp_ses */ tcp_ses = cifs_find_tcp_session((struct sockaddr *)&addr, volume_info); if (tcp_ses) return tcp_ses; tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL); if (!tcp_ses) { rc = -ENOMEM; goto out_err; } rc = cifs_crypto_shash_allocate(tcp_ses); if (rc) { cERROR(1, "could not setup hash structures rc %d", rc); goto out_err; } cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns)); tcp_ses->hostname = extract_hostname(volume_info->UNC); if (IS_ERR(tcp_ses->hostname)) { rc = PTR_ERR(tcp_ses->hostname); goto out_err_crypto_release; } tcp_ses->noblocksnd = volume_info->noblocksnd; tcp_ses->noautotune = volume_info->noautotune; tcp_ses->tcp_nodelay = volume_info->sockopt_tcp_nodelay; atomic_set(&tcp_ses->inFlight, 0); init_waitqueue_head(&tcp_ses->response_q); init_waitqueue_head(&tcp_ses->request_q); INIT_LIST_HEAD(&tcp_ses->pending_mid_q); mutex_init(&tcp_ses->srv_mutex); memcpy(tcp_ses->workstation_RFC1001_name, volume_info->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL); memcpy(tcp_ses->server_RFC1001_name, volume_info->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL); tcp_ses->session_estab = false; tcp_ses->sequence_number = 0; tcp_ses->lstrp = jiffies; INIT_LIST_HEAD(&tcp_ses->tcp_ses_list); INIT_LIST_HEAD(&tcp_ses->smb_ses_list); INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request); /* * at this point we are the only ones with the pointer * to the struct since the kernel thread not created yet * no need to spinlock this init of tcpStatus or srv_count */ tcp_ses->tcpStatus = CifsNew; memcpy(&tcp_ses->srcaddr, &volume_info->srcaddr, sizeof(tcp_ses->srcaddr)); ++tcp_ses->srv_count; if (addr.ss_family == AF_INET6) { cFYI(1, "attempting ipv6 connect"); /* BB should we allow ipv6 on port 139? */ /* other OS never observed in Wild doing 139 with v6 */ memcpy(&tcp_ses->dstaddr, sin_server6, sizeof(struct sockaddr_in6)); } else memcpy(&tcp_ses->dstaddr, sin_server, sizeof(struct sockaddr_in)); rc = ip_connect(tcp_ses); if (rc < 0) { cERROR(1, "Error connecting to socket. Aborting operation"); goto out_err_crypto_release; } /* * since we're in a cifs function already, we know that * this will succeed. No need for try_module_get(). */ __module_get(THIS_MODULE); tcp_ses->tsk = kthread_run((void *)(void *)cifs_demultiplex_thread, tcp_ses, "cifsd"); if (IS_ERR(tcp_ses->tsk)) { rc = PTR_ERR(tcp_ses->tsk); cERROR(1, "error %d create cifsd thread", rc); module_put(THIS_MODULE); goto out_err_crypto_release; } /* thread spawned, put it on the list */ spin_lock(&cifs_tcp_ses_lock); list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list); spin_unlock(&cifs_tcp_ses_lock); cifs_fscache_get_client_cookie(tcp_ses); /* queue echo request delayed work */ queue_delayed_work(system_nrt_wq, &tcp_ses->echo, SMB_ECHO_INTERVAL); return tcp_ses; out_err_crypto_release: cifs_crypto_shash_release(tcp_ses); put_net(cifs_net_ns(tcp_ses)); out_err: if (tcp_ses) { if (!IS_ERR(tcp_ses->hostname)) kfree(tcp_ses->hostname); if (tcp_ses->ssocket) sock_release(tcp_ses->ssocket); kfree(tcp_ses); } return ERR_PTR(rc); }
0
[ "CWE-20" ]
linux
70945643722ffeac779d2529a348f99567fa5c33
255,372,489,296,652,200,000,000,000,000,000,000,000
145
cifs: always do is_path_accessible check in cifs_mount Currently, we skip doing the is_path_accessible check in cifs_mount if there is no prefixpath. I have a report of at least one server however that allows a TREE_CONNECT to a share that has a DFS referral at its root. The reporter in this case was using a UNC that had no prefixpath, so the is_path_accessible check was not triggered and the box later hit a BUG() because we were chasing a DFS referral on the root dentry for the mount. This patch fixes this by removing the check for a zero-length prefixpath. That should make the is_path_accessible check be done in this situation and should allow the client to chase the DFS referral at mount time instead. Cc: [email protected] Reported-and-Tested-by: Yogesh Sharma <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]>
xmlDictQLookup(xmlDictPtr dict, const xmlChar *prefix, const xmlChar *name) { unsigned long okey, key, nbi = 0; xmlDictEntryPtr entry; xmlDictEntryPtr insert; const xmlChar *ret; unsigned int len, plen, l; if ((dict == NULL) || (name == NULL)) return(NULL); if (prefix == NULL) return(xmlDictLookup(dict, name, -1)); l = len = strlen((const char *) name); plen = strlen((const char *) prefix); len += 1 + plen; /* * Check for duplicate and insertion location. */ okey = xmlDictComputeQKey(dict, prefix, plen, name, l); key = okey % dict->size; if (dict->dict[key].valid == 0) { insert = NULL; } else { for (insert = &(dict->dict[key]); insert->next != NULL; insert = insert->next) { if ((insert->okey == okey) && (insert->len == len) && (xmlStrQEqual(prefix, name, insert->name))) return(insert->name); nbi++; } if ((insert->okey == okey) && (insert->len == len) && (xmlStrQEqual(prefix, name, insert->name))) return(insert->name); } if (dict->subdict) { unsigned long skey; /* we cannot always reuse the same okey for the subdict */ if (((dict->size == MIN_DICT_SIZE) && (dict->subdict->size != MIN_DICT_SIZE)) || ((dict->size != MIN_DICT_SIZE) && (dict->subdict->size == MIN_DICT_SIZE))) skey = xmlDictComputeQKey(dict->subdict, prefix, plen, name, l); else skey = okey; key = skey % dict->subdict->size; if (dict->subdict->dict[key].valid != 0) { xmlDictEntryPtr tmp; for (tmp = &(dict->subdict->dict[key]); tmp->next != NULL; tmp = tmp->next) { if ((tmp->okey == skey) && (tmp->len == len) && (xmlStrQEqual(prefix, name, tmp->name))) return(tmp->name); nbi++; } if ((tmp->okey == skey) && (tmp->len == len) && (xmlStrQEqual(prefix, name, tmp->name))) return(tmp->name); } key = okey % dict->size; } ret = xmlDictAddQString(dict, prefix, plen, name, l); if (ret == NULL) return(NULL); if (insert == NULL) { entry = &(dict->dict[key]); } else { entry = xmlMalloc(sizeof(xmlDictEntry)); if (entry == NULL) return(NULL); } entry->name = ret; entry->len = len; entry->next = NULL; entry->valid = 1; entry->okey = okey; if (insert != NULL) insert->next = entry; dict->nbElems++; if ((nbi > MAX_HASH_LEN) && (dict->size <= ((MAX_DICT_HASH / 2) / MAX_HASH_LEN))) xmlDictGrow(dict, MAX_HASH_LEN * 2 * dict->size); /* Note that entry may have been freed at this point by xmlDictGrow */ return(ret); }
0
[ "CWE-119" ]
libxml2
6360a31a84efe69d155ed96306b9a931a40beab9
147,468,554,162,670,840,000,000,000,000,000,000,000
93
CVE-2015-7497 Avoid an heap buffer overflow in xmlDictComputeFastQKey For https://bugzilla.gnome.org/show_bug.cgi?id=756528 It was possible to hit a negative offset in the name indexing used to randomize the dictionary key generation Reported and fix provided by David Drysdale @ Google
static inline u32 keepalive_time_elapsed(const struct tcp_sock *tp) { const struct inet_connection_sock *icsk = &tp->inet_conn; return min_t(u32, tcp_time_stamp - icsk->icsk_ack.lrcvtime, tcp_time_stamp - tp->rcv_tstamp); }
0
[ "CWE-416", "CWE-269" ]
linux
bb1fceca22492109be12640d49f5ea5a544c6bb4
180,664,203,543,868,140,000,000,000,000,000,000,000
7
tcp: fix use after free in tcp_xmit_retransmit_queue() When tcp_sendmsg() allocates a fresh and empty skb, it puts it at the tail of the write queue using tcp_add_write_queue_tail() Then it attempts to copy user data into this fresh skb. If the copy fails, we undo the work and remove the fresh skb. Unfortunately, this undo lacks the change done to tp->highest_sack and we can leave a dangling pointer (to a freed skb) Later, tcp_xmit_retransmit_queue() can dereference this pointer and access freed memory. For regular kernels where memory is not unmapped, this might cause SACK bugs because tcp_highest_sack_seq() is buggy, returning garbage instead of tp->snd_nxt, but with various debug features like CONFIG_DEBUG_PAGEALLOC, this can crash the kernel. This bug was found by Marco Grassi thanks to syzkaller. Fixes: 6859d49475d4 ("[TCP]: Abstract tp->highest_sack accessing & point to next skb") Reported-by: Marco Grassi <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Cc: Ilpo Järvinen <[email protected]> Cc: Yuchung Cheng <[email protected]> Cc: Neal Cardwell <[email protected]> Acked-by: Neal Cardwell <[email protected]> Reviewed-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]>
SmartArrayPointer<char> GetGVNFlagsString(GVNFlagSet flags) { char underlying_buffer[kLastFlag * 128]; Vector<char> buffer(underlying_buffer, sizeof(underlying_buffer)); #if DEBUG int offset = 0; const char* separator = ""; const char* comma = ", "; buffer[0] = 0; uint32_t set_depends_on = 0; uint32_t set_changes = 0; for (int bit = 0; bit < kLastFlag; ++bit) { if ((flags.ToIntegral() & (1 << bit)) != 0) { if (bit % 2 == 0) { set_changes++; } else { set_depends_on++; } } } bool positive_changes = set_changes < (kLastFlag / 2); bool positive_depends_on = set_depends_on < (kLastFlag / 2); if (set_changes > 0) { if (positive_changes) { offset += OS::SNPrintF(buffer + offset, "changes ["); } else { offset += OS::SNPrintF(buffer + offset, "changes all except ["); } for (int bit = 0; bit < kLastFlag; ++bit) { if (((flags.ToIntegral() & (1 << bit)) != 0) == positive_changes) { switch (static_cast<GVNFlag>(bit)) { #define DECLARE_FLAG(type) \ case kChanges##type: \ offset += OS::SNPrintF(buffer + offset, separator); \ offset += OS::SNPrintF(buffer + offset, #type); \ separator = comma; \ break; GVN_TRACKED_FLAG_LIST(DECLARE_FLAG) GVN_UNTRACKED_FLAG_LIST(DECLARE_FLAG) #undef DECLARE_FLAG default: break; } } } offset += OS::SNPrintF(buffer + offset, "]"); } if (set_depends_on > 0) { separator = ""; if (set_changes > 0) { offset += OS::SNPrintF(buffer + offset, ", "); } if (positive_depends_on) { offset += OS::SNPrintF(buffer + offset, "depends on ["); } else { offset += OS::SNPrintF(buffer + offset, "depends on all except ["); } for (int bit = 0; bit < kLastFlag; ++bit) { if (((flags.ToIntegral() & (1 << bit)) != 0) == positive_depends_on) { switch (static_cast<GVNFlag>(bit)) { #define DECLARE_FLAG(type) \ case kDependsOn##type: \ offset += OS::SNPrintF(buffer + offset, separator); \ offset += OS::SNPrintF(buffer + offset, #type); \ separator = comma; \ break; GVN_TRACKED_FLAG_LIST(DECLARE_FLAG) GVN_UNTRACKED_FLAG_LIST(DECLARE_FLAG) #undef DECLARE_FLAG default: break; } } } offset += OS::SNPrintF(buffer + offset, "]"); } #else OS::SNPrintF(buffer, "0x%08X", flags.ToIntegral()); #endif size_t string_len = strlen(underlying_buffer) + 1; ASSERT(string_len <= sizeof(underlying_buffer)); char* result = new char[strlen(underlying_buffer) + 1]; memcpy(result, underlying_buffer, string_len); return SmartArrayPointer<char>(result); }
0
[]
node
fd80a31e0697d6317ce8c2d289575399f4e06d21
8,017,850,465,771,217,000,000,000,000,000,000,000
84
deps: backport 5f836c from v8 upstream Original commit message: Fix Hydrogen bounds check elimination When combining bounds checks, they must all be moved before the first load/store that they are guarding. BUG=chromium:344186 LOG=y [email protected] Review URL: https://codereview.chromium.org/172093002 git-svn-id: https://v8.googlecode.com/svn/branches/bleeding_edge@19475 ce2b1a6d-e550-0410-aec6-3dcde31c8c00 fix #8070
static int decode_slice_header(H264Context *h, H264Context *h0) { unsigned int first_mb_in_slice; unsigned int pps_id; int ret; unsigned int slice_type, tmp, i, j; int last_pic_structure, last_pic_droppable; int must_reinit; int needs_reinit = 0; int field_pic_flag, bottom_field_flag; h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab; h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab; first_mb_in_slice = get_ue_golomb_long(&h->gb); if (first_mb_in_slice == 0) { // FIXME better field boundary detection if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) { field_end(h, 1); } h0->current_slice = 0; if (!h0->first_field) { if (h->cur_pic_ptr && !h->droppable) { ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, h->picture_structure == PICT_BOTTOM_FIELD); } h->cur_pic_ptr = NULL; } } slice_type = get_ue_golomb_31(&h->gb); if (slice_type > 9) { av_log(h->avctx, AV_LOG_ERROR, "slice type too large (%d) at %d %d\n", slice_type, h->mb_x, h->mb_y); return AVERROR_INVALIDDATA; } if (slice_type > 4) { slice_type -= 5; h->slice_type_fixed = 1; } else h->slice_type_fixed = 0; slice_type = golomb_to_pict_type[slice_type]; h->slice_type = slice_type; h->slice_type_nos = slice_type & 3; if (h->nal_unit_type == NAL_IDR_SLICE && h->slice_type_nos != AV_PICTURE_TYPE_I) { av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n"); return AVERROR_INVALIDDATA; } // to make a few old functions happy, it's wrong though h->pict_type = h->slice_type; pps_id = get_ue_golomb(&h->gb); if (pps_id >= MAX_PPS_COUNT) { av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id); return AVERROR_INVALIDDATA; } if (!h0->pps_buffers[pps_id]) { av_log(h->avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id); return AVERROR_INVALIDDATA; } if (h0->au_pps_id >= 0 && pps_id != h0->au_pps_id) { av_log(h->avctx, AV_LOG_ERROR, "PPS change from %d to %d forbidden\n", h0->au_pps_id, pps_id); return AVERROR_INVALIDDATA; } h->pps = *h0->pps_buffers[pps_id]; if (!h0->sps_buffers[h->pps.sps_id]) { av_log(h->avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id); return AVERROR_INVALIDDATA; } if (h->pps.sps_id != h->current_sps_id || h0->sps_buffers[h->pps.sps_id]->new) { h0->sps_buffers[h->pps.sps_id]->new = 0; h->current_sps_id = h->pps.sps_id; h->sps = *h0->sps_buffers[h->pps.sps_id]; if (h->mb_width != h->sps.mb_width || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma || h->cur_chroma_format_idc != h->sps.chroma_format_idc ) needs_reinit = 1; if (h->bit_depth_luma != h->sps.bit_depth_luma || h->chroma_format_idc != h->sps.chroma_format_idc) { h->bit_depth_luma = h->sps.bit_depth_luma; h->chroma_format_idc = h->sps.chroma_format_idc; needs_reinit = 1; } if ((ret = h264_set_parameter_from_sps(h)) < 0) return ret; } h->avctx->profile = ff_h264_get_profile(&h->sps); h->avctx->level = h->sps.level_idc; h->avctx->refs = h->sps.ref_frame_count; must_reinit = (h->context_initialized && ( 16*h->sps.mb_width != h->avctx->coded_width || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma || h->cur_chroma_format_idc != h->sps.chroma_format_idc || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio) || h->mb_width != h->sps.mb_width || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) )); if (h0->avctx->pix_fmt != get_pixel_format(h0, 0)) must_reinit = 1; h->mb_width = h->sps.mb_width; h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag); h->mb_num = h->mb_width * h->mb_height; h->mb_stride = h->mb_width + 1; h->b_stride = h->mb_width * 4; h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p h->width = 16 * h->mb_width; h->height = 16 * h->mb_height; ret = init_dimensions(h); if (ret < 0) return ret; if (h->sps.video_signal_type_present_flag) { h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; if (h->sps.colour_description_present_flag) { if (h->avctx->colorspace != h->sps.colorspace) needs_reinit = 1; h->avctx->color_primaries = h->sps.color_primaries; h->avctx->color_trc = h->sps.color_trc; h->avctx->colorspace = h->sps.colorspace; } } if (h->context_initialized && (h->width != h->avctx->coded_width || h->height != h->avctx->coded_height || must_reinit || needs_reinit)) { if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, "changing width/height on " "slice %d\n", h0->current_slice + 1); return AVERROR_INVALIDDATA; } flush_change(h); if ((ret = get_pixel_format(h, 1)) < 0) return ret; h->avctx->pix_fmt = ret; av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, " "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt)); if ((ret = h264_slice_header_init(h, 1)) < 0) { av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed\n"); return ret; } } if (!h->context_initialized) { if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, "Cannot (re-)initialize context during parallel decoding.\n"); return AVERROR_PATCHWELCOME; } if ((ret = get_pixel_format(h, 1)) < 0) return ret; h->avctx->pix_fmt = ret; if ((ret = h264_slice_header_init(h, 0)) < 0) { av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed\n"); return ret; } } if (h == h0 && h->dequant_coeff_pps != pps_id) { h->dequant_coeff_pps = pps_id; init_dequant_tables(h); } h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num); h->mb_mbaff = 0; h->mb_aff_frame = 0; last_pic_structure = h0->picture_structure; last_pic_droppable = h0->droppable; h->droppable = h->nal_ref_idc == 0; if (h->sps.frame_mbs_only_flag) { h->picture_structure = PICT_FRAME; } else { if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) { av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n"); return -1; } field_pic_flag = get_bits1(&h->gb); if (field_pic_flag) { bottom_field_flag = get_bits1(&h->gb); h->picture_structure = PICT_TOP_FIELD + bottom_field_flag; } else { h->picture_structure = PICT_FRAME; h->mb_aff_frame = h->sps.mb_aff; } } h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME; if (h0->current_slice != 0) { if (last_pic_structure != h->picture_structure || last_pic_droppable != h->droppable) { av_log(h->avctx, AV_LOG_ERROR, "Changing field mode (%d -> %d) between slices is not allowed\n", last_pic_structure, h->picture_structure); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_INVALIDDATA; } else if (!h0->cur_pic_ptr) { av_log(h->avctx, AV_LOG_ERROR, "unset cur_pic_ptr on %d. slice\n", h0->current_slice + 1); return AVERROR_INVALIDDATA; } } else { /* Shorten frame num gaps so we don't have to allocate reference * frames just to throw them away */ if (h->frame_num != h->prev_frame_num) { int unwrap_prev_frame_num = h->prev_frame_num; int max_frame_num = 1 << h->sps.log2_max_frame_num; if (unwrap_prev_frame_num > h->frame_num) unwrap_prev_frame_num -= max_frame_num; if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) { unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1; if (unwrap_prev_frame_num < 0) unwrap_prev_frame_num += max_frame_num; h->prev_frame_num = unwrap_prev_frame_num; } } /* See if we have a decoded first field looking for a pair... * Here, we're using that to see if we should mark previously * decode frames as "finished". * We have to do that before the "dummy" in-between frame allocation, * since that can modify h->cur_pic_ptr. */ if (h0->first_field) { assert(h0->cur_pic_ptr); assert(h0->cur_pic_ptr->f.buf[0]); assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); /* Mark old field/frame as completed */ if (h0->cur_pic_ptr->tf.owner == h0->avctx) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_BOTTOM_FIELD); } /* figure out if we have a complementary field pair */ if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { /* Previous field is unmatched. Don't display it, but let it * remain for reference if marked as such. */ if (last_pic_structure != PICT_FRAME) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_TOP_FIELD); } } else { if (h0->cur_pic_ptr->frame_num != h->frame_num) { /* This and previous field were reference, but had * different frame_nums. Consider this field first in * pair. Throw away previous field except for reference * purposes. */ if (last_pic_structure != PICT_FRAME) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_TOP_FIELD); } } else { /* Second field in complementary pair */ if (!((last_pic_structure == PICT_TOP_FIELD && h->picture_structure == PICT_BOTTOM_FIELD) || (last_pic_structure == PICT_BOTTOM_FIELD && h->picture_structure == PICT_TOP_FIELD))) { av_log(h->avctx, AV_LOG_ERROR, "Invalid field mode combination %d/%d\n", last_pic_structure, h->picture_structure); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_INVALIDDATA; } else if (last_pic_droppable != h->droppable) { avpriv_request_sample(h->avctx, "Found reference and non-reference fields in the same frame, which"); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_PATCHWELCOME; } } } } while (h->frame_num != h->prev_frame_num && !h0->first_field && h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) { Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL; av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num); if (!h->sps.gaps_in_frame_num_allowed_flag) for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++) h->last_pocs[i] = INT_MIN; ret = h264_frame_start(h); if (ret < 0) { h0->first_field = 0; return ret; } h->prev_frame_num++; h->prev_frame_num %= 1 << h->sps.log2_max_frame_num; h->cur_pic_ptr->frame_num = h->prev_frame_num; ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0); ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1); ret = ff_generate_sliding_window_mmcos(h, 1); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return ret; ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return ret; /* Error concealment: If a ref is missing, copy the previous ref * in its place. * FIXME: Avoiding a memcpy would be nice, but ref handling makes * many assumptions about there being no actual duplicates. * FIXME: This does not copy padding for out-of-frame motion * vectors. Given we are concealing a lost frame, this probably * is not noticeable by comparison, but it should be fixed. */ if (h->short_ref_count) { if (prev) { av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize, (const uint8_t **)prev->f.data, prev->f.linesize, h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16); h->short_ref[0]->poc = prev->poc + 2; } h->short_ref[0]->frame_num = h->prev_frame_num; } } /* See if we have a decoded first field looking for a pair... * We're using that to see whether to continue decoding in that * frame, or to allocate a new one. */ if (h0->first_field) { assert(h0->cur_pic_ptr); assert(h0->cur_pic_ptr->f.buf[0]); assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); /* figure out if we have a complementary field pair */ if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { /* Previous field is unmatched. Don't display it, but let it * remain for reference if marked as such. */ h0->cur_pic_ptr = NULL; h0->first_field = FIELD_PICTURE(h); } else { if (h0->cur_pic_ptr->frame_num != h->frame_num) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, h0->picture_structure==PICT_BOTTOM_FIELD); /* This and the previous field had different frame_nums. * Consider this field first in pair. Throw away previous * one except for reference purposes. */ h0->first_field = 1; h0->cur_pic_ptr = NULL; } else { /* Second field in complementary pair */ h0->first_field = 0; } } } else { /* Frame or first field in a potentially complementary pair */ h0->first_field = FIELD_PICTURE(h); } if (!FIELD_PICTURE(h) || h0->first_field) { if (h264_frame_start(h) < 0) { h0->first_field = 0; return AVERROR_INVALIDDATA; } } else { release_unused_pictures(h, 0); } /* Some macroblocks can be accessed before they're available in case * of lost slices, MBAFF or threading. */ if (FIELD_PICTURE(h)) { for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++) memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table)); } else { memset(h->slice_table, -1, (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table)); } h0->last_slice_type = -1; } if (h != h0 && (ret = clone_slice(h, h0)) < 0) return ret; /* can't be in alloc_tables because linesize isn't known there. * FIXME: redo bipred weight to not require extra buffer? */ for (i = 0; i < h->slice_context_count; i++) if (h->thread_context[i]) { ret = alloc_scratch_buffers(h->thread_context[i], h->linesize); if (ret < 0) return ret; } h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup av_assert1(h->mb_num == h->mb_width * h->mb_height); if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num || first_mb_in_slice >= h->mb_num) { av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n"); return AVERROR_INVALIDDATA; } h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width; h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE(h); if (h->picture_structure == PICT_BOTTOM_FIELD) h->resync_mb_y = h->mb_y = h->mb_y + 1; av_assert1(h->mb_y < h->mb_height); if (h->picture_structure == PICT_FRAME) { h->curr_pic_num = h->frame_num; h->max_pic_num = 1 << h->sps.log2_max_frame_num; } else { h->curr_pic_num = 2 * h->frame_num + 1; h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1); } if (h->nal_unit_type == NAL_IDR_SLICE) get_ue_golomb(&h->gb); /* idr_pic_id */ if (h->sps.poc_type == 0) { h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb); if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) h->delta_poc_bottom = get_se_golomb(&h->gb); } if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) { h->delta_poc[0] = get_se_golomb(&h->gb); if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) h->delta_poc[1] = get_se_golomb(&h->gb); } ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc); if (h->pps.redundant_pic_cnt_present) h->redundant_pic_count = get_ue_golomb(&h->gb); ret = ff_set_ref_count(h); if (ret < 0) return ret; if (slice_type != AV_PICTURE_TYPE_I && (h0->current_slice == 0 || slice_type != h0->last_slice_type || memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) { ff_h264_fill_default_ref_list(h); } if (h->slice_type_nos != AV_PICTURE_TYPE_I) { ret = ff_h264_decode_ref_pic_list_reordering(h); if (ret < 0) { h->ref_count[1] = h->ref_count[0] = 0; return ret; } } if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) || (h->pps.weighted_bipred_idc == 1 && h->slice_type_nos == AV_PICTURE_TYPE_B)) ff_pred_weight_table(h); else if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) { implicit_weight_table(h, -1); } else { h->use_weight = 0; for (i = 0; i < 2; i++) { h->luma_weight_flag[i] = 0; h->chroma_weight_flag[i] = 0; } } // If frame-mt is enabled, only update mmco tables for the first slice // in a field. Subsequent slices can temporarily clobber h->mmco_index // or h->mmco, which will cause ref list mix-ups and decoding errors // further down the line. This may break decoding if the first slice is // corrupt, thus we only do this if frame-mt is enabled. if (h->nal_ref_idc) { ret = ff_h264_decode_ref_pic_marking(h0, &h->gb, !(h->avctx->active_thread_type & FF_THREAD_FRAME) || h0->current_slice == 0); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return AVERROR_INVALIDDATA; } if (FRAME_MBAFF(h)) { ff_h264_fill_mbaff_ref_list(h); if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) { implicit_weight_table(h, 0); implicit_weight_table(h, 1); } } if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred) ff_h264_direct_dist_scale_factor(h); ff_h264_direct_ref_list_init(h); if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) { tmp = get_ue_golomb_31(&h->gb); if (tmp > 2) { av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n"); return AVERROR_INVALIDDATA; } h->cabac_init_idc = tmp; } h->last_qscale_diff = 0; tmp = h->pps.init_qp + get_se_golomb(&h->gb); if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) { av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp); return AVERROR_INVALIDDATA; } h->qscale = tmp; h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale); h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale); // FIXME qscale / qp ... stuff if (h->slice_type == AV_PICTURE_TYPE_SP) get_bits1(&h->gb); /* sp_for_switch_flag */ if (h->slice_type == AV_PICTURE_TYPE_SP || h->slice_type == AV_PICTURE_TYPE_SI) get_se_golomb(&h->gb); /* slice_qs_delta */ h->deblocking_filter = 1; h->slice_alpha_c0_offset = 52; h->slice_beta_offset = 52; if (h->pps.deblocking_filter_parameters_present) { tmp = get_ue_golomb_31(&h->gb); if (tmp > 2) { av_log(h->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp); return AVERROR_INVALIDDATA; } h->deblocking_filter = tmp; if (h->deblocking_filter < 2) h->deblocking_filter ^= 1; // 1<->0 if (h->deblocking_filter) { h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1; h->slice_beta_offset += get_se_golomb(&h->gb) << 1; if (h->slice_alpha_c0_offset > 104U || h->slice_beta_offset > 104U) { av_log(h->avctx, AV_LOG_ERROR, "deblocking filter parameters %d %d out of range\n", h->slice_alpha_c0_offset, h->slice_beta_offset); return AVERROR_INVALIDDATA; } } } if (h->avctx->skip_loop_filter >= AVDISCARD_ALL || (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != AV_PICTURE_TYPE_I) || (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == AV_PICTURE_TYPE_B) || (h->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0)) h->deblocking_filter = 0; if (h->deblocking_filter == 1 && h0->max_contexts > 1) { if (h->avctx->flags2 & CODEC_FLAG2_FAST) { /* Cheat slightly for speed: * Do not bother to deblock across slices. */ h->deblocking_filter = 2; } else { h0->max_contexts = 1; if (!h0->single_decode_warning) { av_log(h->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n"); h0->single_decode_warning = 1; } if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, "Deblocking switched inside frame.\n"); return 1; } } } h->qp_thresh = 15 + 52 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]) + 6 * (h->sps.bit_depth_luma - 8); h0->last_slice_type = slice_type; memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count)); h->slice_num = ++h0->current_slice; if (h->slice_num) h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y; if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y && h->slice_num >= MAX_SLICES) { //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES); } for (j = 0; j < 2; j++) { int id_list[16]; int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j]; for (i = 0; i < 16; i++) { id_list[i] = 60; if (j < h->list_count && i < h->ref_count[j] && h->ref_list[j][i].f.buf[0]) { int k; AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer; for (k = 0; k < h->short_ref_count; k++) if (h->short_ref[k]->f.buf[0]->buffer == buf) { id_list[i] = k; break; } for (k = 0; k < h->long_ref_count; k++) if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) { id_list[i] = h->short_ref_count + k; break; } } } ref2frm[0] = ref2frm[1] = -1; for (i = 0; i < 16; i++) ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3); ref2frm[18 + 0] = ref2frm[18 + 1] = -1; for (i = 16; i < 48; i++) ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] + (h->ref_list[j][i].reference & 3); } if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0]; if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0]; h->er.ref_count = h->ref_count[0]; h0->au_pps_id = pps_id; if (h->avctx->debug & FF_DEBUG_PICT_INFO) { av_log(h->avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n", h->slice_num, (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"), first_mb_in_slice, av_get_picture_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "", pps_id, h->frame_num, h->cur_pic_ptr->field_poc[0], h->cur_pic_ptr->field_poc[1], h->ref_count[0], h->ref_count[1], h->qscale, h->deblocking_filter, h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26, h->use_weight, h->use_weight == 1 && h->use_weight_chroma ? "c" : "", h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""); } return 0; }
1
[ "CWE-703" ]
FFmpeg
8a3b85f3a7952c54a2c36ba1797f7e0cde9f85aa
24,783,762,682,806,170,000,000,000,000,000,000,000
694
avcodec/h264: update current_sps & sps->new only after the whole slice header decoder and init code finished This avoids them being cleared before the full initialization finished Fixes out of array read Fixes: asan_heap-oob_f0c5e6_7071_cov_1605985132_mov_h264_aac__Demo_FlagOfOurFathers.mov Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind Signed-off-by: Michael Niedermayer <[email protected]>
static int cap_inode_link(struct dentry *old_dentry, struct inode *inode, struct dentry *new_dentry) { return 0; }
0
[]
linux-2.6
ee18d64c1f632043a02e6f5ba5e045bb26a5465f
294,393,981,334,092,680,000,000,000,000,000,000,000
5
KEYS: Add a keyctl to install a process's session keyring on its parent [try #6] Add a keyctl to install a process's session keyring onto its parent. This replaces the parent's session keyring. Because the COW credential code does not permit one process to change another process's credentials directly, the change is deferred until userspace next starts executing again. Normally this will be after a wait*() syscall. To support this, three new security hooks have been provided: cred_alloc_blank() to allocate unset security creds, cred_transfer() to fill in the blank security creds and key_session_to_parent() - which asks the LSM if the process may replace its parent's session keyring. The replacement may only happen if the process has the same ownership details as its parent, and the process has LINK permission on the session keyring, and the session keyring is owned by the process, and the LSM permits it. Note that this requires alteration to each architecture's notify_resume path. This has been done for all arches barring blackfin, m68k* and xtensa, all of which need assembly alteration to support TIF_NOTIFY_RESUME. This allows the replacement to be performed at the point the parent process resumes userspace execution. This allows the userspace AFS pioctl emulation to fully emulate newpag() and the VIOCSETTOK and VIOCSETTOK2 pioctls, all of which require the ability to alter the parent process's PAG membership. However, since kAFS doesn't use PAGs per se, but rather dumps the keys into the session keyring, the session keyring of the parent must be replaced if, for example, VIOCSETTOK is passed the newpag flag. This can be tested with the following program: #include <stdio.h> #include <stdlib.h> #include <keyutils.h> #define KEYCTL_SESSION_TO_PARENT 18 #define OSERROR(X, S) do { if ((long)(X) == -1) { perror(S); exit(1); } } while(0) int main(int argc, char **argv) { key_serial_t keyring, key; long ret; keyring = keyctl_join_session_keyring(argv[1]); OSERROR(keyring, "keyctl_join_session_keyring"); key = add_key("user", "a", "b", 1, keyring); OSERROR(key, "add_key"); ret = keyctl(KEYCTL_SESSION_TO_PARENT); OSERROR(ret, "KEYCTL_SESSION_TO_PARENT"); return 0; } Compiled and linked with -lkeyutils, you should see something like: [dhowells@andromeda ~]$ keyctl show Session Keyring -3 --alswrv 4043 4043 keyring: _ses 355907932 --alswrv 4043 -1 \_ keyring: _uid.4043 [dhowells@andromeda ~]$ /tmp/newpag [dhowells@andromeda ~]$ keyctl show Session Keyring -3 --alswrv 4043 4043 keyring: _ses 1055658746 --alswrv 4043 4043 \_ user: a [dhowells@andromeda ~]$ /tmp/newpag hello [dhowells@andromeda ~]$ keyctl show Session Keyring -3 --alswrv 4043 4043 keyring: hello 340417692 --alswrv 4043 4043 \_ user: a Where the test program creates a new session keyring, sticks a user key named 'a' into it and then installs it on its parent. Signed-off-by: David Howells <[email protected]> Signed-off-by: James Morris <[email protected]>
_fill_xrgb32_lerp_spans (void *abstract_renderer, int y, int h, const cairo_half_open_span_t *spans, unsigned num_spans) { cairo_image_span_renderer_t *r = abstract_renderer; if (num_spans == 0) return CAIRO_STATUS_SUCCESS; if (likely(h == 1)) { do { uint8_t a = mul8_8 (spans[0].coverage, r->op); if (a) { int len = spans[1].x - spans[0].x; uint32_t *d = (uint32_t*)(r->u.fill.data + r->u.fill.stride*y + spans[0].x*4); while (len--) { *d = lerp8x4 (r->u.fill.pixel, a, *d); d++; } } spans++; } while (--num_spans > 1); } else { do { uint8_t a = mul8_8 (spans[0].coverage, r->op); if (a) { int yy = y, hh = h; do { int len = spans[1].x - spans[0].x; uint32_t *d = (uint32_t *)(r->u.fill.data + r->u.fill.stride*yy + spans[0].x*4); while (len--) { *d = lerp8x4 (r->u.fill.pixel, a, *d); d++; } yy++; } while (--hh); } spans++; } while (--num_spans > 1); } return CAIRO_STATUS_SUCCESS; }
1
[ "CWE-787" ]
cairo
c986a7310bb06582b7d8a566d5f007ba4e5e75bf
193,829,035,771,489,200,000,000,000,000,000,000,000
42
image: Enable inplace compositing with opacities for general routines On a SNB i5-2500: Speedups ======== firefox-chalkboard 34284.16 -> 19637.40: 1.74x speedup swfdec-giant-steps 778.35 -> 665.37: 1.17x speedup ocitysmap 485.64 -> 431.94: 1.12x speedup Slowdowns ========= firefox-fishbowl 46878.98 -> 54407.14: 1.16x slowdown That slow down is due to overhead of the increased number of calls to pixman_image_composite32() (pixman_transform_point for analyzing the source extents in particular) outweighing any advantage gained by performing the rasterisation in a single pass and eliding gaps. The solution that has been floated in the past is for an interface into pixman to only perform the analysis once and then to return a kernel to use for all spans. Signed-off-by: Chris Wilson <[email protected]>
static int extract_min_max(IPAddressOrRange *aor, unsigned char *min, unsigned char *max, int length) { if (aor == NULL || min == NULL || max == NULL) return 0; switch (aor->type) { case IPAddressOrRange_addressPrefix: return (addr_expand(min, aor->u.addressPrefix, length, 0x00) && addr_expand(max, aor->u.addressPrefix, length, 0xFF)); case IPAddressOrRange_addressRange: return (addr_expand(min, aor->u.addressRange->min, length, 0x00) && addr_expand(max, aor->u.addressRange->max, length, 0xFF)); } return 0; }
0
[ "CWE-119", "CWE-787" ]
openssl
068b963bb7afc57f5bdd723de0dd15e7795d5822
23,525,152,507,353,740,000,000,000,000,000,000,000
15
Avoid out-of-bounds read Fixes CVE 2017-3735 Reviewed-by: Kurt Roeckx <[email protected]> (Merged from https://github.com/openssl/openssl/pull/4276) (cherry picked from commit b23171744b01e473ebbfd6edad70c1c3825ffbcd)
check_no_proxy(char *domain) { TextListItem *tl; volatile int ret = 0; MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL; if (NO_proxy_domains == NULL || NO_proxy_domains->nitem == 0 || domain == NULL) return 0; for (tl = NO_proxy_domains->first; tl != NULL; tl = tl->next) { if (domain_match(tl->ptr, domain)) return 1; } if (!NOproxy_netaddr) { return 0; } /* * to check noproxy by network addr */ if (SETJMP(AbortLoading) != 0) { ret = 0; goto end; } TRAP_ON; { #ifndef INET6 struct hostent *he; int n; unsigned char **h_addr_list; char addr[4 * 16], buf[5]; he = gethostbyname(domain); if (!he) { ret = 0; goto end; } for (h_addr_list = (unsigned char **)he->h_addr_list; *h_addr_list; h_addr_list++) { sprintf(addr, "%d", h_addr_list[0][0]); for (n = 1; n < he->h_length; n++) { sprintf(buf, ".%d", h_addr_list[0][n]); strcat(addr, buf); } for (tl = NO_proxy_domains->first; tl != NULL; tl = tl->next) { if (strncmp(tl->ptr, addr, strlen(tl->ptr)) == 0) { ret = 1; goto end; } } } #else /* INET6 */ int error; struct addrinfo hints; struct addrinfo *res, *res0; char addr[4 * 16]; int *af; for (af = ai_family_order_table[DNS_order];; af++) { memset(&hints, 0, sizeof(hints)); hints.ai_family = *af; error = getaddrinfo(domain, NULL, &hints, &res0); if (error) { if (*af == PF_UNSPEC) { break; } /* try next */ continue; } for (res = res0; res != NULL; res = res->ai_next) { switch (res->ai_family) { case AF_INET: inet_ntop(AF_INET, &((struct sockaddr_in *)res->ai_addr)->sin_addr, addr, sizeof(addr)); break; case AF_INET6: inet_ntop(AF_INET6, &((struct sockaddr_in6 *)res->ai_addr)-> sin6_addr, addr, sizeof(addr)); break; default: /* unknown */ continue; } for (tl = NO_proxy_domains->first; tl != NULL; tl = tl->next) { if (strncmp(tl->ptr, addr, strlen(tl->ptr)) == 0) { freeaddrinfo(res0); ret = 1; goto end; } } } freeaddrinfo(res0); if (*af == PF_UNSPEC) { break; } } #endif /* INET6 */ } end: TRAP_OFF; return ret; }
0
[ "CWE-119" ]
w3m
ba9d78faeba9024c3e8840579c3b0e959ae2cb0f
131,686,969,676,735,760,000,000,000,000,000,000,000
103
Prevent global-buffer-overflow in parseURL() Bug-Debian: https://github.com/tats/w3m/issues/41
R_API RBinJavaCPTypeObj *r_bin_java_find_cp_ref_info_from_name_and_type(RBinJavaObj *bin, ut16 name_idx, ut16 descriptor_idx) { RBinJavaCPTypeObj *obj = r_bin_java_find_cp_name_and_type_info (bin, name_idx, descriptor_idx); if (obj) { return r_bin_java_find_cp_ref_info (bin, obj->metas->ord); } return NULL; }
0
[ "CWE-119", "CWE-788" ]
radare2
6c4428f018d385fc80a33ecddcb37becea685dd5
205,987,599,135,130,400,000,000,000,000,000,000,000
7
Improve boundary checks to fix oobread segfaults ##crash * Reported by Cen Zhang via huntr.dev * Reproducer: bins/fuzzed/javaoob-havoc.class
struct vport *ovs_lookup_vport(const struct datapath *dp, u16 port_no) { struct vport *vport; struct hlist_head *head; head = vport_hash_bucket(dp, port_no); hlist_for_each_entry_rcu(vport, head, dp_hash_node) { if (vport->port_no == port_no) return vport; } return NULL; }
0
[ "CWE-416" ]
net
36d5fe6a000790f56039afe26834265db0a3ad4c
53,844,672,766,947,050,000,000,000,000,000,000,000
12
core, nfqueue, openvswitch: Orphan frags in skb_zerocopy and handle errors skb_zerocopy can copy elements of the frags array between skbs, but it doesn't orphan them. Also, it doesn't handle errors, so this patch takes care of that as well, and modify the callers accordingly. skb_tx_error() is also added to the callers so they will signal the failed delivery towards the creator of the skb. Signed-off-by: Zoltan Kiss <[email protected]> Signed-off-by: David S. Miller <[email protected]>
static pyc_object *get_binary_float_object(RzBuffer *buffer) { pyc_object *ret = NULL; bool error = false; double f; f = get_float64(buffer, &error); if (error) { return NULL; } ret = RZ_NEW0(pyc_object); if (!ret) { return NULL; } ret->type = TYPE_FLOAT; ret->data = rz_str_newf("%.15g", f); if (!ret->data) { RZ_FREE(ret); return NULL; } return ret; }
0
[ "CWE-190" ]
rizin
e645e5827327d945307ddfde4f617ae4c36561fd
12,838,104,146,011,217,000,000,000,000,000,000,000
21
Fix the crash caused by get_long_object() #2739 from PeiweiHu/Peiwei_0625
static PHP_RSHUTDOWN_FUNCTION(session) /* {{{ */ { int i; zend_try { php_session_flush(TSRMLS_C); } zend_end_try(); php_rshutdown_session_globals(TSRMLS_C); /* this should NOT be done in php_rshutdown_session_globals() */ for (i = 0; i < 7; i++) { if (PS(mod_user_names).names[i] != NULL) { zval_ptr_dtor(&PS(mod_user_names).names[i]); PS(mod_user_names).names[i] = NULL; } } return SUCCESS; }
0
[ "CWE-264" ]
php-src
25e8fcc88fa20dc9d4c47184471003f436927cde
47,744,362,063,156,380,000,000,000,000,000,000,000
19
Strict session
static void loongarch_qemu_write(void *opaque, hwaddr addr, uint64_t val, unsigned size) { }
0
[]
qemu
3517fb726741c109cae7995f9ea46f0cab6187d6
29,091,883,490,871,030,000,000,000,000,000,000,000
4
target/loongarch: Clean up tlb when cpu reset We should make sure that tlb is clean when cpu reset. Signed-off-by: Song Gao <[email protected]> Message-Id: <[email protected]> Reviewed-by: Richard Henderson <[email protected]> Signed-off-by: Richard Henderson <[email protected]>
Status ReductionShape(InferenceContext* c) { ShapeHandle input = c->input(0); ShapeHandle indices; // Older versions of TensorFlow accidentally allowed higher rank tensors like // [[1,2]] or [[1],[2]] to represent axis=[1,2]. if (c->graph_def_version() < 21) { indices = c->input(1); } else { TF_RETURN_IF_ERROR(c->WithRankAtMost(c->input(1), 1, &indices)); } bool keep_dims; TF_RETURN_IF_ERROR(c->GetAttr("keep_dims", &keep_dims)); const Tensor* reduction_indices_t = c->input_tensor(1); if (reduction_indices_t == nullptr || !c->RankKnown(input)) { // If we do not have the reduction values at runtime, or the // rank of the input, we don't know the output shape. if (keep_dims && c->RankKnown(input)) { // output rank matches input input if <keep_dims>. c->set_output(0, c->UnknownShapeOfRank(c->Rank(input))); return Status::OK(); } else { return shape_inference::UnknownShape(c); } } const int32_t input_rank = c->Rank(input); std::set<int64> true_indices; if (reduction_indices_t->dtype() == DataType::DT_INT32) { TF_RETURN_IF_ERROR(ReductionShapeHelper<int32>(reduction_indices_t, input_rank, &true_indices)); } else if (reduction_indices_t->dtype() == DataType::DT_INT64) { TF_RETURN_IF_ERROR(ReductionShapeHelper<int64>(reduction_indices_t, input_rank, &true_indices)); } else { return errors::InvalidArgument( "reduction_indices can only be int32 or int64"); } std::vector<DimensionHandle> dims; for (int i = 0; i < input_rank; ++i) { if (true_indices.count(i) > 0) { if (keep_dims) { dims.emplace_back(c->MakeDim(1)); } } else { dims.emplace_back(c->Dim(input, i)); } } c->set_output(0, c->MakeShape(dims)); return Status::OK(); }
0
[ "CWE-369" ]
tensorflow
8a793b5d7f59e37ac7f3cd0954a750a2fe76bad4
90,198,227,210,960,300,000,000,000,000,000,000,000
56
Prevent division by 0 in common shape functions. PiperOrigin-RevId: 387712197 Change-Id: Id25c7460e35b68aeeeac23b9a88e455b443ee149