instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: isis_print_id(const uint8_t *cp, int id_len) { int i; static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")]; char *pos = id; for (i = 1; i <= SYSTEM_ID_LEN; i++) { snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++); pos += strlen(pos); if (i == 2 || i == 4) *pos++ = '.'; } if (id_len >= NODE_ID_LEN) { snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++); pos += strlen(pos); } if (id_len == LSP_ID_LEN) snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp); return (id); } Commit Message: CVE-2017-13035/Properly handle IS-IS IDs shorter than a system ID (MAC address). Some of them are variable-length, with a field giving the total length, and therefore they can be shorter than 6 octets. If one is, don't run past the end. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-125
isis_print_id(const uint8_t *cp, int id_len) { int i; static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")]; char *pos = id; int sysid_len; sysid_len = SYSTEM_ID_LEN; if (sysid_len > id_len) sysid_len = id_len; for (i = 1; i <= sysid_len; i++) { snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++); pos += strlen(pos); if (i == 2 || i == 4) *pos++ = '.'; } if (id_len >= NODE_ID_LEN) { snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++); pos += strlen(pos); } if (id_len == LSP_ID_LEN) snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp); return (id); }
167,848
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int x1h = x1, x1v = x1, y1h = y1, y1v = y1, x2h = x2, x2v = x2, y2h = y2, y2v = y2; int thick = im->thick; int t; if (x1 == x2 && y1 == y2 && thick == 1) { gdImageSetPixel(im, x1, y1, color); return; } if (y2 < y1) { t=y1; y1 = y2; y2 = t; t = x1; x1 = x2; x2 = t; } x1h = x1; x1v = x1; y1h = y1; y1v = y1; x2h = x2; x2v = x2; y2h = y2; y2v = y2; if (thick > 1) { int cx, cy, x1ul, y1ul, x2lr, y2lr; int half = thick >> 1; x1ul = x1 - half; y1ul = y1 - half; x2lr = x2 + half; y2lr = y2 + half; cy = y1ul + thick; while (cy-- > y1ul) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y2lr - thick; while (cy++ < y2lr) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x1ul - 1; while (cx++ < x1ul + thick) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x2lr - thick - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } return; } else { y1v = y1h + 1; y2v = y2h - 1; gdImageLine(im, x1h, y1h, x2h, y1h, color); gdImageLine(im, x1h, y2h, x2h, y2h, color); gdImageLine(im, x1v, y1v, x1v, y2v, color); gdImageLine(im, x2v, y1v, x2v, y2v, color); } } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190
void gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int x1h = x1, x1v = x1, y1h = y1, y1v = y1, x2h = x2, x2v = x2, y2h = y2, y2v = y2; int thick = im->thick; int t; if (x1 == x2 && y1 == y2 && thick == 1) { gdImageSetPixel(im, x1, y1, color); return; } if (y2 < y1) { t=y1; y1 = y2; y2 = t; t = x1; x1 = x2; x2 = t; } x1h = x1; x1v = x1; y1h = y1; y1v = y1; x2h = x2; x2v = x2; y2h = y2; y2v = y2; if (thick > 1) { int cx, cy, x1ul, y1ul, x2lr, y2lr; int half = thick >> 1; x1ul = x1 - half; y1ul = y1 - half; x2lr = x2 + half; y2lr = y2 + half; cy = y1ul + thick; while (cy-- > y1ul) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y2lr - thick; while (cy++ < y2lr) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x1ul - 1; while (cx++ < x1ul + thick) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x2lr - thick - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } return; } else { y1v = y1h + 1; y2v = y2h - 1; gdImageLine(im, x1h, y1h, x2h, y1h, color); gdImageLine(im, x1h, y2h, x2h, y2h, color); gdImageLine(im, x1v, y1v, x1v, y2v, color); gdImageLine(im, x2v, y1v, x2v, y2v, color); } }
167,130
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void copyMono16( short *dst, const int *const *src, unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i]; } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyMono16( short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i]; } }
174,015
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: FileManagerPrivateCustomBindings::FileManagerPrivateCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetFileSystem", base::Bind(&FileManagerPrivateCustomBindings::GetFileSystem, base::Unretained(this))); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
FileManagerPrivateCustomBindings::FileManagerPrivateCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("GetFileSystem", "fileManagerPrivate", base::Bind(&FileManagerPrivateCustomBindings::GetFileSystem, base::Unretained(this))); RouteFunction( "GetExternalFileEntry", "fileManagerPrivate", base::Bind(&FileManagerPrivateCustomBindings::GetExternalFileEntry, base::Unretained(this))); RouteFunction("GetEntryURL", "fileManagerPrivate", base::Bind(&FileManagerPrivateCustomBindings::GetEntryURL, base::Unretained(this))); }
173,274
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebGraphicsContext3DCommandBufferImpl::reshape(int width, int height) { cached_width_ = width; cached_height_ = height; gl_->ResizeCHROMIUM(width, height); #ifdef FLIP_FRAMEBUFFER_VERTICALLY scanline_.reset(new uint8[width * 4]); #endif // FLIP_FRAMEBUFFER_VERTICALLY } Commit Message: Fix mismanagement in handling of temporary scanline for vertical flip. BUG=116637 TEST=manual test from bug report with ASAN Review URL: https://chromiumcodereview.appspot.com/9617038 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125301 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void WebGraphicsContext3DCommandBufferImpl::reshape(int width, int height) { cached_width_ = width; cached_height_ = height; gl_->ResizeCHROMIUM(width, height); }
171,064
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: BaseRenderingContext2D::BaseRenderingContext2D() : clip_antialiasing_(kNotAntiAliased) { state_stack_.push_back(CanvasRenderingContext2DState::Create()); } Commit Message: [PE] Distinguish between tainting due to canvas content and filter. A filter on a canvas can itself lead to origin tainting, for reasons other than that the canvas contents are tainted. This CL changes to distinguish these two causes, so that we recompute filters on content-tainting change. Bug: 778506 Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6 Reviewed-on: https://chromium-review.googlesource.com/811767 Reviewed-by: Fredrik Söderquist <[email protected]> Commit-Queue: Chris Harrelson <[email protected]> Cr-Commit-Position: refs/heads/master@{#522274} CWE ID: CWE-200
BaseRenderingContext2D::BaseRenderingContext2D() : clip_antialiasing_(kNotAntiAliased), origin_tainted_by_content_(false) { state_stack_.push_back(CanvasRenderingContext2DState::Create()); }
172,904
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct edid *drm_load_edid_firmware(struct drm_connector *connector) { const char *connector_name = connector->name; char *edidname, *last, *colon, *fwstr, *edidstr, *fallback = NULL; struct edid *edid; if (edid_firmware[0] == '\0') return ERR_PTR(-ENOENT); /* * If there are multiple edid files specified and separated * by commas, search through the list looking for one that * matches the connector. * * If there's one or more that doesn't specify a connector, keep * the last one found one as a fallback. */ fwstr = kstrdup(edid_firmware, GFP_KERNEL); edidstr = fwstr; while ((edidname = strsep(&edidstr, ","))) { if (strncmp(connector_name, edidname, colon - edidname)) continue; edidname = colon + 1; break; } if (*edidname != '\0') /* corner case: multiple ',' */ fallback = edidname; } Commit Message: CWE ID: CWE-476
struct edid *drm_load_edid_firmware(struct drm_connector *connector) { const char *connector_name = connector->name; char *edidname, *last, *colon, *fwstr, *edidstr, *fallback = NULL; struct edid *edid; if (edid_firmware[0] == '\0') return ERR_PTR(-ENOENT); /* * If there are multiple edid files specified and separated * by commas, search through the list looking for one that * matches the connector. * * If there's one or more that doesn't specify a connector, keep * the last one found one as a fallback. */ fwstr = kstrdup(edid_firmware, GFP_KERNEL); if (!fwstr) return ERR_PTR(-ENOMEM); edidstr = fwstr; while ((edidname = strsep(&edidstr, ","))) { if (strncmp(connector_name, edidname, colon - edidname)) continue; edidname = colon + 1; break; } if (*edidname != '\0') /* corner case: multiple ',' */ fallback = edidname; }
164,709
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ext4_dax_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { return dax_mkwrite(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-362
static int ext4_dax_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { int err; struct inode *inode = file_inode(vma->vm_file); sb_start_pagefault(inode->i_sb); file_update_time(vma->vm_file); down_read(&EXT4_I(inode)->i_mmap_sem); err = __dax_mkwrite(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); up_read(&EXT4_I(inode)->i_mmap_sem); sb_end_pagefault(inode->i_sb); return err; } /* * Handle write fault for VM_MIXEDMAP mappings. Similarly to ext4_dax_mkwrite() * handler we check for races agaist truncate. Note that since we cycle through * i_mmap_sem, we are sure that also any hole punching that began before we * were called is finished by now and so if it included part of the file we * are working on, our pte will get unmapped and the check for pte_same() in * wp_pfn_shared() fails. Thus fault gets retried and things work out as * desired. */ static int ext4_dax_pfn_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct inode *inode = file_inode(vma->vm_file); struct super_block *sb = inode->i_sb; int ret = VM_FAULT_NOPAGE; loff_t size; sb_start_pagefault(sb); file_update_time(vma->vm_file); down_read(&EXT4_I(inode)->i_mmap_sem); size = (i_size_read(inode) + PAGE_SIZE - 1) >> PAGE_SHIFT; if (vmf->pgoff >= size) ret = VM_FAULT_SIGBUS; up_read(&EXT4_I(inode)->i_mmap_sem); sb_end_pagefault(sb); return ret; }
167,487
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltAttrListTemplateProcess(xsltTransformContextPtr ctxt, xmlNodePtr target, xmlAttrPtr attrs) { xmlAttrPtr attr, copy, last; xmlNodePtr oldInsert, text; xmlNsPtr origNs = NULL, copyNs = NULL; const xmlChar *value; xmlChar *valueAVT; if ((ctxt == NULL) || (target == NULL) || (attrs == NULL)) return(NULL); oldInsert = ctxt->insert; ctxt->insert = target; /* * Instantiate LRE-attributes. */ if (target->properties) { last = target->properties; while (last->next != NULL) last = last->next; } else { last = NULL; } attr = attrs; do { /* * Skip XSLT attributes. */ #ifdef XSLT_REFACTORED if (attr->psvi == xsltXSLTAttrMarker) { goto next_attribute; } #else if ((attr->ns != NULL) && xmlStrEqual(attr->ns->href, XSLT_NAMESPACE)) { goto next_attribute; } #endif /* * Get the value. */ if (attr->children != NULL) { if ((attr->children->type != XML_TEXT_NODE) || (attr->children->next != NULL)) { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: The children of an attribute node of a " "literal result element are not in the expected form.\n"); goto error; } value = attr->children->content; if (value == NULL) value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0); } else value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0); /* * Create a new attribute. */ copy = xmlNewDocProp(target->doc, attr->name, NULL); if (copy == NULL) { if (attr->ns) { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: Failed to create attribute '{%s}%s'.\n", attr->ns->href, attr->name); } else { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: Failed to create attribute '%s'.\n", attr->name); } goto error; } /* * Attach it to the target element. */ copy->parent = target; if (last == NULL) { target->properties = copy; last = copy; } else { last->next = copy; copy->prev = last; last = copy; } /* * Set the namespace. Avoid lookups of same namespaces. */ if (attr->ns != origNs) { origNs = attr->ns; if (attr->ns != NULL) { #ifdef XSLT_REFACTORED copyNs = xsltGetSpecialNamespace(ctxt, attr->parent, attr->ns->href, attr->ns->prefix, target); #else copyNs = xsltGetNamespace(ctxt, attr->parent, attr->ns, target); #endif if (copyNs == NULL) goto error; } else copyNs = NULL; } copy->ns = copyNs; /* * Set the value. */ text = xmlNewText(NULL); if (text != NULL) { copy->last = copy->children = text; text->parent = (xmlNodePtr) copy; text->doc = copy->doc; if (attr->psvi != NULL) { /* * Evaluate the Attribute Value Template. */ valueAVT = xsltEvalAVT(ctxt, attr->psvi, attr->parent); if (valueAVT == NULL) { /* * TODO: Damn, we need an easy mechanism to report * qualified names! */ if (attr->ns) { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: Failed to evaluate the AVT " "of attribute '{%s}%s'.\n", attr->ns->href, attr->name); } else { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: Failed to evaluate the AVT " "of attribute '%s'.\n", attr->name); } text->content = xmlStrdup(BAD_CAST ""); goto error; } else { text->content = valueAVT; } } else if ((ctxt->internalized) && (target->doc != NULL) && (target->doc->dict == ctxt->dict)) { text->content = (xmlChar *) value; } else { text->content = xmlStrdup(value); } if ((copy != NULL) && (text != NULL) && (xmlIsID(copy->doc, copy->parent, copy))) xmlAddID(NULL, copy->doc, text->content, copy); } next_attribute: attr = attr->next; } while (attr != NULL); /* * Apply attribute-sets. * The creation of such attributes will not overwrite any existing * attribute. */ attr = attrs; do { #ifdef XSLT_REFACTORED if ((attr->psvi == xsltXSLTAttrMarker) && xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets")) { xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL); } #else if ((attr->ns != NULL) && xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets") && xmlStrEqual(attr->ns->href, XSLT_NAMESPACE)) { xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL); } #endif attr = attr->next; } while (attr != NULL); ctxt->insert = oldInsert; return(target->properties); error: ctxt->insert = oldInsert; return(NULL); } Commit Message: Fix dictionary string usage. BUG=144799 Review URL: https://chromiumcodereview.appspot.com/10919019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@154331 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
xsltAttrListTemplateProcess(xsltTransformContextPtr ctxt, xmlNodePtr target, xmlAttrPtr attrs) { xmlAttrPtr attr, copy, last; xmlNodePtr oldInsert, text; xmlNsPtr origNs = NULL, copyNs = NULL; const xmlChar *value; xmlChar *valueAVT; if ((ctxt == NULL) || (target == NULL) || (attrs == NULL)) return(NULL); oldInsert = ctxt->insert; ctxt->insert = target; /* * Instantiate LRE-attributes. */ if (target->properties) { last = target->properties; while (last->next != NULL) last = last->next; } else { last = NULL; } attr = attrs; do { /* * Skip XSLT attributes. */ #ifdef XSLT_REFACTORED if (attr->psvi == xsltXSLTAttrMarker) { goto next_attribute; } #else if ((attr->ns != NULL) && xmlStrEqual(attr->ns->href, XSLT_NAMESPACE)) { goto next_attribute; } #endif /* * Get the value. */ if (attr->children != NULL) { if ((attr->children->type != XML_TEXT_NODE) || (attr->children->next != NULL)) { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: The children of an attribute node of a " "literal result element are not in the expected form.\n"); goto error; } value = attr->children->content; if (value == NULL) value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0); } else value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0); /* * Create a new attribute. */ copy = xmlNewDocProp(target->doc, attr->name, NULL); if (copy == NULL) { if (attr->ns) { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: Failed to create attribute '{%s}%s'.\n", attr->ns->href, attr->name); } else { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: Failed to create attribute '%s'.\n", attr->name); } goto error; } /* * Attach it to the target element. */ copy->parent = target; if (last == NULL) { target->properties = copy; last = copy; } else { last->next = copy; copy->prev = last; last = copy; } /* * Set the namespace. Avoid lookups of same namespaces. */ if (attr->ns != origNs) { origNs = attr->ns; if (attr->ns != NULL) { #ifdef XSLT_REFACTORED copyNs = xsltGetSpecialNamespace(ctxt, attr->parent, attr->ns->href, attr->ns->prefix, target); #else copyNs = xsltGetNamespace(ctxt, attr->parent, attr->ns, target); #endif if (copyNs == NULL) goto error; } else copyNs = NULL; } copy->ns = copyNs; /* * Set the value. */ text = xmlNewText(NULL); if (text != NULL) { copy->last = copy->children = text; text->parent = (xmlNodePtr) copy; text->doc = copy->doc; if (attr->psvi != NULL) { /* * Evaluate the Attribute Value Template. */ valueAVT = xsltEvalAVT(ctxt, attr->psvi, attr->parent); if (valueAVT == NULL) { /* * TODO: Damn, we need an easy mechanism to report * qualified names! */ if (attr->ns) { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: Failed to evaluate the AVT " "of attribute '{%s}%s'.\n", attr->ns->href, attr->name); } else { xsltTransformError(ctxt, NULL, attr->parent, "Internal error: Failed to evaluate the AVT " "of attribute '%s'.\n", attr->name); } text->content = xmlStrdup(BAD_CAST ""); goto error; } else { text->content = valueAVT; } } else if ((ctxt->internalized) && (target->doc != NULL) && (target->doc->dict == ctxt->dict) && xmlDictOwns(ctxt->dict, value)) { text->content = (xmlChar *) value; } else { text->content = xmlStrdup(value); } if ((copy != NULL) && (text != NULL) && (xmlIsID(copy->doc, copy->parent, copy))) xmlAddID(NULL, copy->doc, text->content, copy); } next_attribute: attr = attr->next; } while (attr != NULL); /* * Apply attribute-sets. * The creation of such attributes will not overwrite any existing * attribute. */ attr = attrs; do { #ifdef XSLT_REFACTORED if ((attr->psvi == xsltXSLTAttrMarker) && xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets")) { xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL); } #else if ((attr->ns != NULL) && xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets") && xmlStrEqual(attr->ns->href, XSLT_NAMESPACE)) { xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL); } #endif attr = attr->next; } while (attr != NULL); ctxt->insert = oldInsert; return(target->properties); error: ctxt->insert = oldInsert; return(NULL); }
170,859
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Event"); if (result != sandbox::SBOX_ALL_OK) return false; policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; } Commit Message: Prevent sandboxed processes from opening each other TBR=brettw BUG=117627 BUG=119150 TEST=sbox_validation_tests Review URL: https://chromiumcodereview.appspot.com/9716027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Event"); if (result != sandbox::SBOX_ALL_OK) return false; policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); // Prevents the renderers from manipulating low-integrity processes. policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; }
170,912
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ft_smooth_render_generic( FT_Renderer render, FT_GlyphSlot slot, FT_Render_Mode mode, const FT_Vector* origin, FT_Render_Mode required_mode ) { FT_Error error; FT_Outline* outline = NULL; FT_BBox cbox; FT_UInt width, height, height_org, width_org, pitch; FT_Bitmap* bitmap; FT_Memory memory; FT_Int hmul = mode == FT_RENDER_MODE_LCD; FT_Int vmul = mode == FT_RENDER_MODE_LCD_V; FT_Pos x_shift, y_shift, x_left, y_top; FT_Raster_Params params; /* check glyph image format */ if ( slot->format != render->glyph_format ) { error = Smooth_Err_Invalid_Argument; goto Exit; } /* check mode */ if ( mode != required_mode ) return Smooth_Err_Cannot_Render_Glyph; outline = &slot->outline; /* translate the outline to the new origin if needed */ if ( origin ) FT_Outline_Translate( outline, origin->x, origin->y ); /* compute the control box, and grid fit it */ FT_Outline_Get_CBox( outline, &cbox ); cbox.xMin = FT_PIX_FLOOR( cbox.xMin ); cbox.yMin = FT_PIX_FLOOR( cbox.yMin ); cbox.xMax = FT_PIX_CEIL( cbox.xMax ); cbox.yMax = FT_PIX_CEIL( cbox.yMax ); width = (FT_UInt)( ( cbox.xMax - cbox.xMin ) >> 6 ); height = (FT_UInt)( ( cbox.yMax - cbox.yMin ) >> 6 ); bitmap = &slot->bitmap; memory = render->root.memory; width_org = width; height_org = height; /* release old bitmap buffer */ if ( slot->internal->flags & FT_GLYPH_OWN_BITMAP ) { FT_FREE( bitmap->buffer ); slot->internal->flags &= ~FT_GLYPH_OWN_BITMAP; } /* allocate new one */ pitch = width; if ( hmul ) { width = width * 3; pitch = FT_PAD_CEIL( width, 4 ); } if ( vmul ) height *= 3; x_shift = (FT_Int) cbox.xMin; y_shift = (FT_Int) cbox.yMin; x_left = (FT_Int)( cbox.xMin >> 6 ); y_top = (FT_Int)( cbox.yMax >> 6 ); #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING if ( slot->library->lcd_filter_func ) { FT_Int extra = slot->library->lcd_extra; if ( hmul ) { x_shift -= 64 * ( extra >> 1 ); width += 3 * extra; pitch = FT_PAD_CEIL( width, 4 ); x_left -= extra >> 1; } if ( vmul ) { y_shift -= 64 * ( extra >> 1 ); height += 3 * extra; y_top += extra >> 1; } } #endif #if FT_UINT_MAX > 0xFFFFU /* Required check is ( pitch * height < FT_ULONG_MAX ), */ /* but we care realistic cases only. Always pitch <= width. */ if ( width > 0xFFFFU || height > 0xFFFFU ) { FT_ERROR(( "ft_smooth_render_generic: glyph too large: %d x %d\n", width, height )); return Smooth_Err_Raster_Overflow; } #endif bitmap->pixel_mode = FT_PIXEL_MODE_GRAY; bitmap->num_grays = 256; bitmap->width = width; bitmap->rows = height; bitmap->pitch = pitch; /* translate outline to render it into the bitmap */ FT_Outline_Translate( outline, -x_shift, -y_shift ); if ( FT_ALLOC( bitmap->buffer, (FT_ULong)pitch * height ) ) goto Exit; slot->internal->flags |= FT_GLYPH_OWN_BITMAP; /* set up parameters */ params.target = bitmap; params.source = outline; params.flags = FT_RASTER_FLAG_AA; #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING /* implode outline if needed */ { FT_Vector* points = outline->points; FT_Vector* points_end = points + outline->n_points; FT_Vector* vec; if ( hmul ) for ( vec = points; vec < points_end; vec++ ) vec->x *= 3; if ( vmul ) for ( vec = points; vec < points_end; vec++ ) vec->y *= 3; } /* render outline into the bitmap */ error = render->raster_render( render->raster, &params ); /* deflate outline if needed */ { FT_Vector* points = outline->points; FT_Vector* points_end = points + outline->n_points; FT_Vector* vec; if ( hmul ) for ( vec = points; vec < points_end; vec++ ) vec->x /= 3; if ( vmul ) for ( vec = points; vec < points_end; vec++ ) vec->y /= 3; } if ( slot->library->lcd_filter_func ) slot->library->lcd_filter_func( bitmap, mode, slot->library ); #else /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */ /* render outline into bitmap */ error = render->raster_render( render->raster, &params ); /* expand it horizontally */ if ( hmul ) { FT_Byte* line = bitmap->buffer; FT_UInt hh; for ( hh = height_org; hh > 0; hh--, line += pitch ) { FT_UInt xx; FT_Byte* end = line + width; for ( xx = width_org; xx > 0; xx-- ) { FT_UInt pixel = line[xx-1]; end[-3] = (FT_Byte)pixel; end[-2] = (FT_Byte)pixel; end[-1] = (FT_Byte)pixel; end -= 3; } } } /* expand it vertically */ if ( vmul ) { FT_Byte* read = bitmap->buffer + ( height - height_org ) * pitch; FT_Byte* write = bitmap->buffer; FT_UInt hh; for ( hh = height_org; hh > 0; hh-- ) { ft_memcpy( write, read, pitch ); write += pitch; ft_memcpy( write, read, pitch ); write += pitch; ft_memcpy( write, read, pitch ); write += pitch; read += pitch; } } #endif /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */ FT_Outline_Translate( outline, x_shift, y_shift ); /* * XXX: on 16bit system, we return an error for huge bitmap * to prevent an overflow. */ if ( x_left > FT_INT_MAX || y_top > FT_INT_MAX ) return Smooth_Err_Invalid_Pixel_Size; if ( error ) goto Exit; slot->format = FT_GLYPH_FORMAT_BITMAP; slot->bitmap_left = (FT_Int)x_left; slot->bitmap_top = (FT_Int)y_top; Exit: if ( outline && origin ) FT_Outline_Translate( outline, -origin->x, -origin->y ); return error; } Commit Message: CWE ID: CWE-189
ft_smooth_render_generic( FT_Renderer render, FT_GlyphSlot slot, FT_Render_Mode mode, const FT_Vector* origin, FT_Render_Mode required_mode ) { FT_Error error; FT_Outline* outline = NULL; FT_BBox cbox; FT_UInt width, height, height_org, width_org, pitch; FT_Bitmap* bitmap; FT_Memory memory; FT_Int hmul = mode == FT_RENDER_MODE_LCD; FT_Int vmul = mode == FT_RENDER_MODE_LCD_V; FT_Pos x_shift, y_shift, x_left, y_top; FT_Raster_Params params; /* check glyph image format */ if ( slot->format != render->glyph_format ) { error = Smooth_Err_Invalid_Argument; goto Exit; } /* check mode */ if ( mode != required_mode ) return Smooth_Err_Cannot_Render_Glyph; outline = &slot->outline; /* translate the outline to the new origin if needed */ if ( origin ) FT_Outline_Translate( outline, origin->x, origin->y ); /* compute the control box, and grid fit it */ FT_Outline_Get_CBox( outline, &cbox ); cbox.xMin = FT_PIX_FLOOR( cbox.xMin ); cbox.yMin = FT_PIX_FLOOR( cbox.yMin ); cbox.xMax = FT_PIX_CEIL( cbox.xMax ); cbox.yMax = FT_PIX_CEIL( cbox.yMax ); width = (FT_UInt)( ( cbox.xMax - cbox.xMin ) >> 6 ); height = (FT_UInt)( ( cbox.yMax - cbox.yMin ) >> 6 ); bitmap = &slot->bitmap; memory = render->root.memory; width_org = width; height_org = height; /* release old bitmap buffer */ if ( slot->internal->flags & FT_GLYPH_OWN_BITMAP ) { FT_FREE( bitmap->buffer ); slot->internal->flags &= ~FT_GLYPH_OWN_BITMAP; } /* allocate new one */ pitch = width; if ( hmul ) { width = width * 3; pitch = FT_PAD_CEIL( width, 4 ); } if ( vmul ) height *= 3; x_shift = (FT_Int) cbox.xMin; y_shift = (FT_Int) cbox.yMin; x_left = (FT_Int)( cbox.xMin >> 6 ); y_top = (FT_Int)( cbox.yMax >> 6 ); #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING if ( slot->library->lcd_filter_func ) { FT_Int extra = slot->library->lcd_extra; if ( hmul ) { x_shift -= 64 * ( extra >> 1 ); width += 3 * extra; pitch = FT_PAD_CEIL( width, 4 ); x_left -= extra >> 1; } if ( vmul ) { y_shift -= 64 * ( extra >> 1 ); height += 3 * extra; y_top += extra >> 1; } } #endif #if FT_UINT_MAX > 0xFFFFU /* Required check is ( pitch * height < FT_ULONG_MAX ), */ /* but we care realistic cases only. Always pitch <= width. */ if ( width > 0x7FFFU || height > 0x7FFFU ) { FT_ERROR(( "ft_smooth_render_generic: glyph too large: %d x %d\n", width, height )); return Smooth_Err_Raster_Overflow; } #endif bitmap->pixel_mode = FT_PIXEL_MODE_GRAY; bitmap->num_grays = 256; bitmap->width = width; bitmap->rows = height; bitmap->pitch = pitch; /* translate outline to render it into the bitmap */ FT_Outline_Translate( outline, -x_shift, -y_shift ); if ( FT_ALLOC( bitmap->buffer, (FT_ULong)pitch * height ) ) goto Exit; slot->internal->flags |= FT_GLYPH_OWN_BITMAP; /* set up parameters */ params.target = bitmap; params.source = outline; params.flags = FT_RASTER_FLAG_AA; #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING /* implode outline if needed */ { FT_Vector* points = outline->points; FT_Vector* points_end = points + outline->n_points; FT_Vector* vec; if ( hmul ) for ( vec = points; vec < points_end; vec++ ) vec->x *= 3; if ( vmul ) for ( vec = points; vec < points_end; vec++ ) vec->y *= 3; } /* render outline into the bitmap */ error = render->raster_render( render->raster, &params ); /* deflate outline if needed */ { FT_Vector* points = outline->points; FT_Vector* points_end = points + outline->n_points; FT_Vector* vec; if ( hmul ) for ( vec = points; vec < points_end; vec++ ) vec->x /= 3; if ( vmul ) for ( vec = points; vec < points_end; vec++ ) vec->y /= 3; } if ( slot->library->lcd_filter_func ) slot->library->lcd_filter_func( bitmap, mode, slot->library ); #else /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */ /* render outline into bitmap */ error = render->raster_render( render->raster, &params ); /* expand it horizontally */ if ( hmul ) { FT_Byte* line = bitmap->buffer; FT_UInt hh; for ( hh = height_org; hh > 0; hh--, line += pitch ) { FT_UInt xx; FT_Byte* end = line + width; for ( xx = width_org; xx > 0; xx-- ) { FT_UInt pixel = line[xx-1]; end[-3] = (FT_Byte)pixel; end[-2] = (FT_Byte)pixel; end[-1] = (FT_Byte)pixel; end -= 3; } } } /* expand it vertically */ if ( vmul ) { FT_Byte* read = bitmap->buffer + ( height - height_org ) * pitch; FT_Byte* write = bitmap->buffer; FT_UInt hh; for ( hh = height_org; hh > 0; hh-- ) { ft_memcpy( write, read, pitch ); write += pitch; ft_memcpy( write, read, pitch ); write += pitch; ft_memcpy( write, read, pitch ); write += pitch; read += pitch; } } #endif /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */ FT_Outline_Translate( outline, x_shift, y_shift ); /* * XXX: on 16bit system, we return an error for huge bitmap * to prevent an overflow. */ if ( x_left > FT_INT_MAX || y_top > FT_INT_MAX ) return Smooth_Err_Invalid_Pixel_Size; if ( error ) goto Exit; slot->format = FT_GLYPH_FORMAT_BITMAP; slot->bitmap_left = (FT_Int)x_left; slot->bitmap_top = (FT_Int)y_top; Exit: if ( outline && origin ) FT_Outline_Translate( outline, -origin->x, -origin->y ); return error; }
165,005
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file, struct snd_ctl_elem_value *control) { struct snd_kcontrol *kctl; struct snd_kcontrol_volatile *vd; unsigned int index_offset; int result; down_read(&card->controls_rwsem); kctl = snd_ctl_find_id(card, &control->id); if (kctl == NULL) { result = -ENOENT; } else { index_offset = snd_ctl_get_ioff(kctl, &control->id); vd = &kctl->vd[index_offset]; if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) || kctl->put == NULL || (file && vd->owner && vd->owner != file)) { result = -EPERM; } else { snd_ctl_build_ioff(&control->id, kctl, index_offset); result = kctl->put(kctl, control); } if (result > 0) { up_read(&card->controls_rwsem); snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, &control->id); return 0; } } up_read(&card->controls_rwsem); return result; } Commit Message: ALSA: control: Don't access controls outside of protected regions A control that is visible on the card->controls list can be freed at any time. This means we must not access any of its memory while not holding the controls_rw_lock. Otherwise we risk a use after free access. Signed-off-by: Lars-Peter Clausen <[email protected]> Acked-by: Jaroslav Kysela <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID:
static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file, struct snd_ctl_elem_value *control) { struct snd_kcontrol *kctl; struct snd_kcontrol_volatile *vd; unsigned int index_offset; int result; down_read(&card->controls_rwsem); kctl = snd_ctl_find_id(card, &control->id); if (kctl == NULL) { result = -ENOENT; } else { index_offset = snd_ctl_get_ioff(kctl, &control->id); vd = &kctl->vd[index_offset]; if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) || kctl->put == NULL || (file && vd->owner && vd->owner != file)) { result = -EPERM; } else { snd_ctl_build_ioff(&control->id, kctl, index_offset); result = kctl->put(kctl, control); } if (result > 0) { struct snd_ctl_elem_id id = control->id; up_read(&card->controls_rwsem); snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, &id); return 0; } } up_read(&card->controls_rwsem); return result; }
166,293
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t Parcel::readUtf8FromUtf16(std::string* str) const { size_t utf16Size = 0; const char16_t* src = readString16Inplace(&utf16Size); if (!src) { return UNEXPECTED_NULL; } if (utf16Size == 0u) { str->clear(); return NO_ERROR; } ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size); if (utf8Size < 0) { return BAD_VALUE; } str->resize(utf8Size + 1); utf16_to_utf8(src, utf16Size, &((*str)[0])); str->resize(utf8Size); return NO_ERROR; } Commit Message: Add bound checks to utf16_to_utf8 Bug: 29250543 Change-Id: I518e7b2fe10aaa3f1c1987586a09b1110aff7e1a (cherry picked from commit 7e93b2ddcb49b5365fbe1dab134ffb38e6f1c719) CWE ID: CWE-119
status_t Parcel::readUtf8FromUtf16(std::string* str) const { size_t utf16Size = 0; const char16_t* src = readString16Inplace(&utf16Size); if (!src) { return UNEXPECTED_NULL; } if (utf16Size == 0u) { str->clear(); return NO_ERROR; } // Allow for closing '\0' ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size) + 1; if (utf8Size < 1) { return BAD_VALUE; } // spare byte around for the trailing null, we still pass the size including the trailing null str->resize(utf8Size); utf16_to_utf8(src, utf16Size, &((*str)[0]), utf8Size); str->resize(utf8Size - 1); return NO_ERROR; }
174,158
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DeviceRequest( int requesting_process_id, int requesting_frame_id, int page_request_id, bool user_gesture, MediaStreamRequestType request_type, const StreamControls& controls, MediaDeviceSaltAndOrigin salt_and_origin, DeviceStoppedCallback device_stopped_cb = DeviceStoppedCallback()) : requesting_process_id(requesting_process_id), requesting_frame_id(requesting_frame_id), page_request_id(page_request_id), user_gesture(user_gesture), controls(controls), salt_and_origin(std::move(salt_and_origin)), device_stopped_cb(std::move(device_stopped_cb)), state_(NUM_MEDIA_TYPES, MEDIA_REQUEST_STATE_NOT_REQUESTED), request_type_(request_type), audio_type_(MEDIA_NO_SERVICE), video_type_(MEDIA_NO_SERVICE), target_process_id_(-1), target_frame_id_(-1) {} Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
DeviceRequest( int requesting_process_id, int requesting_frame_id, int requester_id, int page_request_id, bool user_gesture, MediaStreamRequestType request_type, const StreamControls& controls, MediaDeviceSaltAndOrigin salt_and_origin, DeviceStoppedCallback device_stopped_cb = DeviceStoppedCallback()) : requesting_process_id(requesting_process_id), requesting_frame_id(requesting_frame_id), requester_id(requester_id), page_request_id(page_request_id), user_gesture(user_gesture), controls(controls), salt_and_origin(std::move(salt_and_origin)), device_stopped_cb(std::move(device_stopped_cb)), state_(NUM_MEDIA_TYPES, MEDIA_REQUEST_STATE_NOT_REQUESTED), request_type_(request_type), audio_type_(MEDIA_NO_SERVICE), video_type_(MEDIA_NO_SERVICE), target_process_id_(-1), target_frame_id_(-1) {}
173,102
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: H264SwDecRet H264SwDecInit(H264SwDecInst *decInst, u32 noOutputReordering) { u32 rv = 0; decContainer_t *pDecCont; DEC_API_TRC("H264SwDecInit#"); /* check that right shift on negative numbers is performed signed */ /*lint -save -e* following check causes multiple lint messages */ if ( ((-1)>>1) != (-1) ) { DEC_API_TRC("H264SwDecInit# ERROR: Right shift is not signed"); return(H264SWDEC_INITFAIL); } /*lint -restore */ if (decInst == NULL) { DEC_API_TRC("H264SwDecInit# ERROR: decInst == NULL"); return(H264SWDEC_PARAM_ERR); } pDecCont = (decContainer_t *)H264SwDecMalloc(sizeof(decContainer_t)); if (pDecCont == NULL) { DEC_API_TRC("H264SwDecInit# ERROR: Memory allocation failed"); return(H264SWDEC_MEMFAIL); } #ifdef H264DEC_TRACE sprintf(pDecCont->str, "H264SwDecInit# decInst %p noOutputReordering %d", (void*)decInst, noOutputReordering); DEC_API_TRC(pDecCont->str); #endif rv = h264bsdInit(&pDecCont->storage, noOutputReordering); if (rv != HANTRO_OK) { H264SwDecRelease(pDecCont); return(H264SWDEC_MEMFAIL); } pDecCont->decStat = INITIALIZED; pDecCont->picNumber = 0; #ifdef H264DEC_TRACE sprintf(pDecCont->str, "H264SwDecInit# OK: return %p", (void*)pDecCont); DEC_API_TRC(pDecCont->str); #endif *decInst = (decContainer_t *)pDecCont; return(H264SWDEC_OK); } Commit Message: h264dec: check for overflows when calculating allocation size. Bug: 27855419 Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd CWE ID: CWE-119
H264SwDecRet H264SwDecInit(H264SwDecInst *decInst, u32 noOutputReordering) { u32 rv = 0; decContainer_t *pDecCont; DEC_API_TRC("H264SwDecInit#"); /* check that right shift on negative numbers is performed signed */ /*lint -save -e* following check causes multiple lint messages */ if ( ((-1)>>1) != (-1) ) { DEC_API_TRC("H264SwDecInit# ERROR: Right shift is not signed"); return(H264SWDEC_INITFAIL); } /*lint -restore */ if (decInst == NULL) { DEC_API_TRC("H264SwDecInit# ERROR: decInst == NULL"); return(H264SWDEC_PARAM_ERR); } pDecCont = (decContainer_t *)H264SwDecMalloc(sizeof(decContainer_t), 1); if (pDecCont == NULL) { DEC_API_TRC("H264SwDecInit# ERROR: Memory allocation failed"); return(H264SWDEC_MEMFAIL); } #ifdef H264DEC_TRACE sprintf(pDecCont->str, "H264SwDecInit# decInst %p noOutputReordering %d", (void*)decInst, noOutputReordering); DEC_API_TRC(pDecCont->str); #endif rv = h264bsdInit(&pDecCont->storage, noOutputReordering); if (rv != HANTRO_OK) { H264SwDecRelease(pDecCont); return(H264SWDEC_MEMFAIL); } pDecCont->decStat = INITIALIZED; pDecCont->picNumber = 0; #ifdef H264DEC_TRACE sprintf(pDecCont->str, "H264SwDecInit# OK: return %p", (void*)pDecCont); DEC_API_TRC(pDecCont->str); #endif *decInst = (decContainer_t *)pDecCont; return(H264SWDEC_OK); }
173,874
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; ssize_t j, y; MagickSizeType alpha_bits; PixelPacket *q; register ssize_t i, x; unsigned char a0, a1; size_t alpha, bits, code, alpha_code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x), Min(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read alpha values (8 bytes) */ a0 = (unsigned char) ReadBlobByte(image); a1 = (unsigned char) ReadBlobByte(image); alpha_bits = (MagickSizeType)ReadBlobLSBLong(image); alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); /* Extract alpha value */ alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7; if (alpha_code == 0) alpha = a0; else if (alpha_code == 1) alpha = a1; else if (a0 > a1) alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7; else if (alpha_code == 6) alpha = 0; else if (alpha_code == 7) alpha = 255; else alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) alpha)); q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } SkipDXTMipmaps(image, dds_info, 16); return MagickTrue; } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; ssize_t j, y; MagickSizeType alpha_bits; PixelPacket *q; register ssize_t i, x; unsigned char a0, a1; size_t alpha, bits, code, alpha_code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x), MagickMin(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read alpha values (8 bytes) */ a0 = (unsigned char) ReadBlobByte(image); a1 = (unsigned char) ReadBlobByte(image); alpha_bits = (MagickSizeType)ReadBlobLSBLong(image); alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); /* Extract alpha value */ alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7; if (alpha_code == 0) alpha = a0; else if (alpha_code == 1) alpha = a1; else if (a0 > a1) alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7; else if (alpha_code == 6) alpha = 0; else if (alpha_code == 7) alpha = 255; else alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) alpha)); q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } return(SkipDXTMipmaps(image,dds_info,16,exception)); }
168,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SeekHead::ParseEntry( IMkvReader* pReader, long long start, long long size_, Entry* pEntry) { if (size_ <= 0) return false; long long pos = start; const long long stop = start + size_; long len; const long long seekIdId = ReadUInt(pReader, pos, len); if (seekIdId != 0x13AB) //SeekID ID return false; if ((pos + len) > stop) return false; pos += len; //consume SeekID id const long long seekIdSize = ReadUInt(pReader, pos, len); if (seekIdSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; //consume size of field if ((pos + seekIdSize) > stop) return false; pEntry->id = ReadUInt(pReader, pos, len); //payload if (pEntry->id <= 0) return false; if (len != seekIdSize) return false; pos += seekIdSize; //consume SeekID payload const long long seekPosId = ReadUInt(pReader, pos, len); if (seekPosId != 0x13AC) //SeekPos ID return false; if ((pos + len) > stop) return false; pos += len; //consume id const long long seekPosSize = ReadUInt(pReader, pos, len); if (seekPosSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; //consume size if ((pos + seekPosSize) > stop) return false; pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize); if (pEntry->pos < 0) return false; pos += seekPosSize; //consume payload if (pos != stop) return false; return true; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
bool SeekHead::ParseEntry( bool SeekHead::ParseEntry(IMkvReader* pReader, long long start, long long size_, Entry* pEntry) { if (size_ <= 0) return false; long long pos = start; const long long stop = start + size_; long len; // parse the container for the level-1 element ID const long long seekIdId = ReadUInt(pReader, pos, len); // seekIdId; if (seekIdId != 0x13AB) // SeekID ID return false; if ((pos + len) > stop) return false; pos += len; // consume SeekID id const long long seekIdSize = ReadUInt(pReader, pos, len); if (seekIdSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; // consume size of field if ((pos + seekIdSize) > stop) return false; // Note that the SeekId payload really is serialized // as a "Matroska integer", not as a plain binary value. // In fact, Matroska requires that ID values in the // stream exactly match the binary representation as listed // in the Matroska specification. // // This parser is more liberal, and permits IDs to have // any width. (This could make the representation in the stream // different from what's in the spec, but it doesn't matter here, // since we always normalize "Matroska integer" values.) pEntry->id = ReadUInt(pReader, pos, len); // payload if (pEntry->id <= 0) return false; if (len != seekIdSize) return false; pos += seekIdSize; // consume SeekID payload const long long seekPosId = ReadUInt(pReader, pos, len); if (seekPosId != 0x13AC) // SeekPos ID return false; if ((pos + len) > stop) return false; pos += len; // consume id const long long seekPosSize = ReadUInt(pReader, pos, len); if (seekPosSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; // consume size if ((pos + seekPosSize) > stop) return false; pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize); if (pEntry->pos < 0) return false; pos += seekPosSize; // consume payload if (pos != stop) return false; return true; }
174,426
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: read_one_file(Image *image) { if (!(image->opts & READ_FILE) || (image->opts & USE_STDIO)) { /* memory or stdio. */ FILE *f = fopen(image->file_name, "rb"); if (f != NULL) { if (image->opts & READ_FILE) image->input_file = f; else /* memory */ { if (fseek(f, 0, SEEK_END) == 0) { long int cb = ftell(f); if (cb > 0 && (unsigned long int)cb < (size_t)~(size_t)0) { png_bytep b = voidcast(png_bytep, malloc((size_t)cb)); if (b != NULL) { rewind(f); if (fread(b, (size_t)cb, 1, f) == 1) { fclose(f); image->input_memory_size = cb; image->input_memory = b; } else { free(b); return logclose(image, f, image->file_name, ": read failed: "); } } else return logclose(image, f, image->file_name, ": out of memory: "); } else if (cb == 0) return logclose(image, f, image->file_name, ": zero length: "); else return logclose(image, f, image->file_name, ": tell failed: "); } else return logclose(image, f, image->file_name, ": seek failed: "); } } else return logerror(image, image->file_name, ": open failed: ", strerror(errno)); } return read_file(image, FORMAT_NO_CHANGE, NULL); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
read_one_file(Image *image) { if (!(image->opts & READ_FILE) || (image->opts & USE_STDIO)) { /* memory or stdio. */ FILE *f = fopen(image->file_name, "rb"); if (f != NULL) { if (image->opts & READ_FILE) image->input_file = f; else /* memory */ { if (fseek(f, 0, SEEK_END) == 0) { long int cb = ftell(f); if (cb > 0) { #ifndef __COVERITY__ if ((unsigned long int)cb <= (size_t)~(size_t)0) #endif { png_bytep b = voidcast(png_bytep, malloc((size_t)cb)); if (b != NULL) { rewind(f); if (fread(b, (size_t)cb, 1, f) == 1) { fclose(f); image->input_memory_size = cb; image->input_memory = b; } else { free(b); return logclose(image, f, image->file_name, ": read failed: "); } } else return logclose(image, f, image->file_name, ": out of memory: "); } else return logclose(image, f, image->file_name, ": file too big for this architecture: "); /* cb is the length of the file as a (long) and * this is greater than the maximum amount of * memory that can be requested from malloc. */ } else if (cb == 0) return logclose(image, f, image->file_name, ": zero length: "); else return logclose(image, f, image->file_name, ": tell failed: "); } else return logclose(image, f, image->file_name, ": seek failed: "); } } else return logerror(image, image->file_name, ": open failed: ", strerror(errno)); } return read_file(image, FORMAT_NO_CHANGE, NULL); }
173,596
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FrameLoader::startLoad(FrameLoadRequest& frameLoadRequest, FrameLoadType type, NavigationPolicy navigationPolicy) { ASSERT(client()->hasWebView()); if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal) return; NavigationType navigationType = determineNavigationType(type, frameLoadRequest.resourceRequest().httpBody() || frameLoadRequest.form(), frameLoadRequest.triggeringEvent()); frameLoadRequest.resourceRequest().setRequestContext(determineRequestContextFromNavigationType(navigationType)); frameLoadRequest.resourceRequest().setFrameType(m_frame->isMainFrame() ? WebURLRequest::FrameTypeTopLevel : WebURLRequest::FrameTypeNested); ResourceRequest& request = frameLoadRequest.resourceRequest(); if (!shouldContinueForNavigationPolicy(request, frameLoadRequest.substituteData(), nullptr, frameLoadRequest.shouldCheckMainWorldContentSecurityPolicy(), navigationType, navigationPolicy, type == FrameLoadTypeReplaceCurrentItem, frameLoadRequest.clientRedirect() == ClientRedirectPolicy::ClientRedirect)) return; if (!shouldClose(navigationType == NavigationTypeReload)) return; m_frame->document()->cancelParsing(); detachDocumentLoader(m_provisionalDocumentLoader); if (!m_frame->host()) return; m_provisionalDocumentLoader = client()->createDocumentLoader(m_frame, request, frameLoadRequest.substituteData().isValid() ? frameLoadRequest.substituteData() : defaultSubstituteDataForURL(request.url())); m_provisionalDocumentLoader->setNavigationType(navigationType); m_provisionalDocumentLoader->setReplacesCurrentHistoryItem(type == FrameLoadTypeReplaceCurrentItem); m_provisionalDocumentLoader->setIsClientRedirect(frameLoadRequest.clientRedirect() == ClientRedirectPolicy::ClientRedirect); InspectorInstrumentation::didStartProvisionalLoad(m_frame); m_frame->navigationScheduler().cancel(); m_checkTimer.stop(); m_loadType = type; if (frameLoadRequest.form()) client()->dispatchWillSubmitForm(frameLoadRequest.form()); m_progressTracker->progressStarted(); if (m_provisionalDocumentLoader->isClientRedirect()) m_provisionalDocumentLoader->appendRedirect(m_frame->document()->url()); m_provisionalDocumentLoader->appendRedirect(m_provisionalDocumentLoader->request().url()); double triggeringEventTime = frameLoadRequest.triggeringEvent() ? frameLoadRequest.triggeringEvent()->platformTimeStamp() : 0; client()->dispatchDidStartProvisionalLoad(triggeringEventTime); ASSERT(m_provisionalDocumentLoader); m_provisionalDocumentLoader->startLoadingMainResource(); takeObjectSnapshot(); } Commit Message: Disable frame navigations during DocumentLoader detach in FrameLoader::startLoad BUG=613266 Review-Url: https://codereview.chromium.org/2006033002 Cr-Commit-Position: refs/heads/master@{#396241} CWE ID: CWE-284
void FrameLoader::startLoad(FrameLoadRequest& frameLoadRequest, FrameLoadType type, NavigationPolicy navigationPolicy) { ASSERT(client()->hasWebView()); if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal) return; NavigationType navigationType = determineNavigationType(type, frameLoadRequest.resourceRequest().httpBody() || frameLoadRequest.form(), frameLoadRequest.triggeringEvent()); frameLoadRequest.resourceRequest().setRequestContext(determineRequestContextFromNavigationType(navigationType)); frameLoadRequest.resourceRequest().setFrameType(m_frame->isMainFrame() ? WebURLRequest::FrameTypeTopLevel : WebURLRequest::FrameTypeNested); ResourceRequest& request = frameLoadRequest.resourceRequest(); if (!shouldContinueForNavigationPolicy(request, frameLoadRequest.substituteData(), nullptr, frameLoadRequest.shouldCheckMainWorldContentSecurityPolicy(), navigationType, navigationPolicy, type == FrameLoadTypeReplaceCurrentItem, frameLoadRequest.clientRedirect() == ClientRedirectPolicy::ClientRedirect)) return; if (!shouldClose(navigationType == NavigationTypeReload)) return; m_frame->document()->cancelParsing(); if (m_provisionalDocumentLoader) { FrameNavigationDisabler navigationDisabler(*m_frame); detachDocumentLoader(m_provisionalDocumentLoader); } if (!m_frame->host()) return; m_provisionalDocumentLoader = client()->createDocumentLoader(m_frame, request, frameLoadRequest.substituteData().isValid() ? frameLoadRequest.substituteData() : defaultSubstituteDataForURL(request.url())); m_provisionalDocumentLoader->setNavigationType(navigationType); m_provisionalDocumentLoader->setReplacesCurrentHistoryItem(type == FrameLoadTypeReplaceCurrentItem); m_provisionalDocumentLoader->setIsClientRedirect(frameLoadRequest.clientRedirect() == ClientRedirectPolicy::ClientRedirect); InspectorInstrumentation::didStartProvisionalLoad(m_frame); m_frame->navigationScheduler().cancel(); m_checkTimer.stop(); m_loadType = type; if (frameLoadRequest.form()) client()->dispatchWillSubmitForm(frameLoadRequest.form()); m_progressTracker->progressStarted(); if (m_provisionalDocumentLoader->isClientRedirect()) m_provisionalDocumentLoader->appendRedirect(m_frame->document()->url()); m_provisionalDocumentLoader->appendRedirect(m_provisionalDocumentLoader->request().url()); double triggeringEventTime = frameLoadRequest.triggeringEvent() ? frameLoadRequest.triggeringEvent()->platformTimeStamp() : 0; client()->dispatchDidStartProvisionalLoad(triggeringEventTime); ASSERT(m_provisionalDocumentLoader); m_provisionalDocumentLoader->startLoadingMainResource(); takeObjectSnapshot(); }
172,258
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int l2tp_ip_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); size_t copied = 0; int err = -EOPNOTSUPP; struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*sin); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; sin->sin_port = 0; memset(&sin->sin_zero, 0, sizeof(sin->sin_zero)); } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls Only update *addr_len when we actually fill in sockaddr, otherwise we can return uninitialized memory from the stack to the caller in the recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL) checks because we only get called with a valid addr_len pointer either from sock_common_recvmsg or inet_recvmsg. If a blocking read waits on a socket which is concurrently shut down we now return zero and set msg_msgnamelen to 0. Reported-by: mpb <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int l2tp_ip_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); size_t copied = 0; int err = -EOPNOTSUPP; struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; struct sk_buff *skb; if (flags & MSG_OOB) goto out; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; sin->sin_port = 0; memset(&sin->sin_zero, 0, sizeof(sin->sin_zero)); *addr_len = sizeof(*sin); } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; }
166,482
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DOMHandler::DOMHandler() : DevToolsDomainHandler(DOM::Metainfo::domainName), host_(nullptr) { } Commit Message: [DevTools] Guard DOM.setFileInputFiles under MayAffectLocalFiles Bug: 805557 Change-Id: Ib6f37ec6e1d091ee54621cc0c5c44f1a6beab10f Reviewed-on: https://chromium-review.googlesource.com/c/1334847 Reviewed-by: Pavel Feldman <[email protected]> Commit-Queue: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#607902} CWE ID: CWE-254
DOMHandler::DOMHandler() DOMHandler::DOMHandler(bool allow_file_access) : DevToolsDomainHandler(DOM::Metainfo::domainName),
173,112
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int magicmouse_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct magicmouse_sc *msc = hid_get_drvdata(hdev); struct input_dev *input = msc->input; int x = 0, y = 0, ii, clicks = 0, npoints; switch (data[0]) { case TRACKPAD_REPORT_ID: /* Expect four bytes of prefix, and N*9 bytes of touch data. */ if (size < 4 || ((size - 4) % 9) != 0) return 0; npoints = (size - 4) / 9; msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 9 + 4); clicks = data[1]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[1] >> 6 | data[2] << 2 | data[3] << 10; */ break; case MOUSE_REPORT_ID: /* Expect six bytes of prefix, and N*8 bytes of touch data. */ if (size < 6 || ((size - 6) % 8) != 0) return 0; npoints = (size - 6) / 8; msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 8 + 6); /* When emulating three-button mode, it is important * to have the current touch information before * generating a click event. */ x = (int)(((data[3] & 0x0c) << 28) | (data[1] << 22)) >> 22; y = (int)(((data[3] & 0x30) << 26) | (data[2] << 22)) >> 22; clicks = data[3]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[3] >> 6 | data[4] << 2 | data[5] << 10; */ break; case DOUBLE_REPORT_ID: /* Sometimes the trackpad sends two touch reports in one * packet. */ magicmouse_raw_event(hdev, report, data + 2, data[1]); magicmouse_raw_event(hdev, report, data + 2 + data[1], size - 2 - data[1]); break; default: return 0; } if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE) { magicmouse_emit_buttons(msc, clicks & 3); input_report_rel(input, REL_X, x); input_report_rel(input, REL_Y, y); } else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */ input_report_key(input, BTN_MOUSE, clicks & 1); input_mt_report_pointer_emulation(input, true); } input_sync(input); return 1; } Commit Message: HID: magicmouse: sanity check report size in raw_event() callback The report passed to us from transport driver could potentially be arbitrarily large, therefore we better sanity-check it so that magicmouse_emit_touch() gets only valid values of raw_id. Cc: [email protected] Reported-by: Steven Vittitoe <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static int magicmouse_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct magicmouse_sc *msc = hid_get_drvdata(hdev); struct input_dev *input = msc->input; int x = 0, y = 0, ii, clicks = 0, npoints; switch (data[0]) { case TRACKPAD_REPORT_ID: /* Expect four bytes of prefix, and N*9 bytes of touch data. */ if (size < 4 || ((size - 4) % 9) != 0) return 0; npoints = (size - 4) / 9; if (npoints > 15) { hid_warn(hdev, "invalid size value (%d) for TRACKPAD_REPORT_ID\n", size); return 0; } msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 9 + 4); clicks = data[1]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[1] >> 6 | data[2] << 2 | data[3] << 10; */ break; case MOUSE_REPORT_ID: /* Expect six bytes of prefix, and N*8 bytes of touch data. */ if (size < 6 || ((size - 6) % 8) != 0) return 0; npoints = (size - 6) / 8; if (npoints > 15) { hid_warn(hdev, "invalid size value (%d) for MOUSE_REPORT_ID\n", size); return 0; } msc->ntouches = 0; for (ii = 0; ii < npoints; ii++) magicmouse_emit_touch(msc, ii, data + ii * 8 + 6); /* When emulating three-button mode, it is important * to have the current touch information before * generating a click event. */ x = (int)(((data[3] & 0x0c) << 28) | (data[1] << 22)) >> 22; y = (int)(((data[3] & 0x30) << 26) | (data[2] << 22)) >> 22; clicks = data[3]; /* The following bits provide a device specific timestamp. They * are unused here. * * ts = data[3] >> 6 | data[4] << 2 | data[5] << 10; */ break; case DOUBLE_REPORT_ID: /* Sometimes the trackpad sends two touch reports in one * packet. */ magicmouse_raw_event(hdev, report, data + 2, data[1]); magicmouse_raw_event(hdev, report, data + 2 + data[1], size - 2 - data[1]); break; default: return 0; } if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE) { magicmouse_emit_buttons(msc, clicks & 3); input_report_rel(input, REL_X, x); input_report_rel(input, REL_Y, y); } else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */ input_report_key(input, BTN_MOUSE, clicks & 1); input_mt_report_pointer_emulation(input, true); } input_sync(input); return 1; }
166,379
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)object; if (intern->oth_handler && intern->oth_handler->dtor) { intern->oth_handler->dtor(intern TSRMLS_CC); } zend_object_std_dtor(&intern->std TSRMLS_CC); if (intern->_path) { efree(intern->_path); } if (intern->file_name) { efree(intern->file_name); } switch(intern->type) { case SPL_FS_INFO: break; case SPL_FS_DIR: if (intern->u.dir.dirp) { php_stream_close(intern->u.dir.dirp); intern->u.dir.dirp = NULL; } if (intern->u.dir.sub_path) { efree(intern->u.dir.sub_path); } break; case SPL_FS_FILE: if (intern->u.file.stream) { if (intern->u.file.zcontext) { /* zend_list_delref(Z_RESVAL_P(intern->zcontext));*/ } if (!intern->u.file.stream->is_persistent) { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE); } else { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT); } if (intern->u.file.open_mode) { efree(intern->u.file.open_mode); } if (intern->orig_path) { efree(intern->orig_path); } } spl_filesystem_file_free_line(intern TSRMLS_CC); break; } { zend_object_iterator *iterator; iterator = (zend_object_iterator*) spl_filesystem_object_to_iterator(intern); if (iterator->data != NULL) { iterator->data = NULL; iterator->funcs->dtor(iterator TSRMLS_CC); } } efree(object); } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)object; if (intern->oth_handler && intern->oth_handler->dtor) { intern->oth_handler->dtor(intern TSRMLS_CC); } zend_object_std_dtor(&intern->std TSRMLS_CC); if (intern->_path) { efree(intern->_path); } if (intern->file_name) { efree(intern->file_name); } switch(intern->type) { case SPL_FS_INFO: break; case SPL_FS_DIR: if (intern->u.dir.dirp) { php_stream_close(intern->u.dir.dirp); intern->u.dir.dirp = NULL; } if (intern->u.dir.sub_path) { efree(intern->u.dir.sub_path); } break; case SPL_FS_FILE: if (intern->u.file.stream) { if (intern->u.file.zcontext) { /* zend_list_delref(Z_RESVAL_P(intern->zcontext));*/ } if (!intern->u.file.stream->is_persistent) { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE); } else { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT); } if (intern->u.file.open_mode) { efree(intern->u.file.open_mode); } if (intern->orig_path) { efree(intern->orig_path); } } spl_filesystem_file_free_line(intern TSRMLS_CC); break; } { zend_object_iterator *iterator; iterator = (zend_object_iterator*) spl_filesystem_object_to_iterator(intern); if (iterator->data != NULL) { iterator->data = NULL; iterator->funcs->dtor(iterator TSRMLS_CC); } } efree(object); } /* }}} */
167,083
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: BOOL transport_connect_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->layer == TRANSPORT_LAYER_TSG) return TRUE; if (!transport_connect_tls(transport)) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { if (!connectErrorCode) connectErrorCode = AUTHENTICATIONERROR; fprintf(stderr, "Authentication failure, check credentials.\n" "If credentials are valid, the NTLMSSP implementation may be to blame.\n"); credssp_free(transport->credssp); return FALSE; } credssp_free(transport->credssp); return TRUE; } Commit Message: nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished. CWE ID: CWE-476
BOOL transport_connect_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->layer == TRANSPORT_LAYER_TSG) return TRUE; if (!transport_connect_tls(transport)) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { if (!connectErrorCode) connectErrorCode = AUTHENTICATIONERROR; fprintf(stderr, "Authentication failure, check credentials.\n" "If credentials are valid, the NTLMSSP implementation may be to blame.\n"); credssp_free(transport->credssp); transport->credssp = NULL; return FALSE; } credssp_free(transport->credssp); return TRUE; }
167,602
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DelayedExecutor::delayedExecute(const QString &udi) { Solid::Device device(udi); QString exec = m_service.exec(); MacroExpander mx(device); mx.expandMacros(exec); KRun::runCommand(exec, QString(), m_service.icon(), 0); deleteLater(); } Commit Message: CWE ID: CWE-78
void DelayedExecutor::delayedExecute(const QString &udi) { Solid::Device device(udi); QString exec = m_service.exec(); MacroExpander mx(device); mx.expandMacrosShellQuote(exec); KRun::runCommand(exec, QString(), m_service.icon(), 0); deleteLater(); }
165,024
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual status_t configureVideoTunnelMode( node_id node, OMX_U32 portIndex, OMX_BOOL tunneled, OMX_U32 audioHwSync, native_handle_t **sidebandHandle ) { Parcel data, reply; data.writeInterfaceToken(IOMX::getInterfaceDescriptor()); data.writeInt32((int32_t)node); data.writeInt32(portIndex); data.writeInt32((int32_t)tunneled); data.writeInt32(audioHwSync); remote()->transact(CONFIGURE_VIDEO_TUNNEL_MODE, data, &reply); status_t err = reply.readInt32(); if (sidebandHandle) { *sidebandHandle = (native_handle_t *)reply.readNativeHandle(); } return err; } Commit Message: IOMX.cpp uninitialized pointer in BnOMX::onTransact This can lead to local code execution in media server. Fix initializes the pointer and checks the error conditions before returning Bug: 26403627 Change-Id: I7fa90682060148448dba01d6acbe3471d1ddb500 CWE ID: CWE-264
virtual status_t configureVideoTunnelMode( node_id node, OMX_U32 portIndex, OMX_BOOL tunneled, OMX_U32 audioHwSync, native_handle_t **sidebandHandle ) { Parcel data, reply; data.writeInterfaceToken(IOMX::getInterfaceDescriptor()); data.writeInt32((int32_t)node); data.writeInt32(portIndex); data.writeInt32((int32_t)tunneled); data.writeInt32(audioHwSync); remote()->transact(CONFIGURE_VIDEO_TUNNEL_MODE, data, &reply); status_t err = reply.readInt32(); if (err == OK && sidebandHandle) { *sidebandHandle = (native_handle_t *)reply.readNativeHandle(); } return err; }
173,897
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int translate_desc(struct vhost_dev *dev, u64 addr, u32 len, struct iovec iov[], int iov_size) { const struct vhost_memory_region *reg; struct vhost_memory *mem; struct iovec *_iov; u64 s = 0; int ret = 0; rcu_read_lock(); mem = rcu_dereference(dev->memory); while ((u64)len > s) { u64 size; if (unlikely(ret >= iov_size)) { ret = -ENOBUFS; break; } reg = find_region(mem, addr, len); if (unlikely(!reg)) { ret = -EFAULT; break; } _iov = iov + ret; size = reg->memory_size - addr + reg->guest_phys_addr; _iov->iov_len = min((u64)len, size); _iov->iov_base = (void __user *)(unsigned long) (reg->userspace_addr + addr - reg->guest_phys_addr); s += size; addr += size; ++ret; } rcu_read_unlock(); return ret; } Commit Message: vhost: fix length for cross region descriptor If a single descriptor crosses a region, the second chunk length should be decremented by size translated so far, instead it includes the full descriptor length. Signed-off-by: Michael S. Tsirkin <[email protected]> Acked-by: Jason Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static int translate_desc(struct vhost_dev *dev, u64 addr, u32 len, struct iovec iov[], int iov_size) { const struct vhost_memory_region *reg; struct vhost_memory *mem; struct iovec *_iov; u64 s = 0; int ret = 0; rcu_read_lock(); mem = rcu_dereference(dev->memory); while ((u64)len > s) { u64 size; if (unlikely(ret >= iov_size)) { ret = -ENOBUFS; break; } reg = find_region(mem, addr, len); if (unlikely(!reg)) { ret = -EFAULT; break; } _iov = iov + ret; size = reg->memory_size - addr + reg->guest_phys_addr; _iov->iov_len = min((u64)len - s, size); _iov->iov_base = (void __user *)(unsigned long) (reg->userspace_addr + addr - reg->guest_phys_addr); s += size; addr += size; ++ret; } rcu_read_unlock(); return ret; }
166,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int aesni_cbc_hmac_sha256_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_HMAC_SHA256 *key = data(ctx); unsigned int l; size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and * later */ sha_off = 0; # if defined(STITCHED_CALL) size_t aes_off = 0, blocks; sha_off = SHA256_CBLOCK - key->md.num; # endif key->payload_length = NO_PAYLOAD_LENGTH; if (len % AES_BLOCK_SIZE) return 0; if (ctx->encrypt) { if (plen == NO_PAYLOAD_LENGTH) plen = len; else if (len != ((plen + SHA256_DIGEST_LENGTH + AES_BLOCK_SIZE) & -AES_BLOCK_SIZE)) return 0; else if (key->aux.tls_ver >= TLS1_1_VERSION) iv = AES_BLOCK_SIZE; # if defined(STITCHED_CALL) /* * Assembly stitch handles AVX-capable processors, but its * performance is not optimal on AMD Jaguar, ~40% worse, for * unknown reasons. Incidentally processor in question supports * AVX, but not AMD-specific XOP extension, which can be used * to identify it and avoid stitch invocation. So that after we * establish that current CPU supports AVX, we even see if it's * either even XOP-capable Bulldozer-based or GenuineIntel one. */ if (OPENSSL_ia32cap_P[1] & (1 << (60 - 32)) && /* AVX? */ ((OPENSSL_ia32cap_P[1] & (1 << (43 - 32))) /* XOP? */ | (OPENSSL_ia32cap_P[0] & (1<<30))) && /* "Intel CPU"? */ plen > (sha_off + iv) && (blocks = (plen - (sha_off + iv)) / SHA256_CBLOCK)) { SHA256_Update(&key->md, in + iv, sha_off); (void)aesni_cbc_sha256_enc(in, out, blocks, &key->ks, ctx->iv, &key->md, in + iv + sha_off); blocks *= SHA256_CBLOCK; aes_off += blocks; sha_off += blocks; key->md.Nh += blocks >> 29; key->md.Nl += blocks <<= 3; if (key->md.Nl < (unsigned int)blocks) key->md.Nh++; } else { sha_off = 0; } # endif sha_off += iv; SHA256_Update(&key->md, in + sha_off, plen - sha_off); if (plen != len) { /* "TLS" mode of operation */ if (in != out) memcpy(out + aes_off, in + aes_off, plen - aes_off); /* calculate HMAC and append it to payload */ SHA256_Final(out + plen, &key->md); key->md = key->tail; SHA256_Update(&key->md, out + plen, SHA256_DIGEST_LENGTH); SHA256_Final(out + plen, &key->md); /* pad the payload|hmac */ plen += SHA256_DIGEST_LENGTH; for (l = len - plen - 1; plen < len; plen++) out[plen] = l; /* encrypt HMAC|padding at once */ aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off, &key->ks, ctx->iv, 1); } else { aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off, &key->ks, ctx->iv, 1); } } else { union { unsigned int u[SHA256_DIGEST_LENGTH / sizeof(unsigned int)]; unsigned char c[64 + SHA256_DIGEST_LENGTH]; } mac, *pmac; /* arrange cache line alignment */ pmac = (void *)(((size_t)mac.c + 63) & ((size_t)0 - 64)); /* decrypt HMAC|padding at once */ aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0); if (plen != NO_PAYLOAD_LENGTH) { /* "TLS" mode of operation */ size_t inp_len, mask, j, i; unsigned int res, maxpad, pad, bitlen; int ret = 1; union { unsigned int u[SHA_LBLOCK]; unsigned char c[SHA256_CBLOCK]; } *data = (void *)key->md.data; if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3]) >= TLS1_1_VERSION) iv = AES_BLOCK_SIZE; if (len < (iv + SHA256_DIGEST_LENGTH + 1)) return 0; /* omit explicit iv */ out += iv; len -= iv; /* figure out payload length */ pad = out[len - 1]; maxpad = len - (SHA256_DIGEST_LENGTH + 1); maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8); maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8); maxpad &= 255; inp_len = len - (SHA256_DIGEST_LENGTH + pad + 1); mask = (0 - ((inp_len - len) >> (sizeof(inp_len) * 8 - 1))); inp_len &= mask; key->aux.tls_aad[plen - 1] = inp_len; /* calculate HMAC */ key->md = key->head; SHA256_Update(&key->md, key->aux.tls_aad, plen); # if 1 len -= SHA256_DIGEST_LENGTH; /* amend mac */ if (len >= (256 + SHA256_CBLOCK)) { j = (len - (256 + SHA256_CBLOCK)) & (0 - SHA256_CBLOCK); j += SHA256_CBLOCK - key->md.num; SHA256_Update(&key->md, out, j); out += j; len -= j; inp_len -= j; } /* but pretend as if we hashed padded payload */ bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */ # ifdef BSWAP4 bitlen = BSWAP4(bitlen); # else mac.c[0] = 0; mac.c[1] = (unsigned char)(bitlen >> 16); mac.c[2] = (unsigned char)(bitlen >> 8); mac.c[3] = (unsigned char)bitlen; bitlen = mac.u[0]; # endif pmac->u[0] = 0; pmac->u[1] = 0; pmac->u[2] = 0; pmac->u[3] = 0; pmac->u[4] = 0; pmac->u[5] = 0; pmac->u[6] = 0; pmac->u[7] = 0; for (res = key->md.num, j = 0; j < len; j++) { size_t c = out[j]; mask = (j - inp_len) >> (sizeof(j) * 8 - 8); c &= mask; c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8)); data->c[res++] = (unsigned char)c; if (res != SHA256_CBLOCK) continue; /* j is not incremented yet */ mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1)); data->u[SHA_LBLOCK - 1] |= bitlen & mask; sha256_block_data_order(&key->md, data, 1); mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h[0] & mask; pmac->u[1] |= key->md.h[1] & mask; pmac->u[2] |= key->md.h[2] & mask; pmac->u[3] |= key->md.h[3] & mask; pmac->u[4] |= key->md.h[4] & mask; pmac->u[5] |= key->md.h[5] & mask; pmac->u[6] |= key->md.h[6] & mask; pmac->u[7] |= key->md.h[7] & mask; res = 0; } for (i = res; i < SHA256_CBLOCK; i++, j++) data->c[i] = 0; if (res > SHA256_CBLOCK - 8) { mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1)); data->u[SHA_LBLOCK - 1] |= bitlen & mask; sha256_block_data_order(&key->md, data, 1); mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h[0] & mask; pmac->u[1] |= key->md.h[1] & mask; pmac->u[2] |= key->md.h[2] & mask; pmac->u[3] |= key->md.h[3] & mask; pmac->u[4] |= key->md.h[4] & mask; pmac->u[5] |= key->md.h[5] & mask; pmac->u[6] |= key->md.h[6] & mask; pmac->u[7] |= key->md.h[7] & mask; memset(data, 0, SHA256_CBLOCK); j += 64; } data->u[SHA_LBLOCK - 1] = bitlen; sha256_block_data_order(&key->md, data, 1); mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h[0] & mask; pmac->u[1] |= key->md.h[1] & mask; pmac->u[2] |= key->md.h[2] & mask; pmac->u[3] |= key->md.h[3] & mask; pmac->u[4] |= key->md.h[4] & mask; pmac->u[5] |= key->md.h[5] & mask; pmac->u[6] |= key->md.h[6] & mask; pmac->u[7] |= key->md.h[7] & mask; # ifdef BSWAP4 pmac->u[0] = BSWAP4(pmac->u[0]); pmac->u[1] = BSWAP4(pmac->u[1]); pmac->u[2] = BSWAP4(pmac->u[2]); pmac->u[3] = BSWAP4(pmac->u[3]); pmac->u[4] = BSWAP4(pmac->u[4]); pmac->u[5] = BSWAP4(pmac->u[5]); pmac->u[6] = BSWAP4(pmac->u[6]); pmac->u[7] = BSWAP4(pmac->u[7]); # else for (i = 0; i < 8; i++) { res = pmac->u[i]; pmac->c[4 * i + 0] = (unsigned char)(res >> 24); pmac->c[4 * i + 1] = (unsigned char)(res >> 16); pmac->c[4 * i + 2] = (unsigned char)(res >> 8); pmac->c[4 * i + 3] = (unsigned char)res; } # endif len += SHA256_DIGEST_LENGTH; # else SHA256_Update(&key->md, out, inp_len); res = key->md.num; SHA256_Final(pmac->c, &key->md); { unsigned int inp_blocks, pad_blocks; /* but pretend as if we hashed padded payload */ inp_blocks = 1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1)); res += (unsigned int)(len - inp_len); pad_blocks = res / SHA256_CBLOCK; res %= SHA256_CBLOCK; pad_blocks += 1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1)); for (; inp_blocks < pad_blocks; inp_blocks++) sha1_block_data_order(&key->md, data, 1); } # endif key->md = key->tail; SHA256_Update(&key->md, pmac->c, SHA256_DIGEST_LENGTH); SHA256_Final(pmac->c, &key->md); /* verify HMAC */ out += inp_len; len -= inp_len; # if 1 { unsigned char *p = out + len - 1 - maxpad - SHA256_DIGEST_LENGTH; size_t off = out - p; unsigned int c, cmask; maxpad += SHA256_DIGEST_LENGTH; for (res = 0, i = 0, j = 0; j < maxpad; j++) { c = p[j]; cmask = ((int)(j - off - SHA256_DIGEST_LENGTH)) >> (sizeof(int) * 8 - 1); res |= (c ^ pad) & ~cmask; /* ... and padding */ cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1); res |= (c ^ pmac->c[i]) & cmask; i += 1 & cmask; } maxpad -= SHA256_DIGEST_LENGTH; res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; } # else for (res = 0, i = 0; i < SHA256_DIGEST_LENGTH; i++) res |= out[i] ^ pmac->c[i]; res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; /* verify padding */ pad = (pad & ~res) | (maxpad & res); out = out + len - 1 - pad; for (res = 0, i = 0; i < pad; i++) res |= out[i] ^ pad; res = (0 - res) >> (sizeof(res) * 8 - 1); ret &= (int)~res; # endif return ret; } else { SHA256_Update(&key->md, out, len); } } return 1; } Commit Message: CWE ID: CWE-310
static int aesni_cbc_hmac_sha256_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_HMAC_SHA256 *key = data(ctx); unsigned int l; size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and * later */ sha_off = 0; # if defined(STITCHED_CALL) size_t aes_off = 0, blocks; sha_off = SHA256_CBLOCK - key->md.num; # endif key->payload_length = NO_PAYLOAD_LENGTH; if (len % AES_BLOCK_SIZE) return 0; if (ctx->encrypt) { if (plen == NO_PAYLOAD_LENGTH) plen = len; else if (len != ((plen + SHA256_DIGEST_LENGTH + AES_BLOCK_SIZE) & -AES_BLOCK_SIZE)) return 0; else if (key->aux.tls_ver >= TLS1_1_VERSION) iv = AES_BLOCK_SIZE; # if defined(STITCHED_CALL) /* * Assembly stitch handles AVX-capable processors, but its * performance is not optimal on AMD Jaguar, ~40% worse, for * unknown reasons. Incidentally processor in question supports * AVX, but not AMD-specific XOP extension, which can be used * to identify it and avoid stitch invocation. So that after we * establish that current CPU supports AVX, we even see if it's * either even XOP-capable Bulldozer-based or GenuineIntel one. */ if (OPENSSL_ia32cap_P[1] & (1 << (60 - 32)) && /* AVX? */ ((OPENSSL_ia32cap_P[1] & (1 << (43 - 32))) /* XOP? */ | (OPENSSL_ia32cap_P[0] & (1<<30))) && /* "Intel CPU"? */ plen > (sha_off + iv) && (blocks = (plen - (sha_off + iv)) / SHA256_CBLOCK)) { SHA256_Update(&key->md, in + iv, sha_off); (void)aesni_cbc_sha256_enc(in, out, blocks, &key->ks, ctx->iv, &key->md, in + iv + sha_off); blocks *= SHA256_CBLOCK; aes_off += blocks; sha_off += blocks; key->md.Nh += blocks >> 29; key->md.Nl += blocks <<= 3; if (key->md.Nl < (unsigned int)blocks) key->md.Nh++; } else { sha_off = 0; } # endif sha_off += iv; SHA256_Update(&key->md, in + sha_off, plen - sha_off); if (plen != len) { /* "TLS" mode of operation */ if (in != out) memcpy(out + aes_off, in + aes_off, plen - aes_off); /* calculate HMAC and append it to payload */ SHA256_Final(out + plen, &key->md); key->md = key->tail; SHA256_Update(&key->md, out + plen, SHA256_DIGEST_LENGTH); SHA256_Final(out + plen, &key->md); /* pad the payload|hmac */ plen += SHA256_DIGEST_LENGTH; for (l = len - plen - 1; plen < len; plen++) out[plen] = l; /* encrypt HMAC|padding at once */ aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off, &key->ks, ctx->iv, 1); } else { aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off, &key->ks, ctx->iv, 1); } } else { union { unsigned int u[SHA256_DIGEST_LENGTH / sizeof(unsigned int)]; unsigned char c[64 + SHA256_DIGEST_LENGTH]; } mac, *pmac; /* arrange cache line alignment */ pmac = (void *)(((size_t)mac.c + 63) & ((size_t)0 - 64)); /* decrypt HMAC|padding at once */ aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0); if (plen != NO_PAYLOAD_LENGTH) { /* "TLS" mode of operation */ size_t inp_len, mask, j, i; unsigned int res, maxpad, pad, bitlen; int ret = 1; union { unsigned int u[SHA_LBLOCK]; unsigned char c[SHA256_CBLOCK]; } *data = (void *)key->md.data; if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3]) >= TLS1_1_VERSION) iv = AES_BLOCK_SIZE; if (len < (iv + SHA256_DIGEST_LENGTH + 1)) return 0; /* omit explicit iv */ out += iv; len -= iv; /* figure out payload length */ pad = out[len - 1]; maxpad = len - (SHA256_DIGEST_LENGTH + 1); maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8); maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8); maxpad &= 255; ret &= constant_time_ge(maxpad, pad); inp_len = len - (SHA256_DIGEST_LENGTH + pad + 1); mask = (0 - ((inp_len - len) >> (sizeof(inp_len) * 8 - 1))); inp_len &= mask; key->aux.tls_aad[plen - 1] = inp_len; /* calculate HMAC */ key->md = key->head; SHA256_Update(&key->md, key->aux.tls_aad, plen); # if 1 len -= SHA256_DIGEST_LENGTH; /* amend mac */ if (len >= (256 + SHA256_CBLOCK)) { j = (len - (256 + SHA256_CBLOCK)) & (0 - SHA256_CBLOCK); j += SHA256_CBLOCK - key->md.num; SHA256_Update(&key->md, out, j); out += j; len -= j; inp_len -= j; } /* but pretend as if we hashed padded payload */ bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */ # ifdef BSWAP4 bitlen = BSWAP4(bitlen); # else mac.c[0] = 0; mac.c[1] = (unsigned char)(bitlen >> 16); mac.c[2] = (unsigned char)(bitlen >> 8); mac.c[3] = (unsigned char)bitlen; bitlen = mac.u[0]; # endif pmac->u[0] = 0; pmac->u[1] = 0; pmac->u[2] = 0; pmac->u[3] = 0; pmac->u[4] = 0; pmac->u[5] = 0; pmac->u[6] = 0; pmac->u[7] = 0; for (res = key->md.num, j = 0; j < len; j++) { size_t c = out[j]; mask = (j - inp_len) >> (sizeof(j) * 8 - 8); c &= mask; c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8)); data->c[res++] = (unsigned char)c; if (res != SHA256_CBLOCK) continue; /* j is not incremented yet */ mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1)); data->u[SHA_LBLOCK - 1] |= bitlen & mask; sha256_block_data_order(&key->md, data, 1); mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h[0] & mask; pmac->u[1] |= key->md.h[1] & mask; pmac->u[2] |= key->md.h[2] & mask; pmac->u[3] |= key->md.h[3] & mask; pmac->u[4] |= key->md.h[4] & mask; pmac->u[5] |= key->md.h[5] & mask; pmac->u[6] |= key->md.h[6] & mask; pmac->u[7] |= key->md.h[7] & mask; res = 0; } for (i = res; i < SHA256_CBLOCK; i++, j++) data->c[i] = 0; if (res > SHA256_CBLOCK - 8) { mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1)); data->u[SHA_LBLOCK - 1] |= bitlen & mask; sha256_block_data_order(&key->md, data, 1); mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h[0] & mask; pmac->u[1] |= key->md.h[1] & mask; pmac->u[2] |= key->md.h[2] & mask; pmac->u[3] |= key->md.h[3] & mask; pmac->u[4] |= key->md.h[4] & mask; pmac->u[5] |= key->md.h[5] & mask; pmac->u[6] |= key->md.h[6] & mask; pmac->u[7] |= key->md.h[7] & mask; memset(data, 0, SHA256_CBLOCK); j += 64; } data->u[SHA_LBLOCK - 1] = bitlen; sha256_block_data_order(&key->md, data, 1); mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h[0] & mask; pmac->u[1] |= key->md.h[1] & mask; pmac->u[2] |= key->md.h[2] & mask; pmac->u[3] |= key->md.h[3] & mask; pmac->u[4] |= key->md.h[4] & mask; pmac->u[5] |= key->md.h[5] & mask; pmac->u[6] |= key->md.h[6] & mask; pmac->u[7] |= key->md.h[7] & mask; # ifdef BSWAP4 pmac->u[0] = BSWAP4(pmac->u[0]); pmac->u[1] = BSWAP4(pmac->u[1]); pmac->u[2] = BSWAP4(pmac->u[2]); pmac->u[3] = BSWAP4(pmac->u[3]); pmac->u[4] = BSWAP4(pmac->u[4]); pmac->u[5] = BSWAP4(pmac->u[5]); pmac->u[6] = BSWAP4(pmac->u[6]); pmac->u[7] = BSWAP4(pmac->u[7]); # else for (i = 0; i < 8; i++) { res = pmac->u[i]; pmac->c[4 * i + 0] = (unsigned char)(res >> 24); pmac->c[4 * i + 1] = (unsigned char)(res >> 16); pmac->c[4 * i + 2] = (unsigned char)(res >> 8); pmac->c[4 * i + 3] = (unsigned char)res; } # endif len += SHA256_DIGEST_LENGTH; # else SHA256_Update(&key->md, out, inp_len); res = key->md.num; SHA256_Final(pmac->c, &key->md); { unsigned int inp_blocks, pad_blocks; /* but pretend as if we hashed padded payload */ inp_blocks = 1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1)); res += (unsigned int)(len - inp_len); pad_blocks = res / SHA256_CBLOCK; res %= SHA256_CBLOCK; pad_blocks += 1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1)); for (; inp_blocks < pad_blocks; inp_blocks++) sha1_block_data_order(&key->md, data, 1); } # endif key->md = key->tail; SHA256_Update(&key->md, pmac->c, SHA256_DIGEST_LENGTH); SHA256_Final(pmac->c, &key->md); /* verify HMAC */ out += inp_len; len -= inp_len; # if 1 { unsigned char *p = out + len - 1 - maxpad - SHA256_DIGEST_LENGTH; size_t off = out - p; unsigned int c, cmask; maxpad += SHA256_DIGEST_LENGTH; for (res = 0, i = 0, j = 0; j < maxpad; j++) { c = p[j]; cmask = ((int)(j - off - SHA256_DIGEST_LENGTH)) >> (sizeof(int) * 8 - 1); res |= (c ^ pad) & ~cmask; /* ... and padding */ cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1); res |= (c ^ pmac->c[i]) & cmask; i += 1 & cmask; } maxpad -= SHA256_DIGEST_LENGTH; res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; } # else for (res = 0, i = 0; i < SHA256_DIGEST_LENGTH; i++) res |= out[i] ^ pmac->c[i]; res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; /* verify padding */ pad = (pad & ~res) | (maxpad & res); out = out + len - 1 - pad; for (res = 0, i = 0; i < pad; i++) res |= out[i] ^ pad; res = (0 - res) >> (sizeof(res) * 8 - 1); ret &= (int)~res; # endif return ret; } else { SHA256_Update(&key->md, out, len); } } return 1; }
165,215
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int udf_translate_to_linux(uint8_t *newName, uint8_t *udfName, int udfLen, uint8_t *fidName, int fidNameLen) { int index, newIndex = 0, needsCRC = 0; int extIndex = 0, newExtIndex = 0, hasExt = 0; unsigned short valueCRC; uint8_t curr; if (udfName[0] == '.' && (udfLen == 1 || (udfLen == 2 && udfName[1] == '.'))) { needsCRC = 1; newIndex = udfLen; memcpy(newName, udfName, udfLen); } else { for (index = 0; index < udfLen; index++) { curr = udfName[index]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (index + 1 < udfLen && (udfName[index + 1] == '/' || udfName[index + 1] == 0)) index++; } if (curr == EXT_MARK && (udfLen - index - 1) <= EXT_SIZE) { if (udfLen == index + 1) hasExt = 0; else { hasExt = 1; extIndex = index; newExtIndex = newIndex; } } if (newIndex < 256) newName[newIndex++] = curr; else needsCRC = 1; } } if (needsCRC) { uint8_t ext[EXT_SIZE]; int localExtIndex = 0; if (hasExt) { int maxFilenameLen; for (index = 0; index < EXT_SIZE && extIndex + index + 1 < udfLen; index++) { curr = udfName[extIndex + index + 1]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (extIndex + index + 2 < udfLen && (index + 1 < EXT_SIZE && (udfName[extIndex + index + 2] == '/' || udfName[extIndex + index + 2] == 0))) index++; } ext[localExtIndex++] = curr; } maxFilenameLen = 250 - localExtIndex; if (newIndex > maxFilenameLen) newIndex = maxFilenameLen; else newIndex = newExtIndex; } else if (newIndex > 250) newIndex = 250; newName[newIndex++] = CRC_MARK; valueCRC = crc_itu_t(0, fidName, fidNameLen); newName[newIndex++] = hex_asc_upper_hi(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_lo(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_hi(valueCRC); newName[newIndex++] = hex_asc_upper_lo(valueCRC); if (hasExt) { newName[newIndex++] = EXT_MARK; for (index = 0; index < localExtIndex; index++) newName[newIndex++] = ext[index]; } } return newIndex; } Commit Message: udf: Check path length when reading symlink Symlink reading code does not check whether the resulting path fits into the page provided by the generic code. This isn't as easy as just checking the symlink size because of various encoding conversions we perform on path. So we have to check whether there is still enough space in the buffer on the fly. CC: [email protected] Reported-by: Carl Henrik Lunde <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-17
static int udf_translate_to_linux(uint8_t *newName, uint8_t *udfName, static int udf_translate_to_linux(uint8_t *newName, int newLen, uint8_t *udfName, int udfLen, uint8_t *fidName, int fidNameLen) { int index, newIndex = 0, needsCRC = 0; int extIndex = 0, newExtIndex = 0, hasExt = 0; unsigned short valueCRC; uint8_t curr; if (udfName[0] == '.' && (udfLen == 1 || (udfLen == 2 && udfName[1] == '.'))) { needsCRC = 1; newIndex = udfLen; memcpy(newName, udfName, udfLen); } else { for (index = 0; index < udfLen; index++) { curr = udfName[index]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (index + 1 < udfLen && (udfName[index + 1] == '/' || udfName[index + 1] == 0)) index++; } if (curr == EXT_MARK && (udfLen - index - 1) <= EXT_SIZE) { if (udfLen == index + 1) hasExt = 0; else { hasExt = 1; extIndex = index; newExtIndex = newIndex; } } if (newIndex < newLen) newName[newIndex++] = curr; else needsCRC = 1; } } if (needsCRC) { uint8_t ext[EXT_SIZE]; int localExtIndex = 0; if (hasExt) { int maxFilenameLen; for (index = 0; index < EXT_SIZE && extIndex + index + 1 < udfLen; index++) { curr = udfName[extIndex + index + 1]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (extIndex + index + 2 < udfLen && (index + 1 < EXT_SIZE && (udfName[extIndex + index + 2] == '/' || udfName[extIndex + index + 2] == 0))) index++; } ext[localExtIndex++] = curr; } maxFilenameLen = newLen - CRC_LEN - localExtIndex; if (newIndex > maxFilenameLen) newIndex = maxFilenameLen; else newIndex = newExtIndex; } else if (newIndex > newLen - CRC_LEN) newIndex = newLen - CRC_LEN; newName[newIndex++] = CRC_MARK; valueCRC = crc_itu_t(0, fidName, fidNameLen); newName[newIndex++] = hex_asc_upper_hi(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_lo(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_hi(valueCRC); newName[newIndex++] = hex_asc_upper_lo(valueCRC); if (hasExt) { newName[newIndex++] = EXT_MARK; for (index = 0; index < localExtIndex; index++) newName[newIndex++] = ext[index]; } } return newIndex; }
166,760
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GpuProcessHost::OnProcessLaunched() { base::ProcessHandle child_handle = in_process_ ? base::GetCurrentProcessHandle() : process_->GetData().handle; #if defined(OS_WIN) DuplicateHandle(base::GetCurrentProcessHandle(), child_handle, base::GetCurrentProcessHandle(), &gpu_process_, PROCESS_DUP_HANDLE, FALSE, 0); #else gpu_process_ = child_handle; #endif UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime", base::TimeTicks::Now() - init_start_time_); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuProcessHost::OnProcessLaunched() { UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime", base::TimeTicks::Now() - init_start_time_); }
170,923
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int yr_re_exec( uint8_t* re_code, uint8_t* input_data, size_t input_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args) { uint8_t* ip; uint8_t* input; uint8_t mask; uint8_t value; RE_FIBER_LIST fibers; RE_THREAD_STORAGE* storage; RE_FIBER* fiber; RE_FIBER* next_fiber; int error; int bytes_matched; int max_bytes_matched; int match; int character_size; int input_incr; int kill; int action; int result = -1; #define ACTION_NONE 0 #define ACTION_CONTINUE 1 #define ACTION_KILL 2 #define ACTION_KILL_TAIL 3 #define prolog if (bytes_matched >= max_bytes_matched) \ { \ action = ACTION_KILL; \ break; \ } #define fail_if_error(e) switch (e) { \ case ERROR_INSUFFICIENT_MEMORY: \ return -2; \ case ERROR_TOO_MANY_RE_FIBERS: \ return -4; \ } if (_yr_re_alloc_storage(&storage) != ERROR_SUCCESS) return -2; if (flags & RE_FLAGS_WIDE) character_size = 2; else character_size = 1; input = input_data; input_incr = character_size; if (flags & RE_FLAGS_BACKWARDS) { input -= character_size; input_incr = -input_incr; } max_bytes_matched = (int) yr_min(input_size, RE_SCAN_LIMIT); max_bytes_matched = max_bytes_matched - max_bytes_matched % character_size; bytes_matched = 0; error = _yr_re_fiber_create(&storage->fiber_pool, &fiber); fail_if_error(error); fiber->ip = re_code; fibers.head = fiber; fibers.tail = fiber; error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber); fail_if_error(error); while (fibers.head != NULL) { fiber = fibers.head; while(fiber != NULL) { ip = fiber->ip; action = ACTION_NONE; switch(*ip) { case RE_OPCODE_ANY: prolog; match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_REPEAT_ANY_GREEDY: case RE_OPCODE_REPEAT_ANY_UNGREEDY: prolog; match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A); action = match ? ACTION_NONE : ACTION_KILL; break; case RE_OPCODE_LITERAL: prolog; if (flags & RE_FLAGS_NO_CASE) match = yr_lowercase[*input] == yr_lowercase[*(ip + 1)]; else match = (*input == *(ip + 1)); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 2; break; case RE_OPCODE_MASKED_LITERAL: prolog; value = *(int16_t*)(ip + 1) & 0xFF; mask = *(int16_t*)(ip + 1) >> 8; match = ((*input & mask) == value); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 3; break; case RE_OPCODE_CLASS: prolog; match = CHAR_IN_CLASS(*input, ip + 1); if (!match && (flags & RE_FLAGS_NO_CASE)) match = CHAR_IN_CLASS(yr_altercase[*input], ip + 1); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 33; break; case RE_OPCODE_WORD_CHAR: prolog; match = IS_WORD_CHAR(*input); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_NON_WORD_CHAR: prolog; match = !IS_WORD_CHAR(*input); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_SPACE: case RE_OPCODE_NON_SPACE: prolog; switch(*input) { case ' ': case '\t': case '\r': case '\n': case '\v': case '\f': match = TRUE; break; default: match = FALSE; } if (*ip == RE_OPCODE_NON_SPACE) match = !match; action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_DIGIT: prolog; match = isdigit(*input); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_NON_DIGIT: prolog; match = !isdigit(*input); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_WORD_BOUNDARY: case RE_OPCODE_NON_WORD_BOUNDARY: if (bytes_matched == 0 && !(flags & RE_FLAGS_NOT_AT_START) && !(flags & RE_FLAGS_BACKWARDS)) match = TRUE; else if (bytes_matched >= max_bytes_matched) match = TRUE; else if (IS_WORD_CHAR(*(input - input_incr)) != IS_WORD_CHAR(*input)) match = TRUE; else match = FALSE; if (*ip == RE_OPCODE_NON_WORD_BOUNDARY) match = !match; action = match ? ACTION_CONTINUE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_MATCH_AT_START: if (flags & RE_FLAGS_BACKWARDS) kill = input_size > (size_t) bytes_matched; else kill = (flags & RE_FLAGS_NOT_AT_START) || (bytes_matched != 0); action = kill ? ACTION_KILL : ACTION_CONTINUE; fiber->ip += 1; break; case RE_OPCODE_MATCH_AT_END: kill = flags & RE_FLAGS_BACKWARDS || input_size > (size_t) bytes_matched; action = kill ? ACTION_KILL : ACTION_CONTINUE; fiber->ip += 1; break; case RE_OPCODE_MATCH: result = bytes_matched; if (flags & RE_FLAGS_EXHAUSTIVE) { if (callback != NULL) { int cb_result; if (flags & RE_FLAGS_BACKWARDS) cb_result = callback( input + character_size, bytes_matched, flags, callback_args); else cb_result = callback( input_data, bytes_matched, flags, callback_args); switch(cb_result) { case ERROR_INSUFFICIENT_MEMORY: return -2; case ERROR_TOO_MANY_MATCHES: return -3; default: if (cb_result != ERROR_SUCCESS) return -4; } } action = ACTION_KILL; } else { action = ACTION_KILL_TAIL; } break; default: assert(FALSE); } switch(action) { case ACTION_KILL: fiber = _yr_re_fiber_kill(&fibers, &storage->fiber_pool, fiber); break; case ACTION_KILL_TAIL: _yr_re_fiber_kill_tail(&fibers, &storage->fiber_pool, fiber); fiber = NULL; break; case ACTION_CONTINUE: error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber); fail_if_error(error); break; default: next_fiber = fiber->next; error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber); fail_if_error(error); fiber = next_fiber; } } if (flags & RE_FLAGS_WIDE && bytes_matched < max_bytes_matched && *(input + 1) != 0) { _yr_re_fiber_kill_all(&fibers, &storage->fiber_pool); } input += input_incr; bytes_matched += character_size; if (flags & RE_FLAGS_SCAN && bytes_matched < max_bytes_matched) { error = _yr_re_fiber_create(&storage->fiber_pool, &fiber); fail_if_error(error); fiber->ip = re_code; _yr_re_fiber_append(&fibers, fiber); error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber); fail_if_error(error); } } return result; } Commit Message: Fix issue #646 (#648) * Fix issue #646 and some edge cases with wide regexps using \b and \B * Rename function IS_WORD_CHAR to _yr_re_is_word_char CWE ID: CWE-125
int yr_re_exec( uint8_t* re_code, uint8_t* input_data, size_t input_forwards_size, size_t input_backwards_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args) { uint8_t* ip; uint8_t* input; uint8_t mask; uint8_t value; RE_FIBER_LIST fibers; RE_THREAD_STORAGE* storage; RE_FIBER* fiber; RE_FIBER* next_fiber; int error; int bytes_matched; int max_bytes_matched; int match; int character_size; int input_incr; int kill; int action; int result = -1; #define ACTION_NONE 0 #define ACTION_CONTINUE 1 #define ACTION_KILL 2 #define ACTION_KILL_TAIL 3 #define prolog { \ if ((bytes_matched >= max_bytes_matched) || \ (character_size == 2 && *(input + 1) != 0)) \ { \ action = ACTION_KILL; \ break; \ } \ } #define fail_if_error(e) { \ switch (e) { \ case ERROR_INSUFFICIENT_MEMORY: \ return -2; \ case ERROR_TOO_MANY_RE_FIBERS: \ return -4; \ } \ } if (_yr_re_alloc_storage(&storage) != ERROR_SUCCESS) return -2; if (flags & RE_FLAGS_WIDE) character_size = 2; else character_size = 1; input = input_data; input_incr = character_size; if (flags & RE_FLAGS_BACKWARDS) { max_bytes_matched = (int) yr_min(input_backwards_size, RE_SCAN_LIMIT); input -= character_size; input_incr = -input_incr; } else { max_bytes_matched = (int) yr_min(input_forwards_size, RE_SCAN_LIMIT); } // character_size is 2 and max_bytes_matched is odd we are ignoring the max_bytes_matched = max_bytes_matched - max_bytes_matched % character_size; bytes_matched = 0; error = _yr_re_fiber_create(&storage->fiber_pool, &fiber); fail_if_error(error); fiber->ip = re_code; fibers.head = fiber; fibers.tail = fiber; error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber); fail_if_error(error); while (fibers.head != NULL) { fiber = fibers.head; while(fiber != NULL) { ip = fiber->ip; action = ACTION_NONE; switch(*ip) { case RE_OPCODE_ANY: prolog; match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_REPEAT_ANY_GREEDY: case RE_OPCODE_REPEAT_ANY_UNGREEDY: prolog; match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A); action = match ? ACTION_NONE : ACTION_KILL; break; case RE_OPCODE_LITERAL: prolog; if (flags & RE_FLAGS_NO_CASE) match = yr_lowercase[*input] == yr_lowercase[*(ip + 1)]; else match = (*input == *(ip + 1)); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 2; break; case RE_OPCODE_MASKED_LITERAL: prolog; value = *(int16_t*)(ip + 1) & 0xFF; mask = *(int16_t*)(ip + 1) >> 8; match = ((*input & mask) == value); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 3; break; case RE_OPCODE_CLASS: prolog; match = CHAR_IN_CLASS(*input, ip + 1); if (!match && (flags & RE_FLAGS_NO_CASE)) match = CHAR_IN_CLASS(yr_altercase[*input], ip + 1); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 33; break; case RE_OPCODE_WORD_CHAR: prolog; match = _yr_re_is_word_char(input, character_size); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_NON_WORD_CHAR: prolog; match = !_yr_re_is_word_char(input, character_size); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_SPACE: case RE_OPCODE_NON_SPACE: prolog; switch(*input) { case ' ': case '\t': case '\r': case '\n': case '\v': case '\f': match = TRUE; break; default: match = FALSE; } if (*ip == RE_OPCODE_NON_SPACE) match = !match; action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_DIGIT: prolog; match = isdigit(*input); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_NON_DIGIT: prolog; match = !isdigit(*input); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_WORD_BOUNDARY: case RE_OPCODE_NON_WORD_BOUNDARY: if (bytes_matched == 0 && input_backwards_size < character_size) { match = TRUE; } else if (bytes_matched >= max_bytes_matched) { match = TRUE; } else { assert(input < input_data + input_forwards_size); assert(input >= input_data - input_backwards_size); assert(input - input_incr < input_data + input_forwards_size); assert(input - input_incr >= input_data - input_backwards_size); match = _yr_re_is_word_char(input, character_size) != \ _yr_re_is_word_char(input - input_incr, character_size); } if (*ip == RE_OPCODE_NON_WORD_BOUNDARY) match = !match; action = match ? ACTION_CONTINUE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_MATCH_AT_START: if (flags & RE_FLAGS_BACKWARDS) kill = input_backwards_size > (size_t) bytes_matched; else kill = input_backwards_size > 0 || (bytes_matched != 0); action = kill ? ACTION_KILL : ACTION_CONTINUE; fiber->ip += 1; break; case RE_OPCODE_MATCH_AT_END: kill = flags & RE_FLAGS_BACKWARDS || input_forwards_size > (size_t) bytes_matched; action = kill ? ACTION_KILL : ACTION_CONTINUE; fiber->ip += 1; break; case RE_OPCODE_MATCH: result = bytes_matched; if (flags & RE_FLAGS_EXHAUSTIVE) { if (callback != NULL) { int cb_result; if (flags & RE_FLAGS_BACKWARDS) cb_result = callback( input + character_size, bytes_matched, flags, callback_args); else cb_result = callback( input_data, bytes_matched, flags, callback_args); switch(cb_result) { case ERROR_INSUFFICIENT_MEMORY: return -2; case ERROR_TOO_MANY_MATCHES: return -3; default: if (cb_result != ERROR_SUCCESS) return -4; } } action = ACTION_KILL; } else { action = ACTION_KILL_TAIL; } break; default: assert(FALSE); } switch(action) { case ACTION_KILL: fiber = _yr_re_fiber_kill(&fibers, &storage->fiber_pool, fiber); break; case ACTION_KILL_TAIL: _yr_re_fiber_kill_tail(&fibers, &storage->fiber_pool, fiber); fiber = NULL; break; case ACTION_CONTINUE: error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber); fail_if_error(error); break; default: next_fiber = fiber->next; error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber); fail_if_error(error); fiber = next_fiber; } } input += input_incr; bytes_matched += character_size; if (flags & RE_FLAGS_SCAN && bytes_matched < max_bytes_matched) { error = _yr_re_fiber_create(&storage->fiber_pool, &fiber); fail_if_error(error); fiber->ip = re_code; _yr_re_fiber_append(&fibers, fiber); error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber); fail_if_error(error); } } return result; }
168,202
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate( const CompactHTMLToken& token, HTMLTokenizer* tokenizer) { SimulatedToken simulated_token = kOtherToken; if (token.GetType() == HTMLToken::kStartTag) { const String& tag_name = token.Data(); if (ThreadSafeMatch(tag_name, SVGNames::svgTag)) namespace_stack_.push_back(SVG); if (ThreadSafeMatch(tag_name, MathMLNames::mathTag)) namespace_stack_.push_back(kMathML); if (InForeignContent() && TokenExitsForeignContent(token)) namespace_stack_.pop_back(); if ((namespace_stack_.back() == SVG && TokenExitsSVG(token)) || (namespace_stack_.back() == kMathML && TokenExitsMath(token))) namespace_stack_.push_back(HTML); if (!InForeignContent()) { if (ThreadSafeMatch(tag_name, textareaTag) || ThreadSafeMatch(tag_name, titleTag)) { tokenizer->SetState(HTMLTokenizer::kRCDATAState); } else if (ThreadSafeMatch(tag_name, scriptTag)) { tokenizer->SetState(HTMLTokenizer::kScriptDataState); simulated_token = kScriptStart; } else if (ThreadSafeMatch(tag_name, linkTag)) { simulated_token = kLink; } else if (!in_select_insertion_mode_) { if (ThreadSafeMatch(tag_name, plaintextTag) && !in_select_insertion_mode_) { tokenizer->SetState(HTMLTokenizer::kPLAINTEXTState); } else if (ThreadSafeMatch(tag_name, styleTag) || ThreadSafeMatch(tag_name, iframeTag) || ThreadSafeMatch(tag_name, xmpTag) || (ThreadSafeMatch(tag_name, noembedTag) && options_.plugins_enabled) || ThreadSafeMatch(tag_name, noframesTag) || (ThreadSafeMatch(tag_name, noscriptTag) && options_.script_enabled)) { tokenizer->SetState(HTMLTokenizer::kRAWTEXTState); } } if (ThreadSafeMatch(tag_name, selectTag)) { in_select_insertion_mode_ = true; } else if (in_select_insertion_mode_ && TokenExitsInSelect(token)) { in_select_insertion_mode_ = false; } } } if (token.GetType() == HTMLToken::kEndTag || (token.GetType() == HTMLToken::kStartTag && token.SelfClosing() && InForeignContent())) { const String& tag_name = token.Data(); if ((namespace_stack_.back() == SVG && ThreadSafeMatch(tag_name, SVGNames::svgTag)) || (namespace_stack_.back() == kMathML && ThreadSafeMatch(tag_name, MathMLNames::mathTag)) || (namespace_stack_.Contains(SVG) && namespace_stack_.back() == HTML && TokenExitsSVG(token)) || (namespace_stack_.Contains(kMathML) && namespace_stack_.back() == HTML && TokenExitsMath(token))) { namespace_stack_.pop_back(); } if (ThreadSafeMatch(tag_name, scriptTag)) { if (!InForeignContent()) tokenizer->SetState(HTMLTokenizer::kDataState); return kScriptEnd; } else if (ThreadSafeMatch(tag_name, selectTag)) { in_select_insertion_mode_ = false; } if (ThreadSafeMatch(tag_name, styleTag)) simulated_token = kStyleEnd; } tokenizer->SetForceNullCharacterReplacement(InForeignContent()); tokenizer->SetShouldAllowCDATA(InForeignContent()); return simulated_token; } Commit Message: HTML parser: Fix "HTML integration point" implementation in HTMLTreeBuilderSimulator. HTMLTreeBuilderSimulator assumed only <foreignObject> as an HTML integration point. This CL adds <annotation-xml>, <desc>, and SVG <title>. Bug: 805924 Change-Id: I6793d9163d4c6bc8bf0790415baedddaac7a1fc2 Reviewed-on: https://chromium-review.googlesource.com/964038 Commit-Queue: Kent Tamura <[email protected]> Reviewed-by: Kouhei Ueno <[email protected]> Cr-Commit-Position: refs/heads/master@{#543634} CWE ID: CWE-79
HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate( const CompactHTMLToken& token, HTMLTokenizer* tokenizer) { SimulatedToken simulated_token = kOtherToken; if (token.GetType() == HTMLToken::kStartTag) { const String& tag_name = token.Data(); if (ThreadSafeMatch(tag_name, SVGNames::svgTag)) namespace_stack_.push_back(SVG); if (ThreadSafeMatch(tag_name, MathMLNames::mathTag)) namespace_stack_.push_back(kMathML); if (InForeignContent() && TokenExitsForeignContent(token)) namespace_stack_.pop_back(); if (IsHTMLIntegrationPointForStartTag(token) || (namespace_stack_.back() == kMathML && TokenExitsMath(token))) { namespace_stack_.push_back(HTML); } else if (!InForeignContent()) { if (ThreadSafeMatch(tag_name, textareaTag) || ThreadSafeMatch(tag_name, titleTag)) { tokenizer->SetState(HTMLTokenizer::kRCDATAState); } else if (ThreadSafeMatch(tag_name, scriptTag)) { tokenizer->SetState(HTMLTokenizer::kScriptDataState); simulated_token = kScriptStart; } else if (ThreadSafeMatch(tag_name, linkTag)) { simulated_token = kLink; } else if (!in_select_insertion_mode_) { if (ThreadSafeMatch(tag_name, plaintextTag) && !in_select_insertion_mode_) { tokenizer->SetState(HTMLTokenizer::kPLAINTEXTState); } else if (ThreadSafeMatch(tag_name, styleTag) || ThreadSafeMatch(tag_name, iframeTag) || ThreadSafeMatch(tag_name, xmpTag) || (ThreadSafeMatch(tag_name, noembedTag) && options_.plugins_enabled) || ThreadSafeMatch(tag_name, noframesTag) || (ThreadSafeMatch(tag_name, noscriptTag) && options_.script_enabled)) { tokenizer->SetState(HTMLTokenizer::kRAWTEXTState); } } if (ThreadSafeMatch(tag_name, selectTag)) { in_select_insertion_mode_ = true; } else if (in_select_insertion_mode_ && TokenExitsInSelect(token)) { in_select_insertion_mode_ = false; } } } if (token.GetType() == HTMLToken::kEndTag || (token.GetType() == HTMLToken::kStartTag && token.SelfClosing() && InForeignContent())) { const String& tag_name = token.Data(); if ((namespace_stack_.back() == SVG && ThreadSafeMatch(tag_name, SVGNames::svgTag)) || (namespace_stack_.back() == kMathML && ThreadSafeMatch(tag_name, MathMLNames::mathTag)) || IsHTMLIntegrationPointForEndTag(token) || (namespace_stack_.Contains(kMathML) && namespace_stack_.back() == HTML && TokenExitsMath(token))) { namespace_stack_.pop_back(); } if (ThreadSafeMatch(tag_name, scriptTag)) { if (!InForeignContent()) tokenizer->SetState(HTMLTokenizer::kDataState); return kScriptEnd; } else if (ThreadSafeMatch(tag_name, selectTag)) { in_select_insertion_mode_ = false; } if (ThreadSafeMatch(tag_name, styleTag)) simulated_token = kStyleEnd; } tokenizer->SetForceNullCharacterReplacement(InForeignContent()); tokenizer->SetShouldAllowCDATA(InForeignContent()); return simulated_token; }
173,254
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx) { struct Vmxnet3_TxDesc txd; uint32_t txd_idx; uint32_t data_len; hwaddr data_pa; for (;;) { if (!vmxnet3_pop_next_tx_descr(s, qidx, &txd, &txd_idx)) { break; } vmxnet3_dump_tx_descr(&txd); if (!s->skip_current_tx_pkt) { data_len = (txd.len > 0) ? txd.len : VMXNET3_MAX_TX_BUF_SIZE; data_pa = le64_to_cpu(txd.addr); if (!vmxnet_tx_pkt_add_raw_fragment(s->tx_pkt, data_pa, data_len)) { s->skip_current_tx_pkt = true; } } if (s->tx_sop) { vmxnet3_tx_retrieve_metadata(s, &txd); s->tx_sop = false; } if (txd.eop) { if (!s->skip_current_tx_pkt) { vmxnet_tx_pkt_parse(s->tx_pkt); if (s->needs_vlan) { vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci); } vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci); } vmxnet3_send_packet(s, qidx); } else { vmxnet3_on_tx_done_update_stats(s, qidx, VMXNET3_PKT_STATUS_ERROR); } vmxnet3_complete_packet(s, qidx, txd_idx); s->tx_sop = true; s->skip_current_tx_pkt = false; vmxnet_tx_pkt_reset(s->tx_pkt); } } Commit Message: CWE ID: CWE-20
static void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx) { struct Vmxnet3_TxDesc txd; uint32_t txd_idx; uint32_t data_len; hwaddr data_pa; for (;;) { if (!vmxnet3_pop_next_tx_descr(s, qidx, &txd, &txd_idx)) { break; } vmxnet3_dump_tx_descr(&txd); if (!s->skip_current_tx_pkt) { data_len = (txd.len > 0) ? txd.len : VMXNET3_MAX_TX_BUF_SIZE; data_pa = le64_to_cpu(txd.addr); if (!vmxnet_tx_pkt_add_raw_fragment(s->tx_pkt, data_pa, data_len)) { s->skip_current_tx_pkt = true; } } if (s->tx_sop) { vmxnet3_tx_retrieve_metadata(s, &txd); s->tx_sop = false; } if (txd.eop) { if (!s->skip_current_tx_pkt && vmxnet_tx_pkt_parse(s->tx_pkt)) { if (s->needs_vlan) { vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci); } vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci); } vmxnet3_send_packet(s, qidx); } else { vmxnet3_on_tx_done_update_stats(s, qidx, VMXNET3_PKT_STATUS_ERROR); } vmxnet3_complete_packet(s, qidx, txd_idx); s->tx_sop = true; s->skip_current_tx_pkt = false; vmxnet_tx_pkt_reset(s->tx_pkt); } }
165,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) { enum InjectionPermission { INJECTION_PERMISSION_UNKNOWN, INJECTION_PERMISSION_GRANTED, INJECTION_PERMISSION_DENIED }; nsecs_t startTime = now(); int32_t displayId = entry->displayId; int32_t action = entry->action; int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK; int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING; InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN; sp<InputWindowHandle> newHoverWindowHandle; const TouchState* oldState = NULL; ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId); if (oldStateIndex >= 0) { oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex); mTempTouchState.copyFrom(*oldState); } bool isSplit = mTempTouchState.split; bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 && (mTempTouchState.deviceId != entry->deviceId || mTempTouchState.source != entry->source || mTempTouchState.displayId != displayId); bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT); bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction); bool wrongDevice = false; if (newGesture) { bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN; if (switchedDevice && mTempTouchState.down && !down) { #if DEBUG_FOCUS ALOGD("Dropping event because a pointer for a different device is already down."); #endif injectionResult = INPUT_EVENT_INJECTION_FAILED; switchedDevice = false; wrongDevice = true; goto Failed; } mTempTouchState.reset(); mTempTouchState.down = down; mTempTouchState.deviceId = entry->deviceId; mTempTouchState.source = entry->source; mTempTouchState.displayId = displayId; isSplit = false; } if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) { /* Case 1: New splittable pointer going down, or need target for hover or scroll. */ int32_t pointerIndex = getMotionEventActionPointerIndex(action); int32_t x = int32_t(entry->pointerCoords[pointerIndex]. getAxisValue(AMOTION_EVENT_AXIS_X)); int32_t y = int32_t(entry->pointerCoords[pointerIndex]. getAxisValue(AMOTION_EVENT_AXIS_Y)); sp<InputWindowHandle> newTouchedWindowHandle; bool isTouchModal = false; size_t numWindows = mWindowHandles.size(); for (size_t i = 0; i < numWindows; i++) { sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i); const InputWindowInfo* windowInfo = windowHandle->getInfo(); if (windowInfo->displayId != displayId) { continue; // wrong display } int32_t flags = windowInfo->layoutParamsFlags; if (windowInfo->visible) { if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) { isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0; if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) { newTouchedWindowHandle = windowHandle; break; // found touched window, exit window loop } } if (maskedAction == AMOTION_EVENT_ACTION_DOWN && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) { int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE; if (isWindowObscuredAtPointLocked(windowHandle, x, y)) { outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; } mTempTouchState.addOrUpdateWindow( windowHandle, outsideTargetFlags, BitSet32(0)); } } } if (newTouchedWindowHandle != NULL && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) { isSplit = true; } else if (isSplit) { newTouchedWindowHandle = NULL; } if (newTouchedWindowHandle == NULL) { newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); if (newTouchedWindowHandle == NULL) { ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y); injectionResult = INPUT_EVENT_INJECTION_FAILED; goto Failed; } } int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS; if (isSplit) { targetFlags |= InputTarget::FLAG_SPLIT; } if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) { targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; } if (isHoverAction) { newHoverWindowHandle = newTouchedWindowHandle; } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) { newHoverWindowHandle = mLastHoverWindowHandle; } BitSet32 pointerIds; if (isSplit) { uint32_t pointerId = entry->pointerProperties[pointerIndex].id; pointerIds.markBit(pointerId); } mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds); } else { /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */ if (! mTempTouchState.down) { #if DEBUG_FOCUS ALOGD("Dropping event because the pointer is not down or we previously " "dropped the pointer down event."); #endif injectionResult = INPUT_EVENT_INJECTION_FAILED; goto Failed; } if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry->pointerCount == 1 && mTempTouchState.isSlippery()) { int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X)); int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y)); sp<InputWindowHandle> oldTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y); if (oldTouchedWindowHandle != newTouchedWindowHandle && newTouchedWindowHandle != NULL) { #if DEBUG_FOCUS ALOGD("Touch is slipping out of window %s into window %s.", oldTouchedWindowHandle->getName().string(), newTouchedWindowHandle->getName().string()); #endif mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0)); if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) { isSplit = true; } int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER; if (isSplit) { targetFlags |= InputTarget::FLAG_SPLIT; } if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) { targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; } BitSet32 pointerIds; if (isSplit) { pointerIds.markBit(entry->pointerProperties[0].id); } mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds); } } } if (newHoverWindowHandle != mLastHoverWindowHandle) { if (mLastHoverWindowHandle != NULL) { #if DEBUG_HOVER ALOGD("Sending hover exit event to window %s.", mLastHoverWindowHandle->getName().string()); #endif mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0)); } if (newHoverWindowHandle != NULL) { #if DEBUG_HOVER ALOGD("Sending hover enter event to window %s.", newHoverWindowHandle->getName().string()); #endif mTempTouchState.addOrUpdateWindow(newHoverWindowHandle, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0)); } } { bool haveForegroundWindow = false; for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) { haveForegroundWindow = true; if (! checkInjectionPermission(touchedWindow.windowHandle, entry->injectionState)) { injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED; injectionPermission = INJECTION_PERMISSION_DENIED; goto Failed; } } } if (! haveForegroundWindow) { #if DEBUG_FOCUS ALOGD("Dropping event because there is no touched foreground window to receive it."); #endif injectionResult = INPUT_EVENT_INJECTION_FAILED; goto Failed; } injectionPermission = INJECTION_PERMISSION_GRANTED; } if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { sp<InputWindowHandle> foregroundWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid; for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) { sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle; if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) { mTempTouchState.addOrUpdateWindow(inputWindowHandle, InputTarget::FLAG_ZERO_COORDS, BitSet32(0)); } } } } for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) { String8 reason = checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry, "touched"); if (!reason.isEmpty()) { injectionResult = handleTargetsNotReadyLocked(currentTime, entry, NULL, touchedWindow.windowHandle, nextWakeupTime, reason.string()); goto Unresponsive; } } } if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { sp<InputWindowHandle> foregroundWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); if (foregroundWindowHandle->getInfo()->hasWallpaper) { for (size_t i = 0; i < mWindowHandles.size(); i++) { sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i); const InputWindowInfo* info = windowHandle->getInfo(); if (info->displayId == displayId && windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) { mTempTouchState.addOrUpdateWindow(windowHandle, InputTarget::FLAG_WINDOW_IS_OBSCURED | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0)); } } } } injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED; for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i); addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags, touchedWindow.pointerIds, inputTargets); } mTempTouchState.filterNonAsIsTouchWindows(); Failed: if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) { if (checkInjectionPermission(NULL, entry->injectionState)) { injectionPermission = INJECTION_PERMISSION_GRANTED; } else { injectionPermission = INJECTION_PERMISSION_DENIED; } } if (injectionPermission == INJECTION_PERMISSION_GRANTED) { if (!wrongDevice) { if (switchedDevice) { #if DEBUG_FOCUS ALOGD("Conflicting pointer actions: Switched to a different device."); #endif *outConflictingPointerActions = true; } if (isHoverAction) { if (oldState && oldState->down) { #if DEBUG_FOCUS ALOGD("Conflicting pointer actions: Hover received while pointer was down."); #endif *outConflictingPointerActions = true; } mTempTouchState.reset(); if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) { mTempTouchState.deviceId = entry->deviceId; mTempTouchState.source = entry->source; mTempTouchState.displayId = displayId; } } else if (maskedAction == AMOTION_EVENT_ACTION_UP || maskedAction == AMOTION_EVENT_ACTION_CANCEL) { mTempTouchState.reset(); } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { if (oldState && oldState->down) { #if DEBUG_FOCUS ALOGD("Conflicting pointer actions: Down received while already down."); #endif *outConflictingPointerActions = true; } } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) { if (isSplit) { int32_t pointerIndex = getMotionEventActionPointerIndex(action); uint32_t pointerId = entry->pointerProperties[pointerIndex].id; for (size_t i = 0; i < mTempTouchState.windows.size(); ) { TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i); if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) { touchedWindow.pointerIds.clearBit(pointerId); if (touchedWindow.pointerIds.isEmpty()) { mTempTouchState.windows.removeAt(i); continue; } } i += 1; } } } if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) { if (mTempTouchState.displayId >= 0) { if (oldStateIndex >= 0) { mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState); } else { mTouchStatesByDisplay.add(displayId, mTempTouchState); } } else if (oldStateIndex >= 0) { mTouchStatesByDisplay.removeItemsAt(oldStateIndex); } } mLastHoverWindowHandle = newHoverWindowHandle; } } else { #if DEBUG_FOCUS ALOGD("Not updating touch focus because injection was denied."); #endif } Unresponsive: mTempTouchState.reset(); nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime); updateDispatchStatisticsLocked(currentTime, entry, injectionResult, timeSpentWaitingForApplication); #if DEBUG_FOCUS ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, " "timeSpentWaitingForApplication=%0.1fms", injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0); #endif return injectionResult; } Commit Message: Add new MotionEvent flag for partially obscured windows. Due to more complex window layouts resulting in lots of overlapping windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to only be set when the point at which the window was touched is obscured. Unfortunately, this doesn't prevent tapjacking attacks that overlay the dialog's text, making a potentially dangerous operation seem innocuous. To avoid this on particularly sensitive dialogs, introduce a new flag that really does tell you when your window is being even partially overlapped. We aren't exposing this as API since we plan on making the original flag more robust. This is really a workaround for system dialogs since we generally know their layout and screen position, and that they're unlikely to be overlapped by other applications. Bug: 26677796 Change-Id: I9e336afe90f262ba22015876769a9c510048fd47 CWE ID: CWE-264
int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) { enum InjectionPermission { INJECTION_PERMISSION_UNKNOWN, INJECTION_PERMISSION_GRANTED, INJECTION_PERMISSION_DENIED }; nsecs_t startTime = now(); int32_t displayId = entry->displayId; int32_t action = entry->action; int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK; int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING; InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN; sp<InputWindowHandle> newHoverWindowHandle; const TouchState* oldState = NULL; ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId); if (oldStateIndex >= 0) { oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex); mTempTouchState.copyFrom(*oldState); } bool isSplit = mTempTouchState.split; bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 && (mTempTouchState.deviceId != entry->deviceId || mTempTouchState.source != entry->source || mTempTouchState.displayId != displayId); bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT); bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction); bool wrongDevice = false; if (newGesture) { bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN; if (switchedDevice && mTempTouchState.down && !down) { #if DEBUG_FOCUS ALOGD("Dropping event because a pointer for a different device is already down."); #endif injectionResult = INPUT_EVENT_INJECTION_FAILED; switchedDevice = false; wrongDevice = true; goto Failed; } mTempTouchState.reset(); mTempTouchState.down = down; mTempTouchState.deviceId = entry->deviceId; mTempTouchState.source = entry->source; mTempTouchState.displayId = displayId; isSplit = false; } if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) { /* Case 1: New splittable pointer going down, or need target for hover or scroll. */ int32_t pointerIndex = getMotionEventActionPointerIndex(action); int32_t x = int32_t(entry->pointerCoords[pointerIndex]. getAxisValue(AMOTION_EVENT_AXIS_X)); int32_t y = int32_t(entry->pointerCoords[pointerIndex]. getAxisValue(AMOTION_EVENT_AXIS_Y)); sp<InputWindowHandle> newTouchedWindowHandle; bool isTouchModal = false; size_t numWindows = mWindowHandles.size(); for (size_t i = 0; i < numWindows; i++) { sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i); const InputWindowInfo* windowInfo = windowHandle->getInfo(); if (windowInfo->displayId != displayId) { continue; // wrong display } int32_t flags = windowInfo->layoutParamsFlags; if (windowInfo->visible) { if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) { isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0; if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) { newTouchedWindowHandle = windowHandle; break; // found touched window, exit window loop } } if (maskedAction == AMOTION_EVENT_ACTION_DOWN && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) { int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE; if (isWindowObscuredAtPointLocked(windowHandle, x, y)) { outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; } else if (isWindowObscuredLocked(windowHandle)) { outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED; } mTempTouchState.addOrUpdateWindow( windowHandle, outsideTargetFlags, BitSet32(0)); } } } if (newTouchedWindowHandle != NULL && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) { isSplit = true; } else if (isSplit) { newTouchedWindowHandle = NULL; } if (newTouchedWindowHandle == NULL) { newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); if (newTouchedWindowHandle == NULL) { ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y); injectionResult = INPUT_EVENT_INJECTION_FAILED; goto Failed; } } int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS; if (isSplit) { targetFlags |= InputTarget::FLAG_SPLIT; } if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) { targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; } else if (isWindowObscuredLocked(newTouchedWindowHandle)) { targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED; } if (isHoverAction) { newHoverWindowHandle = newTouchedWindowHandle; } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) { newHoverWindowHandle = mLastHoverWindowHandle; } BitSet32 pointerIds; if (isSplit) { uint32_t pointerId = entry->pointerProperties[pointerIndex].id; pointerIds.markBit(pointerId); } mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds); } else { /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */ if (! mTempTouchState.down) { #if DEBUG_FOCUS ALOGD("Dropping event because the pointer is not down or we previously " "dropped the pointer down event."); #endif injectionResult = INPUT_EVENT_INJECTION_FAILED; goto Failed; } if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry->pointerCount == 1 && mTempTouchState.isSlippery()) { int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X)); int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y)); sp<InputWindowHandle> oldTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y); if (oldTouchedWindowHandle != newTouchedWindowHandle && newTouchedWindowHandle != NULL) { #if DEBUG_FOCUS ALOGD("Touch is slipping out of window %s into window %s.", oldTouchedWindowHandle->getName().string(), newTouchedWindowHandle->getName().string()); #endif mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0)); if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) { isSplit = true; } int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER; if (isSplit) { targetFlags |= InputTarget::FLAG_SPLIT; } if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) { targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; } BitSet32 pointerIds; if (isSplit) { pointerIds.markBit(entry->pointerProperties[0].id); } mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds); } } } if (newHoverWindowHandle != mLastHoverWindowHandle) { if (mLastHoverWindowHandle != NULL) { #if DEBUG_HOVER ALOGD("Sending hover exit event to window %s.", mLastHoverWindowHandle->getName().string()); #endif mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0)); } if (newHoverWindowHandle != NULL) { #if DEBUG_HOVER ALOGD("Sending hover enter event to window %s.", newHoverWindowHandle->getName().string()); #endif mTempTouchState.addOrUpdateWindow(newHoverWindowHandle, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0)); } } { bool haveForegroundWindow = false; for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) { haveForegroundWindow = true; if (! checkInjectionPermission(touchedWindow.windowHandle, entry->injectionState)) { injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED; injectionPermission = INJECTION_PERMISSION_DENIED; goto Failed; } } } if (! haveForegroundWindow) { #if DEBUG_FOCUS ALOGD("Dropping event because there is no touched foreground window to receive it."); #endif injectionResult = INPUT_EVENT_INJECTION_FAILED; goto Failed; } injectionPermission = INJECTION_PERMISSION_GRANTED; } if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { sp<InputWindowHandle> foregroundWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid; for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) { sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle; if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) { mTempTouchState.addOrUpdateWindow(inputWindowHandle, InputTarget::FLAG_ZERO_COORDS, BitSet32(0)); } } } } for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) { String8 reason = checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry, "touched"); if (!reason.isEmpty()) { injectionResult = handleTargetsNotReadyLocked(currentTime, entry, NULL, touchedWindow.windowHandle, nextWakeupTime, reason.string()); goto Unresponsive; } } } if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { sp<InputWindowHandle> foregroundWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); if (foregroundWindowHandle->getInfo()->hasWallpaper) { for (size_t i = 0; i < mWindowHandles.size(); i++) { sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i); const InputWindowInfo* info = windowHandle->getInfo(); if (info->displayId == displayId && windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) { mTempTouchState.addOrUpdateWindow(windowHandle, InputTarget::FLAG_WINDOW_IS_OBSCURED | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0)); } } } } injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED; for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i); addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags, touchedWindow.pointerIds, inputTargets); } mTempTouchState.filterNonAsIsTouchWindows(); Failed: if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) { if (checkInjectionPermission(NULL, entry->injectionState)) { injectionPermission = INJECTION_PERMISSION_GRANTED; } else { injectionPermission = INJECTION_PERMISSION_DENIED; } } if (injectionPermission == INJECTION_PERMISSION_GRANTED) { if (!wrongDevice) { if (switchedDevice) { #if DEBUG_FOCUS ALOGD("Conflicting pointer actions: Switched to a different device."); #endif *outConflictingPointerActions = true; } if (isHoverAction) { if (oldState && oldState->down) { #if DEBUG_FOCUS ALOGD("Conflicting pointer actions: Hover received while pointer was down."); #endif *outConflictingPointerActions = true; } mTempTouchState.reset(); if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) { mTempTouchState.deviceId = entry->deviceId; mTempTouchState.source = entry->source; mTempTouchState.displayId = displayId; } } else if (maskedAction == AMOTION_EVENT_ACTION_UP || maskedAction == AMOTION_EVENT_ACTION_CANCEL) { mTempTouchState.reset(); } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { if (oldState && oldState->down) { #if DEBUG_FOCUS ALOGD("Conflicting pointer actions: Down received while already down."); #endif *outConflictingPointerActions = true; } } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) { if (isSplit) { int32_t pointerIndex = getMotionEventActionPointerIndex(action); uint32_t pointerId = entry->pointerProperties[pointerIndex].id; for (size_t i = 0; i < mTempTouchState.windows.size(); ) { TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i); if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) { touchedWindow.pointerIds.clearBit(pointerId); if (touchedWindow.pointerIds.isEmpty()) { mTempTouchState.windows.removeAt(i); continue; } } i += 1; } } } if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) { if (mTempTouchState.displayId >= 0) { if (oldStateIndex >= 0) { mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState); } else { mTouchStatesByDisplay.add(displayId, mTempTouchState); } } else if (oldStateIndex >= 0) { mTouchStatesByDisplay.removeItemsAt(oldStateIndex); } } mLastHoverWindowHandle = newHoverWindowHandle; } } else { #if DEBUG_FOCUS ALOGD("Not updating touch focus because injection was denied."); #endif } Unresponsive: mTempTouchState.reset(); nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime); updateDispatchStatisticsLocked(currentTime, entry, injectionResult, timeSpentWaitingForApplication); #if DEBUG_FOCUS ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, " "timeSpentWaitingForApplication=%0.1fms", injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0); #endif return injectionResult; }
174,168
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int do_video_set_spu_palette(unsigned int fd, unsigned int cmd, struct compat_video_spu_palette __user *up) { struct video_spu_palette __user *up_native; compat_uptr_t palp; int length, err; err = get_user(palp, &up->palette); err |= get_user(length, &up->length); up_native = compat_alloc_user_space(sizeof(struct video_spu_palette)); err = put_user(compat_ptr(palp), &up_native->palette); err |= put_user(length, &up_native->length); if (err) return -EFAULT; err = sys_ioctl(fd, cmd, (unsigned long) up_native); return err; } Commit Message: fs/compat_ioctl.c: VIDEO_SET_SPU_PALETTE missing error check The compat ioctl for VIDEO_SET_SPU_PALETTE was missing an error check while converting ioctl arguments. This could lead to leaking kernel stack contents into userspace. Patch extracted from existing fix in grsecurity. Signed-off-by: Kees Cook <[email protected]> Cc: David Miller <[email protected]> Cc: Brad Spengler <[email protected]> Cc: PaX Team <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200
static int do_video_set_spu_palette(unsigned int fd, unsigned int cmd, struct compat_video_spu_palette __user *up) { struct video_spu_palette __user *up_native; compat_uptr_t palp; int length, err; err = get_user(palp, &up->palette); err |= get_user(length, &up->length); if (err) return -EFAULT; up_native = compat_alloc_user_space(sizeof(struct video_spu_palette)); err = put_user(compat_ptr(palp), &up_native->palette); err |= put_user(length, &up_native->length); if (err) return -EFAULT; err = sys_ioctl(fd, cmd, (unsigned long) up_native); return err; }
166,102
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_parse_sps(dec_struct_t *ps_dec, dec_bit_stream_t *ps_bitstrm) { UWORD8 i; dec_seq_params_t *ps_seq = NULL; UWORD8 u1_profile_idc, u1_level_idc, u1_seq_parameter_set_id; UWORD16 i2_max_frm_num; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; UWORD8 u1_frm, uc_constraint_set0_flag, uc_constraint_set1_flag; WORD32 i4_cropped_ht, i4_cropped_wd; UWORD32 u4_temp; WORD32 pic_height_in_map_units_minus1 = 0; UWORD32 u2_pic_wd = 0; UWORD32 u2_pic_ht = 0; UWORD32 u2_frm_wd_y = 0; UWORD32 u2_frm_ht_y = 0; UWORD32 u2_frm_wd_uv = 0; UWORD32 u2_frm_ht_uv = 0; UWORD32 u2_crop_offset_y = 0; UWORD32 u2_crop_offset_uv = 0; WORD32 ret; UWORD32 u4_num_reorder_frames; /* High profile related syntax element */ WORD32 i4_i; /* G050 */ UWORD8 u1_frame_cropping_flag, u1_frame_cropping_rect_left_ofst, u1_frame_cropping_rect_right_ofst, u1_frame_cropping_rect_top_ofst, u1_frame_cropping_rect_bottom_ofst; /* G050 */ /*--------------------------------------------------------------------*/ /* Decode seq_parameter_set_id and profile and level values */ /*--------------------------------------------------------------------*/ SWITCHONTRACE; u1_profile_idc = ih264d_get_bits_h264(ps_bitstrm, 8); COPYTHECONTEXT("SPS: profile_idc",u1_profile_idc); /* G050 */ uc_constraint_set0_flag = ih264d_get_bit_h264(ps_bitstrm); uc_constraint_set1_flag = ih264d_get_bit_h264(ps_bitstrm); ih264d_get_bit_h264(ps_bitstrm); /*****************************************************/ /* Read 5 bits for uc_constraint_set3_flag (1 bit) */ /* and reserved_zero_4bits (4 bits) - Sushant */ /*****************************************************/ ih264d_get_bits_h264(ps_bitstrm, 5); /* G050 */ /* Check whether particular profile is suported or not */ /* Check whether particular profile is suported or not */ if((u1_profile_idc != MAIN_PROFILE_IDC) && (u1_profile_idc != BASE_PROFILE_IDC) && (u1_profile_idc != HIGH_PROFILE_IDC) ) { /* Apart from Baseline, main and high profile, * only extended profile is supported provided * uc_constraint_set0_flag or uc_constraint_set1_flag are set to 1 */ if((u1_profile_idc != EXTENDED_PROFILE_IDC) || ((uc_constraint_set1_flag != 1) && (uc_constraint_set0_flag != 1))) { return (ERROR_FEATURE_UNAVAIL); } } u1_level_idc = ih264d_get_bits_h264(ps_bitstrm, 8); COPYTHECONTEXT("SPS: u4_level_idc",u1_level_idc); u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp & MASK_ERR_SEQ_SET_ID) return ERROR_INV_SPS_PPS_T; u1_seq_parameter_set_id = u4_temp; COPYTHECONTEXT("SPS: seq_parameter_set_id", u1_seq_parameter_set_id); /*--------------------------------------------------------------------*/ /* Find an seq param entry in seqparam array of decStruct */ /*--------------------------------------------------------------------*/ ps_seq = ps_dec->pv_scratch_sps_pps; if(ps_dec->i4_header_decoded & 1) { *ps_seq = *ps_dec->ps_cur_sps; } if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_profile_idc != u1_profile_idc)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_level_idc != u1_level_idc)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } ps_seq->u1_profile_idc = u1_profile_idc; ps_seq->u1_level_idc = u1_level_idc; ps_seq->u1_seq_parameter_set_id = u1_seq_parameter_set_id; /*******************************************************************/ /* Initializations for high profile - Sushant */ /*******************************************************************/ ps_seq->i4_chroma_format_idc = 1; ps_seq->i4_bit_depth_luma_minus8 = 0; ps_seq->i4_bit_depth_chroma_minus8 = 0; ps_seq->i4_qpprime_y_zero_transform_bypass_flag = 0; ps_seq->i4_seq_scaling_matrix_present_flag = 0; if(u1_profile_idc == HIGH_PROFILE_IDC) { /* reading chroma_format_idc */ ps_seq->i4_chroma_format_idc = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); /* Monochrome is not supported */ if(ps_seq->i4_chroma_format_idc != 1) { return ERROR_INV_SPS_PPS_T; } /* reading bit_depth_luma_minus8 */ ps_seq->i4_bit_depth_luma_minus8 = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(ps_seq->i4_bit_depth_luma_minus8 != 0) { return ERROR_INV_SPS_PPS_T; } /* reading bit_depth_chroma_minus8 */ ps_seq->i4_bit_depth_chroma_minus8 = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(ps_seq->i4_bit_depth_chroma_minus8 != 0) { return ERROR_INV_SPS_PPS_T; } /* reading qpprime_y_zero_transform_bypass_flag */ ps_seq->i4_qpprime_y_zero_transform_bypass_flag = (WORD32)ih264d_get_bit_h264(ps_bitstrm); if(ps_seq->i4_qpprime_y_zero_transform_bypass_flag != 0) { return ERROR_INV_SPS_PPS_T; } /* reading seq_scaling_matrix_present_flag */ ps_seq->i4_seq_scaling_matrix_present_flag = (WORD32)ih264d_get_bit_h264(ps_bitstrm); if(ps_seq->i4_seq_scaling_matrix_present_flag) { for(i4_i = 0; i4_i < 8; i4_i++) { ps_seq->u1_seq_scaling_list_present_flag[i4_i] = ih264d_get_bit_h264(ps_bitstrm); /* initialize u1_use_default_scaling_matrix_flag[i4_i] to zero */ /* before calling scaling list */ ps_seq->u1_use_default_scaling_matrix_flag[i4_i] = 0; if(ps_seq->u1_seq_scaling_list_present_flag[i4_i]) { if(i4_i < 6) { ih264d_scaling_list( ps_seq->i2_scalinglist4x4[i4_i], 16, &ps_seq->u1_use_default_scaling_matrix_flag[i4_i], ps_bitstrm); } else { ih264d_scaling_list( ps_seq->i2_scalinglist8x8[i4_i - 6], 64, &ps_seq->u1_use_default_scaling_matrix_flag[i4_i], ps_bitstrm); } } } } } /*--------------------------------------------------------------------*/ /* Decode MaxFrameNum */ /*--------------------------------------------------------------------*/ u4_temp = 4 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_BITS_IN_FRAME_NUM) { return ERROR_INV_SPS_PPS_T; } ps_seq->u1_bits_in_frm_num = u4_temp; COPYTHECONTEXT("SPS: log2_max_frame_num_minus4", (ps_seq->u1_bits_in_frm_num - 4)); i2_max_frm_num = (1 << (ps_seq->u1_bits_in_frm_num)); ps_seq->u2_u4_max_pic_num_minus1 = i2_max_frm_num - 1; /*--------------------------------------------------------------------*/ /* Decode picture order count and related values */ /*--------------------------------------------------------------------*/ u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_PIC_ORDER_CNT_TYPE) { return ERROR_INV_POC_TYPE_T; } ps_seq->u1_pic_order_cnt_type = u4_temp; COPYTHECONTEXT("SPS: pic_order_cnt_type",ps_seq->u1_pic_order_cnt_type); ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle = 1; if(ps_seq->u1_pic_order_cnt_type == 0) { u4_temp = 4 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_BITS_IN_POC_LSB) { return ERROR_INV_SPS_PPS_T; } ps_seq->u1_log2_max_pic_order_cnt_lsb_minus = u4_temp; ps_seq->i4_max_pic_order_cntLsb = (1 << u4_temp); COPYTHECONTEXT("SPS: log2_max_pic_order_cnt_lsb_minus4",(u4_temp - 4)); } else if(ps_seq->u1_pic_order_cnt_type == 1) { ps_seq->u1_delta_pic_order_always_zero_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SPS: delta_pic_order_always_zero_flag", ps_seq->u1_delta_pic_order_always_zero_flag); ps_seq->i4_ofst_for_non_ref_pic = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: offset_for_non_ref_pic", ps_seq->i4_ofst_for_non_ref_pic); ps_seq->i4_ofst_for_top_to_bottom_field = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: offset_for_top_to_bottom_field", ps_seq->i4_ofst_for_top_to_bottom_field); u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > 255) return ERROR_INV_SPS_PPS_T; ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle = u4_temp; COPYTHECONTEXT("SPS: num_ref_frames_in_pic_order_cnt_cycle", ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle); for(i = 0; i < ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle; i++) { ps_seq->i4_ofst_for_ref_frame[i] = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: offset_for_ref_frame", ps_seq->i4_ofst_for_ref_frame[i]); } } u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if((u4_temp > H264_MAX_REF_PICS)) { return ERROR_NUM_REF; } /* Compare with older num_ref_frames is header is already once */ if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_num_ref_frames != u4_temp)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } ps_seq->u1_num_ref_frames = u4_temp; COPYTHECONTEXT("SPS: num_ref_frames",ps_seq->u1_num_ref_frames); ps_seq->u1_gaps_in_frame_num_value_allowed_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SPS: gaps_in_frame_num_value_allowed_flag", ps_seq->u1_gaps_in_frame_num_value_allowed_flag); /*--------------------------------------------------------------------*/ /* Decode FrameWidth and FrameHeight and related values */ /*--------------------------------------------------------------------*/ ps_seq->u2_frm_wd_in_mbs = 1 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: pic_width_in_mbs_minus1", ps_seq->u2_frm_wd_in_mbs - 1); u2_pic_wd = (ps_seq->u2_frm_wd_in_mbs << 4); pic_height_in_map_units_minus1 = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_seq->u2_frm_ht_in_mbs = 1 + pic_height_in_map_units_minus1; u2_pic_ht = (ps_seq->u2_frm_ht_in_mbs << 4); /*--------------------------------------------------------------------*/ /* Get the value of MaxMbAddress and Number of bits needed for it */ /*--------------------------------------------------------------------*/ ps_seq->u2_max_mb_addr = (ps_seq->u2_frm_wd_in_mbs * ps_seq->u2_frm_ht_in_mbs) - 1; ps_seq->u2_total_num_of_mbs = ps_seq->u2_max_mb_addr + 1; ps_seq->u1_level_idc = ih264d_correct_level_idc( u1_level_idc, ps_seq->u2_total_num_of_mbs); u1_frm = ih264d_get_bit_h264(ps_bitstrm); if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_frame_mbs_only_flag != u1_frm)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } ps_seq->u1_frame_mbs_only_flag = u1_frm; COPYTHECONTEXT("SPS: frame_mbs_only_flag", u1_frm); if(!u1_frm) { u2_pic_ht <<= 1; ps_seq->u1_mb_aff_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SPS: mb_adaptive_frame_field_flag", ps_seq->u1_mb_aff_flag); } else ps_seq->u1_mb_aff_flag = 0; ps_seq->u1_direct_8x8_inference_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SPS: direct_8x8_inference_flag", ps_seq->u1_direct_8x8_inference_flag); /* G050 */ u1_frame_cropping_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SPS: frame_cropping_flag",u1_frame_cropping_flag); if(u1_frame_cropping_flag) { u1_frame_cropping_rect_left_ofst = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: frame_cropping_rect_left_offset", u1_frame_cropping_rect_left_ofst); u1_frame_cropping_rect_right_ofst = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: frame_cropping_rect_right_offset", u1_frame_cropping_rect_right_ofst); u1_frame_cropping_rect_top_ofst = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: frame_cropping_rect_top_offset", u1_frame_cropping_rect_top_ofst); u1_frame_cropping_rect_bottom_ofst = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: frame_cropping_rect_bottom_offset", u1_frame_cropping_rect_bottom_ofst); } /* G050 */ ps_seq->u1_vui_parameters_present_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SPS: vui_parameters_present_flag", ps_seq->u1_vui_parameters_present_flag); u2_frm_wd_y = u2_pic_wd + (UWORD8)(PAD_LEN_Y_H << 1); if(1 == ps_dec->u4_share_disp_buf) { if(ps_dec->u4_app_disp_width > u2_frm_wd_y) u2_frm_wd_y = ps_dec->u4_app_disp_width; } u2_frm_ht_y = u2_pic_ht + (UWORD8)(PAD_LEN_Y_V << 2); u2_frm_wd_uv = u2_pic_wd + (UWORD8)(PAD_LEN_UV_H << 2); u2_frm_wd_uv = MAX(u2_frm_wd_uv, u2_frm_wd_y); u2_frm_ht_uv = (u2_pic_ht >> 1) + (UWORD8)(PAD_LEN_UV_V << 2); u2_frm_ht_uv = MAX(u2_frm_ht_uv, (u2_frm_ht_y >> 1)); /* Calculate display picture width, height and start u4_ofst from YUV420 */ /* pictute buffers as per cropping information parsed above */ { UWORD16 u2_rgt_ofst = 0; UWORD16 u2_lft_ofst = 0; UWORD16 u2_top_ofst = 0; UWORD16 u2_btm_ofst = 0; UWORD8 u1_frm_mbs_flag; UWORD8 u1_vert_mult_factor; if(u1_frame_cropping_flag) { /* Calculate right and left u4_ofst for cropped picture */ u2_rgt_ofst = u1_frame_cropping_rect_right_ofst << 1; u2_lft_ofst = u1_frame_cropping_rect_left_ofst << 1; /* Know frame MBs only u4_flag */ u1_frm_mbs_flag = (1 == ps_seq->u1_frame_mbs_only_flag); /* Simplify the vertical u4_ofst calculation from field/frame */ u1_vert_mult_factor = (2 - u1_frm_mbs_flag); /* Calculate bottom and top u4_ofst for cropped picture */ u2_btm_ofst = (u1_frame_cropping_rect_bottom_ofst << u1_vert_mult_factor); u2_top_ofst = (u1_frame_cropping_rect_top_ofst << u1_vert_mult_factor); } /* Calculate u4_ofst from start of YUV 420 picture buffer to start of*/ /* cropped picture buffer */ u2_crop_offset_y = (u2_frm_wd_y * u2_top_ofst) + (u2_lft_ofst); u2_crop_offset_uv = (u2_frm_wd_uv * (u2_top_ofst >> 1)) + (u2_lft_ofst >> 1) * YUV420SP_FACTOR; /* Calculate the display picture width and height based on crop */ /* information */ i4_cropped_ht = u2_pic_ht - (u2_btm_ofst + u2_top_ofst); i4_cropped_wd = u2_pic_wd - (u2_rgt_ofst + u2_lft_ofst); if((i4_cropped_ht < MB_SIZE) || (i4_cropped_wd < MB_SIZE)) { return ERROR_INV_SPS_PPS_T; } if((ps_dec->i4_header_decoded & 1) && (ps_dec->u2_pic_wd != u2_pic_wd)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } if((ps_dec->i4_header_decoded & 1) && (ps_dec->u2_pic_ht != u2_pic_ht)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } /* Check for unsupported resolutions */ if((u2_pic_wd > H264_MAX_FRAME_WIDTH) || (u2_pic_ht > H264_MAX_FRAME_HEIGHT) || (u2_pic_wd < H264_MIN_FRAME_WIDTH) || (u2_pic_ht < H264_MIN_FRAME_HEIGHT) || (u2_pic_wd * (UWORD32)u2_pic_ht > H264_MAX_FRAME_SIZE)) { return IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED; } /* If MBAff is enabled, decoder support is limited to streams with * width less than half of H264_MAX_FRAME_WIDTH. * In case of MBAff decoder processes two rows at a time */ if((u2_pic_wd << ps_seq->u1_mb_aff_flag) > H264_MAX_FRAME_WIDTH) { return IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED; } } /* Backup u4_num_reorder_frames if header is already decoded */ if((ps_dec->i4_header_decoded & 1) && (1 == ps_seq->u1_vui_parameters_present_flag) && (1 == ps_seq->s_vui.u1_bitstream_restriction_flag)) { u4_num_reorder_frames = ps_seq->s_vui.u4_num_reorder_frames; } else { u4_num_reorder_frames = -1; } if(1 == ps_seq->u1_vui_parameters_present_flag) { ret = ih264d_parse_vui_parametres(&ps_seq->s_vui, ps_bitstrm); if(ret != OK) return ret; } /* Compare older u4_num_reorder_frames with the new one if header is already decoded */ if((ps_dec->i4_header_decoded & 1) && (-1 != (WORD32)u4_num_reorder_frames) && (1 == ps_seq->u1_vui_parameters_present_flag) && (1 == ps_seq->s_vui.u1_bitstream_restriction_flag) && (ps_seq->s_vui.u4_num_reorder_frames != u4_num_reorder_frames)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } /* In case bitstream read has exceeded the filled size, then return an error */ if (ps_bitstrm->u4_ofst > ps_bitstrm->u4_max_ofst) { return ERROR_INV_SPS_PPS_T; } /*--------------------------------------------------------------------*/ /* All initializations to ps_dec are beyond this point */ /*--------------------------------------------------------------------*/ ps_dec->u2_disp_height = i4_cropped_ht; ps_dec->u2_disp_width = i4_cropped_wd; ps_dec->u2_pic_wd = u2_pic_wd; ps_dec->u2_pic_ht = u2_pic_ht; /* Determining the Width and Height of Frame from that of Picture */ ps_dec->u2_frm_wd_y = u2_frm_wd_y; ps_dec->u2_frm_ht_y = u2_frm_ht_y; ps_dec->u2_frm_wd_uv = u2_frm_wd_uv; ps_dec->u2_frm_ht_uv = u2_frm_ht_uv; ps_dec->s_pad_mgr.u1_pad_len_y_v = (UWORD8)(PAD_LEN_Y_V << (1 - u1_frm)); ps_dec->s_pad_mgr.u1_pad_len_cr_v = (UWORD8)(PAD_LEN_UV_V << (1 - u1_frm)); ps_dec->u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs; ps_dec->u2_frm_ht_in_mbs = ps_seq->u2_frm_ht_in_mbs; ps_dec->u2_crop_offset_y = u2_crop_offset_y; ps_dec->u2_crop_offset_uv = u2_crop_offset_uv; ps_seq->u1_is_valid = TRUE; ps_dec->ps_sps[u1_seq_parameter_set_id] = *ps_seq; ps_dec->ps_cur_sps = &ps_dec->ps_sps[u1_seq_parameter_set_id]; return OK; } Commit Message: Decoder: Detect change of mbaff flag in SPS Change in Mbaff flag needs re-initialization of NMB group and other variables in decoder context. Bug: 64380237 Test: ran poc on ASAN before/after Change-Id: I0fc65e4dfc3cc2c15528ec52da1782ecec61feab (cherry picked from commit d524ba03101c0c662c9d365d7357536b42a0265e) CWE ID: CWE-200
WORD32 ih264d_parse_sps(dec_struct_t *ps_dec, dec_bit_stream_t *ps_bitstrm) { UWORD8 i; dec_seq_params_t *ps_seq = NULL; UWORD8 u1_profile_idc, u1_level_idc, u1_seq_parameter_set_id, u1_mb_aff_flag = 0; UWORD16 i2_max_frm_num; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; UWORD8 u1_frm, uc_constraint_set0_flag, uc_constraint_set1_flag; WORD32 i4_cropped_ht, i4_cropped_wd; UWORD32 u4_temp; WORD32 pic_height_in_map_units_minus1 = 0; UWORD32 u2_pic_wd = 0; UWORD32 u2_pic_ht = 0; UWORD32 u2_frm_wd_y = 0; UWORD32 u2_frm_ht_y = 0; UWORD32 u2_frm_wd_uv = 0; UWORD32 u2_frm_ht_uv = 0; UWORD32 u2_crop_offset_y = 0; UWORD32 u2_crop_offset_uv = 0; WORD32 ret; UWORD32 u4_num_reorder_frames; /* High profile related syntax element */ WORD32 i4_i; /* G050 */ UWORD8 u1_frame_cropping_flag, u1_frame_cropping_rect_left_ofst, u1_frame_cropping_rect_right_ofst, u1_frame_cropping_rect_top_ofst, u1_frame_cropping_rect_bottom_ofst; /* G050 */ /*--------------------------------------------------------------------*/ /* Decode seq_parameter_set_id and profile and level values */ /*--------------------------------------------------------------------*/ SWITCHONTRACE; u1_profile_idc = ih264d_get_bits_h264(ps_bitstrm, 8); COPYTHECONTEXT("SPS: profile_idc",u1_profile_idc); /* G050 */ uc_constraint_set0_flag = ih264d_get_bit_h264(ps_bitstrm); uc_constraint_set1_flag = ih264d_get_bit_h264(ps_bitstrm); ih264d_get_bit_h264(ps_bitstrm); /*****************************************************/ /* Read 5 bits for uc_constraint_set3_flag (1 bit) */ /* and reserved_zero_4bits (4 bits) - Sushant */ /*****************************************************/ ih264d_get_bits_h264(ps_bitstrm, 5); /* G050 */ /* Check whether particular profile is suported or not */ /* Check whether particular profile is suported or not */ if((u1_profile_idc != MAIN_PROFILE_IDC) && (u1_profile_idc != BASE_PROFILE_IDC) && (u1_profile_idc != HIGH_PROFILE_IDC) ) { /* Apart from Baseline, main and high profile, * only extended profile is supported provided * uc_constraint_set0_flag or uc_constraint_set1_flag are set to 1 */ if((u1_profile_idc != EXTENDED_PROFILE_IDC) || ((uc_constraint_set1_flag != 1) && (uc_constraint_set0_flag != 1))) { return (ERROR_FEATURE_UNAVAIL); } } u1_level_idc = ih264d_get_bits_h264(ps_bitstrm, 8); COPYTHECONTEXT("SPS: u4_level_idc",u1_level_idc); u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp & MASK_ERR_SEQ_SET_ID) return ERROR_INV_SPS_PPS_T; u1_seq_parameter_set_id = u4_temp; COPYTHECONTEXT("SPS: seq_parameter_set_id", u1_seq_parameter_set_id); /*--------------------------------------------------------------------*/ /* Find an seq param entry in seqparam array of decStruct */ /*--------------------------------------------------------------------*/ ps_seq = ps_dec->pv_scratch_sps_pps; if(ps_dec->i4_header_decoded & 1) { *ps_seq = *ps_dec->ps_cur_sps; } if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_profile_idc != u1_profile_idc)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_level_idc != u1_level_idc)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } ps_seq->u1_profile_idc = u1_profile_idc; ps_seq->u1_level_idc = u1_level_idc; ps_seq->u1_seq_parameter_set_id = u1_seq_parameter_set_id; /*******************************************************************/ /* Initializations for high profile - Sushant */ /*******************************************************************/ ps_seq->i4_chroma_format_idc = 1; ps_seq->i4_bit_depth_luma_minus8 = 0; ps_seq->i4_bit_depth_chroma_minus8 = 0; ps_seq->i4_qpprime_y_zero_transform_bypass_flag = 0; ps_seq->i4_seq_scaling_matrix_present_flag = 0; if(u1_profile_idc == HIGH_PROFILE_IDC) { /* reading chroma_format_idc */ ps_seq->i4_chroma_format_idc = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); /* Monochrome is not supported */ if(ps_seq->i4_chroma_format_idc != 1) { return ERROR_INV_SPS_PPS_T; } /* reading bit_depth_luma_minus8 */ ps_seq->i4_bit_depth_luma_minus8 = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(ps_seq->i4_bit_depth_luma_minus8 != 0) { return ERROR_INV_SPS_PPS_T; } /* reading bit_depth_chroma_minus8 */ ps_seq->i4_bit_depth_chroma_minus8 = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(ps_seq->i4_bit_depth_chroma_minus8 != 0) { return ERROR_INV_SPS_PPS_T; } /* reading qpprime_y_zero_transform_bypass_flag */ ps_seq->i4_qpprime_y_zero_transform_bypass_flag = (WORD32)ih264d_get_bit_h264(ps_bitstrm); if(ps_seq->i4_qpprime_y_zero_transform_bypass_flag != 0) { return ERROR_INV_SPS_PPS_T; } /* reading seq_scaling_matrix_present_flag */ ps_seq->i4_seq_scaling_matrix_present_flag = (WORD32)ih264d_get_bit_h264(ps_bitstrm); if(ps_seq->i4_seq_scaling_matrix_present_flag) { for(i4_i = 0; i4_i < 8; i4_i++) { ps_seq->u1_seq_scaling_list_present_flag[i4_i] = ih264d_get_bit_h264(ps_bitstrm); /* initialize u1_use_default_scaling_matrix_flag[i4_i] to zero */ /* before calling scaling list */ ps_seq->u1_use_default_scaling_matrix_flag[i4_i] = 0; if(ps_seq->u1_seq_scaling_list_present_flag[i4_i]) { if(i4_i < 6) { ih264d_scaling_list( ps_seq->i2_scalinglist4x4[i4_i], 16, &ps_seq->u1_use_default_scaling_matrix_flag[i4_i], ps_bitstrm); } else { ih264d_scaling_list( ps_seq->i2_scalinglist8x8[i4_i - 6], 64, &ps_seq->u1_use_default_scaling_matrix_flag[i4_i], ps_bitstrm); } } } } } /*--------------------------------------------------------------------*/ /* Decode MaxFrameNum */ /*--------------------------------------------------------------------*/ u4_temp = 4 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_BITS_IN_FRAME_NUM) { return ERROR_INV_SPS_PPS_T; } ps_seq->u1_bits_in_frm_num = u4_temp; COPYTHECONTEXT("SPS: log2_max_frame_num_minus4", (ps_seq->u1_bits_in_frm_num - 4)); i2_max_frm_num = (1 << (ps_seq->u1_bits_in_frm_num)); ps_seq->u2_u4_max_pic_num_minus1 = i2_max_frm_num - 1; /*--------------------------------------------------------------------*/ /* Decode picture order count and related values */ /*--------------------------------------------------------------------*/ u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_PIC_ORDER_CNT_TYPE) { return ERROR_INV_POC_TYPE_T; } ps_seq->u1_pic_order_cnt_type = u4_temp; COPYTHECONTEXT("SPS: pic_order_cnt_type",ps_seq->u1_pic_order_cnt_type); ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle = 1; if(ps_seq->u1_pic_order_cnt_type == 0) { u4_temp = 4 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_BITS_IN_POC_LSB) { return ERROR_INV_SPS_PPS_T; } ps_seq->u1_log2_max_pic_order_cnt_lsb_minus = u4_temp; ps_seq->i4_max_pic_order_cntLsb = (1 << u4_temp); COPYTHECONTEXT("SPS: log2_max_pic_order_cnt_lsb_minus4",(u4_temp - 4)); } else if(ps_seq->u1_pic_order_cnt_type == 1) { ps_seq->u1_delta_pic_order_always_zero_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SPS: delta_pic_order_always_zero_flag", ps_seq->u1_delta_pic_order_always_zero_flag); ps_seq->i4_ofst_for_non_ref_pic = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: offset_for_non_ref_pic", ps_seq->i4_ofst_for_non_ref_pic); ps_seq->i4_ofst_for_top_to_bottom_field = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: offset_for_top_to_bottom_field", ps_seq->i4_ofst_for_top_to_bottom_field); u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > 255) return ERROR_INV_SPS_PPS_T; ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle = u4_temp; COPYTHECONTEXT("SPS: num_ref_frames_in_pic_order_cnt_cycle", ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle); for(i = 0; i < ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle; i++) { ps_seq->i4_ofst_for_ref_frame[i] = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: offset_for_ref_frame", ps_seq->i4_ofst_for_ref_frame[i]); } } u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if((u4_temp > H264_MAX_REF_PICS)) { return ERROR_NUM_REF; } /* Compare with older num_ref_frames is header is already once */ if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_num_ref_frames != u4_temp)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } ps_seq->u1_num_ref_frames = u4_temp; COPYTHECONTEXT("SPS: num_ref_frames",ps_seq->u1_num_ref_frames); ps_seq->u1_gaps_in_frame_num_value_allowed_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SPS: gaps_in_frame_num_value_allowed_flag", ps_seq->u1_gaps_in_frame_num_value_allowed_flag); /*--------------------------------------------------------------------*/ /* Decode FrameWidth and FrameHeight and related values */ /*--------------------------------------------------------------------*/ ps_seq->u2_frm_wd_in_mbs = 1 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: pic_width_in_mbs_minus1", ps_seq->u2_frm_wd_in_mbs - 1); u2_pic_wd = (ps_seq->u2_frm_wd_in_mbs << 4); pic_height_in_map_units_minus1 = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_seq->u2_frm_ht_in_mbs = 1 + pic_height_in_map_units_minus1; u2_pic_ht = (ps_seq->u2_frm_ht_in_mbs << 4); /*--------------------------------------------------------------------*/ /* Get the value of MaxMbAddress and Number of bits needed for it */ /*--------------------------------------------------------------------*/ ps_seq->u2_max_mb_addr = (ps_seq->u2_frm_wd_in_mbs * ps_seq->u2_frm_ht_in_mbs) - 1; ps_seq->u2_total_num_of_mbs = ps_seq->u2_max_mb_addr + 1; ps_seq->u1_level_idc = ih264d_correct_level_idc( u1_level_idc, ps_seq->u2_total_num_of_mbs); u1_frm = ih264d_get_bit_h264(ps_bitstrm); if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_frame_mbs_only_flag != u1_frm)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } ps_seq->u1_frame_mbs_only_flag = u1_frm; COPYTHECONTEXT("SPS: frame_mbs_only_flag", u1_frm); if(!u1_frm) u1_mb_aff_flag = ih264d_get_bit_h264(ps_bitstrm); if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_mb_aff_flag != u1_mb_aff_flag)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } if(!u1_frm) { u2_pic_ht <<= 1; ps_seq->u1_mb_aff_flag = u1_mb_aff_flag; COPYTHECONTEXT("SPS: mb_adaptive_frame_field_flag", ps_seq->u1_mb_aff_flag); } else ps_seq->u1_mb_aff_flag = 0; ps_seq->u1_direct_8x8_inference_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SPS: direct_8x8_inference_flag", ps_seq->u1_direct_8x8_inference_flag); /* G050 */ u1_frame_cropping_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SPS: frame_cropping_flag",u1_frame_cropping_flag); if(u1_frame_cropping_flag) { u1_frame_cropping_rect_left_ofst = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: frame_cropping_rect_left_offset", u1_frame_cropping_rect_left_ofst); u1_frame_cropping_rect_right_ofst = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: frame_cropping_rect_right_offset", u1_frame_cropping_rect_right_ofst); u1_frame_cropping_rect_top_ofst = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: frame_cropping_rect_top_offset", u1_frame_cropping_rect_top_ofst); u1_frame_cropping_rect_bottom_ofst = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SPS: frame_cropping_rect_bottom_offset", u1_frame_cropping_rect_bottom_ofst); } /* G050 */ ps_seq->u1_vui_parameters_present_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SPS: vui_parameters_present_flag", ps_seq->u1_vui_parameters_present_flag); u2_frm_wd_y = u2_pic_wd + (UWORD8)(PAD_LEN_Y_H << 1); if(1 == ps_dec->u4_share_disp_buf) { if(ps_dec->u4_app_disp_width > u2_frm_wd_y) u2_frm_wd_y = ps_dec->u4_app_disp_width; } u2_frm_ht_y = u2_pic_ht + (UWORD8)(PAD_LEN_Y_V << 2); u2_frm_wd_uv = u2_pic_wd + (UWORD8)(PAD_LEN_UV_H << 2); u2_frm_wd_uv = MAX(u2_frm_wd_uv, u2_frm_wd_y); u2_frm_ht_uv = (u2_pic_ht >> 1) + (UWORD8)(PAD_LEN_UV_V << 2); u2_frm_ht_uv = MAX(u2_frm_ht_uv, (u2_frm_ht_y >> 1)); /* Calculate display picture width, height and start u4_ofst from YUV420 */ /* pictute buffers as per cropping information parsed above */ { UWORD16 u2_rgt_ofst = 0; UWORD16 u2_lft_ofst = 0; UWORD16 u2_top_ofst = 0; UWORD16 u2_btm_ofst = 0; UWORD8 u1_frm_mbs_flag; UWORD8 u1_vert_mult_factor; if(u1_frame_cropping_flag) { /* Calculate right and left u4_ofst for cropped picture */ u2_rgt_ofst = u1_frame_cropping_rect_right_ofst << 1; u2_lft_ofst = u1_frame_cropping_rect_left_ofst << 1; /* Know frame MBs only u4_flag */ u1_frm_mbs_flag = (1 == ps_seq->u1_frame_mbs_only_flag); /* Simplify the vertical u4_ofst calculation from field/frame */ u1_vert_mult_factor = (2 - u1_frm_mbs_flag); /* Calculate bottom and top u4_ofst for cropped picture */ u2_btm_ofst = (u1_frame_cropping_rect_bottom_ofst << u1_vert_mult_factor); u2_top_ofst = (u1_frame_cropping_rect_top_ofst << u1_vert_mult_factor); } /* Calculate u4_ofst from start of YUV 420 picture buffer to start of*/ /* cropped picture buffer */ u2_crop_offset_y = (u2_frm_wd_y * u2_top_ofst) + (u2_lft_ofst); u2_crop_offset_uv = (u2_frm_wd_uv * (u2_top_ofst >> 1)) + (u2_lft_ofst >> 1) * YUV420SP_FACTOR; /* Calculate the display picture width and height based on crop */ /* information */ i4_cropped_ht = u2_pic_ht - (u2_btm_ofst + u2_top_ofst); i4_cropped_wd = u2_pic_wd - (u2_rgt_ofst + u2_lft_ofst); if((i4_cropped_ht < MB_SIZE) || (i4_cropped_wd < MB_SIZE)) { return ERROR_INV_SPS_PPS_T; } if((ps_dec->i4_header_decoded & 1) && (ps_dec->u2_pic_wd != u2_pic_wd)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } if((ps_dec->i4_header_decoded & 1) && (ps_dec->u2_pic_ht != u2_pic_ht)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } /* Check for unsupported resolutions */ if((u2_pic_wd > H264_MAX_FRAME_WIDTH) || (u2_pic_ht > H264_MAX_FRAME_HEIGHT) || (u2_pic_wd < H264_MIN_FRAME_WIDTH) || (u2_pic_ht < H264_MIN_FRAME_HEIGHT) || (u2_pic_wd * (UWORD32)u2_pic_ht > H264_MAX_FRAME_SIZE)) { return IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED; } /* If MBAff is enabled, decoder support is limited to streams with * width less than half of H264_MAX_FRAME_WIDTH. * In case of MBAff decoder processes two rows at a time */ if((u2_pic_wd << ps_seq->u1_mb_aff_flag) > H264_MAX_FRAME_WIDTH) { return IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED; } } /* Backup u4_num_reorder_frames if header is already decoded */ if((ps_dec->i4_header_decoded & 1) && (1 == ps_seq->u1_vui_parameters_present_flag) && (1 == ps_seq->s_vui.u1_bitstream_restriction_flag)) { u4_num_reorder_frames = ps_seq->s_vui.u4_num_reorder_frames; } else { u4_num_reorder_frames = -1; } if(1 == ps_seq->u1_vui_parameters_present_flag) { ret = ih264d_parse_vui_parametres(&ps_seq->s_vui, ps_bitstrm); if(ret != OK) return ret; } /* Compare older u4_num_reorder_frames with the new one if header is already decoded */ if((ps_dec->i4_header_decoded & 1) && (-1 != (WORD32)u4_num_reorder_frames) && (1 == ps_seq->u1_vui_parameters_present_flag) && (1 == ps_seq->s_vui.u1_bitstream_restriction_flag) && (ps_seq->s_vui.u4_num_reorder_frames != u4_num_reorder_frames)) { ps_dec->u1_res_changed = 1; return IVD_RES_CHANGED; } /* In case bitstream read has exceeded the filled size, then return an error */ if (ps_bitstrm->u4_ofst > ps_bitstrm->u4_max_ofst) { return ERROR_INV_SPS_PPS_T; } /*--------------------------------------------------------------------*/ /* All initializations to ps_dec are beyond this point */ /*--------------------------------------------------------------------*/ ps_dec->u2_disp_height = i4_cropped_ht; ps_dec->u2_disp_width = i4_cropped_wd; ps_dec->u2_pic_wd = u2_pic_wd; ps_dec->u2_pic_ht = u2_pic_ht; /* Determining the Width and Height of Frame from that of Picture */ ps_dec->u2_frm_wd_y = u2_frm_wd_y; ps_dec->u2_frm_ht_y = u2_frm_ht_y; ps_dec->u2_frm_wd_uv = u2_frm_wd_uv; ps_dec->u2_frm_ht_uv = u2_frm_ht_uv; ps_dec->s_pad_mgr.u1_pad_len_y_v = (UWORD8)(PAD_LEN_Y_V << (1 - u1_frm)); ps_dec->s_pad_mgr.u1_pad_len_cr_v = (UWORD8)(PAD_LEN_UV_V << (1 - u1_frm)); ps_dec->u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs; ps_dec->u2_frm_ht_in_mbs = ps_seq->u2_frm_ht_in_mbs; ps_dec->u2_crop_offset_y = u2_crop_offset_y; ps_dec->u2_crop_offset_uv = u2_crop_offset_uv; ps_seq->u1_is_valid = TRUE; ps_dec->ps_sps[u1_seq_parameter_set_id] = *ps_seq; ps_dec->ps_cur_sps = &ps_dec->ps_sps[u1_seq_parameter_set_id]; return OK; }
174,105
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_mcrypt_module_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */ { php_mcrypt *pm = (php_mcrypt *) rsrc->ptr; if (pm) { mcrypt_generic_deinit(pm->td); mcrypt_module_close(pm->td); efree(pm); pm = NULL; } } /* }}} */ Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
static void php_mcrypt_module_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */ { php_mcrypt *pm = (php_mcrypt *) rsrc->ptr; if (pm) { mcrypt_generic_deinit(pm->td); mcrypt_module_close(pm->td); efree(pm); pm = NULL; } } /* }}} */
167,114
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GKI_delay(UINT32 timeout_ms) { struct timespec delay; delay.tv_sec = timeout_ms / 1000; delay.tv_nsec = 1000 * 1000 * (timeout_ms % 1000); int err; do { err = nanosleep(&delay, &delay); } while (err == -1 && errno == EINTR); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
void GKI_delay(UINT32 timeout_ms) { struct timespec delay; delay.tv_sec = timeout_ms / 1000; delay.tv_nsec = 1000 * 1000 * (timeout_ms % 1000); int err; do { err = TEMP_FAILURE_RETRY(nanosleep(&delay, &delay)); } while (err == -1 && errno == EINTR); }
173,471
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: otp_verify(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request, krb5_enc_tkt_part *enc_tkt_reply, krb5_pa_data *pa, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_kdcpreauth_moddata moddata, krb5_kdcpreauth_verify_respond_fn respond, void *arg) { krb5_keyblock *armor_key = NULL; krb5_pa_otp_req *req = NULL; struct request_state *rs; krb5_error_code retval; krb5_data d, plaintext; char *config; enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH; /* Get the FAST armor key. */ armor_key = cb->fast_armor(context, rock); if (armor_key == NULL) { retval = KRB5KDC_ERR_PREAUTH_FAILED; com_err("otp", retval, "No armor key found when verifying padata"); goto error; } /* Decode the request. */ d = make_data(pa->contents, pa->length); retval = decode_krb5_pa_otp_req(&d, &req); if (retval != 0) { com_err("otp", retval, "Unable to decode OTP request"); goto error; } /* Decrypt the nonce from the request. */ retval = decrypt_encdata(context, armor_key, req, &plaintext); if (retval != 0) { com_err("otp", retval, "Unable to decrypt nonce"); goto error; } /* Verify the nonce or timestamp. */ retval = nonce_verify(context, armor_key, &plaintext); if (retval != 0) retval = timestamp_verify(context, &plaintext); krb5_free_data_contents(context, &plaintext); if (retval != 0) { com_err("otp", retval, "Unable to verify nonce or timestamp"); goto error; } /* Create the request state. */ rs = k5alloc(sizeof(struct request_state), &retval); if (rs == NULL) goto error; rs->arg = arg; rs->respond = respond; /* Get the principal's OTP configuration string. */ retval = cb->get_string(context, rock, "otp", &config); if (retval == 0 && config == NULL) retval = KRB5_PREAUTH_FAILED; if (retval != 0) { free(rs); goto error; } /* Send the request. */ otp_state_verify((otp_state *)moddata, cb->event_context(context, rock), request->client, config, req, on_response, rs); cb->free_string(context, rock, config); k5_free_pa_otp_req(context, req); return; error: k5_free_pa_otp_req(context, req); (*respond)(arg, retval, NULL, NULL, NULL); } Commit Message: Prevent requires_preauth bypass [CVE-2015-2694] In the OTP kdcpreauth module, don't set the TKT_FLG_PRE_AUTH bit until the request is successfully verified. In the PKINIT kdcpreauth module, don't respond with code 0 on empty input or an unconfigured realm. Together these bugs could cause the KDC preauth framework to erroneously treat a request as pre-authenticated. CVE-2015-2694: In MIT krb5 1.12 and later, when the KDC is configured with PKINIT support, an unauthenticated remote attacker can bypass the requires_preauth flag on a client principal and obtain a ciphertext encrypted in the principal's long-term key. This ciphertext could be used to conduct an off-line dictionary attack against the user's password. CVSSv2 Vector: AV:N/AC:M/Au:N/C:P/I:P/A:N/E:POC/RL:OF/RC:C ticket: 8160 (new) target_version: 1.13.2 tags: pullup subject: requires_preauth bypass in PKINIT-enabled KDC [CVE-2015-2694] CWE ID: CWE-264
otp_verify(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request, krb5_enc_tkt_part *enc_tkt_reply, krb5_pa_data *pa, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_kdcpreauth_moddata moddata, krb5_kdcpreauth_verify_respond_fn respond, void *arg) { krb5_keyblock *armor_key = NULL; krb5_pa_otp_req *req = NULL; struct request_state *rs; krb5_error_code retval; krb5_data d, plaintext; char *config; /* Get the FAST armor key. */ armor_key = cb->fast_armor(context, rock); if (armor_key == NULL) { retval = KRB5KDC_ERR_PREAUTH_FAILED; com_err("otp", retval, "No armor key found when verifying padata"); goto error; } /* Decode the request. */ d = make_data(pa->contents, pa->length); retval = decode_krb5_pa_otp_req(&d, &req); if (retval != 0) { com_err("otp", retval, "Unable to decode OTP request"); goto error; } /* Decrypt the nonce from the request. */ retval = decrypt_encdata(context, armor_key, req, &plaintext); if (retval != 0) { com_err("otp", retval, "Unable to decrypt nonce"); goto error; } /* Verify the nonce or timestamp. */ retval = nonce_verify(context, armor_key, &plaintext); if (retval != 0) retval = timestamp_verify(context, &plaintext); krb5_free_data_contents(context, &plaintext); if (retval != 0) { com_err("otp", retval, "Unable to verify nonce or timestamp"); goto error; } /* Create the request state. Save the response callback, and the * enc_tkt_reply pointer so we can set the TKT_FLG_PRE_AUTH flag later. */ rs = k5alloc(sizeof(struct request_state), &retval); if (rs == NULL) goto error; rs->arg = arg; rs->respond = respond; rs->enc_tkt_reply = enc_tkt_reply; /* Get the principal's OTP configuration string. */ retval = cb->get_string(context, rock, "otp", &config); if (retval == 0 && config == NULL) retval = KRB5_PREAUTH_FAILED; if (retval != 0) { free(rs); goto error; } /* Send the request. */ otp_state_verify((otp_state *)moddata, cb->event_context(context, rock), request->client, config, req, on_response, rs); cb->free_string(context, rock, config); k5_free_pa_otp_req(context, req); return; error: k5_free_pa_otp_req(context, req); (*respond)(arg, retval, NULL, NULL, NULL); }
166,677
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int UDPSocketLibevent::InternalConnect(const IPEndPoint& address) { DCHECK(CalledOnValidThread()); DCHECK(!is_connected()); DCHECK(!remote_address_.get()); int addr_family = address.GetSockAddrFamily(); int rv = CreateSocket(addr_family); if (rv < 0) return rv; if (bind_type_ == DatagramSocket::RANDOM_BIND) { size_t addr_size = addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize; IPAddressNumber addr_any(addr_size); rv = RandomBind(addr_any); } if (rv < 0) { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", rv); Close(); return rv; } SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) { Close(); return ERR_ADDRESS_INVALID; } rv = HANDLE_EINTR(connect(socket_, storage.addr, storage.addr_len)); if (rv < 0) { int result = MapSystemError(errno); Close(); return result; } remote_address_.reset(new IPEndPoint(address)); return rv; } Commit Message: Map posix error codes in bind better, and fix one windows mapping. r=wtc BUG=330233 Review URL: https://codereview.chromium.org/101193008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
int UDPSocketLibevent::InternalConnect(const IPEndPoint& address) { DCHECK(CalledOnValidThread()); DCHECK(!is_connected()); DCHECK(!remote_address_.get()); int addr_family = address.GetSockAddrFamily(); int rv = CreateSocket(addr_family); if (rv < 0) return rv; if (bind_type_ == DatagramSocket::RANDOM_BIND) { size_t addr_size = addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize; IPAddressNumber addr_any(addr_size); rv = RandomBind(addr_any); } if (rv < 0) { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", -rv); Close(); return rv; } SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) { Close(); return ERR_ADDRESS_INVALID; } rv = HANDLE_EINTR(connect(socket_, storage.addr, storage.addr_len)); if (rv < 0) { int result = MapSystemError(errno); Close(); return result; } remote_address_.reset(new IPEndPoint(address)); return rv; }
171,316
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m, const struct iovec *iv, unsigned long total_len, size_t count, int noblock) { struct sk_buff *skb; struct macvlan_dev *vlan; unsigned long len = total_len; int err; struct virtio_net_hdr vnet_hdr = { 0 }; int vnet_hdr_len = 0; int copylen; bool zerocopy = false; if (q->flags & IFF_VNET_HDR) { vnet_hdr_len = q->vnet_hdr_sz; err = -EINVAL; if (len < vnet_hdr_len) goto err; len -= vnet_hdr_len; err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0, sizeof(vnet_hdr)); if (err < 0) goto err; if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 > vnet_hdr.hdr_len) vnet_hdr.hdr_len = vnet_hdr.csum_start + vnet_hdr.csum_offset + 2; err = -EINVAL; if (vnet_hdr.hdr_len > len) goto err; } err = -EINVAL; if (unlikely(len < ETH_HLEN)) goto err; if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY)) zerocopy = true; if (zerocopy) { /* There are 256 bytes to be copied in skb, so there is enough * room for skb expand head in case it is used. * The rest buffer is mapped from userspace. */ copylen = vnet_hdr.hdr_len; if (!copylen) copylen = GOODCOPY_LEN; } else copylen = len; skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen, vnet_hdr.hdr_len, noblock, &err); if (!skb) goto err; if (zerocopy) err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count); else err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len, len); if (err) goto err_kfree; skb_set_network_header(skb, ETH_HLEN); skb_reset_mac_header(skb); skb->protocol = eth_hdr(skb)->h_proto; if (vnet_hdr_len) { err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr); if (err) goto err_kfree; } rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_shinfo(skb)->destructor_arg = m->msg_control; skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY; } if (vlan) macvlan_start_xmit(skb, vlan->dev); else kfree_skb(skb); rcu_read_unlock_bh(); return total_len; err_kfree: kfree_skb(skb); err: rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); if (vlan) vlan->dev->stats.tx_dropped++; rcu_read_unlock_bh(); return err; } Commit Message: macvtap: zerocopy: validate vectors before building skb There're several reasons that the vectors need to be validated: - Return error when caller provides vectors whose num is greater than UIO_MAXIOV. - Linearize part of skb when userspace provides vectors grater than MAX_SKB_FRAGS. - Return error when userspace provides vectors whose total length may exceed - MAX_SKB_FRAGS * PAGE_SIZE. Signed-off-by: Jason Wang <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> CWE ID: CWE-119
static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m, const struct iovec *iv, unsigned long total_len, size_t count, int noblock) { struct sk_buff *skb; struct macvlan_dev *vlan; unsigned long len = total_len; int err; struct virtio_net_hdr vnet_hdr = { 0 }; int vnet_hdr_len = 0; int copylen = 0; bool zerocopy = false; if (q->flags & IFF_VNET_HDR) { vnet_hdr_len = q->vnet_hdr_sz; err = -EINVAL; if (len < vnet_hdr_len) goto err; len -= vnet_hdr_len; err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0, sizeof(vnet_hdr)); if (err < 0) goto err; if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 > vnet_hdr.hdr_len) vnet_hdr.hdr_len = vnet_hdr.csum_start + vnet_hdr.csum_offset + 2; err = -EINVAL; if (vnet_hdr.hdr_len > len) goto err; } err = -EINVAL; if (unlikely(len < ETH_HLEN)) goto err; err = -EMSGSIZE; if (unlikely(count > UIO_MAXIOV)) goto err; if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY)) zerocopy = true; if (zerocopy) { /* Userspace may produce vectors with count greater than * MAX_SKB_FRAGS, so we need to linearize parts of the skb * to let the rest of data to be fit in the frags. */ if (count > MAX_SKB_FRAGS) { copylen = iov_length(iv, count - MAX_SKB_FRAGS); if (copylen < vnet_hdr_len) copylen = 0; else copylen -= vnet_hdr_len; } /* There are 256 bytes to be copied in skb, so there is enough * room for skb expand head in case it is used. * The rest buffer is mapped from userspace. */ if (copylen < vnet_hdr.hdr_len) copylen = vnet_hdr.hdr_len; if (!copylen) copylen = GOODCOPY_LEN; } else copylen = len; skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen, vnet_hdr.hdr_len, noblock, &err); if (!skb) goto err; if (zerocopy) err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count); else err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len, len); if (err) goto err_kfree; skb_set_network_header(skb, ETH_HLEN); skb_reset_mac_header(skb); skb->protocol = eth_hdr(skb)->h_proto; if (vnet_hdr_len) { err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr); if (err) goto err_kfree; } rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_shinfo(skb)->destructor_arg = m->msg_control; skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY; } if (vlan) macvlan_start_xmit(skb, vlan->dev); else kfree_skb(skb); rcu_read_unlock_bh(); return total_len; err_kfree: kfree_skb(skb); err: rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); if (vlan) vlan->dev->stats.tx_dropped++; rcu_read_unlock_bh(); return err; }
166,204
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: rpmVerifyAttrs rpmfilesVerify(rpmfiles fi, int ix, rpmVerifyAttrs omitMask) { rpm_mode_t fmode = rpmfilesFMode(fi, ix); rpmfileAttrs fileAttrs = rpmfilesFFlags(fi, ix); rpmVerifyAttrs flags = rpmfilesVFlags(fi, ix); const char * fn = rpmfilesFN(fi, ix); struct stat sb; rpmVerifyAttrs vfy = RPMVERIFY_NONE; /* * Check to see if the file was installed - if not pretend all is OK. */ switch (rpmfilesFState(fi, ix)) { case RPMFILE_STATE_NETSHARED: case RPMFILE_STATE_NOTINSTALLED: goto exit; break; case RPMFILE_STATE_REPLACED: /* For replaced files we can only verify if it exists at all */ flags = RPMVERIFY_LSTATFAIL; break; case RPMFILE_STATE_WRONGCOLOR: /* * Files with wrong color are supposed to share some attributes * with the actually installed file - verify what we can. */ flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_RDEV); break; case RPMFILE_STATE_NORMAL: /* File from a non-installed package, try to verify nevertheless */ case RPMFILE_STATE_MISSING: break; } if (fn == NULL || lstat(fn, &sb) != 0) { vfy |= RPMVERIFY_LSTATFAIL; goto exit; } /* If we expected a directory but got a symlink to one, follow the link */ if (S_ISDIR(fmode) && S_ISLNK(sb.st_mode) && stat(fn, &sb) != 0) { vfy |= RPMVERIFY_LSTATFAIL; goto exit; } /* Links have no mode, other types have no linkto */ if (S_ISLNK(sb.st_mode)) flags &= ~(RPMVERIFY_MODE); else flags &= ~(RPMVERIFY_LINKTO); /* Not all attributes of non-regular files can be verified */ if (!S_ISREG(sb.st_mode)) flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_CAPS); /* Content checks of %ghost files are meaningless. */ if (fileAttrs & RPMFILE_GHOST) flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_LINKTO); /* Don't verify any features in omitMask. */ flags &= ~(omitMask | RPMVERIFY_FAILURES); if (flags & RPMVERIFY_FILEDIGEST) { const unsigned char *digest; int algo; size_t diglen; /* XXX If --nomd5, then prelinked library sizes are not corrected. */ if ((digest = rpmfilesFDigest(fi, ix, &algo, &diglen))) { unsigned char fdigest[diglen]; rpm_loff_t fsize; if (rpmDoDigest(algo, fn, 0, fdigest, &fsize)) { vfy |= (RPMVERIFY_READFAIL|RPMVERIFY_FILEDIGEST); } else { sb.st_size = fsize; if (memcmp(fdigest, digest, diglen)) vfy |= RPMVERIFY_FILEDIGEST; } } else { vfy |= RPMVERIFY_FILEDIGEST; } } if (flags & RPMVERIFY_LINKTO) { char linkto[1024+1]; int size = 0; if ((size = readlink(fn, linkto, sizeof(linkto)-1)) == -1) vfy |= (RPMVERIFY_READLINKFAIL|RPMVERIFY_LINKTO); else { const char * flink = rpmfilesFLink(fi, ix); linkto[size] = '\0'; if (flink == NULL || !rstreq(linkto, flink)) vfy |= RPMVERIFY_LINKTO; } } if (flags & RPMVERIFY_FILESIZE) { if (sb.st_size != rpmfilesFSize(fi, ix)) vfy |= RPMVERIFY_FILESIZE; } if (flags & RPMVERIFY_MODE) { rpm_mode_t metamode = fmode; rpm_mode_t filemode; /* * Platforms (like AIX) where sizeof(rpm_mode_t) != sizeof(mode_t) * need the (rpm_mode_t) cast here. */ filemode = (rpm_mode_t)sb.st_mode; /* * Comparing the type of %ghost files is meaningless, but perms are OK. */ if (fileAttrs & RPMFILE_GHOST) { metamode &= ~0xf000; filemode &= ~0xf000; } if (metamode != filemode) vfy |= RPMVERIFY_MODE; #if WITH_ACL /* * For now, any non-default acl's on a file is a difference as rpm * cannot have set them. */ acl_t facl = acl_get_file(fn, ACL_TYPE_ACCESS); if (facl) { if (acl_equiv_mode(facl, NULL) == 1) { vfy |= RPMVERIFY_MODE; } acl_free(facl); } #endif } if (flags & RPMVERIFY_RDEV) { if (S_ISCHR(fmode) != S_ISCHR(sb.st_mode) || S_ISBLK(fmode) != S_ISBLK(sb.st_mode)) { vfy |= RPMVERIFY_RDEV; } else if (S_ISDEV(fmode) && S_ISDEV(sb.st_mode)) { rpm_rdev_t st_rdev = (sb.st_rdev & 0xffff); rpm_rdev_t frdev = (rpmfilesFRdev(fi, ix) & 0xffff); if (st_rdev != frdev) vfy |= RPMVERIFY_RDEV; } } #if WITH_CAP if (flags & RPMVERIFY_CAPS) { /* * Empty capability set ("=") is not exactly the same as no * capabilities at all but suffices for now... */ cap_t cap, fcap; cap = cap_from_text(rpmfilesFCaps(fi, ix)); if (!cap) { cap = cap_from_text("="); } fcap = cap_get_file(fn); if (!fcap) { fcap = cap_from_text("="); } if (cap_compare(cap, fcap) != 0) vfy |= RPMVERIFY_CAPS; cap_free(fcap); cap_free(cap); } #endif if ((flags & RPMVERIFY_MTIME) && (sb.st_mtime != rpmfilesFMtime(fi, ix))) { vfy |= RPMVERIFY_MTIME; } if (flags & RPMVERIFY_USER) { const char * name = rpmugUname(sb.st_uid); const char * fuser = rpmfilesFUser(fi, ix); uid_t uid; int namematch = 0; int idmatch = 0; if (name && fuser) namematch = rstreq(name, fuser); if (fuser && rpmugUid(fuser, &uid) == 0) idmatch = (uid == sb.st_uid); if (namematch != idmatch) { rpmlog(RPMLOG_WARNING, _("Duplicate username or UID for user %s\n"), fuser); } if (!(namematch || idmatch)) vfy |= RPMVERIFY_USER; } if (flags & RPMVERIFY_GROUP) { const char * name = rpmugGname(sb.st_gid); const char * fgroup = rpmfilesFGroup(fi, ix); gid_t gid; int namematch = 0; int idmatch = 0; if (name && fgroup) namematch = rstreq(name, fgroup); if (fgroup && rpmugGid(fgroup, &gid) == 0) idmatch = (gid == sb.st_gid); if (namematch != idmatch) { rpmlog(RPMLOG_WARNING, _("Duplicate groupname or GID for group %s\n"), fgroup); } if (!(namematch || idmatch)) vfy |= RPMVERIFY_GROUP; } exit: return vfy; } Commit Message: Make verification match the new restricted directory symlink behavior Only follow directory symlinks owned by target directory owner or root during verification to match the behavior of fsmVerify() in the new CVE-2017-7500 world order. The code is klunkier than it should and the logic should use common code with fsmVerify() instead of duplicating it here, but that needs more changes than is comfortable to backport so starting with this. Also worth noting that the previous "follow the link" logic from commit 3ccd774255b8215733e0bdfdf5a683da9dd10923 was not quite right, it'd fail with RPMVERIFY_LSTATFAIL on a broken symlink when it should've ran verification on the symlink itself. This behavior is fixed here too. Finally, once again fakechroot gets in the way and forces the related verify testcase to be changed to be able to create a valid link. Reuse the replacement testcase for the purpose and add another case for verifying an invalid link. CWE ID: CWE-59
rpmVerifyAttrs rpmfilesVerify(rpmfiles fi, int ix, rpmVerifyAttrs omitMask) { rpm_mode_t fmode = rpmfilesFMode(fi, ix); rpmfileAttrs fileAttrs = rpmfilesFFlags(fi, ix); rpmVerifyAttrs flags = rpmfilesVFlags(fi, ix); const char * fn = rpmfilesFN(fi, ix); struct stat sb; rpmVerifyAttrs vfy = RPMVERIFY_NONE; /* * Check to see if the file was installed - if not pretend all is OK. */ switch (rpmfilesFState(fi, ix)) { case RPMFILE_STATE_NETSHARED: case RPMFILE_STATE_NOTINSTALLED: goto exit; break; case RPMFILE_STATE_REPLACED: /* For replaced files we can only verify if it exists at all */ flags = RPMVERIFY_LSTATFAIL; break; case RPMFILE_STATE_WRONGCOLOR: /* * Files with wrong color are supposed to share some attributes * with the actually installed file - verify what we can. */ flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_RDEV); break; case RPMFILE_STATE_NORMAL: /* File from a non-installed package, try to verify nevertheless */ case RPMFILE_STATE_MISSING: break; } if (fn == NULL || lstat(fn, &sb) != 0) { vfy |= RPMVERIFY_LSTATFAIL; goto exit; } /* If we expected a directory but got a symlink to one, follow the link */ if (S_ISDIR(fmode) && S_ISLNK(sb.st_mode)) { struct stat dsb; /* ...if it actually points to a directory */ if (stat(fn, &dsb) == 0 && S_ISDIR(dsb.st_mode)) { uid_t fuid; /* ...and is by a legit user, to match fsmVerify() behavior */ if (sb.st_uid == 0 || (rpmugUid(rpmfilesFUser(fi, ix), &fuid) == 0 && sb.st_uid == fuid)) { sb = dsb; /* struct assignment */ } } } /* Links have no mode, other types have no linkto */ if (S_ISLNK(sb.st_mode)) flags &= ~(RPMVERIFY_MODE); else flags &= ~(RPMVERIFY_LINKTO); /* Not all attributes of non-regular files can be verified */ if (!S_ISREG(sb.st_mode)) flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_CAPS); /* Content checks of %ghost files are meaningless. */ if (fileAttrs & RPMFILE_GHOST) flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_LINKTO); /* Don't verify any features in omitMask. */ flags &= ~(omitMask | RPMVERIFY_FAILURES); if (flags & RPMVERIFY_FILEDIGEST) { const unsigned char *digest; int algo; size_t diglen; /* XXX If --nomd5, then prelinked library sizes are not corrected. */ if ((digest = rpmfilesFDigest(fi, ix, &algo, &diglen))) { unsigned char fdigest[diglen]; rpm_loff_t fsize; if (rpmDoDigest(algo, fn, 0, fdigest, &fsize)) { vfy |= (RPMVERIFY_READFAIL|RPMVERIFY_FILEDIGEST); } else { sb.st_size = fsize; if (memcmp(fdigest, digest, diglen)) vfy |= RPMVERIFY_FILEDIGEST; } } else { vfy |= RPMVERIFY_FILEDIGEST; } } if (flags & RPMVERIFY_LINKTO) { char linkto[1024+1]; int size = 0; if ((size = readlink(fn, linkto, sizeof(linkto)-1)) == -1) vfy |= (RPMVERIFY_READLINKFAIL|RPMVERIFY_LINKTO); else { const char * flink = rpmfilesFLink(fi, ix); linkto[size] = '\0'; if (flink == NULL || !rstreq(linkto, flink)) vfy |= RPMVERIFY_LINKTO; } } if (flags & RPMVERIFY_FILESIZE) { if (sb.st_size != rpmfilesFSize(fi, ix)) vfy |= RPMVERIFY_FILESIZE; } if (flags & RPMVERIFY_MODE) { rpm_mode_t metamode = fmode; rpm_mode_t filemode; /* * Platforms (like AIX) where sizeof(rpm_mode_t) != sizeof(mode_t) * need the (rpm_mode_t) cast here. */ filemode = (rpm_mode_t)sb.st_mode; /* * Comparing the type of %ghost files is meaningless, but perms are OK. */ if (fileAttrs & RPMFILE_GHOST) { metamode &= ~0xf000; filemode &= ~0xf000; } if (metamode != filemode) vfy |= RPMVERIFY_MODE; #if WITH_ACL /* * For now, any non-default acl's on a file is a difference as rpm * cannot have set them. */ acl_t facl = acl_get_file(fn, ACL_TYPE_ACCESS); if (facl) { if (acl_equiv_mode(facl, NULL) == 1) { vfy |= RPMVERIFY_MODE; } acl_free(facl); } #endif } if (flags & RPMVERIFY_RDEV) { if (S_ISCHR(fmode) != S_ISCHR(sb.st_mode) || S_ISBLK(fmode) != S_ISBLK(sb.st_mode)) { vfy |= RPMVERIFY_RDEV; } else if (S_ISDEV(fmode) && S_ISDEV(sb.st_mode)) { rpm_rdev_t st_rdev = (sb.st_rdev & 0xffff); rpm_rdev_t frdev = (rpmfilesFRdev(fi, ix) & 0xffff); if (st_rdev != frdev) vfy |= RPMVERIFY_RDEV; } } #if WITH_CAP if (flags & RPMVERIFY_CAPS) { /* * Empty capability set ("=") is not exactly the same as no * capabilities at all but suffices for now... */ cap_t cap, fcap; cap = cap_from_text(rpmfilesFCaps(fi, ix)); if (!cap) { cap = cap_from_text("="); } fcap = cap_get_file(fn); if (!fcap) { fcap = cap_from_text("="); } if (cap_compare(cap, fcap) != 0) vfy |= RPMVERIFY_CAPS; cap_free(fcap); cap_free(cap); } #endif if ((flags & RPMVERIFY_MTIME) && (sb.st_mtime != rpmfilesFMtime(fi, ix))) { vfy |= RPMVERIFY_MTIME; } if (flags & RPMVERIFY_USER) { const char * name = rpmugUname(sb.st_uid); const char * fuser = rpmfilesFUser(fi, ix); uid_t uid; int namematch = 0; int idmatch = 0; if (name && fuser) namematch = rstreq(name, fuser); if (fuser && rpmugUid(fuser, &uid) == 0) idmatch = (uid == sb.st_uid); if (namematch != idmatch) { rpmlog(RPMLOG_WARNING, _("Duplicate username or UID for user %s\n"), fuser); } if (!(namematch || idmatch)) vfy |= RPMVERIFY_USER; } if (flags & RPMVERIFY_GROUP) { const char * name = rpmugGname(sb.st_gid); const char * fgroup = rpmfilesFGroup(fi, ix); gid_t gid; int namematch = 0; int idmatch = 0; if (name && fgroup) namematch = rstreq(name, fgroup); if (fgroup && rpmugGid(fgroup, &gid) == 0) idmatch = (gid == sb.st_gid); if (namematch != idmatch) { rpmlog(RPMLOG_WARNING, _("Duplicate groupname or GID for group %s\n"), fgroup); } if (!(namematch || idmatch)) vfy |= RPMVERIFY_GROUP; } exit: return vfy; }
169,434
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: lexer_process_char_literal (parser_context_t *context_p, /**< context */ const uint8_t *char_p, /**< characters */ size_t length, /**< length of string */ uint8_t literal_type, /**< final literal type */ bool has_escape) /**< has escape sequences */ { parser_list_iterator_t literal_iterator; lexer_literal_t *literal_p; uint32_t literal_index = 0; JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL || literal_type == LEXER_STRING_LITERAL); JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH); JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH); parser_list_iterator_init (&context_p->literal_pool, &literal_iterator); while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL) { if (literal_p->type == literal_type && literal_p->prop.length == length && memcmp (literal_p->u.char_p, char_p, length) == 0) { context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT); return; } literal_index++; } JERRY_ASSERT (literal_index == context_p->literal_count); if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS) { parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED); } literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool); literal_p->prop.length = (uint16_t) length; literal_p->type = literal_type; literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR; if (has_escape) { literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length); memcpy ((uint8_t *) literal_p->u.char_p, char_p, length); } else { literal_p->u.char_p = char_p; } context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; context_p->literal_count++; } /* lexer_process_char_literal */ Commit Message: Do not allocate memory for zero length strings. Fixes #1821. JerryScript-DCO-1.0-Signed-off-by: Zoltan Herczeg [email protected] CWE ID: CWE-476
lexer_process_char_literal (parser_context_t *context_p, /**< context */ const uint8_t *char_p, /**< characters */ size_t length, /**< length of string */ uint8_t literal_type, /**< final literal type */ bool has_escape) /**< has escape sequences */ { parser_list_iterator_t literal_iterator; lexer_literal_t *literal_p; uint32_t literal_index = 0; JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL || literal_type == LEXER_STRING_LITERAL); JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH); JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH); parser_list_iterator_init (&context_p->literal_pool, &literal_iterator); while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL) { if (literal_p->type == literal_type && literal_p->prop.length == length && memcmp (literal_p->u.char_p, char_p, length) == 0) { context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT); return; } literal_index++; } JERRY_ASSERT (literal_index == context_p->literal_count); if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS) { parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED); } if (length == 0) { has_escape = false; } literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool); literal_p->prop.length = (uint16_t) length; literal_p->type = literal_type; literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR; if (has_escape) { literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length); memcpy ((uint8_t *) literal_p->u.char_p, char_p, length); } else { literal_p->u.char_p = char_p; } context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; context_p->literal_count++; } /* lexer_process_char_literal */
168,105
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu) { u32 data; void *vapic; if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention)) apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic); if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention)) return; vapic = kmap_atomic(vcpu->arch.apic->vapic_page); data = *(u32 *)(vapic + offset_in_page(vcpu->arch.apic->vapic_addr)); kunmap_atomic(vapic); apic_set_tpr(vcpu->arch.apic, data & 0xff); } Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368) In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the potential to corrupt kernel memory if userspace provides an address that is at the end of a page. This patches concerts those functions to use kvm_write_guest_cached and kvm_read_guest_cached. It also checks the vapic_address specified by userspace during ioctl processing and returns an error to userspace if the address is not a valid GPA. This is generally not guest triggerable, because the required write is done by firmware that runs before the guest. Also, it only affects AMD processors and oldish Intel that do not have the FlexPriority feature (unless you disable FlexPriority, of course; then newer processors are also affected). Fixes: b93463aa59d6 ('KVM: Accelerated apic support') Reported-by: Andrew Honig <[email protected]> Cc: [email protected] Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20
void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu) { u32 data; if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention)) apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic); if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention)) return; kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data, sizeof(u32)); apic_set_tpr(vcpu->arch.apic, data & 0xff); }
165,945
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int faultin_page(struct task_struct *tsk, struct vm_area_struct *vma, unsigned long address, unsigned int *flags, int *nonblocking) { unsigned int fault_flags = 0; int ret; /* mlock all present pages, but do not fault in new pages */ if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK) return -ENOENT; /* For mm_populate(), just skip the stack guard page. */ if ((*flags & FOLL_POPULATE) && (stack_guard_page_start(vma, address) || stack_guard_page_end(vma, address + PAGE_SIZE))) return -ENOENT; if (*flags & FOLL_WRITE) fault_flags |= FAULT_FLAG_WRITE; if (*flags & FOLL_REMOTE) fault_flags |= FAULT_FLAG_REMOTE; if (nonblocking) fault_flags |= FAULT_FLAG_ALLOW_RETRY; if (*flags & FOLL_NOWAIT) fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT; if (*flags & FOLL_TRIED) { VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY); fault_flags |= FAULT_FLAG_TRIED; } ret = handle_mm_fault(vma, address, fault_flags); if (ret & VM_FAULT_ERROR) { if (ret & VM_FAULT_OOM) return -ENOMEM; if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE)) return *flags & FOLL_HWPOISON ? -EHWPOISON : -EFAULT; if (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV)) return -EFAULT; BUG(); } if (tsk) { if (ret & VM_FAULT_MAJOR) tsk->maj_flt++; else tsk->min_flt++; } if (ret & VM_FAULT_RETRY) { if (nonblocking) *nonblocking = 0; return -EBUSY; } /* * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when * necessary, even if maybe_mkwrite decided not to set pte_write. We * can thus safely do subsequent page lookups as if they were reads. * But only do so when looping for pte_write is futile: in some cases * userspace may also be wanting to write to the gotten user page, * which a read fault here might prevent (a readonly page might get * reCOWed by userspace write). */ if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE)) *flags &= ~FOLL_WRITE; return 0; } Commit Message: mm: remove gup_flags FOLL_WRITE games from __get_user_pages() This is an ancient bug that was actually attempted to be fixed once (badly) by me eleven years ago in commit 4ceb5db9757a ("Fix get_user_pages() race for write access") but that was then undone due to problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug"). In the meantime, the s390 situation has long been fixed, and we can now fix it by checking the pte_dirty() bit properly (and do it better). The s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement software dirty bits") which made it into v3.9. Earlier kernels will have to look at the page state itself. Also, the VM has become more scalable, and what used a purely theoretical race back then has become easier to trigger. To fix it, we introduce a new internal FOLL_COW flag to mark the "yes, we already did a COW" rather than play racy games with FOLL_WRITE that is very fundamental, and then use the pte dirty flag to validate that the FOLL_COW flag is still valid. Reported-and-tested-by: Phil "not Paul" Oester <[email protected]> Acked-by: Hugh Dickins <[email protected]> Reviewed-by: Michal Hocko <[email protected]> Cc: Andy Lutomirski <[email protected]> Cc: Kees Cook <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: Nick Piggin <[email protected]> Cc: Greg Thelen <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
static int faultin_page(struct task_struct *tsk, struct vm_area_struct *vma, unsigned long address, unsigned int *flags, int *nonblocking) { unsigned int fault_flags = 0; int ret; /* mlock all present pages, but do not fault in new pages */ if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK) return -ENOENT; /* For mm_populate(), just skip the stack guard page. */ if ((*flags & FOLL_POPULATE) && (stack_guard_page_start(vma, address) || stack_guard_page_end(vma, address + PAGE_SIZE))) return -ENOENT; if (*flags & FOLL_WRITE) fault_flags |= FAULT_FLAG_WRITE; if (*flags & FOLL_REMOTE) fault_flags |= FAULT_FLAG_REMOTE; if (nonblocking) fault_flags |= FAULT_FLAG_ALLOW_RETRY; if (*flags & FOLL_NOWAIT) fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT; if (*flags & FOLL_TRIED) { VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY); fault_flags |= FAULT_FLAG_TRIED; } ret = handle_mm_fault(vma, address, fault_flags); if (ret & VM_FAULT_ERROR) { if (ret & VM_FAULT_OOM) return -ENOMEM; if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE)) return *flags & FOLL_HWPOISON ? -EHWPOISON : -EFAULT; if (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV)) return -EFAULT; BUG(); } if (tsk) { if (ret & VM_FAULT_MAJOR) tsk->maj_flt++; else tsk->min_flt++; } if (ret & VM_FAULT_RETRY) { if (nonblocking) *nonblocking = 0; return -EBUSY; } /* * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when * necessary, even if maybe_mkwrite decided not to set pte_write. We * can thus safely do subsequent page lookups as if they were reads. * But only do so when looping for pte_write is futile: in some cases * userspace may also be wanting to write to the gotten user page, * which a read fault here might prevent (a readonly page might get * reCOWed by userspace write). */ if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE)) *flags |= FOLL_COW; return 0; }
167,163
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AwFeatureListCreator::SetUpFieldTrials() { auto* metrics_client = AwMetricsServiceClient::GetInstance(); DCHECK(!field_trial_list_); field_trial_list_ = std::make_unique<base::FieldTrialList>( metrics_client->CreateLowEntropyProvider()); std::unique_ptr<variations::SeedResponse> seed = GetAndClearJavaSeed(); base::Time null_time; base::Time seed_date = seed ? base::Time::FromJavaTime(seed->date) : null_time; variations::UIStringOverrider ui_string_overrider; client_ = std::make_unique<AwVariationsServiceClient>(); auto seed_store = std::make_unique<variations::VariationsSeedStore>( local_state_.get(), /*initial_seed=*/std::move(seed), /*on_initial_seed_stored=*/base::DoNothing()); if (!seed_date.is_null()) seed_store->RecordLastFetchTime(seed_date); variations_field_trial_creator_ = std::make_unique<variations::VariationsFieldTrialCreator>( local_state_.get(), client_.get(), std::move(seed_store), ui_string_overrider); variations_field_trial_creator_->OverrideVariationsPlatform( variations::Study::PLATFORM_ANDROID_WEBVIEW); std::set<std::string> unforceable_field_trials; variations::SafeSeedManager ignored_safe_seed_manager(true, local_state_.get()); variations_field_trial_creator_->SetupFieldTrials( cc::switches::kEnableGpuBenchmarking, switches::kEnableFeatures, switches::kDisableFeatures, unforceable_field_trials, std::vector<std::string>(), content::GetSwitchDependentFeatureOverrides( *base::CommandLine::ForCurrentProcess()), /*low_entropy_provider=*/nullptr, std::make_unique<base::FeatureList>(), aw_field_trials_.get(), &ignored_safe_seed_manager); } Commit Message: [AW] Add Variations.RestartsWithStaleSeed metric. This metric records the number of consecutive times the WebView browser process starts with a stale seed. It's written when a fresh seed is loaded after previously loading a stale seed. Test: Manually verified with logging that the metric was written. Bug: 1010625 Change-Id: Iadedb45af08d59ecd6662472670f848e8e99a8d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1851126 Commit-Queue: Robbie McElrath <[email protected]> Reviewed-by: Nate Fischer <[email protected]> Reviewed-by: Ilya Sherman <[email protected]> Reviewed-by: Changwan Ryu <[email protected]> Cr-Commit-Position: refs/heads/master@{#709417} CWE ID: CWE-20
void AwFeatureListCreator::SetUpFieldTrials() { auto* metrics_client = AwMetricsServiceClient::GetInstance(); DCHECK(!field_trial_list_); field_trial_list_ = std::make_unique<base::FieldTrialList>( metrics_client->CreateLowEntropyProvider()); std::unique_ptr<variations::SeedResponse> seed = GetAndClearJavaSeed(); base::Time null_time; base::Time seed_date = seed ? base::Time::FromJavaTime(seed->date) : null_time; variations::UIStringOverrider ui_string_overrider; client_ = std::make_unique<AwVariationsServiceClient>(); auto seed_store = std::make_unique<variations::VariationsSeedStore>( local_state_.get(), /*initial_seed=*/std::move(seed), /*on_initial_seed_stored=*/base::DoNothing()); if (!seed_date.is_null()) seed_store->RecordLastFetchTime(seed_date); variations_field_trial_creator_ = std::make_unique<variations::VariationsFieldTrialCreator>( local_state_.get(), client_.get(), std::move(seed_store), ui_string_overrider); variations_field_trial_creator_->OverrideVariationsPlatform( variations::Study::PLATFORM_ANDROID_WEBVIEW); std::set<std::string> unforceable_field_trials; variations::SafeSeedManager ignored_safe_seed_manager(true, local_state_.get()); variations_field_trial_creator_->SetupFieldTrials( cc::switches::kEnableGpuBenchmarking, switches::kEnableFeatures, switches::kDisableFeatures, unforceable_field_trials, std::vector<std::string>(), content::GetSwitchDependentFeatureOverrides( *base::CommandLine::ForCurrentProcess()), /*low_entropy_provider=*/nullptr, std::make_unique<base::FeatureList>(), aw_field_trials_.get(), &ignored_safe_seed_manager); CountOrRecordRestartsWithStaleSeed(local_state_.get(), IsSeedFresh()); }
172,360
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport void RemoveDuplicateLayers(Image **images, ExceptionInfo *exception) { register Image *curr, *next; RectangleInfo bounds; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); curr=GetFirstImageInList(*images); for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next) { if ( curr->columns != next->columns || curr->rows != next->rows || curr->page.x != next->page.x || curr->page.y != next->page.y ) continue; bounds=CompareImagesBounds(curr,next,CompareAnyLayer,exception); if ( bounds.x < 0 ) { /* the two images are the same, merge time delays and delete one. */ size_t time; time = curr->delay*1000/curr->ticks_per_second; time += next->delay*1000/next->ticks_per_second; next->ticks_per_second = 100L; next->delay = time*curr->ticks_per_second/1000; next->iterations = curr->iterations; *images = curr; (void) DeleteImageFromList(images); } } *images = GetFirstImageInList(*images); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1629 CWE ID: CWE-369
MagickExport void RemoveDuplicateLayers(Image **images, MagickExport void RemoveDuplicateLayers(Image **images,ExceptionInfo *exception) { RectangleInfo bounds; register Image *image, *next; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(*images); for ( ; (next=GetNextImageInList(image)) != (Image *) NULL; image=next) { if ((image->columns != next->columns) || (image->rows != next->rows) || (image->page.x != next->page.x) || (image->page.y != next->page.y)) continue; bounds=CompareImagesBounds(image,next,CompareAnyLayer,exception); if (bounds.x < 0) { /* Two images are the same, merge time delays and delete one. */ size_t time; time=1000*image->delay*PerceptibleReciprocal(image->ticks_per_second); time+=1000*next->delay*PerceptibleReciprocal(next->ticks_per_second); next->ticks_per_second=100L; next->delay=time*image->ticks_per_second/1000; next->iterations=image->iterations; *images=image; (void) DeleteImageFromList(images); } } *images=GetFirstImageInList(*images); }
170,192
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long kernel_wait4(pid_t upid, int __user *stat_addr, int options, struct rusage *ru) { struct wait_opts wo; struct pid *pid = NULL; enum pid_type type; long ret; if (options & ~(WNOHANG|WUNTRACED|WCONTINUED| __WNOTHREAD|__WCLONE|__WALL)) return -EINVAL; if (upid == -1) type = PIDTYPE_MAX; else if (upid < 0) { type = PIDTYPE_PGID; pid = find_get_pid(-upid); } else if (upid == 0) { type = PIDTYPE_PGID; pid = get_task_pid(current, PIDTYPE_PGID); } else /* upid > 0 */ { type = PIDTYPE_PID; pid = find_get_pid(upid); } wo.wo_type = type; wo.wo_pid = pid; wo.wo_flags = options | WEXITED; wo.wo_info = NULL; wo.wo_stat = 0; wo.wo_rusage = ru; ret = do_wait(&wo); put_pid(pid); if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr)) ret = -EFAULT; return ret; } Commit Message: kernel/exit.c: avoid undefined behaviour when calling wait4() wait4(-2147483648, 0x20, 0, 0xdd0000) triggers: UBSAN: Undefined behaviour in kernel/exit.c:1651:9 The related calltrace is as follows: negation of -2147483648 cannot be represented in type 'int': CPU: 9 PID: 16482 Comm: zj Tainted: G B ---- ------- 3.10.0-327.53.58.71.x86_64+ #66 Hardware name: Huawei Technologies Co., Ltd. Tecal RH2285 /BC11BTSA , BIOS CTSAV036 04/27/2011 Call Trace: dump_stack+0x19/0x1b ubsan_epilogue+0xd/0x50 __ubsan_handle_negate_overflow+0x109/0x14e SyS_wait4+0x1cb/0x1e0 system_call_fastpath+0x16/0x1b Exclude the overflow to avoid the UBSAN warning. Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: zhongjiang <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: David Rientjes <[email protected]> Cc: Aneesh Kumar K.V <[email protected]> Cc: Kirill A. Shutemov <[email protected]> Cc: Xishi Qiu <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20
long kernel_wait4(pid_t upid, int __user *stat_addr, int options, struct rusage *ru) { struct wait_opts wo; struct pid *pid = NULL; enum pid_type type; long ret; if (options & ~(WNOHANG|WUNTRACED|WCONTINUED| __WNOTHREAD|__WCLONE|__WALL)) return -EINVAL; /* -INT_MIN is not defined */ if (upid == INT_MIN) return -ESRCH; if (upid == -1) type = PIDTYPE_MAX; else if (upid < 0) { type = PIDTYPE_PGID; pid = find_get_pid(-upid); } else if (upid == 0) { type = PIDTYPE_PGID; pid = get_task_pid(current, PIDTYPE_PGID); } else /* upid > 0 */ { type = PIDTYPE_PID; pid = find_get_pid(upid); } wo.wo_type = type; wo.wo_pid = pid; wo.wo_flags = options | WEXITED; wo.wo_info = NULL; wo.wo_stat = 0; wo.wo_rusage = ru; ret = do_wait(&wo); put_pid(pid); if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr)) ret = -EFAULT; return ret; }
169,258
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int x86_emulate_insn(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; int rc = X86EMUL_CONTINUE; int saved_dst_type = ctxt->dst.type; ctxt->mem_read.pos = 0; /* LOCK prefix is allowed only with some instructions */ if (ctxt->lock_prefix && (!(ctxt->d & Lock) || ctxt->dst.type != OP_MEM)) { rc = emulate_ud(ctxt); goto done; } if ((ctxt->d & SrcMask) == SrcMemFAddr && ctxt->src.type != OP_MEM) { rc = emulate_ud(ctxt); goto done; } if (unlikely(ctxt->d & (No64|Undefined|Sse|Mmx|Intercept|CheckPerm|Priv|Prot|String))) { if ((ctxt->mode == X86EMUL_MODE_PROT64 && (ctxt->d & No64)) || (ctxt->d & Undefined)) { rc = emulate_ud(ctxt); goto done; } if (((ctxt->d & (Sse|Mmx)) && ((ops->get_cr(ctxt, 0) & X86_CR0_EM))) || ((ctxt->d & Sse) && !(ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR))) { rc = emulate_ud(ctxt); goto done; } if ((ctxt->d & (Sse|Mmx)) && (ops->get_cr(ctxt, 0) & X86_CR0_TS)) { rc = emulate_nm(ctxt); goto done; } if (ctxt->d & Mmx) { rc = flush_pending_x87_faults(ctxt); if (rc != X86EMUL_CONTINUE) goto done; /* * Now that we know the fpu is exception safe, we can fetch * operands from it. */ fetch_possible_mmx_operand(ctxt, &ctxt->src); fetch_possible_mmx_operand(ctxt, &ctxt->src2); if (!(ctxt->d & Mov)) fetch_possible_mmx_operand(ctxt, &ctxt->dst); } if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_PRE_EXCEPT); if (rc != X86EMUL_CONTINUE) goto done; } /* Privileged instruction can be executed only in CPL=0 */ if ((ctxt->d & Priv) && ops->cpl(ctxt)) { if (ctxt->d & PrivUD) rc = emulate_ud(ctxt); else rc = emulate_gp(ctxt, 0); goto done; } /* Instruction can only be executed in protected mode */ if ((ctxt->d & Prot) && ctxt->mode < X86EMUL_MODE_PROT16) { rc = emulate_ud(ctxt); goto done; } /* Do instruction specific permission checks */ if (ctxt->d & CheckPerm) { rc = ctxt->check_perm(ctxt); if (rc != X86EMUL_CONTINUE) goto done; } if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_POST_EXCEPT); if (rc != X86EMUL_CONTINUE) goto done; } if (ctxt->rep_prefix && (ctxt->d & String)) { /* All REP prefixes have the same first termination condition */ if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) { ctxt->eip = ctxt->_eip; ctxt->eflags &= ~EFLG_RF; goto done; } } } if ((ctxt->src.type == OP_MEM) && !(ctxt->d & NoAccess)) { rc = segmented_read(ctxt, ctxt->src.addr.mem, ctxt->src.valptr, ctxt->src.bytes); if (rc != X86EMUL_CONTINUE) goto done; ctxt->src.orig_val64 = ctxt->src.val64; } if (ctxt->src2.type == OP_MEM) { rc = segmented_read(ctxt, ctxt->src2.addr.mem, &ctxt->src2.val, ctxt->src2.bytes); if (rc != X86EMUL_CONTINUE) goto done; } if ((ctxt->d & DstMask) == ImplicitOps) goto special_insn; if ((ctxt->dst.type == OP_MEM) && !(ctxt->d & Mov)) { /* optimisation - avoid slow emulated read if Mov */ rc = segmented_read(ctxt, ctxt->dst.addr.mem, &ctxt->dst.val, ctxt->dst.bytes); if (rc != X86EMUL_CONTINUE) goto done; } ctxt->dst.orig_val = ctxt->dst.val; special_insn: if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_POST_MEMACCESS); if (rc != X86EMUL_CONTINUE) goto done; } if (ctxt->rep_prefix && (ctxt->d & String)) ctxt->eflags |= EFLG_RF; else ctxt->eflags &= ~EFLG_RF; if (ctxt->execute) { if (ctxt->d & Fastop) { void (*fop)(struct fastop *) = (void *)ctxt->execute; rc = fastop(ctxt, fop); if (rc != X86EMUL_CONTINUE) goto done; goto writeback; } rc = ctxt->execute(ctxt); if (rc != X86EMUL_CONTINUE) goto done; goto writeback; } if (ctxt->opcode_len == 2) goto twobyte_insn; else if (ctxt->opcode_len == 3) goto threebyte_insn; switch (ctxt->b) { case 0x63: /* movsxd */ if (ctxt->mode != X86EMUL_MODE_PROT64) goto cannot_emulate; ctxt->dst.val = (s32) ctxt->src.val; break; case 0x70 ... 0x7f: /* jcc (short) */ if (test_cc(ctxt->b, ctxt->eflags)) jmp_rel(ctxt, ctxt->src.val); break; case 0x8d: /* lea r16/r32, m */ ctxt->dst.val = ctxt->src.addr.mem.ea; break; case 0x90 ... 0x97: /* nop / xchg reg, rax */ if (ctxt->dst.addr.reg == reg_rmw(ctxt, VCPU_REGS_RAX)) ctxt->dst.type = OP_NONE; else rc = em_xchg(ctxt); break; case 0x98: /* cbw/cwde/cdqe */ switch (ctxt->op_bytes) { case 2: ctxt->dst.val = (s8)ctxt->dst.val; break; case 4: ctxt->dst.val = (s16)ctxt->dst.val; break; case 8: ctxt->dst.val = (s32)ctxt->dst.val; break; } break; case 0xcc: /* int3 */ rc = emulate_int(ctxt, 3); break; case 0xcd: /* int n */ rc = emulate_int(ctxt, ctxt->src.val); break; case 0xce: /* into */ if (ctxt->eflags & EFLG_OF) rc = emulate_int(ctxt, 4); break; case 0xe9: /* jmp rel */ case 0xeb: /* jmp rel short */ jmp_rel(ctxt, ctxt->src.val); ctxt->dst.type = OP_NONE; /* Disable writeback. */ break; case 0xf4: /* hlt */ ctxt->ops->halt(ctxt); break; case 0xf5: /* cmc */ /* complement carry flag from eflags reg */ ctxt->eflags ^= EFLG_CF; break; case 0xf8: /* clc */ ctxt->eflags &= ~EFLG_CF; break; case 0xf9: /* stc */ ctxt->eflags |= EFLG_CF; break; case 0xfc: /* cld */ ctxt->eflags &= ~EFLG_DF; break; case 0xfd: /* std */ ctxt->eflags |= EFLG_DF; break; default: goto cannot_emulate; } if (rc != X86EMUL_CONTINUE) goto done; writeback: if (ctxt->d & SrcWrite) { BUG_ON(ctxt->src.type == OP_MEM || ctxt->src.type == OP_MEM_STR); rc = writeback(ctxt, &ctxt->src); if (rc != X86EMUL_CONTINUE) goto done; } if (!(ctxt->d & NoWrite)) { rc = writeback(ctxt, &ctxt->dst); if (rc != X86EMUL_CONTINUE) goto done; } /* * restore dst type in case the decoding will be reused * (happens for string instruction ) */ ctxt->dst.type = saved_dst_type; if ((ctxt->d & SrcMask) == SrcSI) string_addr_inc(ctxt, VCPU_REGS_RSI, &ctxt->src); if ((ctxt->d & DstMask) == DstDI) string_addr_inc(ctxt, VCPU_REGS_RDI, &ctxt->dst); if (ctxt->rep_prefix && (ctxt->d & String)) { unsigned int count; struct read_cache *r = &ctxt->io_read; if ((ctxt->d & SrcMask) == SrcSI) count = ctxt->src.count; else count = ctxt->dst.count; register_address_increment(ctxt, reg_rmw(ctxt, VCPU_REGS_RCX), -count); if (!string_insn_completed(ctxt)) { /* * Re-enter guest when pio read ahead buffer is empty * or, if it is not used, after each 1024 iteration. */ if ((r->end != 0 || reg_read(ctxt, VCPU_REGS_RCX) & 0x3ff) && (r->end == 0 || r->end != r->pos)) { /* * Reset read cache. Usually happens before * decode, but since instruction is restarted * we have to do it here. */ ctxt->mem_read.end = 0; writeback_registers(ctxt); return EMULATION_RESTART; } goto done; /* skip rip writeback */ } ctxt->eflags &= ~EFLG_RF; } ctxt->eip = ctxt->_eip; done: if (rc == X86EMUL_PROPAGATE_FAULT) { WARN_ON(ctxt->exception.vector > 0x1f); ctxt->have_exception = true; } if (rc == X86EMUL_INTERCEPTED) return EMULATION_INTERCEPTED; if (rc == X86EMUL_CONTINUE) writeback_registers(ctxt); return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK; twobyte_insn: switch (ctxt->b) { case 0x09: /* wbinvd */ (ctxt->ops->wbinvd)(ctxt); break; case 0x08: /* invd */ case 0x0d: /* GrpP (prefetch) */ case 0x18: /* Grp16 (prefetch/nop) */ case 0x1f: /* nop */ break; case 0x20: /* mov cr, reg */ ctxt->dst.val = ops->get_cr(ctxt, ctxt->modrm_reg); break; case 0x21: /* mov from dr to reg */ ops->get_dr(ctxt, ctxt->modrm_reg, &ctxt->dst.val); break; case 0x40 ... 0x4f: /* cmov */ if (test_cc(ctxt->b, ctxt->eflags)) ctxt->dst.val = ctxt->src.val; else if (ctxt->mode != X86EMUL_MODE_PROT64 || ctxt->op_bytes != 4) ctxt->dst.type = OP_NONE; /* no writeback */ break; case 0x80 ... 0x8f: /* jnz rel, etc*/ if (test_cc(ctxt->b, ctxt->eflags)) jmp_rel(ctxt, ctxt->src.val); break; case 0x90 ... 0x9f: /* setcc r/m8 */ ctxt->dst.val = test_cc(ctxt->b, ctxt->eflags); break; case 0xae: /* clflush */ break; case 0xb6 ... 0xb7: /* movzx */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->src.bytes == 1) ? (u8) ctxt->src.val : (u16) ctxt->src.val; break; case 0xbe ... 0xbf: /* movsx */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->src.bytes == 1) ? (s8) ctxt->src.val : (s16) ctxt->src.val; break; case 0xc3: /* movnti */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->op_bytes == 8) ? (u64) ctxt->src.val : (u32) ctxt->src.val; break; default: goto cannot_emulate; } threebyte_insn: if (rc != X86EMUL_CONTINUE) goto done; goto writeback; cannot_emulate: return EMULATION_FAILED; } Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches Before changing rip (during jmp, call, ret, etc.) the target should be asserted to be canonical one, as real CPUs do. During sysret, both target rsp and rip should be canonical. If any of these values is noncanonical, a #GP exception should occur. The exception to this rule are syscall and sysenter instructions in which the assigned rip is checked during the assignment to the relevant MSRs. This patch fixes the emulator to behave as real CPUs do for near branches. Far branches are handled by the next patch. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
int x86_emulate_insn(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; int rc = X86EMUL_CONTINUE; int saved_dst_type = ctxt->dst.type; ctxt->mem_read.pos = 0; /* LOCK prefix is allowed only with some instructions */ if (ctxt->lock_prefix && (!(ctxt->d & Lock) || ctxt->dst.type != OP_MEM)) { rc = emulate_ud(ctxt); goto done; } if ((ctxt->d & SrcMask) == SrcMemFAddr && ctxt->src.type != OP_MEM) { rc = emulate_ud(ctxt); goto done; } if (unlikely(ctxt->d & (No64|Undefined|Sse|Mmx|Intercept|CheckPerm|Priv|Prot|String))) { if ((ctxt->mode == X86EMUL_MODE_PROT64 && (ctxt->d & No64)) || (ctxt->d & Undefined)) { rc = emulate_ud(ctxt); goto done; } if (((ctxt->d & (Sse|Mmx)) && ((ops->get_cr(ctxt, 0) & X86_CR0_EM))) || ((ctxt->d & Sse) && !(ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR))) { rc = emulate_ud(ctxt); goto done; } if ((ctxt->d & (Sse|Mmx)) && (ops->get_cr(ctxt, 0) & X86_CR0_TS)) { rc = emulate_nm(ctxt); goto done; } if (ctxt->d & Mmx) { rc = flush_pending_x87_faults(ctxt); if (rc != X86EMUL_CONTINUE) goto done; /* * Now that we know the fpu is exception safe, we can fetch * operands from it. */ fetch_possible_mmx_operand(ctxt, &ctxt->src); fetch_possible_mmx_operand(ctxt, &ctxt->src2); if (!(ctxt->d & Mov)) fetch_possible_mmx_operand(ctxt, &ctxt->dst); } if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_PRE_EXCEPT); if (rc != X86EMUL_CONTINUE) goto done; } /* Privileged instruction can be executed only in CPL=0 */ if ((ctxt->d & Priv) && ops->cpl(ctxt)) { if (ctxt->d & PrivUD) rc = emulate_ud(ctxt); else rc = emulate_gp(ctxt, 0); goto done; } /* Instruction can only be executed in protected mode */ if ((ctxt->d & Prot) && ctxt->mode < X86EMUL_MODE_PROT16) { rc = emulate_ud(ctxt); goto done; } /* Do instruction specific permission checks */ if (ctxt->d & CheckPerm) { rc = ctxt->check_perm(ctxt); if (rc != X86EMUL_CONTINUE) goto done; } if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_POST_EXCEPT); if (rc != X86EMUL_CONTINUE) goto done; } if (ctxt->rep_prefix && (ctxt->d & String)) { /* All REP prefixes have the same first termination condition */ if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) { ctxt->eip = ctxt->_eip; ctxt->eflags &= ~EFLG_RF; goto done; } } } if ((ctxt->src.type == OP_MEM) && !(ctxt->d & NoAccess)) { rc = segmented_read(ctxt, ctxt->src.addr.mem, ctxt->src.valptr, ctxt->src.bytes); if (rc != X86EMUL_CONTINUE) goto done; ctxt->src.orig_val64 = ctxt->src.val64; } if (ctxt->src2.type == OP_MEM) { rc = segmented_read(ctxt, ctxt->src2.addr.mem, &ctxt->src2.val, ctxt->src2.bytes); if (rc != X86EMUL_CONTINUE) goto done; } if ((ctxt->d & DstMask) == ImplicitOps) goto special_insn; if ((ctxt->dst.type == OP_MEM) && !(ctxt->d & Mov)) { /* optimisation - avoid slow emulated read if Mov */ rc = segmented_read(ctxt, ctxt->dst.addr.mem, &ctxt->dst.val, ctxt->dst.bytes); if (rc != X86EMUL_CONTINUE) goto done; } ctxt->dst.orig_val = ctxt->dst.val; special_insn: if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_POST_MEMACCESS); if (rc != X86EMUL_CONTINUE) goto done; } if (ctxt->rep_prefix && (ctxt->d & String)) ctxt->eflags |= EFLG_RF; else ctxt->eflags &= ~EFLG_RF; if (ctxt->execute) { if (ctxt->d & Fastop) { void (*fop)(struct fastop *) = (void *)ctxt->execute; rc = fastop(ctxt, fop); if (rc != X86EMUL_CONTINUE) goto done; goto writeback; } rc = ctxt->execute(ctxt); if (rc != X86EMUL_CONTINUE) goto done; goto writeback; } if (ctxt->opcode_len == 2) goto twobyte_insn; else if (ctxt->opcode_len == 3) goto threebyte_insn; switch (ctxt->b) { case 0x63: /* movsxd */ if (ctxt->mode != X86EMUL_MODE_PROT64) goto cannot_emulate; ctxt->dst.val = (s32) ctxt->src.val; break; case 0x70 ... 0x7f: /* jcc (short) */ if (test_cc(ctxt->b, ctxt->eflags)) rc = jmp_rel(ctxt, ctxt->src.val); break; case 0x8d: /* lea r16/r32, m */ ctxt->dst.val = ctxt->src.addr.mem.ea; break; case 0x90 ... 0x97: /* nop / xchg reg, rax */ if (ctxt->dst.addr.reg == reg_rmw(ctxt, VCPU_REGS_RAX)) ctxt->dst.type = OP_NONE; else rc = em_xchg(ctxt); break; case 0x98: /* cbw/cwde/cdqe */ switch (ctxt->op_bytes) { case 2: ctxt->dst.val = (s8)ctxt->dst.val; break; case 4: ctxt->dst.val = (s16)ctxt->dst.val; break; case 8: ctxt->dst.val = (s32)ctxt->dst.val; break; } break; case 0xcc: /* int3 */ rc = emulate_int(ctxt, 3); break; case 0xcd: /* int n */ rc = emulate_int(ctxt, ctxt->src.val); break; case 0xce: /* into */ if (ctxt->eflags & EFLG_OF) rc = emulate_int(ctxt, 4); break; case 0xe9: /* jmp rel */ case 0xeb: /* jmp rel short */ rc = jmp_rel(ctxt, ctxt->src.val); ctxt->dst.type = OP_NONE; /* Disable writeback. */ break; case 0xf4: /* hlt */ ctxt->ops->halt(ctxt); break; case 0xf5: /* cmc */ /* complement carry flag from eflags reg */ ctxt->eflags ^= EFLG_CF; break; case 0xf8: /* clc */ ctxt->eflags &= ~EFLG_CF; break; case 0xf9: /* stc */ ctxt->eflags |= EFLG_CF; break; case 0xfc: /* cld */ ctxt->eflags &= ~EFLG_DF; break; case 0xfd: /* std */ ctxt->eflags |= EFLG_DF; break; default: goto cannot_emulate; } if (rc != X86EMUL_CONTINUE) goto done; writeback: if (ctxt->d & SrcWrite) { BUG_ON(ctxt->src.type == OP_MEM || ctxt->src.type == OP_MEM_STR); rc = writeback(ctxt, &ctxt->src); if (rc != X86EMUL_CONTINUE) goto done; } if (!(ctxt->d & NoWrite)) { rc = writeback(ctxt, &ctxt->dst); if (rc != X86EMUL_CONTINUE) goto done; } /* * restore dst type in case the decoding will be reused * (happens for string instruction ) */ ctxt->dst.type = saved_dst_type; if ((ctxt->d & SrcMask) == SrcSI) string_addr_inc(ctxt, VCPU_REGS_RSI, &ctxt->src); if ((ctxt->d & DstMask) == DstDI) string_addr_inc(ctxt, VCPU_REGS_RDI, &ctxt->dst); if (ctxt->rep_prefix && (ctxt->d & String)) { unsigned int count; struct read_cache *r = &ctxt->io_read; if ((ctxt->d & SrcMask) == SrcSI) count = ctxt->src.count; else count = ctxt->dst.count; register_address_increment(ctxt, reg_rmw(ctxt, VCPU_REGS_RCX), -count); if (!string_insn_completed(ctxt)) { /* * Re-enter guest when pio read ahead buffer is empty * or, if it is not used, after each 1024 iteration. */ if ((r->end != 0 || reg_read(ctxt, VCPU_REGS_RCX) & 0x3ff) && (r->end == 0 || r->end != r->pos)) { /* * Reset read cache. Usually happens before * decode, but since instruction is restarted * we have to do it here. */ ctxt->mem_read.end = 0; writeback_registers(ctxt); return EMULATION_RESTART; } goto done; /* skip rip writeback */ } ctxt->eflags &= ~EFLG_RF; } ctxt->eip = ctxt->_eip; done: if (rc == X86EMUL_PROPAGATE_FAULT) { WARN_ON(ctxt->exception.vector > 0x1f); ctxt->have_exception = true; } if (rc == X86EMUL_INTERCEPTED) return EMULATION_INTERCEPTED; if (rc == X86EMUL_CONTINUE) writeback_registers(ctxt); return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK; twobyte_insn: switch (ctxt->b) { case 0x09: /* wbinvd */ (ctxt->ops->wbinvd)(ctxt); break; case 0x08: /* invd */ case 0x0d: /* GrpP (prefetch) */ case 0x18: /* Grp16 (prefetch/nop) */ case 0x1f: /* nop */ break; case 0x20: /* mov cr, reg */ ctxt->dst.val = ops->get_cr(ctxt, ctxt->modrm_reg); break; case 0x21: /* mov from dr to reg */ ops->get_dr(ctxt, ctxt->modrm_reg, &ctxt->dst.val); break; case 0x40 ... 0x4f: /* cmov */ if (test_cc(ctxt->b, ctxt->eflags)) ctxt->dst.val = ctxt->src.val; else if (ctxt->mode != X86EMUL_MODE_PROT64 || ctxt->op_bytes != 4) ctxt->dst.type = OP_NONE; /* no writeback */ break; case 0x80 ... 0x8f: /* jnz rel, etc*/ if (test_cc(ctxt->b, ctxt->eflags)) rc = jmp_rel(ctxt, ctxt->src.val); break; case 0x90 ... 0x9f: /* setcc r/m8 */ ctxt->dst.val = test_cc(ctxt->b, ctxt->eflags); break; case 0xae: /* clflush */ break; case 0xb6 ... 0xb7: /* movzx */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->src.bytes == 1) ? (u8) ctxt->src.val : (u16) ctxt->src.val; break; case 0xbe ... 0xbf: /* movsx */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->src.bytes == 1) ? (s8) ctxt->src.val : (s16) ctxt->src.val; break; case 0xc3: /* movnti */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->op_bytes == 8) ? (u64) ctxt->src.val : (u32) ctxt->src.val; break; default: goto cannot_emulate; } threebyte_insn: if (rc != X86EMUL_CONTINUE) goto done; goto writeback; cannot_emulate: return EMULATION_FAILED; }
169,917
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltGetQNameProperty(xsltStylesheetPtr style, xmlNodePtr inst, const xmlChar *propName, int mandatory, int *hasProp, const xmlChar **nsName, const xmlChar** localName) { const xmlChar *prop; if (nsName) *nsName = NULL; if (localName) *localName = NULL; if (hasProp) *hasProp = 0; prop = xsltGetCNsProp(style, inst, propName, XSLT_NAMESPACE); if (prop == NULL) { if (mandatory) { xsltTransformError(NULL, style, inst, "The attribute '%s' is missing.\n", propName); style->errors++; return; } } else { const xmlChar *URI; if (xmlValidateQName(prop, 0)) { xsltTransformError(NULL, style, inst, "The value '%s' of the attribute " "'%s' is not a valid QName.\n", prop, propName); style->errors++; return; } else { /* * @prop will be in the string dict afterwards, @URI not. */ URI = xsltGetQNameURI2(style, inst, &prop); if (prop == NULL) { style->errors++; } else { *localName = prop; if (hasProp) *hasProp = 1; if (URI != NULL) { /* * Fixes bug #308441: Put the ns-name in the dict * in order to pointer compare names during XPath's * variable lookup. */ if (nsName) *nsName = xmlDictLookup(style->dict, URI, -1); /* comp->has_ns = 1; */ } } } } return; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltGetQNameProperty(xsltStylesheetPtr style, xmlNodePtr inst, const xmlChar *propName, int mandatory, int *hasProp, const xmlChar **nsName, const xmlChar** localName) { const xmlChar *prop; if (nsName) *nsName = NULL; if (localName) *localName = NULL; if (hasProp) *hasProp = 0; prop = xsltGetCNsProp(style, inst, propName, XSLT_NAMESPACE); if (prop == NULL) { if (mandatory) { xsltTransformError(NULL, style, inst, "The attribute '%s' is missing.\n", propName); style->errors++; return; } } else { const xmlChar *URI; if (xmlValidateQName(prop, 0)) { xsltTransformError(NULL, style, inst, "The value '%s' of the attribute " "'%s' is not a valid QName.\n", prop, propName); style->errors++; return; } else { /* * @prop will be in the string dict afterwards, @URI not. */ URI = xsltGetQNameURI2(style, inst, &prop); if (prop == NULL) { style->errors++; } else { if (localName) *localName = prop; if (hasProp) *hasProp = 1; if (URI != NULL) { /* * Fixes bug #308441: Put the ns-name in the dict * in order to pointer compare names during XPath's * variable lookup. */ if (nsName) *nsName = xmlDictLookup(style->dict, URI, -1); /* comp->has_ns = 1; */ } } } } return; }
173,317
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: usbnet_probe (struct usb_interface *udev, const struct usb_device_id *prod) { struct usbnet *dev; struct net_device *net; struct usb_host_interface *interface; struct driver_info *info; struct usb_device *xdev; int status; const char *name; struct usb_driver *driver = to_usb_driver(udev->dev.driver); /* usbnet already took usb runtime pm, so have to enable the feature * for usb interface, otherwise usb_autopm_get_interface may return * failure if RUNTIME_PM is enabled. */ if (!driver->supports_autosuspend) { driver->supports_autosuspend = 1; pm_runtime_enable(&udev->dev); } name = udev->dev.driver->name; info = (struct driver_info *) prod->driver_info; if (!info) { dev_dbg (&udev->dev, "blacklisted by %s\n", name); return -ENODEV; } xdev = interface_to_usbdev (udev); interface = udev->cur_altsetting; status = -ENOMEM; net = alloc_etherdev(sizeof(*dev)); if (!net) goto out; /* netdev_printk() needs this so do it as early as possible */ SET_NETDEV_DEV(net, &udev->dev); dev = netdev_priv(net); dev->udev = xdev; dev->intf = udev; dev->driver_info = info; dev->driver_name = name; dev->msg_enable = netif_msg_init (msg_level, NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK); init_waitqueue_head(&dev->wait); skb_queue_head_init (&dev->rxq); skb_queue_head_init (&dev->txq); skb_queue_head_init (&dev->done); skb_queue_head_init(&dev->rxq_pause); dev->bh.func = usbnet_bh; dev->bh.data = (unsigned long) dev; INIT_WORK (&dev->kevent, usbnet_deferred_kevent); init_usb_anchor(&dev->deferred); dev->delay.function = usbnet_bh; dev->delay.data = (unsigned long) dev; init_timer (&dev->delay); mutex_init (&dev->phy_mutex); mutex_init(&dev->interrupt_mutex); dev->interrupt_count = 0; dev->net = net; strcpy (net->name, "usb%d"); memcpy (net->dev_addr, node_id, sizeof node_id); /* rx and tx sides can use different message sizes; * bind() should set rx_urb_size in that case. */ dev->hard_mtu = net->mtu + net->hard_header_len; net->netdev_ops = &usbnet_netdev_ops; net->watchdog_timeo = TX_TIMEOUT_JIFFIES; net->ethtool_ops = &usbnet_ethtool_ops; if (info->bind) { status = info->bind (dev, udev); if (status < 0) goto out1; if ((dev->driver_info->flags & FLAG_ETHER) != 0 && ((dev->driver_info->flags & FLAG_POINTTOPOINT) == 0 || (net->dev_addr [0] & 0x02) == 0)) strcpy (net->name, "eth%d"); /* WLAN devices should always be named "wlan%d" */ if ((dev->driver_info->flags & FLAG_WLAN) != 0) strcpy(net->name, "wlan%d"); /* WWAN devices should always be named "wwan%d" */ if ((dev->driver_info->flags & FLAG_WWAN) != 0) strcpy(net->name, "wwan%d"); /* devices that cannot do ARP */ if ((dev->driver_info->flags & FLAG_NOARP) != 0) net->flags |= IFF_NOARP; /* maybe the remote can't receive an Ethernet MTU */ if (net->mtu > (dev->hard_mtu - net->hard_header_len)) net->mtu = dev->hard_mtu - net->hard_header_len; } else if (!info->in || !info->out) status = usbnet_get_endpoints (dev, udev); else { dev->in = usb_rcvbulkpipe (xdev, info->in); dev->out = usb_sndbulkpipe (xdev, info->out); if (!(info->flags & FLAG_NO_SETINT)) status = usb_set_interface (xdev, interface->desc.bInterfaceNumber, interface->desc.bAlternateSetting); else status = 0; } if (status >= 0 && dev->status) status = init_status (dev, udev); if (status < 0) goto out3; if (!dev->rx_urb_size) dev->rx_urb_size = dev->hard_mtu; dev->maxpacket = usb_maxpacket (dev->udev, dev->out, 1); /* let userspace know we have a random address */ if (ether_addr_equal(net->dev_addr, node_id)) net->addr_assign_type = NET_ADDR_RANDOM; if ((dev->driver_info->flags & FLAG_WLAN) != 0) SET_NETDEV_DEVTYPE(net, &wlan_type); if ((dev->driver_info->flags & FLAG_WWAN) != 0) SET_NETDEV_DEVTYPE(net, &wwan_type); /* initialize max rx_qlen and tx_qlen */ usbnet_update_max_qlen(dev); if (dev->can_dma_sg && !(info->flags & FLAG_SEND_ZLP) && !(info->flags & FLAG_MULTI_PACKET)) { dev->padding_pkt = kzalloc(1, GFP_KERNEL); if (!dev->padding_pkt) { status = -ENOMEM; goto out4; } } status = register_netdev (net); if (status) goto out5; netif_info(dev, probe, dev->net, "register '%s' at usb-%s-%s, %s, %pM\n", udev->dev.driver->name, xdev->bus->bus_name, xdev->devpath, dev->driver_info->description, net->dev_addr); usb_set_intfdata (udev, dev); netif_device_attach (net); if (dev->driver_info->flags & FLAG_LINK_INTR) usbnet_link_change(dev, 0, 0); return 0; out5: kfree(dev->padding_pkt); out4: usb_free_urb(dev->interrupt); out3: if (info->unbind) info->unbind (dev, udev); out1: free_netdev(net); out: return status; } Commit Message: usbnet: cleanup after bind() in probe() In case bind() works, but a later error forces bailing in probe() in error cases work and a timer may be scheduled. They must be killed. This fixes an error case related to the double free reported in http://www.spinics.net/lists/netdev/msg367669.html and needs to go on top of Linus' fix to cdc-ncm. Signed-off-by: Oliver Neukum <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
usbnet_probe (struct usb_interface *udev, const struct usb_device_id *prod) { struct usbnet *dev; struct net_device *net; struct usb_host_interface *interface; struct driver_info *info; struct usb_device *xdev; int status; const char *name; struct usb_driver *driver = to_usb_driver(udev->dev.driver); /* usbnet already took usb runtime pm, so have to enable the feature * for usb interface, otherwise usb_autopm_get_interface may return * failure if RUNTIME_PM is enabled. */ if (!driver->supports_autosuspend) { driver->supports_autosuspend = 1; pm_runtime_enable(&udev->dev); } name = udev->dev.driver->name; info = (struct driver_info *) prod->driver_info; if (!info) { dev_dbg (&udev->dev, "blacklisted by %s\n", name); return -ENODEV; } xdev = interface_to_usbdev (udev); interface = udev->cur_altsetting; status = -ENOMEM; net = alloc_etherdev(sizeof(*dev)); if (!net) goto out; /* netdev_printk() needs this so do it as early as possible */ SET_NETDEV_DEV(net, &udev->dev); dev = netdev_priv(net); dev->udev = xdev; dev->intf = udev; dev->driver_info = info; dev->driver_name = name; dev->msg_enable = netif_msg_init (msg_level, NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK); init_waitqueue_head(&dev->wait); skb_queue_head_init (&dev->rxq); skb_queue_head_init (&dev->txq); skb_queue_head_init (&dev->done); skb_queue_head_init(&dev->rxq_pause); dev->bh.func = usbnet_bh; dev->bh.data = (unsigned long) dev; INIT_WORK (&dev->kevent, usbnet_deferred_kevent); init_usb_anchor(&dev->deferred); dev->delay.function = usbnet_bh; dev->delay.data = (unsigned long) dev; init_timer (&dev->delay); mutex_init (&dev->phy_mutex); mutex_init(&dev->interrupt_mutex); dev->interrupt_count = 0; dev->net = net; strcpy (net->name, "usb%d"); memcpy (net->dev_addr, node_id, sizeof node_id); /* rx and tx sides can use different message sizes; * bind() should set rx_urb_size in that case. */ dev->hard_mtu = net->mtu + net->hard_header_len; net->netdev_ops = &usbnet_netdev_ops; net->watchdog_timeo = TX_TIMEOUT_JIFFIES; net->ethtool_ops = &usbnet_ethtool_ops; if (info->bind) { status = info->bind (dev, udev); if (status < 0) goto out1; if ((dev->driver_info->flags & FLAG_ETHER) != 0 && ((dev->driver_info->flags & FLAG_POINTTOPOINT) == 0 || (net->dev_addr [0] & 0x02) == 0)) strcpy (net->name, "eth%d"); /* WLAN devices should always be named "wlan%d" */ if ((dev->driver_info->flags & FLAG_WLAN) != 0) strcpy(net->name, "wlan%d"); /* WWAN devices should always be named "wwan%d" */ if ((dev->driver_info->flags & FLAG_WWAN) != 0) strcpy(net->name, "wwan%d"); /* devices that cannot do ARP */ if ((dev->driver_info->flags & FLAG_NOARP) != 0) net->flags |= IFF_NOARP; /* maybe the remote can't receive an Ethernet MTU */ if (net->mtu > (dev->hard_mtu - net->hard_header_len)) net->mtu = dev->hard_mtu - net->hard_header_len; } else if (!info->in || !info->out) status = usbnet_get_endpoints (dev, udev); else { dev->in = usb_rcvbulkpipe (xdev, info->in); dev->out = usb_sndbulkpipe (xdev, info->out); if (!(info->flags & FLAG_NO_SETINT)) status = usb_set_interface (xdev, interface->desc.bInterfaceNumber, interface->desc.bAlternateSetting); else status = 0; } if (status >= 0 && dev->status) status = init_status (dev, udev); if (status < 0) goto out3; if (!dev->rx_urb_size) dev->rx_urb_size = dev->hard_mtu; dev->maxpacket = usb_maxpacket (dev->udev, dev->out, 1); /* let userspace know we have a random address */ if (ether_addr_equal(net->dev_addr, node_id)) net->addr_assign_type = NET_ADDR_RANDOM; if ((dev->driver_info->flags & FLAG_WLAN) != 0) SET_NETDEV_DEVTYPE(net, &wlan_type); if ((dev->driver_info->flags & FLAG_WWAN) != 0) SET_NETDEV_DEVTYPE(net, &wwan_type); /* initialize max rx_qlen and tx_qlen */ usbnet_update_max_qlen(dev); if (dev->can_dma_sg && !(info->flags & FLAG_SEND_ZLP) && !(info->flags & FLAG_MULTI_PACKET)) { dev->padding_pkt = kzalloc(1, GFP_KERNEL); if (!dev->padding_pkt) { status = -ENOMEM; goto out4; } } status = register_netdev (net); if (status) goto out5; netif_info(dev, probe, dev->net, "register '%s' at usb-%s-%s, %s, %pM\n", udev->dev.driver->name, xdev->bus->bus_name, xdev->devpath, dev->driver_info->description, net->dev_addr); usb_set_intfdata (udev, dev); netif_device_attach (net); if (dev->driver_info->flags & FLAG_LINK_INTR) usbnet_link_change(dev, 0, 0); return 0; out5: kfree(dev->padding_pkt); out4: usb_free_urb(dev->interrupt); out3: if (info->unbind) info->unbind (dev, udev); out1: /* subdrivers must undo all they did in bind() if they * fail it, but we may fail later and a deferred kevent * may trigger an error resubmitting itself and, worse, * schedule a timer. So we kill it all just in case. */ cancel_work_sync(&dev->kevent); del_timer_sync(&dev->delay); free_netdev(net); out: return status; }
169,970
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltResolveSASCallback(xsltAttrElemPtr values, xsltStylesheetPtr style, const xmlChar *name, const xmlChar *ns, ATTRIBUTE_UNUSED const xmlChar *ignored) { xsltAttrElemPtr tmp; xsltAttrElemPtr refs; tmp = values; while (tmp != NULL) { if (tmp->set != NULL) { /* * Check against cycles ! */ if ((xmlStrEqual(name, tmp->set)) && (xmlStrEqual(ns, tmp->ns))) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : use-attribute-sets recursion detected on %s\n", name); } else { #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "Importing attribute list %s\n", tmp->set); #endif refs = xsltGetSAS(style, tmp->set, tmp->ns); if (refs == NULL) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : use-attribute-sets %s reference missing %s\n", name, tmp->set); } else { /* * recurse first for cleanup */ xsltResolveSASCallback(refs, style, name, ns, NULL); /* * Then merge */ xsltMergeAttrElemList(style, values, refs); /* * Then suppress the reference */ tmp->set = NULL; tmp->ns = NULL; } } } tmp = tmp->next; } } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltResolveSASCallback(xsltAttrElemPtr values, xsltStylesheetPtr style, xsltResolveSASCallbackInt(xsltAttrElemPtr values, xsltStylesheetPtr style, const xmlChar *name, const xmlChar *ns, int depth) { xsltAttrElemPtr tmp; xsltAttrElemPtr refs; tmp = values; if ((name == NULL) || (name[0] == 0)) return; if (depth > 100) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : use-attribute-sets recursion detected on %s\n", name); return; } while (tmp != NULL) { if (tmp->set != NULL) { /* * Check against cycles ! */ if ((xmlStrEqual(name, tmp->set)) && (xmlStrEqual(ns, tmp->ns))) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : use-attribute-sets recursion detected on %s\n", name); } else { #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "Importing attribute list %s\n", tmp->set); #endif refs = xsltGetSAS(style, tmp->set, tmp->ns); if (refs == NULL) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : use-attribute-sets %s reference missing %s\n", name, tmp->set); } else { /* * recurse first for cleanup */ xsltResolveSASCallbackInt(refs, style, name, ns, depth + 1); /* * Then merge */ xsltMergeAttrElemList(style, values, refs); /* * Then suppress the reference */ tmp->set = NULL; tmp->ns = NULL; } } } tmp = tmp->next; } }
173,299
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index++; spl_filesystem_dir_read(object TSRMLS_CC); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index++; spl_filesystem_dir_read(object TSRMLS_CC); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } }
167,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mount_entry_on_relative_rootfs(struct mntent *mntent, const char *rootfs) { char path[MAXPATHLEN]; int ret; /* relative to root mount point */ ret = snprintf(path, sizeof(path), "%s/%s", rootfs, mntent->mnt_dir); if (ret >= sizeof(path)) { ERROR("path name too long"); return -1; } return mount_entry_on_generic(mntent, path); } Commit Message: CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[email protected]> CWE ID: CWE-59
static int mount_entry_on_relative_rootfs(struct mntent *mntent, const char *rootfs) { char path[MAXPATHLEN]; int ret; /* relative to root mount point */ ret = snprintf(path, sizeof(path), "%s/%s", rootfs, mntent->mnt_dir); if (ret >= sizeof(path)) { ERROR("path name too long"); return -1; } return mount_entry_on_generic(mntent, path, rootfs); }
166,718
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(pg_get_notify) { zval *pgsql_link; int id = -1; long result_type = PGSQL_ASSOC; PGconn *pgsql; PGnotify *pgsql_notify; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &pgsql_link, &result_type) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (!(result_type & PGSQL_BOTH)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type"); RETURN_FALSE; } PQconsumeInput(pgsql); pgsql_notify = PQnotifies(pgsql); if (!pgsql_notify) { /* no notify message */ RETURN_FALSE; } array_init(return_value); if (result_type & PGSQL_NUM) { add_index_string(return_value, 0, pgsql_notify->relname, 1); add_index_long(return_value, 1, pgsql_notify->be_pid); #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) { #else if (atof(PG_VERSION) >= 9.0) { #endif #if HAVE_PQPARAMETERSTATUS add_index_string(return_value, 2, pgsql_notify->extra, 1); #endif } } if (result_type & PGSQL_ASSOC) { add_assoc_string(return_value, "message", pgsql_notify->relname, 1); add_assoc_long(return_value, "pid", pgsql_notify->be_pid); #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) { #else if (atof(PG_VERSION) >= 9.0) { #endif #if HAVE_PQPARAMETERSTATUS add_assoc_string(return_value, "payload", pgsql_notify->extra, 1); #endif } } PQfreemem(pgsql_notify); } /* }}} */ /* {{{ proto int pg_get_pid([resource connection) Get backend(server) pid */ PHP_FUNCTION(pg_get_pid) { zval *pgsql_link; int id = -1; PGconn *pgsql; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); RETURN_LONG(PQbackendPID(pgsql)); } /* }}} */ /* {{{ php_pgsql_meta_data * TODO: Add meta_data cache for better performance */ PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, zval *meta TSRMLS_DC) { PGresult *pg_result; char *src, *tmp_name, *tmp_name2 = NULL; char *escaped; smart_str querystr = {0}; size_t new_len; int i, num_rows; zval *elem; if (!*table_name) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The table name must be specified"); return FAILURE; } src = estrdup(table_name); tmp_name = php_strtok_r(src, ".", &tmp_name2); if (!tmp_name2 || !*tmp_name2) { /* Default schema */ tmp_name2 = tmp_name; "SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotnull, a.atthasdef, a.attndims, t.typtype = 'e' " "FROM pg_class as c, pg_attribute a, pg_type t, pg_namespace n " "WHERE a.attnum > 0 AND a.attrelid = c.oid AND c.relname = '"); escaped = (char *)safe_emalloc(strlen(tmp_name2), 2, 1); new_len = PQescapeStringConn(pg_link, escaped, tmp_name2, strlen(tmp_name2), NULL); if (new_len) { smart_str_appendl(&querystr, escaped, new_len); } efree(escaped); smart_str_appends(&querystr, "' AND c.relnamespace = n.oid AND n.nspname = '"); escaped = (char *)safe_emalloc(strlen(tmp_name), 2, 1); new_len = PQescapeStringConn(pg_link, escaped, tmp_name, strlen(tmp_name), NULL); if (new_len) { smart_str_appendl(&querystr, escaped, new_len); } efree(escaped); smart_str_appends(&querystr, "' AND a.atttypid = t.oid ORDER BY a.attnum;"); smart_str_0(&querystr); efree(src); pg_result = PQexec(pg_link, querystr.c); if (PQresultStatus(pg_result) != PGRES_TUPLES_OK || (num_rows = PQntuples(pg_result)) == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Table '%s' doesn't exists", table_name); smart_str_free(&querystr); PQclear(pg_result); return FAILURE; } smart_str_free(&querystr); for (i = 0; i < num_rows; i++) { char *name; MAKE_STD_ZVAL(elem); array_init(elem); add_assoc_long(elem, "num", atoi(PQgetvalue(pg_result,i,1))); add_assoc_string(elem, "type", PQgetvalue(pg_result,i,2), 1); add_assoc_long(elem, "len", atoi(PQgetvalue(pg_result,i,3))); if (!strcmp(PQgetvalue(pg_result,i,4), "t")) { add_assoc_bool(elem, "not null", 1); } else { add_assoc_bool(elem, "not null", 0); } if (!strcmp(PQgetvalue(pg_result,i,5), "t")) { add_assoc_bool(elem, "has default", 1); } else { add_assoc_bool(elem, "has default", 0); } add_assoc_long(elem, "array dims", atoi(PQgetvalue(pg_result,i,6))); if (!strcmp(PQgetvalue(pg_result,i,7), "t")) { add_assoc_bool(elem, "is enum", 1); } else { add_assoc_bool(elem, "is enum", 0); } name = PQgetvalue(pg_result,i,0); add_assoc_zval(meta, name, elem); } PQclear(pg_result); return SUCCESS; } /* }}} */ Commit Message: CWE ID:
PHP_FUNCTION(pg_get_notify) { zval *pgsql_link; int id = -1; long result_type = PGSQL_ASSOC; PGconn *pgsql; PGnotify *pgsql_notify; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &pgsql_link, &result_type) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (!(result_type & PGSQL_BOTH)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type"); RETURN_FALSE; } PQconsumeInput(pgsql); pgsql_notify = PQnotifies(pgsql); if (!pgsql_notify) { /* no notify message */ RETURN_FALSE; } array_init(return_value); if (result_type & PGSQL_NUM) { add_index_string(return_value, 0, pgsql_notify->relname, 1); add_index_long(return_value, 1, pgsql_notify->be_pid); #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) { #else if (atof(PG_VERSION) >= 9.0) { #endif #if HAVE_PQPARAMETERSTATUS add_index_string(return_value, 2, pgsql_notify->extra, 1); #endif } } if (result_type & PGSQL_ASSOC) { add_assoc_string(return_value, "message", pgsql_notify->relname, 1); add_assoc_long(return_value, "pid", pgsql_notify->be_pid); #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) { #else if (atof(PG_VERSION) >= 9.0) { #endif #if HAVE_PQPARAMETERSTATUS add_assoc_string(return_value, "payload", pgsql_notify->extra, 1); #endif } } PQfreemem(pgsql_notify); } /* }}} */ /* {{{ proto int pg_get_pid([resource connection) Get backend(server) pid */ PHP_FUNCTION(pg_get_pid) { zval *pgsql_link; int id = -1; PGconn *pgsql; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); RETURN_LONG(PQbackendPID(pgsql)); } /* }}} */ /* {{{ php_pgsql_meta_data * TODO: Add meta_data cache for better performance */ PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, zval *meta TSRMLS_DC) { PGresult *pg_result; char *src, *tmp_name, *tmp_name2 = NULL; char *escaped; smart_str querystr = {0}; size_t new_len; int i, num_rows; zval *elem; if (!*table_name) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The table name must be specified"); return FAILURE; } src = estrdup(table_name); tmp_name = php_strtok_r(src, ".", &tmp_name2); if (!tmp_name) { efree(src); php_error_docref(NULL TSRMLS_CC, E_WARNING, "The table name must be specified"); return FAILURE; } if (!tmp_name2 || !*tmp_name2) { /* Default schema */ tmp_name2 = tmp_name; "SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotnull, a.atthasdef, a.attndims, t.typtype = 'e' " "FROM pg_class as c, pg_attribute a, pg_type t, pg_namespace n " "WHERE a.attnum > 0 AND a.attrelid = c.oid AND c.relname = '"); escaped = (char *)safe_emalloc(strlen(tmp_name2), 2, 1); new_len = PQescapeStringConn(pg_link, escaped, tmp_name2, strlen(tmp_name2), NULL); if (new_len) { smart_str_appendl(&querystr, escaped, new_len); } efree(escaped); smart_str_appends(&querystr, "' AND c.relnamespace = n.oid AND n.nspname = '"); escaped = (char *)safe_emalloc(strlen(tmp_name), 2, 1); new_len = PQescapeStringConn(pg_link, escaped, tmp_name, strlen(tmp_name), NULL); if (new_len) { smart_str_appendl(&querystr, escaped, new_len); } efree(escaped); smart_str_appends(&querystr, "' AND a.atttypid = t.oid ORDER BY a.attnum;"); smart_str_0(&querystr); efree(src); pg_result = PQexec(pg_link, querystr.c); if (PQresultStatus(pg_result) != PGRES_TUPLES_OK || (num_rows = PQntuples(pg_result)) == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Table '%s' doesn't exists", table_name); smart_str_free(&querystr); PQclear(pg_result); return FAILURE; } smart_str_free(&querystr); for (i = 0; i < num_rows; i++) { char *name; MAKE_STD_ZVAL(elem); array_init(elem); add_assoc_long(elem, "num", atoi(PQgetvalue(pg_result,i,1))); add_assoc_string(elem, "type", PQgetvalue(pg_result,i,2), 1); add_assoc_long(elem, "len", atoi(PQgetvalue(pg_result,i,3))); if (!strcmp(PQgetvalue(pg_result,i,4), "t")) { add_assoc_bool(elem, "not null", 1); } else { add_assoc_bool(elem, "not null", 0); } if (!strcmp(PQgetvalue(pg_result,i,5), "t")) { add_assoc_bool(elem, "has default", 1); } else { add_assoc_bool(elem, "has default", 0); } add_assoc_long(elem, "array dims", atoi(PQgetvalue(pg_result,i,6))); if (!strcmp(PQgetvalue(pg_result,i,7), "t")) { add_assoc_bool(elem, "is enum", 1); } else { add_assoc_bool(elem, "is enum", 0); } name = PQgetvalue(pg_result,i,0); add_assoc_zval(meta, name, elem); } PQclear(pg_result); return SUCCESS; } /* }}} */
165,300
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ShellWindowFrameView::Layout() { gfx::Size close_size = close_button_->GetPreferredSize(); int closeButtonOffsetY = (kCaptionHeight - close_size.height()) / 2; int closeButtonOffsetX = closeButtonOffsetY; close_button_->SetBounds( width() - closeButtonOffsetX - close_size.width(), closeButtonOffsetY, close_size.width(), close_size.height()); } Commit Message: [views] Remove header bar on shell windows created with {frame: none}. BUG=130182 [email protected] Review URL: https://chromiumcodereview.appspot.com/10597003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-79
void ShellWindowFrameView::Layout() { if (is_frameless_) return; gfx::Size close_size = close_button_->GetPreferredSize(); int closeButtonOffsetY = (kCaptionHeight - close_size.height()) / 2; int closeButtonOffsetX = closeButtonOffsetY; close_button_->SetBounds( width() - closeButtonOffsetX - close_size.width(), closeButtonOffsetY, close_size.width(), close_size.height()); }
170,716
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int tap_if_down(const char *devname) { struct ifreq ifr; int sk; sk = socket(AF_INET, SOCK_DGRAM, 0); if (sk < 0) return -1; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1); ifr.ifr_flags &= ~IFF_UP; ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr); close(sk); return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int tap_if_down(const char *devname) { struct ifreq ifr; int sk; sk = socket(AF_INET, SOCK_DGRAM, 0); if (sk < 0) return -1; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1); ifr.ifr_flags &= ~IFF_UP; TEMP_FAILURE_RETRY(ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr)); close(sk); return 0; }
173,448
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool IsSystemModal(aura::Window* window) { return window->transient_parent() && window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM; } Commit Message: Removed requirement for ash::Window::transient_parent() presence for system modal dialogs. BUG=130420 TEST=SystemModalContainerLayoutManagerTest.ModalTransientAndNonTransient Review URL: https://chromiumcodereview.appspot.com/10514012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@140647 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool IsSystemModal(aura::Window* window) { return window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM; }
170,801
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,"NotAVIFFImage"); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); (void) ReadBlob(image,512,(unsigned char *) viff_info.comment); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,"comment",viff_info.comment); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=(int) ReadBlobLong(image); viff_info.y_offset=(int) ReadBlobLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (number_pixels == 0) ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported"); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported"); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported"); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported"); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,"LocationTypeIsNotSupported"); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported"); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read VIFF raster colormap. */ (void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=ScaleCharToQuantum( (unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=ScaleCharToQuantum( (unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } /* Initialize image structure. */ image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse; image->storage_class= (viff_info.number_data_bands < 3 ? PseudoClass : DirectClass); image->columns=viff_info.rows; image->rows=viff_info.columns; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) max_packets=((image->columns+7UL) >> 3UL)*image->rows; else max_packets=(size_t) (number_pixels*viff_info.number_data_bands); pixels=(unsigned char *) AcquireQuantumMemory(max_packets, bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(MagickRealType) QuantumRange/min_value; min_value=0; } else scale_factor=(MagickRealType) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ if (image->storage_class != PseudoClass) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels))); SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels))); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(q); SetPixelRed(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].red); index=(ssize_t) GetPixelGreen(q); SetPixelGreen(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].green); index=(ssize_t) GetPixelRed(q); SetPixelBlue(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].blue); } SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange- ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count != 0) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/99 CWE ID: CWE-125
static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,"NotAVIFFImage"); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); (void) ReadBlob(image,512,(unsigned char *) viff_info.comment); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,"comment",viff_info.comment); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=(int) ReadBlobLong(image); viff_info.y_offset=(int) ReadBlobLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (number_pixels == 0) ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported"); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported"); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported"); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported"); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,"LocationTypeIsNotSupported"); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported"); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read VIFF raster colormap. */ (void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=ScaleCharToQuantum( (unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=ScaleCharToQuantum( (unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } /* Initialize image structure. */ image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse; image->storage_class= (viff_info.number_data_bands < 3 ? PseudoClass : DirectClass); image->columns=viff_info.rows; image->rows=viff_info.columns; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) max_packets=((image->columns+7UL) >> 3UL)*image->rows; else max_packets=(size_t) (number_pixels*viff_info.number_data_bands); pixels=(unsigned char *) AcquireQuantumMemory(MagickMax(number_pixels, max_packets),bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(MagickRealType) QuantumRange/min_value; min_value=0; } else scale_factor=(MagickRealType) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ if (image->storage_class != PseudoClass) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels))); SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels))); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(q); SetPixelRed(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].red); index=(ssize_t) GetPixelGreen(q); SetPixelGreen(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].green); index=(ssize_t) GetPixelRed(q); SetPixelBlue(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].blue); } SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange- ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count != 0) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,801
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int __kprobes do_page_fault(struct pt_regs *regs, unsigned long address, unsigned long error_code) { struct vm_area_struct * vma; struct mm_struct *mm = current->mm; siginfo_t info; int code = SEGV_MAPERR; int is_write = 0, ret; int trap = TRAP(regs); int is_exec = trap == 0x400; #if !(defined(CONFIG_4xx) || defined(CONFIG_BOOKE)) /* * Fortunately the bit assignments in SRR1 for an instruction * fault and DSISR for a data fault are mostly the same for the * bits we are interested in. But there are some bits which * indicate errors in DSISR but can validly be set in SRR1. */ if (trap == 0x400) error_code &= 0x48200000; else is_write = error_code & DSISR_ISSTORE; #else is_write = error_code & ESR_DST; #endif /* CONFIG_4xx || CONFIG_BOOKE */ if (notify_page_fault(regs)) return 0; if (unlikely(debugger_fault_handler(regs))) return 0; /* On a kernel SLB miss we can only check for a valid exception entry */ if (!user_mode(regs) && (address >= TASK_SIZE)) return SIGSEGV; #if !(defined(CONFIG_4xx) || defined(CONFIG_BOOKE) || \ defined(CONFIG_PPC_BOOK3S_64)) if (error_code & DSISR_DABRMATCH) { /* DABR match */ do_dabr(regs, address, error_code); return 0; } #endif if (in_atomic() || mm == NULL) { if (!user_mode(regs)) return SIGSEGV; /* in_atomic() in user mode is really bad, as is current->mm == NULL. */ printk(KERN_EMERG "Page fault in user mode with " "in_atomic() = %d mm = %p\n", in_atomic(), mm); printk(KERN_EMERG "NIP = %lx MSR = %lx\n", regs->nip, regs->msr); die("Weird page fault", regs, SIGSEGV); } perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address); /* When running in the kernel we expect faults to occur only to * addresses in user space. All other faults represent errors in the * kernel and should generate an OOPS. Unfortunately, in the case of an * erroneous fault occurring in a code path which already holds mmap_sem * we will deadlock attempting to validate the fault against the * address space. Luckily the kernel only validly references user * space from well defined areas of code, which are listed in the * exceptions table. * * As the vast majority of faults will be valid we will only perform * the source reference check when there is a possibility of a deadlock. * Attempt to lock the address space, if we cannot we then validate the * source. If this is invalid we can skip the address space check, * thus avoiding the deadlock. */ if (!down_read_trylock(&mm->mmap_sem)) { if (!user_mode(regs) && !search_exception_tables(regs->nip)) goto bad_area_nosemaphore; down_read(&mm->mmap_sem); } vma = find_vma(mm, address); if (!vma) goto bad_area; if (vma->vm_start <= address) goto good_area; if (!(vma->vm_flags & VM_GROWSDOWN)) goto bad_area; /* * N.B. The POWER/Open ABI allows programs to access up to * 288 bytes below the stack pointer. * The kernel signal delivery code writes up to about 1.5kB * below the stack pointer (r1) before decrementing it. * The exec code can write slightly over 640kB to the stack * before setting the user r1. Thus we allow the stack to * expand to 1MB without further checks. */ if (address + 0x100000 < vma->vm_end) { /* get user regs even if this fault is in kernel mode */ struct pt_regs *uregs = current->thread.regs; if (uregs == NULL) goto bad_area; /* * A user-mode access to an address a long way below * the stack pointer is only valid if the instruction * is one which would update the stack pointer to the * address accessed if the instruction completed, * i.e. either stwu rs,n(r1) or stwux rs,r1,rb * (or the byte, halfword, float or double forms). * * If we don't check this then any write to the area * between the last mapped region and the stack will * expand the stack rather than segfaulting. */ if (address + 2048 < uregs->gpr[1] && (!user_mode(regs) || !store_updates_sp(regs))) goto bad_area; } if (expand_stack(vma, address)) goto bad_area; good_area: code = SEGV_ACCERR; #if defined(CONFIG_6xx) if (error_code & 0x95700000) /* an error such as lwarx to I/O controller space, address matching DABR, eciwx, etc. */ goto bad_area; #endif /* CONFIG_6xx */ #if defined(CONFIG_8xx) /* 8xx sometimes need to load a invalid/non-present TLBs. * These must be invalidated separately as linux mm don't. */ if (error_code & 0x40000000) /* no translation? */ _tlbil_va(address, 0, 0, 0); /* The MPC8xx seems to always set 0x80000000, which is * "undefined". Of those that can be set, this is the only * one which seems bad. */ if (error_code & 0x10000000) /* Guarded storage error. */ goto bad_area; #endif /* CONFIG_8xx */ if (is_exec) { #ifdef CONFIG_PPC_STD_MMU /* Protection fault on exec go straight to failure on * Hash based MMUs as they either don't support per-page * execute permission, or if they do, it's handled already * at the hash level. This test would probably have to * be removed if we change the way this works to make hash * processors use the same I/D cache coherency mechanism * as embedded. */ if (error_code & DSISR_PROTFAULT) goto bad_area; #endif /* CONFIG_PPC_STD_MMU */ /* * Allow execution from readable areas if the MMU does not * provide separate controls over reading and executing. * * Note: That code used to not be enabled for 4xx/BookE. * It is now as I/D cache coherency for these is done at * set_pte_at() time and I see no reason why the test * below wouldn't be valid on those processors. This -may- * break programs compiled with a really old ABI though. */ if (!(vma->vm_flags & VM_EXEC) && (cpu_has_feature(CPU_FTR_NOEXECUTE) || !(vma->vm_flags & (VM_READ | VM_WRITE)))) goto bad_area; /* a write */ } else if (is_write) { if (!(vma->vm_flags & VM_WRITE)) goto bad_area; /* a read */ } else { /* protection fault */ if (error_code & 0x08000000) goto bad_area; if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE))) goto bad_area; } /* * If for any reason at all we couldn't handle the fault, * make sure we exit gracefully rather than endlessly redo * the fault. */ ret = handle_mm_fault(mm, vma, address, is_write ? FAULT_FLAG_WRITE : 0); if (unlikely(ret & VM_FAULT_ERROR)) { if (ret & VM_FAULT_OOM) goto out_of_memory; else if (ret & VM_FAULT_SIGBUS) goto do_sigbus; BUG(); } if (ret & VM_FAULT_MAJOR) { current->maj_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0, regs, address); #ifdef CONFIG_PPC_SMLPAR if (firmware_has_feature(FW_FEATURE_CMO)) { preempt_disable(); get_lppaca()->page_ins += (1 << PAGE_FACTOR); preempt_enable(); } #endif } else { current->min_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0, regs, address); } up_read(&mm->mmap_sem); return 0; bad_area: up_read(&mm->mmap_sem); bad_area_nosemaphore: /* User mode accesses cause a SIGSEGV */ if (user_mode(regs)) { _exception(SIGSEGV, regs, code, address); return 0; } if (is_exec && (error_code & DSISR_PROTFAULT) && printk_ratelimit()) printk(KERN_CRIT "kernel tried to execute NX-protected" " page (%lx) - exploit attempt? (uid: %d)\n", address, current_uid()); return SIGSEGV; /* * We ran out of memory, or some other thing happened to us that made * us unable to handle the page fault gracefully. */ out_of_memory: up_read(&mm->mmap_sem); if (!user_mode(regs)) return SIGKILL; pagefault_out_of_memory(); return 0; do_sigbus: up_read(&mm->mmap_sem); if (user_mode(regs)) { info.si_signo = SIGBUS; info.si_errno = 0; info.si_code = BUS_ADRERR; info.si_addr = (void __user *)address; force_sig_info(SIGBUS, &info, current); return 0; } return SIGBUS; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
int __kprobes do_page_fault(struct pt_regs *regs, unsigned long address, unsigned long error_code) { struct vm_area_struct * vma; struct mm_struct *mm = current->mm; siginfo_t info; int code = SEGV_MAPERR; int is_write = 0, ret; int trap = TRAP(regs); int is_exec = trap == 0x400; #if !(defined(CONFIG_4xx) || defined(CONFIG_BOOKE)) /* * Fortunately the bit assignments in SRR1 for an instruction * fault and DSISR for a data fault are mostly the same for the * bits we are interested in. But there are some bits which * indicate errors in DSISR but can validly be set in SRR1. */ if (trap == 0x400) error_code &= 0x48200000; else is_write = error_code & DSISR_ISSTORE; #else is_write = error_code & ESR_DST; #endif /* CONFIG_4xx || CONFIG_BOOKE */ if (notify_page_fault(regs)) return 0; if (unlikely(debugger_fault_handler(regs))) return 0; /* On a kernel SLB miss we can only check for a valid exception entry */ if (!user_mode(regs) && (address >= TASK_SIZE)) return SIGSEGV; #if !(defined(CONFIG_4xx) || defined(CONFIG_BOOKE) || \ defined(CONFIG_PPC_BOOK3S_64)) if (error_code & DSISR_DABRMATCH) { /* DABR match */ do_dabr(regs, address, error_code); return 0; } #endif if (in_atomic() || mm == NULL) { if (!user_mode(regs)) return SIGSEGV; /* in_atomic() in user mode is really bad, as is current->mm == NULL. */ printk(KERN_EMERG "Page fault in user mode with " "in_atomic() = %d mm = %p\n", in_atomic(), mm); printk(KERN_EMERG "NIP = %lx MSR = %lx\n", regs->nip, regs->msr); die("Weird page fault", regs, SIGSEGV); } perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address); /* When running in the kernel we expect faults to occur only to * addresses in user space. All other faults represent errors in the * kernel and should generate an OOPS. Unfortunately, in the case of an * erroneous fault occurring in a code path which already holds mmap_sem * we will deadlock attempting to validate the fault against the * address space. Luckily the kernel only validly references user * space from well defined areas of code, which are listed in the * exceptions table. * * As the vast majority of faults will be valid we will only perform * the source reference check when there is a possibility of a deadlock. * Attempt to lock the address space, if we cannot we then validate the * source. If this is invalid we can skip the address space check, * thus avoiding the deadlock. */ if (!down_read_trylock(&mm->mmap_sem)) { if (!user_mode(regs) && !search_exception_tables(regs->nip)) goto bad_area_nosemaphore; down_read(&mm->mmap_sem); } vma = find_vma(mm, address); if (!vma) goto bad_area; if (vma->vm_start <= address) goto good_area; if (!(vma->vm_flags & VM_GROWSDOWN)) goto bad_area; /* * N.B. The POWER/Open ABI allows programs to access up to * 288 bytes below the stack pointer. * The kernel signal delivery code writes up to about 1.5kB * below the stack pointer (r1) before decrementing it. * The exec code can write slightly over 640kB to the stack * before setting the user r1. Thus we allow the stack to * expand to 1MB without further checks. */ if (address + 0x100000 < vma->vm_end) { /* get user regs even if this fault is in kernel mode */ struct pt_regs *uregs = current->thread.regs; if (uregs == NULL) goto bad_area; /* * A user-mode access to an address a long way below * the stack pointer is only valid if the instruction * is one which would update the stack pointer to the * address accessed if the instruction completed, * i.e. either stwu rs,n(r1) or stwux rs,r1,rb * (or the byte, halfword, float or double forms). * * If we don't check this then any write to the area * between the last mapped region and the stack will * expand the stack rather than segfaulting. */ if (address + 2048 < uregs->gpr[1] && (!user_mode(regs) || !store_updates_sp(regs))) goto bad_area; } if (expand_stack(vma, address)) goto bad_area; good_area: code = SEGV_ACCERR; #if defined(CONFIG_6xx) if (error_code & 0x95700000) /* an error such as lwarx to I/O controller space, address matching DABR, eciwx, etc. */ goto bad_area; #endif /* CONFIG_6xx */ #if defined(CONFIG_8xx) /* 8xx sometimes need to load a invalid/non-present TLBs. * These must be invalidated separately as linux mm don't. */ if (error_code & 0x40000000) /* no translation? */ _tlbil_va(address, 0, 0, 0); /* The MPC8xx seems to always set 0x80000000, which is * "undefined". Of those that can be set, this is the only * one which seems bad. */ if (error_code & 0x10000000) /* Guarded storage error. */ goto bad_area; #endif /* CONFIG_8xx */ if (is_exec) { #ifdef CONFIG_PPC_STD_MMU /* Protection fault on exec go straight to failure on * Hash based MMUs as they either don't support per-page * execute permission, or if they do, it's handled already * at the hash level. This test would probably have to * be removed if we change the way this works to make hash * processors use the same I/D cache coherency mechanism * as embedded. */ if (error_code & DSISR_PROTFAULT) goto bad_area; #endif /* CONFIG_PPC_STD_MMU */ /* * Allow execution from readable areas if the MMU does not * provide separate controls over reading and executing. * * Note: That code used to not be enabled for 4xx/BookE. * It is now as I/D cache coherency for these is done at * set_pte_at() time and I see no reason why the test * below wouldn't be valid on those processors. This -may- * break programs compiled with a really old ABI though. */ if (!(vma->vm_flags & VM_EXEC) && (cpu_has_feature(CPU_FTR_NOEXECUTE) || !(vma->vm_flags & (VM_READ | VM_WRITE)))) goto bad_area; /* a write */ } else if (is_write) { if (!(vma->vm_flags & VM_WRITE)) goto bad_area; /* a read */ } else { /* protection fault */ if (error_code & 0x08000000) goto bad_area; if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE))) goto bad_area; } /* * If for any reason at all we couldn't handle the fault, * make sure we exit gracefully rather than endlessly redo * the fault. */ ret = handle_mm_fault(mm, vma, address, is_write ? FAULT_FLAG_WRITE : 0); if (unlikely(ret & VM_FAULT_ERROR)) { if (ret & VM_FAULT_OOM) goto out_of_memory; else if (ret & VM_FAULT_SIGBUS) goto do_sigbus; BUG(); } if (ret & VM_FAULT_MAJOR) { current->maj_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address); #ifdef CONFIG_PPC_SMLPAR if (firmware_has_feature(FW_FEATURE_CMO)) { preempt_disable(); get_lppaca()->page_ins += (1 << PAGE_FACTOR); preempt_enable(); } #endif } else { current->min_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address); } up_read(&mm->mmap_sem); return 0; bad_area: up_read(&mm->mmap_sem); bad_area_nosemaphore: /* User mode accesses cause a SIGSEGV */ if (user_mode(regs)) { _exception(SIGSEGV, regs, code, address); return 0; } if (is_exec && (error_code & DSISR_PROTFAULT) && printk_ratelimit()) printk(KERN_CRIT "kernel tried to execute NX-protected" " page (%lx) - exploit attempt? (uid: %d)\n", address, current_uid()); return SIGSEGV; /* * We ran out of memory, or some other thing happened to us that made * us unable to handle the page fault gracefully. */ out_of_memory: up_read(&mm->mmap_sem); if (!user_mode(regs)) return SIGKILL; pagefault_out_of_memory(); return 0; do_sigbus: up_read(&mm->mmap_sem); if (user_mode(regs)) { info.si_signo = SIGBUS; info.si_errno = 0; info.si_code = BUS_ADRERR; info.si_addr = (void __user *)address; force_sig_info(SIGBUS, &info, current); return 0; } return SIGBUS; }
165,793
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ring_buffer_resize(struct ring_buffer *buffer, unsigned long size, int cpu_id) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long nr_pages; int cpu, err = 0; /* * Always succeed at resizing a non-existent buffer: */ if (!buffer) return size; /* Make sure the requested buffer exists */ if (cpu_id != RING_BUFFER_ALL_CPUS && !cpumask_test_cpu(cpu_id, buffer->cpumask)) return size; size = DIV_ROUND_UP(size, BUF_PAGE_SIZE); size *= BUF_PAGE_SIZE; /* we need a minimum of two pages */ if (size < BUF_PAGE_SIZE * 2) size = BUF_PAGE_SIZE * 2; nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE); /* * Don't succeed if resizing is disabled, as a reader might be * manipulating the ring buffer and is expecting a sane state while * this is true. */ if (atomic_read(&buffer->resize_disabled)) return -EBUSY; /* prevent another thread from changing buffer sizes */ mutex_lock(&buffer->mutex); if (cpu_id == RING_BUFFER_ALL_CPUS) { /* calculate the pages to update */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; cpu_buffer->nr_pages_to_update = nr_pages - cpu_buffer->nr_pages; /* * nothing more to do for removing pages or no update */ if (cpu_buffer->nr_pages_to_update <= 0) continue; /* * to add pages, make sure all new pages can be * allocated without receiving ENOMEM */ INIT_LIST_HEAD(&cpu_buffer->new_pages); if (__rb_allocate_pages(cpu_buffer->nr_pages_to_update, &cpu_buffer->new_pages, cpu)) { /* not enough memory for new pages */ err = -ENOMEM; goto out_err; } } get_online_cpus(); /* * Fire off all the required work handlers * We can't schedule on offline CPUs, but it's not necessary * since we can change their buffer sizes without any race. */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; if (!cpu_buffer->nr_pages_to_update) continue; /* Can't run something on an offline CPU. */ if (!cpu_online(cpu)) { rb_update_pages(cpu_buffer); cpu_buffer->nr_pages_to_update = 0; } else { schedule_work_on(cpu, &cpu_buffer->update_pages_work); } } /* wait for all the updates to complete */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; if (!cpu_buffer->nr_pages_to_update) continue; if (cpu_online(cpu)) wait_for_completion(&cpu_buffer->update_done); cpu_buffer->nr_pages_to_update = 0; } put_online_cpus(); } else { /* Make sure this CPU has been intitialized */ if (!cpumask_test_cpu(cpu_id, buffer->cpumask)) goto out; cpu_buffer = buffer->buffers[cpu_id]; if (nr_pages == cpu_buffer->nr_pages) goto out; cpu_buffer->nr_pages_to_update = nr_pages - cpu_buffer->nr_pages; INIT_LIST_HEAD(&cpu_buffer->new_pages); if (cpu_buffer->nr_pages_to_update > 0 && __rb_allocate_pages(cpu_buffer->nr_pages_to_update, &cpu_buffer->new_pages, cpu_id)) { err = -ENOMEM; goto out_err; } get_online_cpus(); /* Can't run something on an offline CPU. */ if (!cpu_online(cpu_id)) rb_update_pages(cpu_buffer); else { schedule_work_on(cpu_id, &cpu_buffer->update_pages_work); wait_for_completion(&cpu_buffer->update_done); } cpu_buffer->nr_pages_to_update = 0; put_online_cpus(); } out: /* * The ring buffer resize can happen with the ring buffer * enabled, so that the update disturbs the tracing as little * as possible. But if the buffer is disabled, we do not need * to worry about that, and we can take the time to verify * that the buffer is not corrupt. */ if (atomic_read(&buffer->record_disabled)) { atomic_inc(&buffer->record_disabled); /* * Even though the buffer was disabled, we must make sure * that it is truly disabled before calling rb_check_pages. * There could have been a race between checking * record_disable and incrementing it. */ synchronize_sched(); for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; rb_check_pages(cpu_buffer); } atomic_dec(&buffer->record_disabled); } mutex_unlock(&buffer->mutex); return size; out_err: for_each_buffer_cpu(buffer, cpu) { struct buffer_page *bpage, *tmp; cpu_buffer = buffer->buffers[cpu]; cpu_buffer->nr_pages_to_update = 0; if (list_empty(&cpu_buffer->new_pages)) continue; list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages, list) { list_del_init(&bpage->list); free_buffer_page(bpage); } } mutex_unlock(&buffer->mutex); return err; } Commit Message: ring-buffer: Prevent overflow of size in ring_buffer_resize() If the size passed to ring_buffer_resize() is greater than MAX_LONG - BUF_PAGE_SIZE then the DIV_ROUND_UP() will return zero. Here's the details: # echo 18014398509481980 > /sys/kernel/debug/tracing/buffer_size_kb tracing_entries_write() processes this and converts kb to bytes. 18014398509481980 << 10 = 18446744073709547520 and this is passed to ring_buffer_resize() as unsigned long size. size = DIV_ROUND_UP(size, BUF_PAGE_SIZE); Where DIV_ROUND_UP(a, b) is (a + b - 1)/b BUF_PAGE_SIZE is 4080 and here 18446744073709547520 + 4080 - 1 = 18446744073709551599 where 18446744073709551599 is still smaller than 2^64 2^64 - 18446744073709551599 = 17 But now 18446744073709551599 / 4080 = 4521260802379792 and size = size * 4080 = 18446744073709551360 This is checked to make sure its still greater than 2 * 4080, which it is. Then we convert to the number of buffer pages needed. nr_page = DIV_ROUND_UP(size, BUF_PAGE_SIZE) but this time size is 18446744073709551360 and 2^64 - (18446744073709551360 + 4080 - 1) = -3823 Thus it overflows and the resulting number is less than 4080, which makes 3823 / 4080 = 0 an nr_pages is set to this. As we already checked against the minimum that nr_pages may be, this causes the logic to fail as well, and we crash the kernel. There's no reason to have the two DIV_ROUND_UP() (that's just result of historical code changes), clean up the code and fix this bug. Cc: [email protected] # 3.5+ Fixes: 83f40318dab00 ("ring-buffer: Make removal of ring buffer pages atomic") Signed-off-by: Steven Rostedt <[email protected]> CWE ID: CWE-190
int ring_buffer_resize(struct ring_buffer *buffer, unsigned long size, int cpu_id) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long nr_pages; int cpu, err = 0; /* * Always succeed at resizing a non-existent buffer: */ if (!buffer) return size; /* Make sure the requested buffer exists */ if (cpu_id != RING_BUFFER_ALL_CPUS && !cpumask_test_cpu(cpu_id, buffer->cpumask)) return size; nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE); /* we need a minimum of two pages */ if (nr_pages < 2) nr_pages = 2; size = nr_pages * BUF_PAGE_SIZE; /* * Don't succeed if resizing is disabled, as a reader might be * manipulating the ring buffer and is expecting a sane state while * this is true. */ if (atomic_read(&buffer->resize_disabled)) return -EBUSY; /* prevent another thread from changing buffer sizes */ mutex_lock(&buffer->mutex); if (cpu_id == RING_BUFFER_ALL_CPUS) { /* calculate the pages to update */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; cpu_buffer->nr_pages_to_update = nr_pages - cpu_buffer->nr_pages; /* * nothing more to do for removing pages or no update */ if (cpu_buffer->nr_pages_to_update <= 0) continue; /* * to add pages, make sure all new pages can be * allocated without receiving ENOMEM */ INIT_LIST_HEAD(&cpu_buffer->new_pages); if (__rb_allocate_pages(cpu_buffer->nr_pages_to_update, &cpu_buffer->new_pages, cpu)) { /* not enough memory for new pages */ err = -ENOMEM; goto out_err; } } get_online_cpus(); /* * Fire off all the required work handlers * We can't schedule on offline CPUs, but it's not necessary * since we can change their buffer sizes without any race. */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; if (!cpu_buffer->nr_pages_to_update) continue; /* Can't run something on an offline CPU. */ if (!cpu_online(cpu)) { rb_update_pages(cpu_buffer); cpu_buffer->nr_pages_to_update = 0; } else { schedule_work_on(cpu, &cpu_buffer->update_pages_work); } } /* wait for all the updates to complete */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; if (!cpu_buffer->nr_pages_to_update) continue; if (cpu_online(cpu)) wait_for_completion(&cpu_buffer->update_done); cpu_buffer->nr_pages_to_update = 0; } put_online_cpus(); } else { /* Make sure this CPU has been intitialized */ if (!cpumask_test_cpu(cpu_id, buffer->cpumask)) goto out; cpu_buffer = buffer->buffers[cpu_id]; if (nr_pages == cpu_buffer->nr_pages) goto out; cpu_buffer->nr_pages_to_update = nr_pages - cpu_buffer->nr_pages; INIT_LIST_HEAD(&cpu_buffer->new_pages); if (cpu_buffer->nr_pages_to_update > 0 && __rb_allocate_pages(cpu_buffer->nr_pages_to_update, &cpu_buffer->new_pages, cpu_id)) { err = -ENOMEM; goto out_err; } get_online_cpus(); /* Can't run something on an offline CPU. */ if (!cpu_online(cpu_id)) rb_update_pages(cpu_buffer); else { schedule_work_on(cpu_id, &cpu_buffer->update_pages_work); wait_for_completion(&cpu_buffer->update_done); } cpu_buffer->nr_pages_to_update = 0; put_online_cpus(); } out: /* * The ring buffer resize can happen with the ring buffer * enabled, so that the update disturbs the tracing as little * as possible. But if the buffer is disabled, we do not need * to worry about that, and we can take the time to verify * that the buffer is not corrupt. */ if (atomic_read(&buffer->record_disabled)) { atomic_inc(&buffer->record_disabled); /* * Even though the buffer was disabled, we must make sure * that it is truly disabled before calling rb_check_pages. * There could have been a race between checking * record_disable and incrementing it. */ synchronize_sched(); for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; rb_check_pages(cpu_buffer); } atomic_dec(&buffer->record_disabled); } mutex_unlock(&buffer->mutex); return size; out_err: for_each_buffer_cpu(buffer, cpu) { struct buffer_page *bpage, *tmp; cpu_buffer = buffer->buffers[cpu]; cpu_buffer->nr_pages_to_update = 0; if (list_empty(&cpu_buffer->new_pages)) continue; list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages, list) { list_del_init(&bpage->list); free_buffer_page(bpage); } } mutex_unlock(&buffer->mutex); return err; }
168,676
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: zrestore(i_ctx_t *i_ctx_p) { os_ptr op = osp; alloc_save_t *asave; bool last; vm_save_t *vmsave; int code = restore_check_operand(op, &asave, idmemory); if (code < 0) return code; if_debug2m('u', imemory, "[u]vmrestore 0x%lx, id = %lu\n", (ulong) alloc_save_client_data(asave), (ulong) op->value.saveid); if (I_VALIDATE_BEFORE_RESTORE) ivalidate_clean_spaces(i_ctx_p); ivalidate_clean_spaces(i_ctx_p); /* Check the contents of the stacks. */ { int code; if ((code = restore_check_stack(i_ctx_p, &o_stack, asave, false)) < 0 || (code = restore_check_stack(i_ctx_p, &e_stack, asave, true)) < 0 || (code = restore_check_stack(i_ctx_p, &d_stack, asave, false)) < 0 ) { osp++; return code; } } /* Reset l_new in all stack entries if the new save level is zero. */ /* Also do some special fixing on the e-stack. */ restore_fix_stack(i_ctx_p, &o_stack, asave, false); } Commit Message: CWE ID: CWE-78
zrestore(i_ctx_t *i_ctx_p) restore_check_save(i_ctx_t *i_ctx_p, alloc_save_t **asave) { os_ptr op = osp; int code = restore_check_operand(op, asave, idmemory); if (code < 0) return code; if_debug2m('u', imemory, "[u]vmrestore 0x%lx, id = %lu\n", (ulong) alloc_save_client_data(*asave), (ulong) op->value.saveid); if (I_VALIDATE_BEFORE_RESTORE) ivalidate_clean_spaces(i_ctx_p); ivalidate_clean_spaces(i_ctx_p); /* Check the contents of the stacks. */ { int code; if ((code = restore_check_stack(i_ctx_p, &o_stack, *asave, false)) < 0 || (code = restore_check_stack(i_ctx_p, &e_stack, *asave, true)) < 0 || (code = restore_check_stack(i_ctx_p, &d_stack, *asave, false)) < 0 ) { osp++; return code; } } osp++; return 0; } /* the semantics of restore differ slightly between Level 1 and Level 2 and later - the latter includes restoring the device state (whilst Level 1 didn't have "page devices" as such). Hence we have two restore operators - one here (Level 1) and one in zdevice2.c (Level 2+). For that reason, the operand checking and guts of the restore operation are separated so both implementations can use them to best effect. */ int dorestore(i_ctx_t *i_ctx_p, alloc_save_t *asave) { os_ptr op = osp; bool last; vm_save_t *vmsave; int code; osp--; /* Reset l_new in all stack entries if the new save level is zero. */ /* Also do some special fixing on the e-stack. */ restore_fix_stack(i_ctx_p, &o_stack, asave, false); }
164,688
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::unique_ptr<PrefService> CreatePrefService() { auto pref_registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); metrics::MetricsService::RegisterPrefs(pref_registry.get()); variations::VariationsService::RegisterPrefs(pref_registry.get()); AwBrowserProcess::RegisterNetworkContextLocalStatePrefs(pref_registry.get()); PrefServiceFactory pref_service_factory; std::set<std::string> persistent_prefs; for (const char* const pref_name : kPersistentPrefsWhitelist) persistent_prefs.insert(pref_name); pref_service_factory.set_user_prefs(base::MakeRefCounted<SegregatedPrefStore>( base::MakeRefCounted<InMemoryPrefStore>(), base::MakeRefCounted<JsonPrefStore>(GetPrefStorePath()), persistent_prefs, mojo::Remote<::prefs::mojom::TrackedPreferenceValidationDelegate>())); pref_service_factory.set_read_error_callback( base::BindRepeating(&HandleReadError)); return pref_service_factory.Create(pref_registry); } Commit Message: [AW] Add Variations.RestartsWithStaleSeed metric. This metric records the number of consecutive times the WebView browser process starts with a stale seed. It's written when a fresh seed is loaded after previously loading a stale seed. Test: Manually verified with logging that the metric was written. Bug: 1010625 Change-Id: Iadedb45af08d59ecd6662472670f848e8e99a8d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1851126 Commit-Queue: Robbie McElrath <[email protected]> Reviewed-by: Nate Fischer <[email protected]> Reviewed-by: Ilya Sherman <[email protected]> Reviewed-by: Changwan Ryu <[email protected]> Cr-Commit-Position: refs/heads/master@{#709417} CWE ID: CWE-20
std::unique_ptr<PrefService> CreatePrefService() { auto pref_registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); metrics::MetricsService::RegisterPrefs(pref_registry.get()); variations::VariationsService::RegisterPrefs(pref_registry.get()); pref_registry->RegisterIntegerPref(prefs::kRestartsWithStaleSeed, 0); AwBrowserProcess::RegisterNetworkContextLocalStatePrefs(pref_registry.get()); PrefServiceFactory pref_service_factory; std::set<std::string> persistent_prefs; for (const char* const pref_name : kPersistentPrefsWhitelist) persistent_prefs.insert(pref_name); pref_service_factory.set_user_prefs(base::MakeRefCounted<SegregatedPrefStore>( base::MakeRefCounted<InMemoryPrefStore>(), base::MakeRefCounted<JsonPrefStore>(GetPrefStorePath()), persistent_prefs, mojo::Remote<::prefs::mojom::TrackedPreferenceValidationDelegate>())); pref_service_factory.set_read_error_callback( base::BindRepeating(&HandleReadError)); return pref_service_factory.Create(pref_registry); }
172,359
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void __scm_destroy(struct scm_cookie *scm) { struct scm_fp_list *fpl = scm->fp; int i; if (fpl) { scm->fp = NULL; for (i=fpl->count-1; i>=0; i--) fput(fpl->fp[i]); kfree(fpl); } } Commit Message: unix: correctly track in-flight fds in sending process user_struct The commit referenced in the Fixes tag incorrectly accounted the number of in-flight fds over a unix domain socket to the original opener of the file-descriptor. This allows another process to arbitrary deplete the original file-openers resource limit for the maximum of open files. Instead the sending processes and its struct cred should be credited. To do so, we add a reference counted struct user_struct pointer to the scm_fp_list and use it to account for the number of inflight unix fds. Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets") Reported-by: David Herrmann <[email protected]> Cc: David Herrmann <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: Linus Torvalds <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
void __scm_destroy(struct scm_cookie *scm) { struct scm_fp_list *fpl = scm->fp; int i; if (fpl) { scm->fp = NULL; for (i=fpl->count-1; i>=0; i--) fput(fpl->fp[i]); free_uid(fpl->user); kfree(fpl); } }
167,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { assert((size_t)CDF_SHORT_SEC_SIZE(h) == len); (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + CDF_SHORT_SEC_POS(h, id), len); return len; } Commit Message: add more check found by cert's fuzzer. CWE ID: CWE-119
cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (sst->sst_len < (size_t)id) { DPRINTF(("bad sector id %d > %d\n", id, sst->sst_len)); return -1; } (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + pos, len); return len; }
169,884
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int l2cap_config_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data) { struct l2cap_conf_rsp *rsp = (struct l2cap_conf_rsp *)data; u16 scid, flags, result; struct sock *sk; scid = __le16_to_cpu(rsp->scid); flags = __le16_to_cpu(rsp->flags); result = __le16_to_cpu(rsp->result); BT_DBG("scid 0x%4.4x flags 0x%2.2x result 0x%2.2x", scid, flags, result); sk = l2cap_get_chan_by_scid(&conn->chan_list, scid); if (!sk) return 0; switch (result) { case L2CAP_CONF_SUCCESS: break; case L2CAP_CONF_UNACCEPT: if (++l2cap_pi(sk)->conf_retry < L2CAP_CONF_MAX_RETRIES) { char req[128]; /* It does not make sense to adjust L2CAP parameters * that are currently defined in the spec. We simply * resend config request that we sent earlier. It is * stupid, but it helps qualification testing which * expects at least some response from us. */ l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ, l2cap_build_conf_req(sk, req), req); goto done; } default: sk->sk_state = BT_DISCONN; sk->sk_err = ECONNRESET; l2cap_sock_set_timer(sk, HZ * 5); { struct l2cap_disconn_req req; req.dcid = cpu_to_le16(l2cap_pi(sk)->dcid); req.scid = cpu_to_le16(l2cap_pi(sk)->scid); l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_DISCONN_REQ, sizeof(req), &req); } goto done; } if (flags & 0x01) goto done; l2cap_pi(sk)->conf_state |= L2CAP_CONF_INPUT_DONE; if (l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE) { sk->sk_state = BT_CONNECTED; l2cap_chan_ready(sk); } done: bh_unlock_sock(sk); return 0; } Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode Add support to config_req and config_rsp to configure ERTM and Streaming mode. If the remote device specifies ERTM or Streaming mode, then the same mode is proposed. Otherwise ERTM or Basic mode is used. And in case of a state 2 device, the remote device should propose the same mode. If not, then the channel gets disconnected. Signed-off-by: Gustavo F. Padovan <[email protected]> Signed-off-by: Marcel Holtmann <[email protected]> CWE ID: CWE-119
static inline int l2cap_config_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data) { struct l2cap_conf_rsp *rsp = (struct l2cap_conf_rsp *)data; u16 scid, flags, result; struct sock *sk; scid = __le16_to_cpu(rsp->scid); flags = __le16_to_cpu(rsp->flags); result = __le16_to_cpu(rsp->result); BT_DBG("scid 0x%4.4x flags 0x%2.2x result 0x%2.2x", scid, flags, result); sk = l2cap_get_chan_by_scid(&conn->chan_list, scid); if (!sk) return 0; switch (result) { case L2CAP_CONF_SUCCESS: break; case L2CAP_CONF_UNACCEPT: if (l2cap_pi(sk)->num_conf_rsp <= L2CAP_CONF_MAX_CONF_RSP) { int len = cmd->len - sizeof(*rsp); char req[64]; /* throw out any old stored conf requests */ result = L2CAP_CONF_SUCCESS; len = l2cap_parse_conf_rsp(sk, rsp->data, len, req, &result); if (len < 0) { struct l2cap_disconn_req req; req.dcid = cpu_to_le16(l2cap_pi(sk)->dcid); req.scid = cpu_to_le16(l2cap_pi(sk)->scid); l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_DISCONN_REQ, sizeof(req), &req); goto done; } l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ, len, req); l2cap_pi(sk)->num_conf_req++; if (result != L2CAP_CONF_SUCCESS) goto done; break; } default: sk->sk_state = BT_DISCONN; sk->sk_err = ECONNRESET; l2cap_sock_set_timer(sk, HZ * 5); { struct l2cap_disconn_req req; req.dcid = cpu_to_le16(l2cap_pi(sk)->dcid); req.scid = cpu_to_le16(l2cap_pi(sk)->scid); l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_DISCONN_REQ, sizeof(req), &req); } goto done; } if (flags & 0x01) goto done; l2cap_pi(sk)->conf_state |= L2CAP_CONF_INPUT_DONE; if (l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE) { sk->sk_state = BT_CONNECTED; l2cap_chan_ready(sk); } done: bh_unlock_sock(sk); return 0; }
167,623
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,c); switch (type) { case EVP_CTRL_INIT: gctx->key_set = 0; gctx->iv_set = 0; gctx->ivlen = EVP_CIPHER_CTX_iv_length(c); gctx->iv = EVP_CIPHER_CTX_iv_noconst(c); gctx->taglen = -1; gctx->iv_gen = 0; gctx->tls_aad_len = -1; return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0) return 0; /* Allocate memory for IV if needed */ if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) { if (gctx->iv != EVP_CIPHER_CTX_iv_noconst(c)) OPENSSL_free(gctx->iv); gctx->iv = OPENSSL_malloc(arg); if (gctx->iv == NULL) return 0; } gctx->ivlen = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if (arg <= 0 || arg > 16 || EVP_CIPHER_CTX_encrypting(c)) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); gctx->taglen = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg <= 0 || arg > 16 || !EVP_CIPHER_CTX_encrypting(c) || gctx->taglen < 0) return 0; memcpy(ptr, EVP_CIPHER_CTX_buf_noconst(c), arg); return 1; case EVP_CTRL_GCM_SET_IV_FIXED: /* Special case: -1 length restores whole IV */ if (arg == -1) { memcpy(gctx->iv, ptr, gctx->ivlen); gctx->iv_gen = 1; return 1; } /* * Fixed field must be at least 4 bytes and invocation field at least * 8. */ if ((arg < 4) || (gctx->ivlen - arg) < 8) return 0; if (arg) memcpy(gctx->iv, ptr, arg); if (EVP_CIPHER_CTX_encrypting(c) && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0) return 0; gctx->iv_gen = 1; return 1; case EVP_CTRL_GCM_IV_GEN: if (gctx->iv_gen == 0 || gctx->key_set == 0) return 0; CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); if (arg <= 0 || arg > gctx->ivlen) arg = gctx->ivlen; memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg); /* * Invocation field will be at least 8 bytes in size and so no need * to check wrap around or increment more than last 8 bytes. */ ctr64_inc(gctx->iv + gctx->ivlen - 8); gctx->iv_set = 1; return 1; case EVP_CTRL_GCM_SET_IV_INV: if (gctx->iv_gen == 0 || gctx->key_set == 0 || EVP_CIPHER_CTX_encrypting(c)) return 0; memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg); CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); gctx->iv_set = 1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); gctx->tls_aad_len = arg; { unsigned int len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ len -= EVP_GCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_encrypting(c)) len -= EVP_GCM_TLS_TAG_LEN; EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return EVP_GCM_TLS_TAG_LEN; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_GCM_CTX *gctx_out = EVP_C_DATA(EVP_AES_GCM_CTX,out); if (gctx->gcm.key) { if (gctx->gcm.key != &gctx->ks) return 0; gctx_out->gcm.key = &gctx_out->ks; } if (gctx->iv == EVP_CIPHER_CTX_iv_noconst(c)) gctx_out->iv = EVP_CIPHER_CTX_iv_noconst(out); else { gctx_out->iv = OPENSSL_malloc(gctx->ivlen); if (gctx_out->iv == NULL) return 0; memcpy(gctx_out->iv, gctx->iv, gctx->ivlen); } return 1; } default: return -1; } } Commit Message: crypto/evp: harden AEAD ciphers. Originally a crash in 32-bit build was reported CHACHA20-POLY1305 cipher. The crash is triggered by truncated packet and is result of excessive hashing to the edge of accessible memory. Since hash operation is read-only it is not considered to be exploitable beyond a DoS condition. Other ciphers were hardened. Thanks to Robert Święcki for report. CVE-2017-3731 Reviewed-by: Rich Salz <[email protected]> CWE ID: CWE-125
static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,c); switch (type) { case EVP_CTRL_INIT: gctx->key_set = 0; gctx->iv_set = 0; gctx->ivlen = EVP_CIPHER_CTX_iv_length(c); gctx->iv = EVP_CIPHER_CTX_iv_noconst(c); gctx->taglen = -1; gctx->iv_gen = 0; gctx->tls_aad_len = -1; return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0) return 0; /* Allocate memory for IV if needed */ if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) { if (gctx->iv != EVP_CIPHER_CTX_iv_noconst(c)) OPENSSL_free(gctx->iv); gctx->iv = OPENSSL_malloc(arg); if (gctx->iv == NULL) return 0; } gctx->ivlen = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if (arg <= 0 || arg > 16 || EVP_CIPHER_CTX_encrypting(c)) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); gctx->taglen = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg <= 0 || arg > 16 || !EVP_CIPHER_CTX_encrypting(c) || gctx->taglen < 0) return 0; memcpy(ptr, EVP_CIPHER_CTX_buf_noconst(c), arg); return 1; case EVP_CTRL_GCM_SET_IV_FIXED: /* Special case: -1 length restores whole IV */ if (arg == -1) { memcpy(gctx->iv, ptr, gctx->ivlen); gctx->iv_gen = 1; return 1; } /* * Fixed field must be at least 4 bytes and invocation field at least * 8. */ if ((arg < 4) || (gctx->ivlen - arg) < 8) return 0; if (arg) memcpy(gctx->iv, ptr, arg); if (EVP_CIPHER_CTX_encrypting(c) && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0) return 0; gctx->iv_gen = 1; return 1; case EVP_CTRL_GCM_IV_GEN: if (gctx->iv_gen == 0 || gctx->key_set == 0) return 0; CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); if (arg <= 0 || arg > gctx->ivlen) arg = gctx->ivlen; memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg); /* * Invocation field will be at least 8 bytes in size and so no need * to check wrap around or increment more than last 8 bytes. */ ctr64_inc(gctx->iv + gctx->ivlen - 8); gctx->iv_set = 1; return 1; case EVP_CTRL_GCM_SET_IV_INV: if (gctx->iv_gen == 0 || gctx->key_set == 0 || EVP_CIPHER_CTX_encrypting(c)) return 0; memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg); CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); gctx->iv_set = 1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); gctx->tls_aad_len = arg; { unsigned int len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ if (len < EVP_GCM_TLS_EXPLICIT_IV_LEN) return 0; len -= EVP_GCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_encrypting(c)) { if (len < EVP_GCM_TLS_TAG_LEN) return 0; len -= EVP_GCM_TLS_TAG_LEN; } EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return EVP_GCM_TLS_TAG_LEN; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_GCM_CTX *gctx_out = EVP_C_DATA(EVP_AES_GCM_CTX,out); if (gctx->gcm.key) { if (gctx->gcm.key != &gctx->ks) return 0; gctx_out->gcm.key = &gctx_out->ks; } if (gctx->iv == EVP_CIPHER_CTX_iv_noconst(c)) gctx_out->iv = EVP_CIPHER_CTX_iv_noconst(out); else { gctx_out->iv = OPENSSL_malloc(gctx->ivlen); if (gctx_out->iv == NULL) return 0; memcpy(gctx_out->iv, gctx->iv, gctx->ivlen); } return 1; } default: return -1; } }
168,431
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: pax_decode_header (struct tar_sparse_file *file) { if (file->stat_info->sparse_major > 0) { uintmax_t u; char nbuf[UINTMAX_STRSIZE_BOUND]; union block *blk; char *p; size_t i; off_t start; #define COPY_BUF(b,buf,src) do \ { \ char *endp = b->buffer + BLOCKSIZE; \ char *dst = buf; \ do \ { \ if (dst == buf + UINTMAX_STRSIZE_BOUND -1) \ { \ ERROR ((0, 0, _("%s: numeric overflow in sparse archive member"), \ file->stat_info->orig_file_name)); \ return false; \ } \ if (src == endp) \ { \ set_next_block_after (b); \ b = find_next_block (); \ src = b->buffer; \ endp = b->buffer + BLOCKSIZE; \ } \ while (*dst++ != '\n'); \ dst[-1] = 0; \ } while (0) start = current_block_ordinal (); set_next_block_after (current_header); start = current_block_ordinal (); set_next_block_after (current_header); blk = find_next_block (); p = blk->buffer; COPY_BUF (blk,nbuf,p); if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t))) } file->stat_info->sparse_map_size = u; file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size, sizeof (*file->stat_info->sparse_map)); file->stat_info->sparse_map_avail = 0; for (i = 0; i < file->stat_info->sparse_map_size; i++) { struct sp_array sp; COPY_BUF (blk,nbuf,p); if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t))) { ERROR ((0, 0, _("%s: malformed sparse archive member"), file->stat_info->orig_file_name)); return false; } sp.offset = u; COPY_BUF (blk,nbuf,p); if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t))) { ERROR ((0, 0, _("%s: malformed sparse archive member"), file->stat_info->orig_file_name)); return false; } sp.numbytes = u; sparse_add_map (file->stat_info, &sp); } set_next_block_after (blk); file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start); } return true; } Commit Message: CWE ID: CWE-476
pax_decode_header (struct tar_sparse_file *file) { if (file->stat_info->sparse_major > 0) { uintmax_t u; char nbuf[UINTMAX_STRSIZE_BOUND]; union block *blk; char *p; size_t i; off_t start; #define COPY_BUF(b,buf,src) do \ { \ char *endp = b->buffer + BLOCKSIZE; \ char *dst = buf; \ do \ { \ if (dst == buf + UINTMAX_STRSIZE_BOUND -1) \ { \ ERROR ((0, 0, _("%s: numeric overflow in sparse archive member"), \ file->stat_info->orig_file_name)); \ return false; \ } \ if (src == endp) \ { \ set_next_block_after (b); \ b = find_next_block (); \ if (!b) \ FATAL_ERROR ((0, 0, _("Unexpected EOF in archive"))); \ src = b->buffer; \ endp = b->buffer + BLOCKSIZE; \ } \ while (*dst++ != '\n'); \ dst[-1] = 0; \ } while (0) start = current_block_ordinal (); set_next_block_after (current_header); start = current_block_ordinal (); set_next_block_after (current_header); blk = find_next_block (); if (!blk) FATAL_ERROR ((0, 0, _("Unexpected EOF in archive"))); p = blk->buffer; COPY_BUF (blk,nbuf,p); if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t))) } file->stat_info->sparse_map_size = u; file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size, sizeof (*file->stat_info->sparse_map)); file->stat_info->sparse_map_avail = 0; for (i = 0; i < file->stat_info->sparse_map_size; i++) { struct sp_array sp; COPY_BUF (blk,nbuf,p); if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t))) { ERROR ((0, 0, _("%s: malformed sparse archive member"), file->stat_info->orig_file_name)); return false; } sp.offset = u; COPY_BUF (blk,nbuf,p); if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t))) { ERROR ((0, 0, _("%s: malformed sparse archive member"), file->stat_info->orig_file_name)); return false; } sp.numbytes = u; sparse_add_map (file->stat_info, &sp); } set_next_block_after (blk); file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start); } return true; }
164,776
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_expand_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { /* The general expand case depends on what the colour type is: */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); else if (that->bit_depth < 8) /* grayscale */ that->sample_depth = that->bit_depth = 8; if (that->have_tRNS) image_pixel_add_alpha(that, &display->this); this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_mod(PNG_CONST image_transform *this, image_transform_png_set_expand_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* The general expand case depends on what the colour type is: */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); else if (that->bit_depth < 8) /* grayscale */ that->sample_depth = that->bit_depth = 8; if (that->have_tRNS) image_pixel_add_alpha(that, &display->this, 0/*!for background*/); this->next->mod(this->next, that, pp, display); }
173,633
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int create_qp_common(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct ib_qp_init_attr *init_attr, struct ib_udata *udata, struct mlx5_ib_qp *qp) { struct mlx5_ib_resources *devr = &dev->devr; int inlen = MLX5_ST_SZ_BYTES(create_qp_in); struct mlx5_core_dev *mdev = dev->mdev; struct mlx5_ib_create_qp_resp resp; struct mlx5_ib_cq *send_cq; struct mlx5_ib_cq *recv_cq; unsigned long flags; u32 uidx = MLX5_IB_DEFAULT_UIDX; struct mlx5_ib_create_qp ucmd; struct mlx5_ib_qp_base *base; int mlx5_st; void *qpc; u32 *in; int err; mutex_init(&qp->mutex); spin_lock_init(&qp->sq.lock); spin_lock_init(&qp->rq.lock); mlx5_st = to_mlx5_st(init_attr->qp_type); if (mlx5_st < 0) return -EINVAL; if (init_attr->rwq_ind_tbl) { if (!udata) return -ENOSYS; err = create_rss_raw_qp_tir(dev, qp, pd, init_attr, udata); return err; } if (init_attr->create_flags & IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK) { if (!MLX5_CAP_GEN(mdev, block_lb_mc)) { mlx5_ib_dbg(dev, "block multicast loopback isn't supported\n"); return -EINVAL; } else { qp->flags |= MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK; } } if (init_attr->create_flags & (IB_QP_CREATE_CROSS_CHANNEL | IB_QP_CREATE_MANAGED_SEND | IB_QP_CREATE_MANAGED_RECV)) { if (!MLX5_CAP_GEN(mdev, cd)) { mlx5_ib_dbg(dev, "cross-channel isn't supported\n"); return -EINVAL; } if (init_attr->create_flags & IB_QP_CREATE_CROSS_CHANNEL) qp->flags |= MLX5_IB_QP_CROSS_CHANNEL; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_SEND) qp->flags |= MLX5_IB_QP_MANAGED_SEND; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_RECV) qp->flags |= MLX5_IB_QP_MANAGED_RECV; } if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) if (!MLX5_CAP_GEN(mdev, ipoib_basic_offloads)) { mlx5_ib_dbg(dev, "ipoib UD lso qp isn't supported\n"); return -EOPNOTSUPP; } if (init_attr->create_flags & IB_QP_CREATE_SCATTER_FCS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET) { mlx5_ib_dbg(dev, "Scatter FCS is supported only for Raw Packet QPs"); return -EOPNOTSUPP; } if (!MLX5_CAP_GEN(dev->mdev, eth_net_offloads) || !MLX5_CAP_ETH(dev->mdev, scatter_fcs)) { mlx5_ib_dbg(dev, "Scatter FCS isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_CAP_SCATTER_FCS; } if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) qp->sq_signal_bits = MLX5_WQE_CTRL_CQ_UPDATE; if (init_attr->create_flags & IB_QP_CREATE_CVLAN_STRIPPING) { if (!(MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, vlan_cap)) || (init_attr->qp_type != IB_QPT_RAW_PACKET)) return -EOPNOTSUPP; qp->flags |= MLX5_IB_QP_CVLAN_STRIPPING; } if (pd && pd->uobject) { if (ib_copy_from_udata(&ucmd, udata, sizeof(ucmd))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } err = get_qp_user_index(to_mucontext(pd->uobject->context), &ucmd, udata->inlen, &uidx); if (err) return err; qp->wq_sig = !!(ucmd.flags & MLX5_QP_FLAG_SIGNATURE); qp->scat_cqe = !!(ucmd.flags & MLX5_QP_FLAG_SCATTER_CQE); if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET || !tunnel_offload_supported(mdev)) { mlx5_ib_dbg(dev, "Tunnel offload isn't supported\n"); return -EOPNOTSUPP; } qp->tunnel_offload_en = true; } if (init_attr->create_flags & IB_QP_CREATE_SOURCE_QPN) { if (init_attr->qp_type != IB_QPT_UD || (MLX5_CAP_GEN(dev->mdev, port_type) != MLX5_CAP_PORT_TYPE_IB) || !mlx5_get_flow_namespace(dev->mdev, MLX5_FLOW_NAMESPACE_BYPASS)) { mlx5_ib_dbg(dev, "Source QP option isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_UNDERLAY; qp->underlay_qpn = init_attr->source_qpn; } } else { qp->wq_sig = !!wq_signature; } base = (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) ? &qp->raw_packet_qp.rq.base : &qp->trans_qp.base; qp->has_rq = qp_has_rq(init_attr); err = set_rq_size(dev, &init_attr->cap, qp->has_rq, qp, (pd && pd->uobject) ? &ucmd : NULL); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } if (pd) { if (pd->uobject) { __u32 max_wqes = 1 << MLX5_CAP_GEN(mdev, log_max_qp_sz); mlx5_ib_dbg(dev, "requested sq_wqe_count (%d)\n", ucmd.sq_wqe_count); if (ucmd.rq_wqe_shift != qp->rq.wqe_shift || ucmd.rq_wqe_count != qp->rq.wqe_cnt) { mlx5_ib_dbg(dev, "invalid rq params\n"); return -EINVAL; } if (ucmd.sq_wqe_count > max_wqes) { mlx5_ib_dbg(dev, "requested sq_wqe_count (%d) > max allowed (%d)\n", ucmd.sq_wqe_count, max_wqes); return -EINVAL; } if (init_attr->create_flags & mlx5_ib_create_qp_sqpn_qp1()) { mlx5_ib_dbg(dev, "user-space is not allowed to create UD QPs spoofing as QP1\n"); return -EINVAL; } err = create_user_qp(dev, pd, qp, udata, init_attr, &in, &resp, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } else { err = create_kernel_qp(dev, init_attr, qp, &in, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } if (err) return err; } else { in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; qp->create_type = MLX5_QP_EMPTY; } if (is_sqp(init_attr->qp_type)) qp->port = init_attr->port_num; qpc = MLX5_ADDR_OF(create_qp_in, in, qpc); MLX5_SET(qpc, qpc, st, mlx5_st); MLX5_SET(qpc, qpc, pm_state, MLX5_QP_PM_MIGRATED); if (init_attr->qp_type != MLX5_IB_QPT_REG_UMR) MLX5_SET(qpc, qpc, pd, to_mpd(pd ? pd : devr->p0)->pdn); else MLX5_SET(qpc, qpc, latency_sensitive, 1); if (qp->wq_sig) MLX5_SET(qpc, qpc, wq_signature, 1); if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK) MLX5_SET(qpc, qpc, block_lb_mc, 1); if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) MLX5_SET(qpc, qpc, cd_master, 1); if (qp->flags & MLX5_IB_QP_MANAGED_SEND) MLX5_SET(qpc, qpc, cd_slave_send, 1); if (qp->flags & MLX5_IB_QP_MANAGED_RECV) MLX5_SET(qpc, qpc, cd_slave_receive, 1); if (qp->scat_cqe && is_connected(init_attr->qp_type)) { int rcqe_sz; int scqe_sz; rcqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->recv_cq); scqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->send_cq); if (rcqe_sz == 128) MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA32_CQE); if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) { if (scqe_sz == 128) MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA32_CQE); } } if (qp->rq.wqe_cnt) { MLX5_SET(qpc, qpc, log_rq_stride, qp->rq.wqe_shift - 4); MLX5_SET(qpc, qpc, log_rq_size, ilog2(qp->rq.wqe_cnt)); } MLX5_SET(qpc, qpc, rq_type, get_rx_type(qp, init_attr)); if (qp->sq.wqe_cnt) { MLX5_SET(qpc, qpc, log_sq_size, ilog2(qp->sq.wqe_cnt)); } else { MLX5_SET(qpc, qpc, no_sq, 1); if (init_attr->srq && init_attr->srq->srq_type == IB_SRQT_TM) MLX5_SET(qpc, qpc, offload_type, MLX5_QPC_OFFLOAD_TYPE_RNDV); } /* Set default resources */ switch (init_attr->qp_type) { case IB_QPT_XRC_TGT: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, cqn_snd, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(init_attr->xrcd)->xrcdn); break; case IB_QPT_XRC_INI: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); break; default: if (init_attr->srq) { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x0)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(init_attr->srq)->msrq.srqn); } else { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s1)->msrq.srqn); } } if (init_attr->send_cq) MLX5_SET(qpc, qpc, cqn_snd, to_mcq(init_attr->send_cq)->mcq.cqn); if (init_attr->recv_cq) MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(init_attr->recv_cq)->mcq.cqn); MLX5_SET64(qpc, qpc, dbr_addr, qp->db.dma); /* 0xffffff means we ask to work with cqe version 0 */ if (MLX5_CAP_GEN(mdev, cqe_version) == MLX5_CQE_VERSION_V1) MLX5_SET(qpc, qpc, user_index, uidx); /* we use IB_QP_CREATE_IPOIB_UD_LSO to indicates ipoib qp */ if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) { MLX5_SET(qpc, qpc, ulp_stateless_offload_mode, 1); qp->flags |= MLX5_IB_QP_LSO; } if (init_attr->create_flags & IB_QP_CREATE_PCI_WRITE_END_PADDING) { if (!MLX5_CAP_GEN(dev->mdev, end_pad)) { mlx5_ib_dbg(dev, "scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto err; } else if (init_attr->qp_type != IB_QPT_RAW_PACKET) { MLX5_SET(qpc, qpc, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); } else { qp->flags |= MLX5_IB_QP_PCI_WRITE_END_PADDING; } } if (inlen < 0) { err = -EINVAL; goto err; } if (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { qp->raw_packet_qp.sq.ubuffer.buf_addr = ucmd.sq_buf_addr; raw_packet_qp_copy_info(qp, &qp->raw_packet_qp); err = create_raw_packet_qp(dev, qp, in, inlen, pd); } else { err = mlx5_core_create_qp(dev->mdev, &base->mqp, in, inlen); } if (err) { mlx5_ib_dbg(dev, "create qp failed\n"); goto err_create; } kvfree(in); base->container_mibqp = qp; base->mqp.event = mlx5_ib_qp_event; get_cqs(init_attr->qp_type, init_attr->send_cq, init_attr->recv_cq, &send_cq, &recv_cq); spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); mlx5_ib_lock_cqs(send_cq, recv_cq); /* Maintain device to QPs access, needed for further handling via reset * flow */ list_add_tail(&qp->qps_list, &dev->qp_list); /* Maintain CQ to QPs access, needed for further handling via reset flow */ if (send_cq) list_add_tail(&qp->cq_send_list, &send_cq->list_send_qp); if (recv_cq) list_add_tail(&qp->cq_recv_list, &recv_cq->list_recv_qp); mlx5_ib_unlock_cqs(send_cq, recv_cq); spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); return 0; err_create: if (qp->create_type == MLX5_QP_USER) destroy_qp_user(dev, pd, qp, base); else if (qp->create_type == MLX5_QP_KERNEL) destroy_qp_kernel(dev, qp); err: kvfree(in); return err; } Commit Message: IB/mlx5: Fix leaking stack memory to userspace mlx5_ib_create_qp_resp was never initialized and only the first 4 bytes were written. Fixes: 41d902cb7c32 ("RDMA/mlx5: Fix definition of mlx5_ib_create_qp_resp") Cc: <[email protected]> Acked-by: Leon Romanovsky <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> CWE ID: CWE-119
static int create_qp_common(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct ib_qp_init_attr *init_attr, struct ib_udata *udata, struct mlx5_ib_qp *qp) { struct mlx5_ib_resources *devr = &dev->devr; int inlen = MLX5_ST_SZ_BYTES(create_qp_in); struct mlx5_core_dev *mdev = dev->mdev; struct mlx5_ib_create_qp_resp resp = {}; struct mlx5_ib_cq *send_cq; struct mlx5_ib_cq *recv_cq; unsigned long flags; u32 uidx = MLX5_IB_DEFAULT_UIDX; struct mlx5_ib_create_qp ucmd; struct mlx5_ib_qp_base *base; int mlx5_st; void *qpc; u32 *in; int err; mutex_init(&qp->mutex); spin_lock_init(&qp->sq.lock); spin_lock_init(&qp->rq.lock); mlx5_st = to_mlx5_st(init_attr->qp_type); if (mlx5_st < 0) return -EINVAL; if (init_attr->rwq_ind_tbl) { if (!udata) return -ENOSYS; err = create_rss_raw_qp_tir(dev, qp, pd, init_attr, udata); return err; } if (init_attr->create_flags & IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK) { if (!MLX5_CAP_GEN(mdev, block_lb_mc)) { mlx5_ib_dbg(dev, "block multicast loopback isn't supported\n"); return -EINVAL; } else { qp->flags |= MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK; } } if (init_attr->create_flags & (IB_QP_CREATE_CROSS_CHANNEL | IB_QP_CREATE_MANAGED_SEND | IB_QP_CREATE_MANAGED_RECV)) { if (!MLX5_CAP_GEN(mdev, cd)) { mlx5_ib_dbg(dev, "cross-channel isn't supported\n"); return -EINVAL; } if (init_attr->create_flags & IB_QP_CREATE_CROSS_CHANNEL) qp->flags |= MLX5_IB_QP_CROSS_CHANNEL; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_SEND) qp->flags |= MLX5_IB_QP_MANAGED_SEND; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_RECV) qp->flags |= MLX5_IB_QP_MANAGED_RECV; } if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) if (!MLX5_CAP_GEN(mdev, ipoib_basic_offloads)) { mlx5_ib_dbg(dev, "ipoib UD lso qp isn't supported\n"); return -EOPNOTSUPP; } if (init_attr->create_flags & IB_QP_CREATE_SCATTER_FCS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET) { mlx5_ib_dbg(dev, "Scatter FCS is supported only for Raw Packet QPs"); return -EOPNOTSUPP; } if (!MLX5_CAP_GEN(dev->mdev, eth_net_offloads) || !MLX5_CAP_ETH(dev->mdev, scatter_fcs)) { mlx5_ib_dbg(dev, "Scatter FCS isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_CAP_SCATTER_FCS; } if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) qp->sq_signal_bits = MLX5_WQE_CTRL_CQ_UPDATE; if (init_attr->create_flags & IB_QP_CREATE_CVLAN_STRIPPING) { if (!(MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, vlan_cap)) || (init_attr->qp_type != IB_QPT_RAW_PACKET)) return -EOPNOTSUPP; qp->flags |= MLX5_IB_QP_CVLAN_STRIPPING; } if (pd && pd->uobject) { if (ib_copy_from_udata(&ucmd, udata, sizeof(ucmd))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } err = get_qp_user_index(to_mucontext(pd->uobject->context), &ucmd, udata->inlen, &uidx); if (err) return err; qp->wq_sig = !!(ucmd.flags & MLX5_QP_FLAG_SIGNATURE); qp->scat_cqe = !!(ucmd.flags & MLX5_QP_FLAG_SCATTER_CQE); if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET || !tunnel_offload_supported(mdev)) { mlx5_ib_dbg(dev, "Tunnel offload isn't supported\n"); return -EOPNOTSUPP; } qp->tunnel_offload_en = true; } if (init_attr->create_flags & IB_QP_CREATE_SOURCE_QPN) { if (init_attr->qp_type != IB_QPT_UD || (MLX5_CAP_GEN(dev->mdev, port_type) != MLX5_CAP_PORT_TYPE_IB) || !mlx5_get_flow_namespace(dev->mdev, MLX5_FLOW_NAMESPACE_BYPASS)) { mlx5_ib_dbg(dev, "Source QP option isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_UNDERLAY; qp->underlay_qpn = init_attr->source_qpn; } } else { qp->wq_sig = !!wq_signature; } base = (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) ? &qp->raw_packet_qp.rq.base : &qp->trans_qp.base; qp->has_rq = qp_has_rq(init_attr); err = set_rq_size(dev, &init_attr->cap, qp->has_rq, qp, (pd && pd->uobject) ? &ucmd : NULL); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } if (pd) { if (pd->uobject) { __u32 max_wqes = 1 << MLX5_CAP_GEN(mdev, log_max_qp_sz); mlx5_ib_dbg(dev, "requested sq_wqe_count (%d)\n", ucmd.sq_wqe_count); if (ucmd.rq_wqe_shift != qp->rq.wqe_shift || ucmd.rq_wqe_count != qp->rq.wqe_cnt) { mlx5_ib_dbg(dev, "invalid rq params\n"); return -EINVAL; } if (ucmd.sq_wqe_count > max_wqes) { mlx5_ib_dbg(dev, "requested sq_wqe_count (%d) > max allowed (%d)\n", ucmd.sq_wqe_count, max_wqes); return -EINVAL; } if (init_attr->create_flags & mlx5_ib_create_qp_sqpn_qp1()) { mlx5_ib_dbg(dev, "user-space is not allowed to create UD QPs spoofing as QP1\n"); return -EINVAL; } err = create_user_qp(dev, pd, qp, udata, init_attr, &in, &resp, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } else { err = create_kernel_qp(dev, init_attr, qp, &in, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } if (err) return err; } else { in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; qp->create_type = MLX5_QP_EMPTY; } if (is_sqp(init_attr->qp_type)) qp->port = init_attr->port_num; qpc = MLX5_ADDR_OF(create_qp_in, in, qpc); MLX5_SET(qpc, qpc, st, mlx5_st); MLX5_SET(qpc, qpc, pm_state, MLX5_QP_PM_MIGRATED); if (init_attr->qp_type != MLX5_IB_QPT_REG_UMR) MLX5_SET(qpc, qpc, pd, to_mpd(pd ? pd : devr->p0)->pdn); else MLX5_SET(qpc, qpc, latency_sensitive, 1); if (qp->wq_sig) MLX5_SET(qpc, qpc, wq_signature, 1); if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK) MLX5_SET(qpc, qpc, block_lb_mc, 1); if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) MLX5_SET(qpc, qpc, cd_master, 1); if (qp->flags & MLX5_IB_QP_MANAGED_SEND) MLX5_SET(qpc, qpc, cd_slave_send, 1); if (qp->flags & MLX5_IB_QP_MANAGED_RECV) MLX5_SET(qpc, qpc, cd_slave_receive, 1); if (qp->scat_cqe && is_connected(init_attr->qp_type)) { int rcqe_sz; int scqe_sz; rcqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->recv_cq); scqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->send_cq); if (rcqe_sz == 128) MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA32_CQE); if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) { if (scqe_sz == 128) MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA32_CQE); } } if (qp->rq.wqe_cnt) { MLX5_SET(qpc, qpc, log_rq_stride, qp->rq.wqe_shift - 4); MLX5_SET(qpc, qpc, log_rq_size, ilog2(qp->rq.wqe_cnt)); } MLX5_SET(qpc, qpc, rq_type, get_rx_type(qp, init_attr)); if (qp->sq.wqe_cnt) { MLX5_SET(qpc, qpc, log_sq_size, ilog2(qp->sq.wqe_cnt)); } else { MLX5_SET(qpc, qpc, no_sq, 1); if (init_attr->srq && init_attr->srq->srq_type == IB_SRQT_TM) MLX5_SET(qpc, qpc, offload_type, MLX5_QPC_OFFLOAD_TYPE_RNDV); } /* Set default resources */ switch (init_attr->qp_type) { case IB_QPT_XRC_TGT: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, cqn_snd, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(init_attr->xrcd)->xrcdn); break; case IB_QPT_XRC_INI: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); break; default: if (init_attr->srq) { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x0)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(init_attr->srq)->msrq.srqn); } else { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s1)->msrq.srqn); } } if (init_attr->send_cq) MLX5_SET(qpc, qpc, cqn_snd, to_mcq(init_attr->send_cq)->mcq.cqn); if (init_attr->recv_cq) MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(init_attr->recv_cq)->mcq.cqn); MLX5_SET64(qpc, qpc, dbr_addr, qp->db.dma); /* 0xffffff means we ask to work with cqe version 0 */ if (MLX5_CAP_GEN(mdev, cqe_version) == MLX5_CQE_VERSION_V1) MLX5_SET(qpc, qpc, user_index, uidx); /* we use IB_QP_CREATE_IPOIB_UD_LSO to indicates ipoib qp */ if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) { MLX5_SET(qpc, qpc, ulp_stateless_offload_mode, 1); qp->flags |= MLX5_IB_QP_LSO; } if (init_attr->create_flags & IB_QP_CREATE_PCI_WRITE_END_PADDING) { if (!MLX5_CAP_GEN(dev->mdev, end_pad)) { mlx5_ib_dbg(dev, "scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto err; } else if (init_attr->qp_type != IB_QPT_RAW_PACKET) { MLX5_SET(qpc, qpc, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); } else { qp->flags |= MLX5_IB_QP_PCI_WRITE_END_PADDING; } } if (inlen < 0) { err = -EINVAL; goto err; } if (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { qp->raw_packet_qp.sq.ubuffer.buf_addr = ucmd.sq_buf_addr; raw_packet_qp_copy_info(qp, &qp->raw_packet_qp); err = create_raw_packet_qp(dev, qp, in, inlen, pd); } else { err = mlx5_core_create_qp(dev->mdev, &base->mqp, in, inlen); } if (err) { mlx5_ib_dbg(dev, "create qp failed\n"); goto err_create; } kvfree(in); base->container_mibqp = qp; base->mqp.event = mlx5_ib_qp_event; get_cqs(init_attr->qp_type, init_attr->send_cq, init_attr->recv_cq, &send_cq, &recv_cq); spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); mlx5_ib_lock_cqs(send_cq, recv_cq); /* Maintain device to QPs access, needed for further handling via reset * flow */ list_add_tail(&qp->qps_list, &dev->qp_list); /* Maintain CQ to QPs access, needed for further handling via reset flow */ if (send_cq) list_add_tail(&qp->cq_send_list, &send_cq->list_send_qp); if (recv_cq) list_add_tail(&qp->cq_recv_list, &recv_cq->list_recv_qp); mlx5_ib_unlock_cqs(send_cq, recv_cq); spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); return 0; err_create: if (qp->create_type == MLX5_QP_USER) destroy_qp_user(dev, pd, qp, base); else if (qp->create_type == MLX5_QP_KERNEL) destroy_qp_kernel(dev, qp); err: kvfree(in); return err; }
169,763
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct vrend_linked_shader_program *add_shader_program(struct vrend_context *ctx, struct vrend_shader *vs, struct vrend_shader *fs, struct vrend_shader *gs) { struct vrend_linked_shader_program *sprog = CALLOC_STRUCT(vrend_linked_shader_program); char name[16]; int i; GLuint prog_id; GLint lret; int id; int last_shader; if (!sprog) return NULL; /* need to rewrite VS code to add interpolation params */ if ((gs && gs->compiled_fs_id != fs->id) || (!gs && vs->compiled_fs_id != fs->id)) { bool ret; if (gs) vrend_patch_vertex_shader_interpolants(gs->glsl_prog, &gs->sel->sinfo, &fs->sel->sinfo, true, fs->key.flatshade); else vrend_patch_vertex_shader_interpolants(vs->glsl_prog, &vs->sel->sinfo, &fs->sel->sinfo, false, fs->key.flatshade); ret = vrend_compile_shader(ctx, gs ? gs : vs); if (ret == false) { glDeleteShader(gs ? gs->id : vs->id); free(sprog); return NULL; } if (gs) gs->compiled_fs_id = fs->id; else vs->compiled_fs_id = fs->id; } prog_id = glCreateProgram(); glAttachShader(prog_id, vs->id); if (gs) { if (gs->id > 0) glAttachShader(prog_id, gs->id); set_stream_out_varyings(prog_id, &gs->sel->sinfo); } else set_stream_out_varyings(prog_id, &vs->sel->sinfo); glAttachShader(prog_id, fs->id); if (fs->sel->sinfo.num_outputs > 1) { if (util_blend_state_is_dual(&ctx->sub->blend_state, 0)) { glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0"); glBindFragDataLocationIndexed(prog_id, 0, 1, "fsout_c1"); sprog->dual_src_linked = true; } else { glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0"); glBindFragDataLocationIndexed(prog_id, 1, 0, "fsout_c1"); sprog->dual_src_linked = false; } } else sprog->dual_src_linked = false; if (vrend_state.have_vertex_attrib_binding) { uint32_t mask = vs->sel->sinfo.attrib_input_mask; while (mask) { i = u_bit_scan(&mask); snprintf(name, 10, "in_%d", i); glBindAttribLocation(prog_id, i, name); } } glLinkProgram(prog_id); glGetProgramiv(prog_id, GL_LINK_STATUS, &lret); if (lret == GL_FALSE) { char infolog[65536]; int len; glGetProgramInfoLog(prog_id, 65536, &len, infolog); fprintf(stderr,"got error linking\n%s\n", infolog); /* dump shaders */ report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SHADER, 0); fprintf(stderr,"vert shader: %d GLSL\n%s\n", vs->id, vs->glsl_prog); if (gs) fprintf(stderr,"geom shader: %d GLSL\n%s\n", gs->id, gs->glsl_prog); fprintf(stderr,"frag shader: %d GLSL\n%s\n", fs->id, fs->glsl_prog); glDeleteProgram(prog_id); return NULL; } sprog->ss[PIPE_SHADER_FRAGMENT] = fs; sprog->ss[PIPE_SHADER_GEOMETRY] = gs; list_add(&sprog->sl[PIPE_SHADER_VERTEX], &vs->programs); list_add(&sprog->sl[PIPE_SHADER_FRAGMENT], &fs->programs); if (gs) list_add(&sprog->sl[PIPE_SHADER_GEOMETRY], &gs->programs); last_shader = gs ? PIPE_SHADER_GEOMETRY : PIPE_SHADER_FRAGMENT; sprog->id = prog_id; list_addtail(&sprog->head, &ctx->sub->programs); if (fs->key.pstipple_tex) sprog->fs_stipple_loc = glGetUniformLocation(prog_id, "pstipple_sampler"); else sprog->fs_stipple_loc = -1; sprog->vs_ws_adjust_loc = glGetUniformLocation(prog_id, "winsys_adjust"); for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) { if (sprog->ss[id]->sel->sinfo.samplers_used_mask) { uint32_t mask = sprog->ss[id]->sel->sinfo.samplers_used_mask; int nsamp = util_bitcount(sprog->ss[id]->sel->sinfo.samplers_used_mask); int index; sprog->shadow_samp_mask[id] = sprog->ss[id]->sel->sinfo.shadow_samp_mask; if (sprog->ss[id]->sel->sinfo.shadow_samp_mask) { sprog->shadow_samp_mask_locs[id] = calloc(nsamp, sizeof(uint32_t)); sprog->shadow_samp_add_locs[id] = calloc(nsamp, sizeof(uint32_t)); } else { sprog->shadow_samp_mask_locs[id] = sprog->shadow_samp_add_locs[id] = NULL; } sprog->samp_locs[id] = calloc(nsamp, sizeof(uint32_t)); if (sprog->samp_locs[id]) { const char *prefix = pipe_shader_to_prefix(id); index = 0; while(mask) { i = u_bit_scan(&mask); snprintf(name, 10, "%ssamp%d", prefix, i); sprog->samp_locs[id][index] = glGetUniformLocation(prog_id, name); if (sprog->ss[id]->sel->sinfo.shadow_samp_mask & (1 << i)) { snprintf(name, 14, "%sshadmask%d", prefix, i); sprog->shadow_samp_mask_locs[id][index] = glGetUniformLocation(prog_id, name); snprintf(name, 14, "%sshadadd%d", prefix, i); sprog->shadow_samp_add_locs[id][index] = glGetUniformLocation(prog_id, name); } index++; } } } else { sprog->samp_locs[id] = NULL; sprog->shadow_samp_mask_locs[id] = NULL; sprog->shadow_samp_add_locs[id] = NULL; sprog->shadow_samp_mask[id] = 0; } sprog->samplers_used_mask[id] = sprog->ss[id]->sel->sinfo.samplers_used_mask; } for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) { if (sprog->ss[id]->sel->sinfo.num_consts) { sprog->const_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_consts, sizeof(uint32_t)); if (sprog->const_locs[id]) { const char *prefix = pipe_shader_to_prefix(id); for (i = 0; i < sprog->ss[id]->sel->sinfo.num_consts; i++) { snprintf(name, 16, "%sconst0[%d]", prefix, i); sprog->const_locs[id][i] = glGetUniformLocation(prog_id, name); } } } else sprog->const_locs[id] = NULL; } if (!vrend_state.have_vertex_attrib_binding) { if (vs->sel->sinfo.num_inputs) { sprog->attrib_locs = calloc(vs->sel->sinfo.num_inputs, sizeof(uint32_t)); if (sprog->attrib_locs) { for (i = 0; i < vs->sel->sinfo.num_inputs; i++) { snprintf(name, 10, "in_%d", i); sprog->attrib_locs[i] = glGetAttribLocation(prog_id, name); } } } else sprog->attrib_locs = NULL; } for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) { if (sprog->ss[id]->sel->sinfo.num_ubos) { const char *prefix = pipe_shader_to_prefix(id); sprog->ubo_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_ubos, sizeof(uint32_t)); for (i = 0; i < sprog->ss[id]->sel->sinfo.num_ubos; i++) { snprintf(name, 16, "%subo%d", prefix, i + 1); sprog->ubo_locs[id][i] = glGetUniformBlockIndex(prog_id, name); } } else sprog->ubo_locs[id] = NULL; } if (vs->sel->sinfo.num_ucp) { for (i = 0; i < vs->sel->sinfo.num_ucp; i++) { snprintf(name, 10, "clipp[%d]", i); sprog->clip_locs[i] = glGetUniformLocation(prog_id, name); } } return sprog; } Commit Message: CWE ID: CWE-772
static struct vrend_linked_shader_program *add_shader_program(struct vrend_context *ctx, struct vrend_shader *vs, struct vrend_shader *fs, struct vrend_shader *gs) { struct vrend_linked_shader_program *sprog = CALLOC_STRUCT(vrend_linked_shader_program); char name[16]; int i; GLuint prog_id; GLint lret; int id; int last_shader; if (!sprog) return NULL; /* need to rewrite VS code to add interpolation params */ if ((gs && gs->compiled_fs_id != fs->id) || (!gs && vs->compiled_fs_id != fs->id)) { bool ret; if (gs) vrend_patch_vertex_shader_interpolants(gs->glsl_prog, &gs->sel->sinfo, &fs->sel->sinfo, true, fs->key.flatshade); else vrend_patch_vertex_shader_interpolants(vs->glsl_prog, &vs->sel->sinfo, &fs->sel->sinfo, false, fs->key.flatshade); ret = vrend_compile_shader(ctx, gs ? gs : vs); if (ret == false) { glDeleteShader(gs ? gs->id : vs->id); free(sprog); return NULL; } if (gs) gs->compiled_fs_id = fs->id; else vs->compiled_fs_id = fs->id; } prog_id = glCreateProgram(); glAttachShader(prog_id, vs->id); if (gs) { if (gs->id > 0) glAttachShader(prog_id, gs->id); set_stream_out_varyings(prog_id, &gs->sel->sinfo); } else set_stream_out_varyings(prog_id, &vs->sel->sinfo); glAttachShader(prog_id, fs->id); if (fs->sel->sinfo.num_outputs > 1) { if (util_blend_state_is_dual(&ctx->sub->blend_state, 0)) { glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0"); glBindFragDataLocationIndexed(prog_id, 0, 1, "fsout_c1"); sprog->dual_src_linked = true; } else { glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0"); glBindFragDataLocationIndexed(prog_id, 1, 0, "fsout_c1"); sprog->dual_src_linked = false; } } else sprog->dual_src_linked = false; if (vrend_state.have_vertex_attrib_binding) { uint32_t mask = vs->sel->sinfo.attrib_input_mask; while (mask) { i = u_bit_scan(&mask); snprintf(name, 10, "in_%d", i); glBindAttribLocation(prog_id, i, name); } } glLinkProgram(prog_id); glGetProgramiv(prog_id, GL_LINK_STATUS, &lret); if (lret == GL_FALSE) { char infolog[65536]; int len; glGetProgramInfoLog(prog_id, 65536, &len, infolog); fprintf(stderr,"got error linking\n%s\n", infolog); /* dump shaders */ report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SHADER, 0); fprintf(stderr,"vert shader: %d GLSL\n%s\n", vs->id, vs->glsl_prog); if (gs) fprintf(stderr,"geom shader: %d GLSL\n%s\n", gs->id, gs->glsl_prog); fprintf(stderr,"frag shader: %d GLSL\n%s\n", fs->id, fs->glsl_prog); glDeleteProgram(prog_id); free(sprog); return NULL; } sprog->ss[PIPE_SHADER_FRAGMENT] = fs; sprog->ss[PIPE_SHADER_GEOMETRY] = gs; list_add(&sprog->sl[PIPE_SHADER_VERTEX], &vs->programs); list_add(&sprog->sl[PIPE_SHADER_FRAGMENT], &fs->programs); if (gs) list_add(&sprog->sl[PIPE_SHADER_GEOMETRY], &gs->programs); last_shader = gs ? PIPE_SHADER_GEOMETRY : PIPE_SHADER_FRAGMENT; sprog->id = prog_id; list_addtail(&sprog->head, &ctx->sub->programs); if (fs->key.pstipple_tex) sprog->fs_stipple_loc = glGetUniformLocation(prog_id, "pstipple_sampler"); else sprog->fs_stipple_loc = -1; sprog->vs_ws_adjust_loc = glGetUniformLocation(prog_id, "winsys_adjust"); for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) { if (sprog->ss[id]->sel->sinfo.samplers_used_mask) { uint32_t mask = sprog->ss[id]->sel->sinfo.samplers_used_mask; int nsamp = util_bitcount(sprog->ss[id]->sel->sinfo.samplers_used_mask); int index; sprog->shadow_samp_mask[id] = sprog->ss[id]->sel->sinfo.shadow_samp_mask; if (sprog->ss[id]->sel->sinfo.shadow_samp_mask) { sprog->shadow_samp_mask_locs[id] = calloc(nsamp, sizeof(uint32_t)); sprog->shadow_samp_add_locs[id] = calloc(nsamp, sizeof(uint32_t)); } else { sprog->shadow_samp_mask_locs[id] = sprog->shadow_samp_add_locs[id] = NULL; } sprog->samp_locs[id] = calloc(nsamp, sizeof(uint32_t)); if (sprog->samp_locs[id]) { const char *prefix = pipe_shader_to_prefix(id); index = 0; while(mask) { i = u_bit_scan(&mask); snprintf(name, 10, "%ssamp%d", prefix, i); sprog->samp_locs[id][index] = glGetUniformLocation(prog_id, name); if (sprog->ss[id]->sel->sinfo.shadow_samp_mask & (1 << i)) { snprintf(name, 14, "%sshadmask%d", prefix, i); sprog->shadow_samp_mask_locs[id][index] = glGetUniformLocation(prog_id, name); snprintf(name, 14, "%sshadadd%d", prefix, i); sprog->shadow_samp_add_locs[id][index] = glGetUniformLocation(prog_id, name); } index++; } } } else { sprog->samp_locs[id] = NULL; sprog->shadow_samp_mask_locs[id] = NULL; sprog->shadow_samp_add_locs[id] = NULL; sprog->shadow_samp_mask[id] = 0; } sprog->samplers_used_mask[id] = sprog->ss[id]->sel->sinfo.samplers_used_mask; } for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) { if (sprog->ss[id]->sel->sinfo.num_consts) { sprog->const_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_consts, sizeof(uint32_t)); if (sprog->const_locs[id]) { const char *prefix = pipe_shader_to_prefix(id); for (i = 0; i < sprog->ss[id]->sel->sinfo.num_consts; i++) { snprintf(name, 16, "%sconst0[%d]", prefix, i); sprog->const_locs[id][i] = glGetUniformLocation(prog_id, name); } } } else sprog->const_locs[id] = NULL; } if (!vrend_state.have_vertex_attrib_binding) { if (vs->sel->sinfo.num_inputs) { sprog->attrib_locs = calloc(vs->sel->sinfo.num_inputs, sizeof(uint32_t)); if (sprog->attrib_locs) { for (i = 0; i < vs->sel->sinfo.num_inputs; i++) { snprintf(name, 10, "in_%d", i); sprog->attrib_locs[i] = glGetAttribLocation(prog_id, name); } } } else sprog->attrib_locs = NULL; } for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) { if (sprog->ss[id]->sel->sinfo.num_ubos) { const char *prefix = pipe_shader_to_prefix(id); sprog->ubo_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_ubos, sizeof(uint32_t)); for (i = 0; i < sprog->ss[id]->sel->sinfo.num_ubos; i++) { snprintf(name, 16, "%subo%d", prefix, i + 1); sprog->ubo_locs[id][i] = glGetUniformBlockIndex(prog_id, name); } } else sprog->ubo_locs[id] = NULL; } if (vs->sel->sinfo.num_ucp) { for (i = 0; i < vs->sel->sinfo.num_ucp; i++) { snprintf(name, 10, "clipp[%d]", i); sprog->clip_locs[i] = glGetUniformLocation(prog_id, name); } } return sprog; }
164,946
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; } Commit Message: CVE-2017-13043/BGP: fix decoding of MVPN route types 6 and 7 RFC 6514 Section 4.6 defines the structure for Shared Tree Join (6) and Source Tree Join (7) multicast VPN route types. decode_multicast_vpn() didn't implement the Source AS field of that structure properly, adjust the offsets to put it right. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN + 4; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; }
167,832
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long ContentEncoding::ParseEncryptionEntry( long long start, long long size, IMkvReader* pReader, ContentEncryption* encryption) { assert(pReader); assert(encryption); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x7E1) { encryption->algo = UnserializeUInt(pReader, pos, size); if (encryption->algo != 5) return E_FILE_FORMAT_INVALID; } else if (id == 0x7E2) { delete[] encryption->key_id; encryption->key_id = NULL; encryption->key_id_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, buflen, buf); if (read_status) { delete [] buf; return status; } encryption->key_id = buf; encryption->key_id_len = buflen; } else if (id == 0x7E3) { delete[] encryption->signature; encryption->signature = NULL; encryption->signature_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, buflen, buf); if (read_status) { delete [] buf; return status; } encryption->signature = buf; encryption->signature_len = buflen; } else if (id == 0x7E4) { delete[] encryption->sig_key_id; encryption->sig_key_id = NULL; encryption->sig_key_id_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, buflen, buf); if (read_status) { delete [] buf; return status; } encryption->sig_key_id = buf; encryption->sig_key_id_len = buflen; } else if (id == 0x7E5) { encryption->sig_algo = UnserializeUInt(pReader, pos, size); } else if (id == 0x7E6) { encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size); } else if (id == 0x7E7) { const long status = ParseContentEncAESSettingsEntry( pos, size, pReader, &encryption->aes_settings); if (status) return status; } pos += size; //consume payload assert(pos <= stop); } return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long ContentEncoding::ParseEncryptionEntry( long ContentEncoding::ParseEncryptionEntry(long long start, long long size, IMkvReader* pReader, ContentEncryption* encryption) { assert(pReader); assert(encryption); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x7E1) { encryption->algo = UnserializeUInt(pReader, pos, size); if (encryption->algo != 5) return E_FILE_FORMAT_INVALID; } else if (id == 0x7E2) { delete[] encryption -> key_id; encryption->key_id = NULL; encryption->key_id_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, static_cast<long>(buflen), buf); if (read_status) { delete[] buf; return status; } encryption->key_id = buf; encryption->key_id_len = buflen; } else if (id == 0x7E3) { delete[] encryption -> signature; encryption->signature = NULL; encryption->signature_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, static_cast<long>(buflen), buf); if (read_status) { delete[] buf; return status; } encryption->signature = buf; encryption->signature_len = buflen; } else if (id == 0x7E4) { delete[] encryption -> sig_key_id; encryption->sig_key_id = NULL; encryption->sig_key_id_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, static_cast<long>(buflen), buf); if (read_status) { delete[] buf; return status; } encryption->sig_key_id = buf; encryption->sig_key_id_len = buflen; } else if (id == 0x7E5) { encryption->sig_algo = UnserializeUInt(pReader, pos, size); } else if (id == 0x7E6) { encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size); } else if (id == 0x7E7) { const long status = ParseContentEncAESSettingsEntry( pos, size, pReader, &encryption->aes_settings); if (status) return status; } pos += size; // consume payload assert(pos <= stop); } return 0; }
174,425
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static __u8 *lg_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { struct lg_drv_data *drv_data = hid_get_drvdata(hdev); struct usb_device_descriptor *udesc; __u16 bcdDevice, rev_maj, rev_min; if ((drv_data->quirks & LG_RDESC) && *rsize >= 90 && rdesc[83] == 0x26 && rdesc[84] == 0x8c && rdesc[85] == 0x02) { hid_info(hdev, "fixing up Logitech keyboard report descriptor\n"); rdesc[84] = rdesc[89] = 0x4d; rdesc[85] = rdesc[90] = 0x10; } if ((drv_data->quirks & LG_RDESC_REL_ABS) && *rsize >= 50 && rdesc[32] == 0x81 && rdesc[33] == 0x06 && rdesc[49] == 0x81 && rdesc[50] == 0x06) { hid_info(hdev, "fixing up rel/abs in Logitech report descriptor\n"); rdesc[33] = rdesc[50] = 0x02; } switch (hdev->product) { /* Several wheels report as this id when operating in emulation mode. */ case USB_DEVICE_ID_LOGITECH_WHEEL: udesc = &(hid_to_usb_dev(hdev)->descriptor); if (!udesc) { hid_err(hdev, "NULL USB device descriptor\n"); break; } bcdDevice = le16_to_cpu(udesc->bcdDevice); rev_maj = bcdDevice >> 8; rev_min = bcdDevice & 0xff; /* Update the report descriptor for only the Driving Force wheel */ if (rev_maj == 1 && rev_min == 2 && *rsize == DF_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force report descriptor\n"); rdesc = df_rdesc_fixed; *rsize = sizeof(df_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL: if (*rsize == MOMO_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Force (Red) report descriptor\n"); rdesc = momo_rdesc_fixed; *rsize = sizeof(momo_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL2: if (*rsize == MOMO2_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Racing Force (Black) report descriptor\n"); rdesc = momo2_rdesc_fixed; *rsize = sizeof(momo2_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_VIBRATION_WHEEL: if (*rsize == FV_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Formula Vibration report descriptor\n"); rdesc = fv_rdesc_fixed; *rsize = sizeof(fv_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_DFP_WHEEL: if (*rsize == DFP_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force Pro report descriptor\n"); rdesc = dfp_rdesc_fixed; *rsize = sizeof(dfp_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_WII_WHEEL: if (*rsize >= 101 && rdesc[41] == 0x95 && rdesc[42] == 0x0B && rdesc[47] == 0x05 && rdesc[48] == 0x09) { hid_info(hdev, "fixing up Logitech Speed Force Wireless report descriptor\n"); rdesc[41] = 0x05; rdesc[42] = 0x09; rdesc[47] = 0x95; rdesc[48] = 0x0B; } break; } return rdesc; } Commit Message: HID: fix a couple of off-by-ones There are a few very theoretical off-by-one bugs in report descriptor size checking when performing a pre-parsing fixup. Fix those. Cc: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static __u8 *lg_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { struct lg_drv_data *drv_data = hid_get_drvdata(hdev); struct usb_device_descriptor *udesc; __u16 bcdDevice, rev_maj, rev_min; if ((drv_data->quirks & LG_RDESC) && *rsize >= 91 && rdesc[83] == 0x26 && rdesc[84] == 0x8c && rdesc[85] == 0x02) { hid_info(hdev, "fixing up Logitech keyboard report descriptor\n"); rdesc[84] = rdesc[89] = 0x4d; rdesc[85] = rdesc[90] = 0x10; } if ((drv_data->quirks & LG_RDESC_REL_ABS) && *rsize >= 51 && rdesc[32] == 0x81 && rdesc[33] == 0x06 && rdesc[49] == 0x81 && rdesc[50] == 0x06) { hid_info(hdev, "fixing up rel/abs in Logitech report descriptor\n"); rdesc[33] = rdesc[50] = 0x02; } switch (hdev->product) { /* Several wheels report as this id when operating in emulation mode. */ case USB_DEVICE_ID_LOGITECH_WHEEL: udesc = &(hid_to_usb_dev(hdev)->descriptor); if (!udesc) { hid_err(hdev, "NULL USB device descriptor\n"); break; } bcdDevice = le16_to_cpu(udesc->bcdDevice); rev_maj = bcdDevice >> 8; rev_min = bcdDevice & 0xff; /* Update the report descriptor for only the Driving Force wheel */ if (rev_maj == 1 && rev_min == 2 && *rsize == DF_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force report descriptor\n"); rdesc = df_rdesc_fixed; *rsize = sizeof(df_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL: if (*rsize == MOMO_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Force (Red) report descriptor\n"); rdesc = momo_rdesc_fixed; *rsize = sizeof(momo_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL2: if (*rsize == MOMO2_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Racing Force (Black) report descriptor\n"); rdesc = momo2_rdesc_fixed; *rsize = sizeof(momo2_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_VIBRATION_WHEEL: if (*rsize == FV_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Formula Vibration report descriptor\n"); rdesc = fv_rdesc_fixed; *rsize = sizeof(fv_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_DFP_WHEEL: if (*rsize == DFP_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force Pro report descriptor\n"); rdesc = dfp_rdesc_fixed; *rsize = sizeof(dfp_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_WII_WHEEL: if (*rsize >= 101 && rdesc[41] == 0x95 && rdesc[42] == 0x0B && rdesc[47] == 0x05 && rdesc[48] == 0x09) { hid_info(hdev, "fixing up Logitech Speed Force Wireless report descriptor\n"); rdesc[41] = 0x05; rdesc[42] = 0x09; rdesc[47] = 0x95; rdesc[48] = 0x0B; } break; } return rdesc; }
166,372
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SpdyWriteQueue::RemovePendingWritesForStreamsAfter( SpdyStreamId last_good_stream_id) { CHECK(!removing_writes_); removing_writes_ = true; for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) { std::deque<PendingWrite>* queue = &queue_[i]; std::deque<PendingWrite>::iterator out_it = queue->begin(); for (std::deque<PendingWrite>::const_iterator it = queue->begin(); it != queue->end(); ++it) { if (it->stream.get() && (it->stream->stream_id() > last_good_stream_id || it->stream->stream_id() == 0)) { delete it->frame_producer; } else { *out_it = *it; ++out_it; } } queue->erase(out_it, queue->end()); } removing_writes_ = false; } Commit Message: These can post callbacks which re-enter into SpdyWriteQueue. BUG=369539 Review URL: https://codereview.chromium.org/265933007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268730 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void SpdyWriteQueue::RemovePendingWritesForStreamsAfter( SpdyStreamId last_good_stream_id) { CHECK(!removing_writes_); removing_writes_ = true; std::vector<SpdyBufferProducer*> erased_buffer_producers; for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) { std::deque<PendingWrite>* queue = &queue_[i]; std::deque<PendingWrite>::iterator out_it = queue->begin(); for (std::deque<PendingWrite>::const_iterator it = queue->begin(); it != queue->end(); ++it) { if (it->stream.get() && (it->stream->stream_id() > last_good_stream_id || it->stream->stream_id() == 0)) { erased_buffer_producers.push_back(it->frame_producer); } else { *out_it = *it; ++out_it; } } queue->erase(out_it, queue->end()); } removing_writes_ = false; STLDeleteElements(&erased_buffer_producers); // Invokes callbacks. }
171,675
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: authentic_set_current_files(struct sc_card *card, struct sc_path *path, unsigned char *resp, size_t resplen, struct sc_file **file_out) { struct sc_context *ctx = card->ctx; struct sc_file *file = NULL; int rv; LOG_FUNC_CALLED(ctx); if (resplen) { switch (resp[0]) { case 0x62: case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); if (path) file->path = *path; rv = authentic_process_fci(card, file, resp, resplen); LOG_TEST_RET(ctx, rv, "cannot set 'current file': FCI process error"); break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } if (file->type == SC_FILE_TYPE_DF) { struct sc_path cur_df_path; memset(&cur_df_path, 0, sizeof(cur_df_path)); if (card->cache.valid && card->cache.current_df) { cur_df_path = card->cache.current_df->path; sc_file_free(card->cache.current_df); } card->cache.current_df = NULL; sc_file_dup(&card->cache.current_df, file); if (cur_df_path.len) { memcpy(card->cache.current_df->path.value + cur_df_path.len, card->cache.current_df->path.value, card->cache.current_df->path.len); memcpy(card->cache.current_df->path.value, cur_df_path.value, cur_df_path.len); card->cache.current_df->path.len += cur_df_path.len; } sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; card->cache.valid = 1; } else { sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_ef, file); } if (file_out) *file_out = file; else sc_file_free(file); } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
authentic_set_current_files(struct sc_card *card, struct sc_path *path, unsigned char *resp, size_t resplen, struct sc_file **file_out) { struct sc_context *ctx = card->ctx; struct sc_file *file = NULL; int rv; LOG_FUNC_CALLED(ctx); if (resplen) { switch (resp[0]) { case 0x62: case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); if (path) file->path = *path; rv = authentic_process_fci(card, file, resp, resplen); LOG_TEST_RET(ctx, rv, "cannot set 'current file': FCI process error"); break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } if (file->type == SC_FILE_TYPE_DF) { struct sc_path cur_df_path; memset(&cur_df_path, 0, sizeof(cur_df_path)); if (card->cache.valid && card->cache.current_df) { cur_df_path = card->cache.current_df->path; sc_file_free(card->cache.current_df); } card->cache.current_df = NULL; sc_file_dup(&card->cache.current_df, file); if (cur_df_path.len) { if (cur_df_path.len + card->cache.current_df->path.len > sizeof card->cache.current_df->path.value || cur_df_path.len > sizeof card->cache.current_df->path.value) LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); memcpy(card->cache.current_df->path.value + cur_df_path.len, card->cache.current_df->path.value, card->cache.current_df->path.len); memcpy(card->cache.current_df->path.value, cur_df_path.value, cur_df_path.len); card->cache.current_df->path.len += cur_df_path.len; } sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; card->cache.valid = 1; } else { sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_ef, file); } if (file_out) *file_out = file; else sc_file_free(file); } LOG_FUNC_RETURN(ctx, SC_SUCCESS); }
169,049
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void scsi_free_request(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); qemu_vfree(r->iov.iov_base); } Commit Message: scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]> CWE ID: CWE-119
static void scsi_free_request(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); if (r->iov.iov_base) { qemu_vfree(r->iov.iov_base); } }
166,553
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl(ScriptExecutionContext* context, PassRefPtr<RTCSessionDescriptionCallback> successCallback, PassRefPtr<RTCErrorCallback> errorCallback) : ActiveDOMObject(context, this) , m_successCallback(successCallback) , m_errorCallback(errorCallback) { } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl(ScriptExecutionContext* context, PassRefPtr<RTCSessionDescriptionCallback> successCallback, PassRefPtr<RTCErrorCallback> errorCallback) RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl(ScriptExecutionContext* context, PassRefPtr<RTCSessionDescriptionCallback> successCallback, PassRefPtr<RTCErrorCallback> errorCallback, PassRefPtr<RTCPeerConnection> owner) : ActiveDOMObject(context, this) , m_successCallback(successCallback) , m_errorCallback(errorCallback) , m_owner(owner) { }
170,340
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HttpBridge::MakeAsynchronousPost() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); base::AutoLock lock(fetch_state_lock_); DCHECK(!fetch_state_.request_completed); if (fetch_state_.aborted) return; fetch_state_.url_poster = new URLFetcher(url_for_request_, URLFetcher::POST, this); fetch_state_.url_poster->set_request_context(context_getter_for_request_); fetch_state_.url_poster->set_upload_data(content_type_, request_content_); fetch_state_.url_poster->set_extra_request_headers(extra_headers_); fetch_state_.url_poster->set_load_flags(net::LOAD_DO_NOT_SEND_COOKIES); fetch_state_.url_poster->Start(); } Commit Message: Use URLFetcher::Create instead of new in http_bridge.cc. This change modified http_bridge so that it uses a factory to construct the URLFetcher. Moreover, it modified sync_backend_host_unittest.cc to use an URLFetcher factory which will prevent access to www.example.com during the test. BUG=none TEST=sync_backend_host_unittest.cc Review URL: http://codereview.chromium.org/7053011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87227 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void HttpBridge::MakeAsynchronousPost() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); base::AutoLock lock(fetch_state_lock_); DCHECK(!fetch_state_.request_completed); if (fetch_state_.aborted) return; fetch_state_.url_poster = URLFetcher::Create(0, url_for_request_, URLFetcher::POST, this); fetch_state_.url_poster->set_request_context(context_getter_for_request_); fetch_state_.url_poster->set_upload_data(content_type_, request_content_); fetch_state_.url_poster->set_extra_request_headers(extra_headers_); fetch_state_.url_poster->set_load_flags(net::LOAD_DO_NOT_SEND_COOKIES); fetch_state_.url_poster->Start(); }
170,428
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *lxclock_name(const char *p, const char *n) { int ret; int len; char *dest; char *rundir; /* lockfile will be: * "/run" + "/lock/lxc/$lxcpath/$lxcname + '\0' if root * or * $XDG_RUNTIME_DIR + "/lock/lxc/$lxcpath/$lxcname + '\0' if non-root */ /* length of "/lock/lxc/" + $lxcpath + "/" + "." + $lxcname + '\0' */ len = strlen("/lock/lxc/") + strlen(n) + strlen(p) + 3; rundir = get_rundir(); if (!rundir) return NULL; len += strlen(rundir); if ((dest = malloc(len)) == NULL) { free(rundir); return NULL; } ret = snprintf(dest, len, "%s/lock/lxc/%s", rundir, p); if (ret < 0 || ret >= len) { free(dest); free(rundir); return NULL; } ret = mkdir_p(dest, 0755); if (ret < 0) { /* fall back to "/tmp/" + $(id -u) + "/lxc" + $lxcpath + "/" + "." + $lxcname + '\0' * * maximum length of $(id -u) is 10 calculated by (log (2 ** (sizeof(uid_t) * 8) - 1) / log 10 + 1) * * lxcpath always starts with '/' */ int l2 = 22 + strlen(n) + strlen(p); if (l2 > len) { char *d; d = realloc(dest, l2); if (!d) { free(dest); free(rundir); return NULL; } len = l2; dest = d; } ret = snprintf(dest, len, "/tmp/%d/lxc%s", geteuid(), p); if (ret < 0 || ret >= len) { free(dest); free(rundir); return NULL; } ret = mkdir_p(dest, 0755); if (ret < 0) { free(dest); free(rundir); return NULL; } ret = snprintf(dest, len, "/tmp/%d/lxc%s/.%s", geteuid(), p, n); } else ret = snprintf(dest, len, "%s/lock/lxc/%s/.%s", rundir, p, n); free(rundir); if (ret < 0 || ret >= len) { free(dest); return NULL; } return dest; } Commit Message: CVE-2015-1331: lxclock: use /run/lxc/lock rather than /run/lock/lxc This prevents an unprivileged user to use LXC to create arbitrary file on the filesystem. Signed-off-by: Serge Hallyn <[email protected]> Signed-off-by: Tyler Hicks <[email protected]> Acked-by: Stéphane Graber <[email protected]> CWE ID: CWE-59
static char *lxclock_name(const char *p, const char *n) { int ret; int len; char *dest; char *rundir; /* lockfile will be: * "/run" + "/lxc/lock/$lxcpath/$lxcname + '\0' if root * or * $XDG_RUNTIME_DIR + "/lxc/lock/$lxcpath/$lxcname + '\0' if non-root */ /* length of "/lxc/lock/" + $lxcpath + "/" + "." + $lxcname + '\0' */ len = strlen("/lxc/lock/") + strlen(n) + strlen(p) + 3; rundir = get_rundir(); if (!rundir) return NULL; len += strlen(rundir); if ((dest = malloc(len)) == NULL) { free(rundir); return NULL; } ret = snprintf(dest, len, "%s/lxc/lock/%s", rundir, p); if (ret < 0 || ret >= len) { free(dest); free(rundir); return NULL; } ret = mkdir_p(dest, 0755); if (ret < 0) { free(dest); free(rundir); return NULL; } ret = snprintf(dest, len, "%s/lxc/lock/%s/.%s", rundir, p, n); free(rundir); if (ret < 0 || ret >= len) { free(dest); return NULL; } return dest; }
166,725
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static long ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct ion_client *client = filp->private_data; struct ion_device *dev = client->dev; struct ion_handle *cleanup_handle = NULL; int ret = 0; unsigned int dir; union { struct ion_fd_data fd; struct ion_allocation_data allocation; struct ion_handle_data handle; struct ion_custom_data custom; } data; dir = ion_ioctl_dir(cmd); if (_IOC_SIZE(cmd) > sizeof(data)) return -EINVAL; if (dir & _IOC_WRITE) if (copy_from_user(&data, (void __user *)arg, _IOC_SIZE(cmd))) return -EFAULT; switch (cmd) { case ION_IOC_ALLOC: { struct ion_handle *handle; handle = ion_alloc(client, data.allocation.len, data.allocation.align, data.allocation.heap_id_mask, data.allocation.flags); if (IS_ERR(handle)) return PTR_ERR(handle); data.allocation.handle = handle->id; cleanup_handle = handle; break; } case ION_IOC_FREE: { struct ion_handle *handle; handle = ion_handle_get_by_id(client, data.handle.handle); if (IS_ERR(handle)) return PTR_ERR(handle); ion_free(client, handle); ion_handle_put(handle); break; } case ION_IOC_SHARE: case ION_IOC_MAP: { struct ion_handle *handle; handle = ion_handle_get_by_id(client, data.handle.handle); if (IS_ERR(handle)) return PTR_ERR(handle); data.fd.fd = ion_share_dma_buf_fd(client, handle); ion_handle_put(handle); if (data.fd.fd < 0) ret = data.fd.fd; break; } case ION_IOC_IMPORT: { struct ion_handle *handle; handle = ion_import_dma_buf_fd(client, data.fd.fd); if (IS_ERR(handle)) ret = PTR_ERR(handle); else data.handle.handle = handle->id; break; } case ION_IOC_SYNC: { ret = ion_sync_for_device(client, data.fd.fd); break; } case ION_IOC_CUSTOM: { if (!dev->custom_ioctl) return -ENOTTY; ret = dev->custom_ioctl(client, data.custom.cmd, data.custom.arg); break; } default: return -ENOTTY; } if (dir & _IOC_READ) { if (copy_to_user((void __user *)arg, &data, _IOC_SIZE(cmd))) { if (cleanup_handle) ion_free(client, cleanup_handle); return -EFAULT; } } return ret; } Commit Message: staging/android/ion : fix a race condition in the ion driver There is a use-after-free problem in the ion driver. This is caused by a race condition in the ion_ioctl() function. A handle has ref count of 1 and two tasks on different cpus calls ION_IOC_FREE simultaneously. cpu 0 cpu 1 ------------------------------------------------------- ion_handle_get_by_id() (ref == 2) ion_handle_get_by_id() (ref == 3) ion_free() (ref == 2) ion_handle_put() (ref == 1) ion_free() (ref == 0 so ion_handle_destroy() is called and the handle is freed.) ion_handle_put() is called and it decreases the slub's next free pointer The problem is detected as an unaligned access in the spin lock functions since it uses load exclusive instruction. In some cases it corrupts the slub's free pointer which causes a mis-aligned access to the next free pointer.(kmalloc returns a pointer like ffffc0745b4580aa). And it causes lots of other hard-to-debug problems. This symptom is caused since the first member in the ion_handle structure is the reference count and the ion driver decrements the reference after it has been freed. To fix this problem client->lock mutex is extended to protect all the codes that uses the handle. Signed-off-by: Eun Taik Lee <[email protected]> Reviewed-by: Laura Abbott <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-416
static long ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct ion_client *client = filp->private_data; struct ion_device *dev = client->dev; struct ion_handle *cleanup_handle = NULL; int ret = 0; unsigned int dir; union { struct ion_fd_data fd; struct ion_allocation_data allocation; struct ion_handle_data handle; struct ion_custom_data custom; } data; dir = ion_ioctl_dir(cmd); if (_IOC_SIZE(cmd) > sizeof(data)) return -EINVAL; if (dir & _IOC_WRITE) if (copy_from_user(&data, (void __user *)arg, _IOC_SIZE(cmd))) return -EFAULT; switch (cmd) { case ION_IOC_ALLOC: { struct ion_handle *handle; handle = ion_alloc(client, data.allocation.len, data.allocation.align, data.allocation.heap_id_mask, data.allocation.flags); if (IS_ERR(handle)) return PTR_ERR(handle); data.allocation.handle = handle->id; cleanup_handle = handle; break; } case ION_IOC_FREE: { struct ion_handle *handle; mutex_lock(&client->lock); handle = ion_handle_get_by_id_nolock(client, data.handle.handle); if (IS_ERR(handle)) { mutex_unlock(&client->lock); return PTR_ERR(handle); } ion_free_nolock(client, handle); ion_handle_put_nolock(handle); mutex_unlock(&client->lock); break; } case ION_IOC_SHARE: case ION_IOC_MAP: { struct ion_handle *handle; handle = ion_handle_get_by_id(client, data.handle.handle); if (IS_ERR(handle)) return PTR_ERR(handle); data.fd.fd = ion_share_dma_buf_fd(client, handle); ion_handle_put(handle); if (data.fd.fd < 0) ret = data.fd.fd; break; } case ION_IOC_IMPORT: { struct ion_handle *handle; handle = ion_import_dma_buf_fd(client, data.fd.fd); if (IS_ERR(handle)) ret = PTR_ERR(handle); else data.handle.handle = handle->id; break; } case ION_IOC_SYNC: { ret = ion_sync_for_device(client, data.fd.fd); break; } case ION_IOC_CUSTOM: { if (!dev->custom_ioctl) return -ENOTTY; ret = dev->custom_ioctl(client, data.custom.cmd, data.custom.arg); break; } default: return -ENOTTY; } if (dir & _IOC_READ) { if (copy_to_user((void __user *)arg, &data, _IOC_SIZE(cmd))) { if (cleanup_handle) ion_free(client, cleanup_handle); return -EFAULT; } } return ret; }
166,899
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static php_stream *phar_make_dirstream(char *dir, HashTable *manifest TSRMLS_DC) /* {{{ */ { HashTable *data; int dirlen = strlen(dir); phar_zstr key; char *entry, *found, *save, *str_key; uint keylen; ulong unused; ALLOC_HASHTABLE(data); zend_hash_init(data, 64, zend_get_hash_value, NULL, 0); if ((*dir == '/' && dirlen == 1 && (manifest->nNumOfElements == 0)) || (dirlen >= sizeof(".phar")-1 && !memcmp(dir, ".phar", sizeof(".phar")-1))) { /* make empty root directory for empty phar */ /* make empty directory for .phar magic directory */ efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } zend_hash_internal_pointer_reset(manifest); while (FAILURE != zend_hash_has_more_elements(manifest)) { if (HASH_KEY_IS_STRING != zend_hash_get_current_key_ex(manifest, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen <= (uint)dirlen) { if (keylen < (uint)dirlen || !strncmp(str_key, dir, dirlen)) { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } if (*dir == '/') { /* root directory */ if (keylen >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { PHAR_STR_FREE(str_key); /* do not add any magic entries to this directory */ if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } if (NULL != (found = (char *) memchr(str_key, '/', keylen))) { /* the entry has a path separator and is a subdirectory */ entry = (char *) safe_emalloc(found - str_key, 1, 1); memcpy(entry, str_key, found - str_key); keylen = found - str_key; entry[keylen] = '\0'; } else { entry = (char *) safe_emalloc(keylen, 1, 1); memcpy(entry, str_key, keylen); entry[keylen] = '\0'; } PHAR_STR_FREE(str_key); goto PHAR_ADD_ENTRY; } else { if (0 != memcmp(str_key, dir, dirlen)) { /* entry in directory not found */ PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } else { if (str_key[dirlen] != '/') { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } } save = str_key; save += dirlen + 1; /* seek to just past the path separator */ if (NULL != (found = (char *) memchr(save, '/', keylen - dirlen - 1))) { /* is subdirectory */ save -= dirlen + 1; entry = (char *) safe_emalloc(found - save + dirlen, 1, 1); memcpy(entry, save + dirlen + 1, found - save - dirlen - 1); keylen = found - save - dirlen - 1; entry[keylen] = '\0'; } else { /* is file */ save -= dirlen + 1; entry = (char *) safe_emalloc(keylen - dirlen, 1, 1); memcpy(entry, save + dirlen + 1, keylen - dirlen - 1); entry[keylen - dirlen - 1] = '\0'; keylen = keylen - dirlen - 1; } PHAR_STR_FREE(str_key); PHAR_ADD_ENTRY: if (keylen) { phar_add_empty(data, entry, keylen); } efree(entry); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } } if (FAILURE != zend_hash_has_more_elements(data)) { efree(dir); if (zend_hash_sort(data, zend_qsort, phar_compare_dir_name, 0 TSRMLS_CC) == FAILURE) { FREE_HASHTABLE(data); return NULL; } return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } else { efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } } /* }}}*/ Commit Message: CWE ID: CWE-189
static php_stream *phar_make_dirstream(char *dir, HashTable *manifest TSRMLS_DC) /* {{{ */ { HashTable *data; int dirlen = strlen(dir); phar_zstr key; char *entry, *found, *save, *str_key; uint keylen; ulong unused; ALLOC_HASHTABLE(data); zend_hash_init(data, 64, zend_get_hash_value, NULL, 0); if ((*dir == '/' && dirlen == 1 && (manifest->nNumOfElements == 0)) || (dirlen >= sizeof(".phar")-1 && !memcmp(dir, ".phar", sizeof(".phar")-1))) { /* make empty root directory for empty phar */ /* make empty directory for .phar magic directory */ efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } zend_hash_internal_pointer_reset(manifest); while (FAILURE != zend_hash_has_more_elements(manifest)) { if (HASH_KEY_NON_EXISTENT == zend_hash_get_current_key_ex(manifest, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen <= (uint)dirlen) { if (keylen < (uint)dirlen || !strncmp(str_key, dir, dirlen)) { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } if (*dir == '/') { /* root directory */ if (keylen >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { PHAR_STR_FREE(str_key); /* do not add any magic entries to this directory */ if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } if (NULL != (found = (char *) memchr(str_key, '/', keylen))) { /* the entry has a path separator and is a subdirectory */ entry = (char *) safe_emalloc(found - str_key, 1, 1); memcpy(entry, str_key, found - str_key); keylen = found - str_key; entry[keylen] = '\0'; } else { entry = (char *) safe_emalloc(keylen, 1, 1); memcpy(entry, str_key, keylen); entry[keylen] = '\0'; } PHAR_STR_FREE(str_key); goto PHAR_ADD_ENTRY; } else { if (0 != memcmp(str_key, dir, dirlen)) { /* entry in directory not found */ PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } else { if (str_key[dirlen] != '/') { PHAR_STR_FREE(str_key); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } continue; } } } save = str_key; save += dirlen + 1; /* seek to just past the path separator */ if (NULL != (found = (char *) memchr(save, '/', keylen - dirlen - 1))) { /* is subdirectory */ save -= dirlen + 1; entry = (char *) safe_emalloc(found - save + dirlen, 1, 1); memcpy(entry, save + dirlen + 1, found - save - dirlen - 1); keylen = found - save - dirlen - 1; entry[keylen] = '\0'; } else { /* is file */ save -= dirlen + 1; entry = (char *) safe_emalloc(keylen - dirlen, 1, 1); memcpy(entry, save + dirlen + 1, keylen - dirlen - 1); entry[keylen - dirlen - 1] = '\0'; keylen = keylen - dirlen - 1; } PHAR_STR_FREE(str_key); PHAR_ADD_ENTRY: if (keylen) { phar_add_empty(data, entry, keylen); } efree(entry); if (SUCCESS != zend_hash_move_forward(manifest)) { break; } } if (FAILURE != zend_hash_has_more_elements(data)) { efree(dir); if (zend_hash_sort(data, zend_qsort, phar_compare_dir_name, 0 TSRMLS_CC) == FAILURE) { FREE_HASHTABLE(data); return NULL; } return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } else { efree(dir); return php_stream_alloc(&phar_dir_ops, data, NULL, "r"); } } /* }}}*/
164,571
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jas_iccputsint(jas_stream_t *out, int n, longlong val) { ulonglong tmp; tmp = (val < 0) ? (abort(), 0) : val; return jas_iccputuint(out, n, tmp); } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
static int jas_iccputsint(jas_stream_t *out, int n, longlong val) static int jas_iccputsint(jas_stream_t *out, int n, jas_longlong val) { jas_ulonglong tmp; tmp = (val < 0) ? (abort(), 0) : val; return jas_iccputuint(out, n, tmp); }
168,689
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftVPXEncoder::onQueueFilled(OMX_U32 /* portIndex */) { if (mCodecContext == NULL) { if (OK != initEncoder()) { ALOGE("Failed to initialize encoder"); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer return; } } vpx_codec_err_t codec_return; List<BufferInfo *> &inputBufferInfoQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outputBufferInfoQueue = getPortQueue(kOutputPortIndex); while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) { BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin(); OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader; BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin(); OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader; if ((inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) && inputBufferHeader->nFilledLen == 0) { inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); inputBufferInfo->mOwnedByUs = false; notifyEmptyBufferDone(inputBufferHeader); outputBufferHeader->nFilledLen = 0; outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS; outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); outputBufferInfo->mOwnedByUs = false; notifyFillBufferDone(outputBufferHeader); return; } const uint8_t *source = inputBufferHeader->pBuffer + inputBufferHeader->nOffset; if (mInputDataIsMeta) { source = extractGraphicBuffer( mConversionBuffer, mWidth * mHeight * 3 / 2, source, inputBufferHeader->nFilledLen, mWidth, mHeight); if (source == NULL) { ALOGE("Unable to extract gralloc buffer in metadata mode"); notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return; } } else if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) { ConvertYUV420SemiPlanarToYUV420Planar( source, mConversionBuffer, mWidth, mHeight); source = mConversionBuffer; } vpx_image_t raw_frame; vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight, kInputBufferAlignment, (uint8_t *)source); vpx_enc_frame_flags_t flags = 0; if (mTemporalPatternLength > 0) { flags = getEncodeFlags(); } if (mKeyFrameRequested) { flags |= VPX_EFLAG_FORCE_KF; mKeyFrameRequested = false; } if (mBitrateUpdated) { mCodecConfiguration->rc_target_bitrate = mBitrate/1000; vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext, mCodecConfiguration); if (res != VPX_CODEC_OK) { ALOGE("vp8 encoder failed to update bitrate: %s", vpx_codec_err_to_string(res)); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer } mBitrateUpdated = false; } uint32_t frameDuration; if (inputBufferHeader->nTimeStamp > mLastTimestamp) { frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp); } else { frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / mFramerate); } mLastTimestamp = inputBufferHeader->nTimeStamp; codec_return = vpx_codec_encode( mCodecContext, &raw_frame, inputBufferHeader->nTimeStamp, // in timebase units frameDuration, // frame duration in timebase units flags, // frame flags VPX_DL_REALTIME); // encoding deadline if (codec_return != VPX_CODEC_OK) { ALOGE("vpx encoder failed to encode frame"); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer return; } vpx_codec_iter_t encoded_packet_iterator = NULL; const vpx_codec_cx_pkt_t* encoded_packet; while ((encoded_packet = vpx_codec_get_cx_data( mCodecContext, &encoded_packet_iterator))) { if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) { outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts; outputBufferHeader->nFlags = 0; if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY) outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME; outputBufferHeader->nOffset = 0; outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz; memcpy(outputBufferHeader->pBuffer, encoded_packet->data.frame.buf, encoded_packet->data.frame.sz); outputBufferInfo->mOwnedByUs = false; outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) { outputBufferHeader->nFlags |= OMX_BUFFERFLAG_EOS; } notifyFillBufferDone(outputBufferHeader); } } inputBufferInfo->mOwnedByUs = false; inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); notifyEmptyBufferDone(inputBufferHeader); } } Commit Message: codecs: check OMX buffer size before use in VP8 encoder. Bug: 27569635 Change-Id: I469573f40e21dc9f4c200749d4f220e3a2d31761 CWE ID: CWE-264
void SoftVPXEncoder::onQueueFilled(OMX_U32 /* portIndex */) { if (mCodecContext == NULL) { if (OK != initEncoder()) { ALOGE("Failed to initialize encoder"); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer return; } } vpx_codec_err_t codec_return; List<BufferInfo *> &inputBufferInfoQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outputBufferInfoQueue = getPortQueue(kOutputPortIndex); while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) { BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin(); OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader; BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin(); OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader; if ((inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) && inputBufferHeader->nFilledLen == 0) { inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); inputBufferInfo->mOwnedByUs = false; notifyEmptyBufferDone(inputBufferHeader); outputBufferHeader->nFilledLen = 0; outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS; outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); outputBufferInfo->mOwnedByUs = false; notifyFillBufferDone(outputBufferHeader); return; } const uint8_t *source = inputBufferHeader->pBuffer + inputBufferHeader->nOffset; size_t frameSize = mWidth * mHeight * 3 / 2; if (mInputDataIsMeta) { source = extractGraphicBuffer( mConversionBuffer, frameSize, source, inputBufferHeader->nFilledLen, mWidth, mHeight); if (source == NULL) { ALOGE("Unable to extract gralloc buffer in metadata mode"); notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return; } } else { if (inputBufferHeader->nFilledLen < frameSize) { android_errorWriteLog(0x534e4554, "27569635"); notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return; } else if (inputBufferHeader->nFilledLen > frameSize) { ALOGW("Input buffer contains too many pixels"); } if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) { ConvertYUV420SemiPlanarToYUV420Planar( source, mConversionBuffer, mWidth, mHeight); source = mConversionBuffer; } } vpx_image_t raw_frame; vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight, kInputBufferAlignment, (uint8_t *)source); vpx_enc_frame_flags_t flags = 0; if (mTemporalPatternLength > 0) { flags = getEncodeFlags(); } if (mKeyFrameRequested) { flags |= VPX_EFLAG_FORCE_KF; mKeyFrameRequested = false; } if (mBitrateUpdated) { mCodecConfiguration->rc_target_bitrate = mBitrate/1000; vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext, mCodecConfiguration); if (res != VPX_CODEC_OK) { ALOGE("vp8 encoder failed to update bitrate: %s", vpx_codec_err_to_string(res)); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer } mBitrateUpdated = false; } uint32_t frameDuration; if (inputBufferHeader->nTimeStamp > mLastTimestamp) { frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp); } else { frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / mFramerate); } mLastTimestamp = inputBufferHeader->nTimeStamp; codec_return = vpx_codec_encode( mCodecContext, &raw_frame, inputBufferHeader->nTimeStamp, // in timebase units frameDuration, // frame duration in timebase units flags, // frame flags VPX_DL_REALTIME); // encoding deadline if (codec_return != VPX_CODEC_OK) { ALOGE("vpx encoder failed to encode frame"); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer return; } vpx_codec_iter_t encoded_packet_iterator = NULL; const vpx_codec_cx_pkt_t* encoded_packet; while ((encoded_packet = vpx_codec_get_cx_data( mCodecContext, &encoded_packet_iterator))) { if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) { outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts; outputBufferHeader->nFlags = 0; if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY) outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME; outputBufferHeader->nOffset = 0; outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz; if (outputBufferHeader->nFilledLen > outputBufferHeader->nAllocLen) { android_errorWriteLog(0x534e4554, "27569635"); notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return; } memcpy(outputBufferHeader->pBuffer, encoded_packet->data.frame.buf, encoded_packet->data.frame.sz); outputBufferInfo->mOwnedByUs = false; outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) { outputBufferHeader->nFlags |= OMX_BUFFERFLAG_EOS; } notifyFillBufferDone(outputBufferHeader); } } inputBufferInfo->mOwnedByUs = false; inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); notifyEmptyBufferDone(inputBufferHeader); } }
173,882
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: pdf_read_old_xref(fz_context *ctx, pdf_document *doc, pdf_lexbuf *buf) { fz_stream *file = doc->file; int64_t ofs; int len; char *s; size_t n; pdf_token tok; int64_t i; int c; int xref_len = pdf_xref_size_from_old_trailer(ctx, doc, buf); pdf_xref_entry *table; int carried; fz_skip_space(ctx, doc->file); if (fz_skip_string(ctx, doc->file, "xref")) fz_throw(ctx, FZ_ERROR_GENERIC, "cannot find xref marker"); fz_skip_space(ctx, doc->file); while (1) { c = fz_peek_byte(ctx, file); if (!(c >= '0' && c <= '9')) break; fz_read_line(ctx, file, buf->scratch, buf->size); s = buf->scratch; ofs = fz_atoi64(fz_strsep(&s, " ")); len = fz_atoi(fz_strsep(&s, " ")); /* broken pdfs where the section is not on a separate line */ if (s && *s != '\0') { fz_warn(ctx, "broken xref section. proceeding anyway."); fz_seek(ctx, file, -(2 + (int)strlen(s)), SEEK_CUR); } if (ofs < 0) fz_throw(ctx, FZ_ERROR_GENERIC, "out of range object num in xref: %d", (int)ofs); if (ofs > INT64_MAX - len) fz_throw(ctx, FZ_ERROR_GENERIC, "xref section object numbers too big"); /* broken pdfs where size in trailer undershoots entries in xref sections */ if (ofs + len > xref_len) { } table = pdf_xref_find_subsection(ctx, doc, ofs, len); /* Xref entries SHOULD be 20 bytes long, but we see 19 byte * ones more frequently than we'd like (e.g. PCLm drivers). * Cope with this by 'carrying' data forward. */ carried = 0; for (i = ofs; i < ofs + len; i++) { pdf_xref_entry *entry = &table[i-ofs]; n = fz_read(ctx, file, (unsigned char *) buf->scratch + carried, 20-carried); if (n != 20-carried) fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected EOF in xref table"); n += carried; if (!entry->type) { s = buf->scratch; /* broken pdfs where line start with white space */ while (*s != '\0' && iswhite(*s)) s++; entry->ofs = fz_atoi64(s); entry->gen = fz_atoi(s + 11); entry->num = (int)i; entry->type = s[17]; if (s[17] != 'f' && s[17] != 'n' && s[17] != 'o') fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected xref type: 0x%x (%d %d R)", s[17], entry->num, entry->gen); /* If the last byte of our buffer isn't an EOL (or space), carry one byte forward */ carried = s[19] > 32; if (carried) s[0] = s[19]; } } if (carried) fz_unread_byte(ctx, file); } tok = pdf_lex(ctx, file, buf); if (tok != PDF_TOK_TRAILER) fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer marker"); tok = pdf_lex(ctx, file, buf); if (tok != PDF_TOK_OPEN_DICT) fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer dictionary"); return pdf_parse_dict(ctx, doc, file, buf); } Commit Message: CWE ID: CWE-119
pdf_read_old_xref(fz_context *ctx, pdf_document *doc, pdf_lexbuf *buf) { fz_stream *file = doc->file; int64_t ofs; int len; char *s; size_t n; pdf_token tok; int64_t i; int c; int xref_len = pdf_xref_size_from_old_trailer(ctx, doc, buf); pdf_xref_entry *table; int carried; fz_skip_space(ctx, doc->file); if (fz_skip_string(ctx, doc->file, "xref")) fz_throw(ctx, FZ_ERROR_GENERIC, "cannot find xref marker"); fz_skip_space(ctx, doc->file); while (1) { c = fz_peek_byte(ctx, file); if (!(c >= '0' && c <= '9')) break; fz_read_line(ctx, file, buf->scratch, buf->size); s = buf->scratch; ofs = fz_atoi64(fz_strsep(&s, " ")); len = fz_atoi(fz_strsep(&s, " ")); /* broken pdfs where the section is not on a separate line */ if (s && *s != '\0') { fz_warn(ctx, "broken xref section. proceeding anyway."); fz_seek(ctx, file, -(2 + (int)strlen(s)), SEEK_CUR); } if (ofs < 0 || ofs > PDF_MAX_OBJECT_NUMBER || len < 0 || len > PDF_MAX_OBJECT_NUMBER || ofs + len - 1 > PDF_MAX_OBJECT_NUMBER) { fz_throw(ctx, FZ_ERROR_GENERIC, "xref subsection object numbers are out of range"); } /* broken pdfs where size in trailer undershoots entries in xref sections */ if (ofs + len > xref_len) { } table = pdf_xref_find_subsection(ctx, doc, ofs, len); /* Xref entries SHOULD be 20 bytes long, but we see 19 byte * ones more frequently than we'd like (e.g. PCLm drivers). * Cope with this by 'carrying' data forward. */ carried = 0; for (i = ofs; i < ofs + len; i++) { pdf_xref_entry *entry = &table[i-ofs]; n = fz_read(ctx, file, (unsigned char *) buf->scratch + carried, 20-carried); if (n != 20-carried) fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected EOF in xref table"); n += carried; if (!entry->type) { s = buf->scratch; /* broken pdfs where line start with white space */ while (*s != '\0' && iswhite(*s)) s++; entry->ofs = fz_atoi64(s); entry->gen = fz_atoi(s + 11); entry->num = (int)i; entry->type = s[17]; if (s[17] != 'f' && s[17] != 'n' && s[17] != 'o') fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected xref type: 0x%x (%d %d R)", s[17], entry->num, entry->gen); /* If the last byte of our buffer isn't an EOL (or space), carry one byte forward */ carried = s[19] > 32; if (carried) s[0] = s[19]; } } if (carried) fz_unread_byte(ctx, file); } tok = pdf_lex(ctx, file, buf); if (tok != PDF_TOK_TRAILER) fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer marker"); tok = pdf_lex(ctx, file, buf); if (tok != PDF_TOK_OPEN_DICT) fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer dictionary"); return pdf_parse_dict(ctx, doc, file, buf); }
165,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadJPEGImage(const ImageInfo *image_info, ExceptionInfo *exception) { char value[MaxTextExtent]; const char *option; ErrorManager error_manager; Image *image; IndexPacket index; JSAMPLE *volatile jpeg_pixels; JSAMPROW scanline[1]; MagickBooleanType debug, status; MagickSizeType number_pixels; MemoryInfo *memory_info; register ssize_t i; struct jpeg_decompress_struct jpeg_info; struct jpeg_error_mgr jpeg_error; register JSAMPLE *p; size_t units; ssize_t y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); debug=IsEventLogging(); (void) debug; image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize JPEG parameters. */ (void) ResetMagickMemory(&error_manager,0,sizeof(error_manager)); (void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info)); (void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error)); jpeg_info.err=jpeg_std_error(&jpeg_error); jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler; jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler; memory_info=(MemoryInfo *) NULL; error_manager.image=image; if (setjmp(error_manager.error_recovery) != 0) { jpeg_destroy_decompress(&jpeg_info); if (error_manager.profile != (StringInfo *) NULL) error_manager.profile=DestroyStringInfo(error_manager.profile); (void) CloseBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != 0) return(GetFirstImageInList(image)); InheritException(exception,&image->exception); return(DestroyImage(image)); } jpeg_info.client_data=(void *) &error_manager; jpeg_create_decompress(&jpeg_info); JPEGSourceManager(&jpeg_info,image); jpeg_set_marker_processor(&jpeg_info,JPEG_COM,ReadComment); option=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,ICC_MARKER,ReadICCProfile); if (IsOptionMember("IPTC",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,IPTC_MARKER,ReadIPTCProfile); for (i=1; i < 16; i++) if ((i != 2) && (i != 13) && (i != 14)) if (IsOptionMember("APP",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,(int) (JPEG_APP0+i),ReadProfile); i=(ssize_t) jpeg_read_header(&jpeg_info,TRUE); if ((image_info->colorspace == YCbCrColorspace) || (image_info->colorspace == Rec601YCbCrColorspace) || (image_info->colorspace == Rec709YCbCrColorspace)) jpeg_info.out_color_space=JCS_YCbCr; /* Set image resolution. */ units=0; if ((jpeg_info.saw_JFIF_marker != 0) && (jpeg_info.X_density != 1) && (jpeg_info.Y_density != 1)) { image->x_resolution=(double) jpeg_info.X_density; image->y_resolution=(double) jpeg_info.Y_density; units=(size_t) jpeg_info.density_unit; } if (units == 1) image->units=PixelsPerInchResolution; if (units == 2) image->units=PixelsPerCentimeterResolution; number_pixels=(MagickSizeType) image->columns*image->rows; option=GetImageOption(image_info,"jpeg:size"); if ((option != (const char *) NULL) && (jpeg_info.out_color_space != JCS_YCbCr)) { double scale_factor; GeometryInfo geometry_info; MagickStatusType flags; /* Scale the image. */ flags=ParseGeometry(option,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; jpeg_calc_output_dimensions(&jpeg_info); image->magick_columns=jpeg_info.output_width; image->magick_rows=jpeg_info.output_height; scale_factor=1.0; if (geometry_info.rho != 0.0) scale_factor=jpeg_info.output_width/geometry_info.rho; if ((geometry_info.sigma != 0.0) && (scale_factor > (jpeg_info.output_height/geometry_info.sigma))) scale_factor=jpeg_info.output_height/geometry_info.sigma; jpeg_info.scale_num=1U; jpeg_info.scale_denom=(unsigned int) scale_factor; jpeg_calc_output_dimensions(&jpeg_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Scale factor: %.20g",(double) scale_factor); } #if (JPEG_LIB_VERSION >= 61) && defined(D_PROGRESSIVE_SUPPORTED) #if defined(D_LOSSLESS_SUPPORTED) image->interlace=jpeg_info.process == JPROC_PROGRESSIVE ? JPEGInterlace : NoInterlace; image->compression=jpeg_info.process == JPROC_LOSSLESS ? LosslessJPEGCompression : JPEGCompression; if (jpeg_info.data_precision > 8) (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "12-bit JPEG not supported. Reducing pixel data to 8 bits","`%s'", image->filename); if (jpeg_info.data_precision == 16) jpeg_info.data_precision=12; #else image->interlace=jpeg_info.progressive_mode != 0 ? JPEGInterlace : NoInterlace; image->compression=JPEGCompression; #endif #else image->compression=JPEGCompression; image->interlace=JPEGInterlace; #endif option=GetImageOption(image_info,"jpeg:colors"); if (option != (const char *) NULL) { /* Let the JPEG library quantize for us. */ jpeg_info.quantize_colors=TRUE; jpeg_info.desired_number_of_colors=(int) StringToUnsignedLong(option); } option=GetImageOption(image_info,"jpeg:block-smoothing"); if (option != (const char *) NULL) jpeg_info.do_block_smoothing=IsStringTrue(option) != MagickFalse ? TRUE : FALSE; jpeg_info.dct_method=JDCT_FLOAT; option=GetImageOption(image_info,"jpeg:dct-method"); if (option != (const char *) NULL) switch (*option) { case 'D': case 'd': { if (LocaleCompare(option,"default") == 0) jpeg_info.dct_method=JDCT_DEFAULT; break; } case 'F': case 'f': { if (LocaleCompare(option,"fastest") == 0) jpeg_info.dct_method=JDCT_FASTEST; if (LocaleCompare(option,"float") == 0) jpeg_info.dct_method=JDCT_FLOAT; break; } case 'I': case 'i': { if (LocaleCompare(option,"ifast") == 0) jpeg_info.dct_method=JDCT_IFAST; if (LocaleCompare(option,"islow") == 0) jpeg_info.dct_method=JDCT_ISLOW; break; } } option=GetImageOption(image_info,"jpeg:fancy-upsampling"); if (option != (const char *) NULL) jpeg_info.do_fancy_upsampling=IsStringTrue(option) != MagickFalse ? TRUE : FALSE; (void) jpeg_start_decompress(&jpeg_info); image->columns=jpeg_info.output_width; image->rows=jpeg_info.output_height; image->depth=(size_t) jpeg_info.data_precision; switch (jpeg_info.out_color_space) { case JCS_RGB: default: { (void) SetImageColorspace(image,sRGBColorspace); break; } case JCS_GRAYSCALE: { (void) SetImageColorspace(image,GRAYColorspace); break; } case JCS_YCbCr: { (void) SetImageColorspace(image,YCbCrColorspace); break; } case JCS_CMYK: { (void) SetImageColorspace(image,CMYKColorspace); break; } } if (IsITUFaxImage(image) != MagickFalse) { (void) SetImageColorspace(image,LabColorspace); jpeg_info.out_color_space=JCS_YCbCr; } option=GetImageOption(image_info,"jpeg:colors"); if (option != (const char *) NULL) if (AcquireImageColormap(image,StringToUnsignedLong(option)) == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((jpeg_info.output_components == 1) && (jpeg_info.quantize_colors == 0)) { size_t colors; colors=(size_t) GetQuantumRange(image->depth)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } } if (image->debug != MagickFalse) { if (image->interlace != NoInterlace) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: progressive"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: nonprogressive"); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Data precision: %d", (int) jpeg_info.data_precision); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %dx%d", (int) jpeg_info.output_width,(int) jpeg_info.output_height); } JPEGSetImageQuality(&jpeg_info,image); JPEGSetImageSamplingFactor(&jpeg_info,image); (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) jpeg_info.out_color_space); (void) SetImageProperty(image,"jpeg:colorspace",value); if (image_info->ping != MagickFalse) { jpeg_destroy_decompress(&jpeg_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { jpeg_destroy_decompress(&jpeg_info); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((jpeg_info.output_components != 1) && (jpeg_info.output_components != 3) && (jpeg_info.output_components != 4)) { jpeg_destroy_decompress(&jpeg_info); ThrowReaderException(CorruptImageError,"ImageTypeNotSupported"); } memory_info=AcquireVirtualMemory((size_t) image->columns, jpeg_info.output_components*sizeof(*jpeg_pixels)); if (memory_info == (MemoryInfo *) NULL) { jpeg_destroy_decompress(&jpeg_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info); /* Convert JPEG pixels to pixel packets. */ if (setjmp(error_manager.error_recovery) != 0) { if (memory_info != (MemoryInfo *) NULL) memory_info=RelinquishVirtualMemory(memory_info); jpeg_destroy_decompress(&jpeg_info); (void) CloseBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != 0) return(GetFirstImageInList(image)); return(DestroyImage(image)); } if (jpeg_info.quantize_colors != 0) { image->colors=(size_t) jpeg_info.actual_number_of_colors; if (jpeg_info.out_color_space == JCS_GRAYSCALE) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]); image->colormap[i].green=image->colormap[i].red; image->colormap[i].blue=image->colormap[i].red; image->colormap[i].opacity=OpaqueOpacity; } else for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]); image->colormap[i].green=ScaleCharToQuantum(jpeg_info.colormap[1][i]); image->colormap[i].blue=ScaleCharToQuantum(jpeg_info.colormap[2][i]); image->colormap[i].opacity=OpaqueOpacity; } } scanline[0]=(JSAMPROW) jpeg_pixels; for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (jpeg_read_scanlines(&jpeg_info,scanline,1) != 1) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename); continue; } p=jpeg_pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); if (jpeg_info.data_precision > 8) { unsigned short scale; scale=65535/(unsigned short) GetQuantumRange((size_t) jpeg_info.data_precision); if (jpeg_info.output_components == 1) for (x=0; x < (ssize_t) image->columns; x++) { size_t pixel; pixel=(size_t) (scale*GETJSAMPLE(*p)); index=ConstrainColormapIndex(image,pixel); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } else if (image->colorspace != CMYKColorspace) for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleShortToQuantum((unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelOpacity(q,OpaqueOpacity); q++; } else for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelMagenta(q,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelYellow(q,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelBlack(indexes+x,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelOpacity(q,OpaqueOpacity); q++; } } else if (jpeg_info.output_components == 1) for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,(size_t) GETJSAMPLE(*p)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } else if (image->colorspace != CMYKColorspace) for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelOpacity(q,OpaqueOpacity); q++; } else for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelMagenta(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelYellow(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelBlack(indexes+x,QuantumRange-ScaleCharToQuantum( (unsigned char) GETJSAMPLE(*p++))); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) { jpeg_abort_decompress(&jpeg_info); break; } } if (status != MagickFalse) { error_manager.finished=MagickTrue; if (setjmp(error_manager.error_recovery) == 0) (void) jpeg_finish_decompress(&jpeg_info); } /* Free jpeg resources. */ jpeg_destroy_decompress(&jpeg_info); memory_info=RelinquishVirtualMemory(memory_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: ... CWE ID: CWE-20
static Image *ReadJPEGImage(const ImageInfo *image_info, ExceptionInfo *exception) { char value[MaxTextExtent]; const char *option; ErrorManager error_manager; Image *image; IndexPacket index; JSAMPLE *volatile jpeg_pixels; JSAMPROW scanline[1]; MagickBooleanType debug, status; MagickSizeType number_pixels; MemoryInfo *memory_info; register ssize_t i; struct jpeg_decompress_struct jpeg_info; struct jpeg_error_mgr jpeg_error; register JSAMPLE *p; size_t units; ssize_t y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); debug=IsEventLogging(); (void) debug; image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Verify that file size large enough to contain a JPEG datastream. */ if (GetBlobSize(image) < 107) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Initialize JPEG parameters. */ (void) ResetMagickMemory(&error_manager,0,sizeof(error_manager)); (void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info)); (void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error)); jpeg_info.err=jpeg_std_error(&jpeg_error); jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler; jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler; memory_info=(MemoryInfo *) NULL; error_manager.image=image; if (setjmp(error_manager.error_recovery) != 0) { jpeg_destroy_decompress(&jpeg_info); if (error_manager.profile != (StringInfo *) NULL) error_manager.profile=DestroyStringInfo(error_manager.profile); (void) CloseBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != 0) return(GetFirstImageInList(image)); InheritException(exception,&image->exception); return(DestroyImage(image)); } jpeg_info.client_data=(void *) &error_manager; jpeg_create_decompress(&jpeg_info); JPEGSourceManager(&jpeg_info,image); jpeg_set_marker_processor(&jpeg_info,JPEG_COM,ReadComment); option=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,ICC_MARKER,ReadICCProfile); if (IsOptionMember("IPTC",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,IPTC_MARKER,ReadIPTCProfile); for (i=1; i < 16; i++) if ((i != 2) && (i != 13) && (i != 14)) if (IsOptionMember("APP",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,(int) (JPEG_APP0+i),ReadProfile); i=(ssize_t) jpeg_read_header(&jpeg_info,TRUE); if ((image_info->colorspace == YCbCrColorspace) || (image_info->colorspace == Rec601YCbCrColorspace) || (image_info->colorspace == Rec709YCbCrColorspace)) jpeg_info.out_color_space=JCS_YCbCr; /* Set image resolution. */ units=0; if ((jpeg_info.saw_JFIF_marker != 0) && (jpeg_info.X_density != 1) && (jpeg_info.Y_density != 1)) { image->x_resolution=(double) jpeg_info.X_density; image->y_resolution=(double) jpeg_info.Y_density; units=(size_t) jpeg_info.density_unit; } if (units == 1) image->units=PixelsPerInchResolution; if (units == 2) image->units=PixelsPerCentimeterResolution; number_pixels=(MagickSizeType) image->columns*image->rows; option=GetImageOption(image_info,"jpeg:size"); if ((option != (const char *) NULL) && (jpeg_info.out_color_space != JCS_YCbCr)) { double scale_factor; GeometryInfo geometry_info; MagickStatusType flags; /* Scale the image. */ flags=ParseGeometry(option,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; jpeg_calc_output_dimensions(&jpeg_info); image->magick_columns=jpeg_info.output_width; image->magick_rows=jpeg_info.output_height; scale_factor=1.0; if (geometry_info.rho != 0.0) scale_factor=jpeg_info.output_width/geometry_info.rho; if ((geometry_info.sigma != 0.0) && (scale_factor > (jpeg_info.output_height/geometry_info.sigma))) scale_factor=jpeg_info.output_height/geometry_info.sigma; jpeg_info.scale_num=1U; jpeg_info.scale_denom=(unsigned int) scale_factor; jpeg_calc_output_dimensions(&jpeg_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Scale factor: %.20g",(double) scale_factor); } #if (JPEG_LIB_VERSION >= 61) && defined(D_PROGRESSIVE_SUPPORTED) #if defined(D_LOSSLESS_SUPPORTED) image->interlace=jpeg_info.process == JPROC_PROGRESSIVE ? JPEGInterlace : NoInterlace; image->compression=jpeg_info.process == JPROC_LOSSLESS ? LosslessJPEGCompression : JPEGCompression; if (jpeg_info.data_precision > 8) (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "12-bit JPEG not supported. Reducing pixel data to 8 bits","`%s'", image->filename); if (jpeg_info.data_precision == 16) jpeg_info.data_precision=12; #else image->interlace=jpeg_info.progressive_mode != 0 ? JPEGInterlace : NoInterlace; image->compression=JPEGCompression; #endif #else image->compression=JPEGCompression; image->interlace=JPEGInterlace; #endif option=GetImageOption(image_info,"jpeg:colors"); if (option != (const char *) NULL) { /* Let the JPEG library quantize for us. */ jpeg_info.quantize_colors=TRUE; jpeg_info.desired_number_of_colors=(int) StringToUnsignedLong(option); } option=GetImageOption(image_info,"jpeg:block-smoothing"); if (option != (const char *) NULL) jpeg_info.do_block_smoothing=IsStringTrue(option) != MagickFalse ? TRUE : FALSE; jpeg_info.dct_method=JDCT_FLOAT; option=GetImageOption(image_info,"jpeg:dct-method"); if (option != (const char *) NULL) switch (*option) { case 'D': case 'd': { if (LocaleCompare(option,"default") == 0) jpeg_info.dct_method=JDCT_DEFAULT; break; } case 'F': case 'f': { if (LocaleCompare(option,"fastest") == 0) jpeg_info.dct_method=JDCT_FASTEST; if (LocaleCompare(option,"float") == 0) jpeg_info.dct_method=JDCT_FLOAT; break; } case 'I': case 'i': { if (LocaleCompare(option,"ifast") == 0) jpeg_info.dct_method=JDCT_IFAST; if (LocaleCompare(option,"islow") == 0) jpeg_info.dct_method=JDCT_ISLOW; break; } } option=GetImageOption(image_info,"jpeg:fancy-upsampling"); if (option != (const char *) NULL) jpeg_info.do_fancy_upsampling=IsStringTrue(option) != MagickFalse ? TRUE : FALSE; (void) jpeg_start_decompress(&jpeg_info); image->columns=jpeg_info.output_width; image->rows=jpeg_info.output_height; image->depth=(size_t) jpeg_info.data_precision; switch (jpeg_info.out_color_space) { case JCS_RGB: default: { (void) SetImageColorspace(image,sRGBColorspace); break; } case JCS_GRAYSCALE: { (void) SetImageColorspace(image,GRAYColorspace); break; } case JCS_YCbCr: { (void) SetImageColorspace(image,YCbCrColorspace); break; } case JCS_CMYK: { (void) SetImageColorspace(image,CMYKColorspace); break; } } if (IsITUFaxImage(image) != MagickFalse) { (void) SetImageColorspace(image,LabColorspace); jpeg_info.out_color_space=JCS_YCbCr; } option=GetImageOption(image_info,"jpeg:colors"); if (option != (const char *) NULL) if (AcquireImageColormap(image,StringToUnsignedLong(option)) == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((jpeg_info.output_components == 1) && (jpeg_info.quantize_colors == 0)) { size_t colors; colors=(size_t) GetQuantumRange(image->depth)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } } if (image->debug != MagickFalse) { if (image->interlace != NoInterlace) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: progressive"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: nonprogressive"); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Data precision: %d", (int) jpeg_info.data_precision); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %dx%d", (int) jpeg_info.output_width,(int) jpeg_info.output_height); } JPEGSetImageQuality(&jpeg_info,image); JPEGSetImageSamplingFactor(&jpeg_info,image); (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) jpeg_info.out_color_space); (void) SetImageProperty(image,"jpeg:colorspace",value); if (image_info->ping != MagickFalse) { jpeg_destroy_decompress(&jpeg_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { jpeg_destroy_decompress(&jpeg_info); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((jpeg_info.output_components != 1) && (jpeg_info.output_components != 3) && (jpeg_info.output_components != 4)) { jpeg_destroy_decompress(&jpeg_info); ThrowReaderException(CorruptImageError,"ImageTypeNotSupported"); } memory_info=AcquireVirtualMemory((size_t) image->columns, jpeg_info.output_components*sizeof(*jpeg_pixels)); if (memory_info == (MemoryInfo *) NULL) { jpeg_destroy_decompress(&jpeg_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info); /* Convert JPEG pixels to pixel packets. */ if (setjmp(error_manager.error_recovery) != 0) { if (memory_info != (MemoryInfo *) NULL) memory_info=RelinquishVirtualMemory(memory_info); jpeg_destroy_decompress(&jpeg_info); (void) CloseBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != 0) return(GetFirstImageInList(image)); return(DestroyImage(image)); } if (jpeg_info.quantize_colors != 0) { image->colors=(size_t) jpeg_info.actual_number_of_colors; if (jpeg_info.out_color_space == JCS_GRAYSCALE) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]); image->colormap[i].green=image->colormap[i].red; image->colormap[i].blue=image->colormap[i].red; image->colormap[i].opacity=OpaqueOpacity; } else for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]); image->colormap[i].green=ScaleCharToQuantum(jpeg_info.colormap[1][i]); image->colormap[i].blue=ScaleCharToQuantum(jpeg_info.colormap[2][i]); image->colormap[i].opacity=OpaqueOpacity; } } scanline[0]=(JSAMPROW) jpeg_pixels; for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (jpeg_read_scanlines(&jpeg_info,scanline,1) != 1) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename); continue; } p=jpeg_pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); if (jpeg_info.data_precision > 8) { unsigned short scale; scale=65535/(unsigned short) GetQuantumRange((size_t) jpeg_info.data_precision); if (jpeg_info.output_components == 1) for (x=0; x < (ssize_t) image->columns; x++) { size_t pixel; pixel=(size_t) (scale*GETJSAMPLE(*p)); index=ConstrainColormapIndex(image,pixel); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } else if (image->colorspace != CMYKColorspace) for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleShortToQuantum((unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelOpacity(q,OpaqueOpacity); q++; } else for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelMagenta(q,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelYellow(q,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelBlack(indexes+x,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelOpacity(q,OpaqueOpacity); q++; } } else if (jpeg_info.output_components == 1) for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,(size_t) GETJSAMPLE(*p)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } else if (image->colorspace != CMYKColorspace) for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelOpacity(q,OpaqueOpacity); q++; } else for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelMagenta(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelYellow(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelBlack(indexes+x,QuantumRange-ScaleCharToQuantum( (unsigned char) GETJSAMPLE(*p++))); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) { jpeg_abort_decompress(&jpeg_info); break; } } if (status != MagickFalse) { error_manager.finished=MagickTrue; if (setjmp(error_manager.error_recovery) == 0) (void) jpeg_finish_decompress(&jpeg_info); } /* Free jpeg resources. */ jpeg_destroy_decompress(&jpeg_info); memory_info=RelinquishVirtualMemory(memory_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,033
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: IW_IMPL(unsigned int) iw_get_ui32be(const iw_byte *b) { return (b[0]<<24) | (b[1]<<16) | (b[2]<<8) | b[3]; } Commit Message: Trying to fix some invalid left shift operations Fixes issue #16 CWE ID: CWE-682
IW_IMPL(unsigned int) iw_get_ui32be(const iw_byte *b) { return ((unsigned int)b[0]<<24) | ((unsigned int)b[1]<<16) | ((unsigned int)b[2]<<8) | (unsigned int)b[3]; }
168,199
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image) { MagickBooleanType status; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; size_t depth, packet_size; ssize_t y; unsigned char *colormap, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); /* Allocate colormap. */ if (IsPaletteImage(image,&image->exception) == MagickFalse) (void) SetImageType(image,PaletteType); depth=GetImageQuantumDepth(image,MagickTrue); packet_size=(size_t) (depth/8); pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*pixels)); packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size* sizeof(*colormap)); if ((pixels == (unsigned char *) NULL) || (colormap == (unsigned char *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Write colormap to file. */ q=colormap; if (image->depth <= 8) for (i=0; i < (ssize_t) image->colors; i++) { *q++=(unsigned char) image->colormap[i].red; *q++=(unsigned char) image->colormap[i].green; *q++=(unsigned char) image->colormap[i].blue; } else for (i=0; i < (ssize_t) image->colors; i++) { *q++=(unsigned char) ((size_t) image->colormap[i].red >> 8); *q++=(unsigned char) image->colormap[i].red; *q++=(unsigned char) ((size_t) image->colormap[i].green >> 8); *q++=(unsigned char) image->colormap[i].green; *q++=(unsigned char) ((size_t) image->colormap[i].blue >> 8); *q++=(unsigned char) image->colormap[i].blue; } (void) WriteBlob(image,packet_size*image->colors,colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); /* Write image pixels to file. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels; for (x=0; x < (ssize_t) image->columns; x++) { if (image->colors > 256) *q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8); *q++=(unsigned char) GetPixelIndex(indexes+x); } (void) WriteBlob(image,(size_t) (q-pixels),pixels); } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(status); } Commit Message: Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu) CWE ID: CWE-119
static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image) { MagickBooleanType status; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; size_t depth, packet_size; ssize_t y; unsigned char *colormap, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); /* Allocate colormap. */ if (IsPaletteImage(image,&image->exception) == MagickFalse) (void) SetImageType(image,PaletteType); depth=GetImageQuantumDepth(image,MagickTrue); packet_size=(size_t) (depth/8); pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*pixels)); packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size* sizeof(*colormap)); if ((pixels == (unsigned char *) NULL) || (colormap == (unsigned char *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Write colormap to file. */ q=colormap; q=colormap; if (image->colors <= 256) for (i=0; i < (ssize_t) image->colors; i++) { *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red); *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green); *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue); } else for (i=0; i < (ssize_t) image->colors; i++) { *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) & 0xff);; *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & 0xff); } (void) WriteBlob(image,packet_size*image->colors,colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); /* Write image pixels to file. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels; for (x=0; x < (ssize_t) image->columns; x++) { if (image->colors > 256) *q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8); *q++=(unsigned char) GetPixelIndex(indexes+x); } (void) WriteBlob(image,(size_t) (q-pixels),pixels); } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(status); }
168,632
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: l2tp_proxy_auth_type_print(netdissect_options *ndo, const u_char *dat) { const uint16_t *ptr = (const uint16_t *)dat; ND_PRINT((ndo, "%s", tok2str(l2tp_authentype2str, "AuthType-#%u", EXTRACT_16BITS(ptr)))); } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_proxy_auth_type_print(netdissect_options *ndo, const u_char *dat) l2tp_proxy_auth_type_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; if (length < 2) { ND_PRINT((ndo, "AVP too short")); return; } ND_PRINT((ndo, "%s", tok2str(l2tp_authentype2str, "AuthType-#%u", EXTRACT_16BITS(ptr)))); }
167,900
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int vp8dx_receive_compressed_data(VP8D_COMP *pbi, size_t size, const uint8_t *source, int64_t time_stamp) { VP8_COMMON *cm = &pbi->common; int retcode = -1; (void)size; (void)source; pbi->common.error.error_code = VPX_CODEC_OK; retcode = check_fragments_for_errors(pbi); if(retcode <= 0) return retcode; cm->new_fb_idx = get_free_fb (cm); /* setup reference frames for vp8_decode_frame */ pbi->dec_fb_ref[INTRA_FRAME] = &cm->yv12_fb[cm->new_fb_idx]; pbi->dec_fb_ref[LAST_FRAME] = &cm->yv12_fb[cm->lst_fb_idx]; pbi->dec_fb_ref[GOLDEN_FRAME] = &cm->yv12_fb[cm->gld_fb_idx]; pbi->dec_fb_ref[ALTREF_FRAME] = &cm->yv12_fb[cm->alt_fb_idx]; if (setjmp(pbi->common.error.jmp)) { /* We do not know if the missing frame(s) was supposed to update * any of the reference buffers, but we act conservative and * mark only the last buffer as corrupted. */ cm->yv12_fb[cm->lst_fb_idx].corrupted = 1; if (cm->fb_idx_ref_cnt[cm->new_fb_idx] > 0) cm->fb_idx_ref_cnt[cm->new_fb_idx]--; goto decode_exit; } pbi->common.error.setjmp = 1; retcode = vp8_decode_frame(pbi); if (retcode < 0) { if (cm->fb_idx_ref_cnt[cm->new_fb_idx] > 0) cm->fb_idx_ref_cnt[cm->new_fb_idx]--; pbi->common.error.error_code = VPX_CODEC_ERROR; goto decode_exit; } if (swap_frame_buffers (cm)) { pbi->common.error.error_code = VPX_CODEC_ERROR; goto decode_exit; } vp8_clear_system_state(); if (cm->show_frame) { cm->current_video_frame++; cm->show_frame_mi = cm->mi; } #if CONFIG_ERROR_CONCEALMENT /* swap the mode infos to storage for future error concealment */ if (pbi->ec_enabled && pbi->common.prev_mi) { MODE_INFO* tmp = pbi->common.prev_mi; int row, col; pbi->common.prev_mi = pbi->common.mi; pbi->common.mi = tmp; /* Propagate the segment_ids to the next frame */ for (row = 0; row < pbi->common.mb_rows; ++row) { for (col = 0; col < pbi->common.mb_cols; ++col) { const int i = row*pbi->common.mode_info_stride + col; pbi->common.mi[i].mbmi.segment_id = pbi->common.prev_mi[i].mbmi.segment_id; } } } #endif pbi->ready_for_new_data = 0; pbi->last_time_stamp = time_stamp; decode_exit: pbi->common.error.setjmp = 0; vp8_clear_system_state(); return retcode; } Commit Message: vp8:fix threading issues 1 - stops de allocating before threads are closed. 2 - limits threads to mb_rows when mb_rows < partitions BUG=webm:851 Bug: 30436808 Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b (cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e) CWE ID:
int vp8dx_receive_compressed_data(VP8D_COMP *pbi, size_t size, const uint8_t *source, int64_t time_stamp) { VP8_COMMON *cm = &pbi->common; int retcode = -1; (void)size; (void)source; pbi->common.error.error_code = VPX_CODEC_OK; retcode = check_fragments_for_errors(pbi); if(retcode <= 0) return retcode; cm->new_fb_idx = get_free_fb (cm); /* setup reference frames for vp8_decode_frame */ pbi->dec_fb_ref[INTRA_FRAME] = &cm->yv12_fb[cm->new_fb_idx]; pbi->dec_fb_ref[LAST_FRAME] = &cm->yv12_fb[cm->lst_fb_idx]; pbi->dec_fb_ref[GOLDEN_FRAME] = &cm->yv12_fb[cm->gld_fb_idx]; pbi->dec_fb_ref[ALTREF_FRAME] = &cm->yv12_fb[cm->alt_fb_idx]; if (setjmp(pbi->common.error.jmp)) { /* We do not know if the missing frame(s) was supposed to update * any of the reference buffers, but we act conservative and * mark only the last buffer as corrupted. */ cm->yv12_fb[cm->lst_fb_idx].corrupted = 1; if (cm->fb_idx_ref_cnt[cm->new_fb_idx] > 0) cm->fb_idx_ref_cnt[cm->new_fb_idx]--; goto decode_exit; } pbi->common.error.setjmp = 1; retcode = vp8_decode_frame(pbi); if (retcode < 0) { if (cm->fb_idx_ref_cnt[cm->new_fb_idx] > 0) cm->fb_idx_ref_cnt[cm->new_fb_idx]--; pbi->common.error.error_code = VPX_CODEC_ERROR; goto decode_exit; } if (swap_frame_buffers (cm)) { pbi->common.error.error_code = VPX_CODEC_ERROR; goto decode_exit; } vp8_clear_system_state(); if (cm->show_frame) { cm->current_video_frame++; cm->show_frame_mi = cm->mi; } #if CONFIG_ERROR_CONCEALMENT /* swap the mode infos to storage for future error concealment */ if (pbi->ec_enabled && pbi->common.prev_mi) { MODE_INFO* tmp = pbi->common.prev_mi; int row, col; pbi->common.prev_mi = pbi->common.mi; pbi->common.mi = tmp; /* Propagate the segment_ids to the next frame */ for (row = 0; row < pbi->common.mb_rows; ++row) { for (col = 0; col < pbi->common.mb_cols; ++col) { const int i = row*pbi->common.mode_info_stride + col; pbi->common.mi[i].mbmi.segment_id = pbi->common.prev_mi[i].mbmi.segment_id; } } } #endif pbi->ready_for_new_data = 0; pbi->last_time_stamp = time_stamp; decode_exit: pbi->common.error.setjmp = 0; vp8_clear_system_state(); return retcode; }
174,066
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ihevcd_parse_transform_tree(codec_t *ps_codec, WORD32 x0, WORD32 y0, WORD32 cu_x_base, WORD32 cu_y_base, WORD32 log2_trafo_size, WORD32 trafo_depth, WORD32 blk_idx, WORD32 intra_pred_mode) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; sps_t *ps_sps; pps_t *ps_pps; WORD32 value; WORD32 x1, y1; WORD32 max_trafo_depth; bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm; WORD32 intra_split_flag; WORD32 split_transform_flag; WORD32 ctxt_idx; cab_ctxt_t *ps_cabac = &ps_codec->s_parse.s_cabac; max_trafo_depth = ps_codec->s_parse.s_cu.i4_max_trafo_depth; ps_sps = ps_codec->s_parse.ps_sps; ps_pps = ps_codec->s_parse.ps_pps; intra_split_flag = ps_codec->s_parse.s_cu.i4_intra_split_flag; { split_transform_flag = 0; if((log2_trafo_size <= ps_sps->i1_log2_max_transform_block_size) && (log2_trafo_size > ps_sps->i1_log2_min_transform_block_size) && (trafo_depth < max_trafo_depth) && !(intra_split_flag && (trafo_depth == 0))) { /* encode the split transform flag, context derived as per Table9-37 */ ctxt_idx = IHEVC_CAB_SPLIT_TFM + (5 - log2_trafo_size); TRACE_CABAC_CTXT("split_transform_flag", ps_cabac->u4_range, ctxt_idx); split_transform_flag = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx); AEV_TRACE("split_transform_flag", split_transform_flag, ps_cabac->u4_range); } else { WORD32 inter_split_flag = 0; if((0 == ps_sps->i1_max_transform_hierarchy_depth_inter) && (PRED_MODE_INTER == ps_codec->s_parse.s_cu.i4_pred_mode) && (PART_2Nx2N != ps_codec->s_parse.s_cu.i4_part_mode) && (0 == trafo_depth)) { inter_split_flag = 1; } if((log2_trafo_size > ps_sps->i1_log2_max_transform_block_size) || ((1 == intra_split_flag) && (0 == trafo_depth)) || (1 == inter_split_flag)) { split_transform_flag = 1; } } if(0 == trafo_depth) { ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth] = 0; ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] = 0; } else { ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] = ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth - 1]; ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth] = ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth - 1]; } if(trafo_depth == 0 || log2_trafo_size > 2) { ctxt_idx = IHEVC_CAB_CBCR_IDX + trafo_depth; /* CBF for Cb/Cr is sent only if the parent CBF for Cb/Cr is non-zero */ if((trafo_depth == 0) || ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth - 1]) { TRACE_CABAC_CTXT("cbf_cb", ps_cabac->u4_range, ctxt_idx); value = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx); AEV_TRACE("cbf_cb", value, ps_cabac->u4_range); ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] = value; } if((trafo_depth == 0) || ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth - 1]) { TRACE_CABAC_CTXT("cbf_cr", ps_cabac->u4_range, ctxt_idx); value = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx); AEV_TRACE("cbf_cr", value, ps_cabac->u4_range); ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth] = value; } } if(split_transform_flag) { WORD32 intra_pred_mode_tmp; x1 = x0 + ((1 << log2_trafo_size) >> 1); y1 = y0 + ((1 << log2_trafo_size) >> 1); /* For transform depth of zero, intra pred mode as decoded at CU */ /* level is sent to the transform tree nodes */ /* When depth is non-zero intra pred mode of parent node is sent */ /* This takes care of passing correct mode to all the child nodes */ intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]; ihevcd_parse_transform_tree(ps_codec, x0, y0, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 0, intra_pred_mode_tmp); intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[1]; ihevcd_parse_transform_tree(ps_codec, x1, y0, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 1, intra_pred_mode_tmp); intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[2]; ihevcd_parse_transform_tree(ps_codec, x0, y1, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 2, intra_pred_mode_tmp); intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[3]; ihevcd_parse_transform_tree(ps_codec, x1, y1, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 3, intra_pred_mode_tmp); } else { WORD32 ctb_x_base; WORD32 ctb_y_base; WORD32 cu_qp_delta_abs; tu_t *ps_tu = ps_codec->s_parse.ps_tu; cu_qp_delta_abs = 0; ctb_x_base = ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size; ctb_y_base = ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size; if((ps_codec->s_parse.s_cu.i4_pred_mode == PRED_MODE_INTRA) || (trafo_depth != 0) || (ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth]) || (ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth])) { ctxt_idx = IHEVC_CAB_CBF_LUMA_IDX; ctxt_idx += (trafo_depth == 0) ? 1 : 0; TRACE_CABAC_CTXT("cbf_luma", ps_cabac->u4_range, ctxt_idx); value = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx); AEV_TRACE("cbf_luma", value, ps_cabac->u4_range); ps_codec->s_parse.s_cu.i1_cbf_luma = value; } else { ps_codec->s_parse.s_cu.i1_cbf_luma = 1; } /* Initialize ps_tu to default values */ /* If required change this to WORD32 packed write */ ps_tu->b1_cb_cbf = 0; ps_tu->b1_cr_cbf = 0; ps_tu->b1_y_cbf = 0; ps_tu->b4_pos_x = ((x0 - ctb_x_base) >> 2); ps_tu->b4_pos_y = ((y0 - ctb_y_base) >> 2); ps_tu->b1_transquant_bypass = ps_codec->s_parse.s_cu.i4_cu_transquant_bypass; ps_tu->b3_size = (log2_trafo_size - 2); ps_tu->b7_qp = ps_codec->s_parse.u4_qp; ps_tu->b6_luma_intra_mode = intra_pred_mode; ps_tu->b3_chroma_intra_mode_idx = ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx; /* Section:7.3.12 Transform unit syntax inlined here */ if(ps_codec->s_parse.s_cu.i1_cbf_luma || ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] || ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth]) { WORD32 intra_pred_mode_chroma; if(ps_pps->i1_cu_qp_delta_enabled_flag && !ps_codec->s_parse.i4_is_cu_qp_delta_coded) { WORD32 c_max = TU_MAX_QP_DELTA_ABS; WORD32 ctxt_inc = IHEVC_CAB_QP_DELTA_ABS; WORD32 ctxt_inc_max = CTXT_MAX_QP_DELTA_ABS; TRACE_CABAC_CTXT("cu_qp_delta_abs", ps_cabac->u4_range, ctxt_inc); /* qp_delta_abs is coded as combination of tunary and eg0 code */ /* See Table 9-32 and Table 9-37 for details on cu_qp_delta_abs */ cu_qp_delta_abs = ihevcd_cabac_decode_bins_tunary(ps_cabac, ps_bitstrm, c_max, ctxt_inc, 0, ctxt_inc_max); if(cu_qp_delta_abs >= c_max) { value = ihevcd_cabac_decode_bypass_bins_egk(ps_cabac, ps_bitstrm, 0); cu_qp_delta_abs += value; } AEV_TRACE("cu_qp_delta_abs", cu_qp_delta_abs, ps_cabac->u4_range); ps_codec->s_parse.i4_is_cu_qp_delta_coded = 1; if(cu_qp_delta_abs) { value = ihevcd_cabac_decode_bypass_bin(ps_cabac, ps_bitstrm); AEV_TRACE("cu_qp_delta_sign", value, ps_cabac->u4_range); if(value) cu_qp_delta_abs = -cu_qp_delta_abs; } ps_codec->s_parse.s_cu.i4_cu_qp_delta = cu_qp_delta_abs; } if(ps_codec->s_parse.s_cu.i1_cbf_luma) { ps_tu->b1_y_cbf = 1; ihevcd_parse_residual_coding(ps_codec, x0, y0, log2_trafo_size, 0, intra_pred_mode); } if(4 == ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx) intra_pred_mode_chroma = ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]; else { intra_pred_mode_chroma = gau1_intra_pred_chroma_modes[ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx]; if(intra_pred_mode_chroma == ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]) { intra_pred_mode_chroma = INTRA_ANGULAR(34); } } if(log2_trafo_size > 2) { if(ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth]) { ps_tu->b1_cb_cbf = 1; ihevcd_parse_residual_coding(ps_codec, x0, y0, log2_trafo_size - 1, 1, intra_pred_mode_chroma); } if(ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth]) { ps_tu->b1_cr_cbf = 1; ihevcd_parse_residual_coding(ps_codec, x0, y0, log2_trafo_size - 1, 2, intra_pred_mode_chroma); } } else if(blk_idx == 3) { if(ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth]) { ps_tu->b1_cb_cbf = 1; ihevcd_parse_residual_coding(ps_codec, cu_x_base, cu_y_base, log2_trafo_size, 1, intra_pred_mode_chroma); } if(ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth]) { ps_tu->b1_cr_cbf = 1; ihevcd_parse_residual_coding(ps_codec, cu_x_base, cu_y_base, log2_trafo_size, 2, intra_pred_mode_chroma); } } else { ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; } } else { if((3 != blk_idx) && (2 == log2_trafo_size)) { ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; } } /* Set the first TU in CU flag */ { if((ps_codec->s_parse.s_cu.i4_pos_x << 3) == (ps_tu->b4_pos_x << 2) && (ps_codec->s_parse.s_cu.i4_pos_y << 3) == (ps_tu->b4_pos_y << 2)) { ps_tu->b1_first_tu_in_cu = 1; } else { ps_tu->b1_first_tu_in_cu = 0; } } ps_codec->s_parse.ps_tu++; ps_codec->s_parse.s_cu.i4_tu_cnt++; ps_codec->s_parse.i4_pic_tu_idx++; } } return ret; } Commit Message: Fix in handling wrong cu_qp_delta cu_qp_delta is now checked for the range as specified in the spec Bug: 33966031 Change-Id: I00420bf68081af92e9f2be9af7ce58d0683094ca CWE ID: CWE-119
WORD32 ihevcd_parse_transform_tree(codec_t *ps_codec, WORD32 x0, WORD32 y0, WORD32 cu_x_base, WORD32 cu_y_base, WORD32 log2_trafo_size, WORD32 trafo_depth, WORD32 blk_idx, WORD32 intra_pred_mode) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; sps_t *ps_sps; pps_t *ps_pps; WORD32 value; WORD32 x1, y1; WORD32 max_trafo_depth; bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm; WORD32 intra_split_flag; WORD32 split_transform_flag; WORD32 ctxt_idx; cab_ctxt_t *ps_cabac = &ps_codec->s_parse.s_cabac; max_trafo_depth = ps_codec->s_parse.s_cu.i4_max_trafo_depth; ps_sps = ps_codec->s_parse.ps_sps; ps_pps = ps_codec->s_parse.ps_pps; intra_split_flag = ps_codec->s_parse.s_cu.i4_intra_split_flag; { split_transform_flag = 0; if((log2_trafo_size <= ps_sps->i1_log2_max_transform_block_size) && (log2_trafo_size > ps_sps->i1_log2_min_transform_block_size) && (trafo_depth < max_trafo_depth) && !(intra_split_flag && (trafo_depth == 0))) { /* encode the split transform flag, context derived as per Table9-37 */ ctxt_idx = IHEVC_CAB_SPLIT_TFM + (5 - log2_trafo_size); TRACE_CABAC_CTXT("split_transform_flag", ps_cabac->u4_range, ctxt_idx); split_transform_flag = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx); AEV_TRACE("split_transform_flag", split_transform_flag, ps_cabac->u4_range); } else { WORD32 inter_split_flag = 0; if((0 == ps_sps->i1_max_transform_hierarchy_depth_inter) && (PRED_MODE_INTER == ps_codec->s_parse.s_cu.i4_pred_mode) && (PART_2Nx2N != ps_codec->s_parse.s_cu.i4_part_mode) && (0 == trafo_depth)) { inter_split_flag = 1; } if((log2_trafo_size > ps_sps->i1_log2_max_transform_block_size) || ((1 == intra_split_flag) && (0 == trafo_depth)) || (1 == inter_split_flag)) { split_transform_flag = 1; } } if(0 == trafo_depth) { ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth] = 0; ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] = 0; } else { ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] = ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth - 1]; ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth] = ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth - 1]; } if(trafo_depth == 0 || log2_trafo_size > 2) { ctxt_idx = IHEVC_CAB_CBCR_IDX + trafo_depth; /* CBF for Cb/Cr is sent only if the parent CBF for Cb/Cr is non-zero */ if((trafo_depth == 0) || ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth - 1]) { TRACE_CABAC_CTXT("cbf_cb", ps_cabac->u4_range, ctxt_idx); value = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx); AEV_TRACE("cbf_cb", value, ps_cabac->u4_range); ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] = value; } if((trafo_depth == 0) || ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth - 1]) { TRACE_CABAC_CTXT("cbf_cr", ps_cabac->u4_range, ctxt_idx); value = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx); AEV_TRACE("cbf_cr", value, ps_cabac->u4_range); ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth] = value; } } if(split_transform_flag) { WORD32 intra_pred_mode_tmp; x1 = x0 + ((1 << log2_trafo_size) >> 1); y1 = y0 + ((1 << log2_trafo_size) >> 1); /* For transform depth of zero, intra pred mode as decoded at CU */ /* level is sent to the transform tree nodes */ /* When depth is non-zero intra pred mode of parent node is sent */ /* This takes care of passing correct mode to all the child nodes */ intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]; ihevcd_parse_transform_tree(ps_codec, x0, y0, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 0, intra_pred_mode_tmp); intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[1]; ihevcd_parse_transform_tree(ps_codec, x1, y0, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 1, intra_pred_mode_tmp); intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[2]; ihevcd_parse_transform_tree(ps_codec, x0, y1, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 2, intra_pred_mode_tmp); intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[3]; ihevcd_parse_transform_tree(ps_codec, x1, y1, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 3, intra_pred_mode_tmp); } else { WORD32 ctb_x_base; WORD32 ctb_y_base; WORD32 cu_qp_delta_abs; tu_t *ps_tu = ps_codec->s_parse.ps_tu; cu_qp_delta_abs = 0; ctb_x_base = ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size; ctb_y_base = ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size; if((ps_codec->s_parse.s_cu.i4_pred_mode == PRED_MODE_INTRA) || (trafo_depth != 0) || (ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth]) || (ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth])) { ctxt_idx = IHEVC_CAB_CBF_LUMA_IDX; ctxt_idx += (trafo_depth == 0) ? 1 : 0; TRACE_CABAC_CTXT("cbf_luma", ps_cabac->u4_range, ctxt_idx); value = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx); AEV_TRACE("cbf_luma", value, ps_cabac->u4_range); ps_codec->s_parse.s_cu.i1_cbf_luma = value; } else { ps_codec->s_parse.s_cu.i1_cbf_luma = 1; } /* Initialize ps_tu to default values */ /* If required change this to WORD32 packed write */ ps_tu->b1_cb_cbf = 0; ps_tu->b1_cr_cbf = 0; ps_tu->b1_y_cbf = 0; ps_tu->b4_pos_x = ((x0 - ctb_x_base) >> 2); ps_tu->b4_pos_y = ((y0 - ctb_y_base) >> 2); ps_tu->b1_transquant_bypass = ps_codec->s_parse.s_cu.i4_cu_transquant_bypass; ps_tu->b3_size = (log2_trafo_size - 2); ps_tu->b7_qp = ps_codec->s_parse.u4_qp; ps_tu->b6_luma_intra_mode = intra_pred_mode; ps_tu->b3_chroma_intra_mode_idx = ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx; /* Section:7.3.12 Transform unit syntax inlined here */ if(ps_codec->s_parse.s_cu.i1_cbf_luma || ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] || ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth]) { WORD32 intra_pred_mode_chroma; if(ps_pps->i1_cu_qp_delta_enabled_flag && !ps_codec->s_parse.i4_is_cu_qp_delta_coded) { WORD32 c_max = TU_MAX_QP_DELTA_ABS; WORD32 ctxt_inc = IHEVC_CAB_QP_DELTA_ABS; WORD32 ctxt_inc_max = CTXT_MAX_QP_DELTA_ABS; TRACE_CABAC_CTXT("cu_qp_delta_abs", ps_cabac->u4_range, ctxt_inc); /* qp_delta_abs is coded as combination of tunary and eg0 code */ /* See Table 9-32 and Table 9-37 for details on cu_qp_delta_abs */ cu_qp_delta_abs = ihevcd_cabac_decode_bins_tunary(ps_cabac, ps_bitstrm, c_max, ctxt_inc, 0, ctxt_inc_max); if(cu_qp_delta_abs >= c_max) { value = ihevcd_cabac_decode_bypass_bins_egk(ps_cabac, ps_bitstrm, 0); cu_qp_delta_abs += value; } AEV_TRACE("cu_qp_delta_abs", cu_qp_delta_abs, ps_cabac->u4_range); ps_codec->s_parse.i4_is_cu_qp_delta_coded = 1; if(cu_qp_delta_abs) { value = ihevcd_cabac_decode_bypass_bin(ps_cabac, ps_bitstrm); AEV_TRACE("cu_qp_delta_sign", value, ps_cabac->u4_range); if(value) cu_qp_delta_abs = -cu_qp_delta_abs; } if (cu_qp_delta_abs < MIN_CU_QP_DELTA_ABS(ps_sps->i1_bit_depth_luma_minus8) || cu_qp_delta_abs > MAX_CU_QP_DELTA_ABS(ps_sps->i1_bit_depth_luma_minus8)) { return IHEVCD_INVALID_PARAMETER; } ps_codec->s_parse.s_cu.i4_cu_qp_delta = cu_qp_delta_abs; } if(ps_codec->s_parse.s_cu.i1_cbf_luma) { ps_tu->b1_y_cbf = 1; ihevcd_parse_residual_coding(ps_codec, x0, y0, log2_trafo_size, 0, intra_pred_mode); } if(4 == ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx) intra_pred_mode_chroma = ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]; else { intra_pred_mode_chroma = gau1_intra_pred_chroma_modes[ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx]; if(intra_pred_mode_chroma == ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]) { intra_pred_mode_chroma = INTRA_ANGULAR(34); } } if(log2_trafo_size > 2) { if(ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth]) { ps_tu->b1_cb_cbf = 1; ihevcd_parse_residual_coding(ps_codec, x0, y0, log2_trafo_size - 1, 1, intra_pred_mode_chroma); } if(ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth]) { ps_tu->b1_cr_cbf = 1; ihevcd_parse_residual_coding(ps_codec, x0, y0, log2_trafo_size - 1, 2, intra_pred_mode_chroma); } } else if(blk_idx == 3) { if(ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth]) { ps_tu->b1_cb_cbf = 1; ihevcd_parse_residual_coding(ps_codec, cu_x_base, cu_y_base, log2_trafo_size, 1, intra_pred_mode_chroma); } if(ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth]) { ps_tu->b1_cr_cbf = 1; ihevcd_parse_residual_coding(ps_codec, cu_x_base, cu_y_base, log2_trafo_size, 2, intra_pred_mode_chroma); } } else { ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; } } else { if((3 != blk_idx) && (2 == log2_trafo_size)) { ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; } } /* Set the first TU in CU flag */ { if((ps_codec->s_parse.s_cu.i4_pos_x << 3) == (ps_tu->b4_pos_x << 2) && (ps_codec->s_parse.s_cu.i4_pos_y << 3) == (ps_tu->b4_pos_y << 2)) { ps_tu->b1_first_tu_in_cu = 1; } else { ps_tu->b1_first_tu_in_cu = 0; } } ps_codec->s_parse.ps_tu++; ps_codec->s_parse.s_cu.i4_tu_cnt++; ps_codec->s_parse.i4_pic_tu_idx++; } } return ret; }
174,052
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: u32 secure_ipv6_port_ephemeral(const __be32 *saddr, const __be32 *daddr, __be16 dport) { struct keydata *keyptr = get_keyptr(); u32 hash[12]; memcpy(hash, saddr, 16); hash[4] = (__force u32)dport; memcpy(&hash[5], keyptr->secret, sizeof(__u32) * 7); return twothirdsMD4Transform((const __u32 *)daddr, hash); } Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
u32 secure_ipv6_port_ephemeral(const __be32 *saddr, const __be32 *daddr,
165,767
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size, png_bytep output, png_size_t output_size) { png_size_t count = 0; png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */ png_ptr->zstream.avail_in = size; while (1) { int ret, avail; /* Reset the output buffer each time round - we empty it * after every inflate call. */ png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = png_ptr->zbuf_size; ret = inflate(&png_ptr->zstream, Z_NO_FLUSH); avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out; /* First copy/count any new output - but only if we didn't * get an error code. */ if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0) { if (output != 0 && output_size > count) { int copy = output_size - count; if (avail < copy) copy = avail; png_memcpy(output + count, png_ptr->zbuf, copy); } count += avail; } if (ret == Z_OK) continue; /* Termination conditions - always reset the zstream, it * must be left in inflateInit state. */ png_ptr->zstream.avail_in = 0; inflateReset(&png_ptr->zstream); if (ret == Z_STREAM_END) return count; /* NOTE: may be zero. */ /* Now handle the error codes - the API always returns 0 * and the error message is dumped into the uncompressed * buffer if available. */ { PNG_CONST char *msg; if (png_ptr->zstream.msg != 0) msg = png_ptr->zstream.msg; else { #if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE) char umsg[52]; switch (ret) { case Z_BUF_ERROR: msg = "Buffer error in compressed datastream in %s chunk"; break; case Z_DATA_ERROR: msg = "Data error in compressed datastream in %s chunk"; break; default: msg = "Incomplete compressed datastream in %s chunk"; break; } png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name); msg = umsg; #else msg = "Damaged compressed datastream in chunk other than IDAT"; #endif } png_warning(png_ptr, msg); } /* 0 means an error - notice that this code simple ignores * zero length compressed chunks as a result. */ return 0; } } Commit Message: Pull follow-up tweak from upstream. BUG=116162 Review URL: http://codereview.chromium.org/9546033 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125311 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size, png_bytep output, png_size_t output_size) { png_size_t count = 0; png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */ png_ptr->zstream.avail_in = size; while (1) { int ret, avail; /* Reset the output buffer each time round - we empty it * after every inflate call. */ png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = png_ptr->zbuf_size; ret = inflate(&png_ptr->zstream, Z_NO_FLUSH); avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out; /* First copy/count any new output - but only if we didn't * get an error code. */ if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0) { if (output != 0 && output_size > count) { png_size_t copy = output_size - count; if ((png_size_t) avail < copy) copy = (png_size_t) avail; png_memcpy(output + count, png_ptr->zbuf, copy); } count += avail; } if (ret == Z_OK) continue; /* Termination conditions - always reset the zstream, it * must be left in inflateInit state. */ png_ptr->zstream.avail_in = 0; inflateReset(&png_ptr->zstream); if (ret == Z_STREAM_END) return count; /* NOTE: may be zero. */ /* Now handle the error codes - the API always returns 0 * and the error message is dumped into the uncompressed * buffer if available. */ { PNG_CONST char *msg; if (png_ptr->zstream.msg != 0) msg = png_ptr->zstream.msg; else { #if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE) char umsg[52]; switch (ret) { case Z_BUF_ERROR: msg = "Buffer error in compressed datastream in %s chunk"; break; case Z_DATA_ERROR: msg = "Data error in compressed datastream in %s chunk"; break; default: msg = "Incomplete compressed datastream in %s chunk"; break; } png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name); msg = umsg; #else msg = "Damaged compressed datastream in chunk other than IDAT"; #endif } png_warning(png_ptr, msg); } /* 0 means an error - notice that this code simple ignores * zero length compressed chunks as a result. */ return 0; } }
171,061
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, int closing, int tx_ring) { struct pgv *pg_vec = NULL; struct packet_sock *po = pkt_sk(sk); int was_running, order = 0; struct packet_ring_buffer *rb; struct sk_buff_head *rb_queue; __be16 num; int err = -EINVAL; /* Added to avoid minimal code churn */ struct tpacket_req *req = &req_u->req; /* Opening a Tx-ring is NOT supported in TPACKET_V3 */ if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) { net_warn_ratelimited("Tx-ring is not supported.\n"); goto out; } rb = tx_ring ? &po->tx_ring : &po->rx_ring; rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue; err = -EBUSY; if (!closing) { if (atomic_read(&po->mapped)) goto out; if (packet_read_pending(rb)) goto out; } if (req->tp_block_nr) { /* Sanity tests and some calculations */ err = -EBUSY; if (unlikely(rb->pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V1: po->tp_hdrlen = TPACKET_HDRLEN; break; case TPACKET_V2: po->tp_hdrlen = TPACKET2_HDRLEN; break; case TPACKET_V3: po->tp_hdrlen = TPACKET3_HDRLEN; break; } err = -EINVAL; if (unlikely((int)req->tp_block_size <= 0)) goto out; if (unlikely(!PAGE_ALIGNED(req->tp_block_size))) goto out; if (po->tp_version >= TPACKET_V3 && (int)(req->tp_block_size - BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0) goto out; if (unlikely(req->tp_frame_size < po->tp_hdrlen + po->tp_reserve)) goto out; if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1))) goto out; rb->frames_per_block = req->tp_block_size / req->tp_frame_size; if (unlikely(rb->frames_per_block == 0)) goto out; if (unlikely((rb->frames_per_block * req->tp_block_nr) != req->tp_frame_nr)) goto out; err = -ENOMEM; order = get_order(req->tp_block_size); pg_vec = alloc_pg_vec(req, order); if (unlikely(!pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V3: /* Transmit path is not supported. We checked * it above but just being paranoid */ if (!tx_ring) init_prb_bdqc(po, rb, pg_vec, req_u); break; default: break; } } /* Done */ else { err = -EINVAL; if (unlikely(req->tp_frame_nr)) goto out; } lock_sock(sk); /* Detach socket from network */ spin_lock(&po->bind_lock); was_running = po->running; num = po->num; if (was_running) { po->num = 0; __unregister_prot_hook(sk, false); } spin_unlock(&po->bind_lock); synchronize_net(); err = -EBUSY; mutex_lock(&po->pg_vec_lock); if (closing || atomic_read(&po->mapped) == 0) { err = 0; spin_lock_bh(&rb_queue->lock); swap(rb->pg_vec, pg_vec); rb->frame_max = (req->tp_frame_nr - 1); rb->head = 0; rb->frame_size = req->tp_frame_size; spin_unlock_bh(&rb_queue->lock); swap(rb->pg_vec_order, order); swap(rb->pg_vec_len, req->tp_block_nr); rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE; po->prot_hook.func = (po->rx_ring.pg_vec) ? tpacket_rcv : packet_rcv; skb_queue_purge(rb_queue); if (atomic_read(&po->mapped)) pr_err("packet_mmap: vma is busy: %d\n", atomic_read(&po->mapped)); } mutex_unlock(&po->pg_vec_lock); spin_lock(&po->bind_lock); if (was_running) { po->num = num; register_prot_hook(sk); } spin_unlock(&po->bind_lock); if (closing && (po->tp_version > TPACKET_V2)) { /* Because we don't support block-based V3 on tx-ring */ if (!tx_ring) prb_shutdown_retire_blk_timer(po, rb_queue); } release_sock(sk); if (pg_vec) free_pg_vec(pg_vec, order, req->tp_block_nr); out: return err; } Commit Message: packet: fix race condition in packet_set_ring When packet_set_ring creates a ring buffer it will initialize a struct timer_list if the packet version is TPACKET_V3. This value can then be raced by a different thread calling setsockopt to set the version to TPACKET_V1 before packet_set_ring has finished. This leads to a use-after-free on a function pointer in the struct timer_list when the socket is closed as the previously initialized timer will not be deleted. The bug is fixed by taking lock_sock(sk) in packet_setsockopt when changing the packet version while also taking the lock at the start of packet_set_ring. Fixes: f6fb8f100b80 ("af-packet: TPACKET_V3 flexible buffer implementation.") Signed-off-by: Philip Pettersson <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, int closing, int tx_ring) { struct pgv *pg_vec = NULL; struct packet_sock *po = pkt_sk(sk); int was_running, order = 0; struct packet_ring_buffer *rb; struct sk_buff_head *rb_queue; __be16 num; int err = -EINVAL; /* Added to avoid minimal code churn */ struct tpacket_req *req = &req_u->req; lock_sock(sk); /* Opening a Tx-ring is NOT supported in TPACKET_V3 */ if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) { net_warn_ratelimited("Tx-ring is not supported.\n"); goto out; } rb = tx_ring ? &po->tx_ring : &po->rx_ring; rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue; err = -EBUSY; if (!closing) { if (atomic_read(&po->mapped)) goto out; if (packet_read_pending(rb)) goto out; } if (req->tp_block_nr) { /* Sanity tests and some calculations */ err = -EBUSY; if (unlikely(rb->pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V1: po->tp_hdrlen = TPACKET_HDRLEN; break; case TPACKET_V2: po->tp_hdrlen = TPACKET2_HDRLEN; break; case TPACKET_V3: po->tp_hdrlen = TPACKET3_HDRLEN; break; } err = -EINVAL; if (unlikely((int)req->tp_block_size <= 0)) goto out; if (unlikely(!PAGE_ALIGNED(req->tp_block_size))) goto out; if (po->tp_version >= TPACKET_V3 && (int)(req->tp_block_size - BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0) goto out; if (unlikely(req->tp_frame_size < po->tp_hdrlen + po->tp_reserve)) goto out; if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1))) goto out; rb->frames_per_block = req->tp_block_size / req->tp_frame_size; if (unlikely(rb->frames_per_block == 0)) goto out; if (unlikely((rb->frames_per_block * req->tp_block_nr) != req->tp_frame_nr)) goto out; err = -ENOMEM; order = get_order(req->tp_block_size); pg_vec = alloc_pg_vec(req, order); if (unlikely(!pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V3: /* Transmit path is not supported. We checked * it above but just being paranoid */ if (!tx_ring) init_prb_bdqc(po, rb, pg_vec, req_u); break; default: break; } } /* Done */ else { err = -EINVAL; if (unlikely(req->tp_frame_nr)) goto out; } /* Detach socket from network */ spin_lock(&po->bind_lock); was_running = po->running; num = po->num; if (was_running) { po->num = 0; __unregister_prot_hook(sk, false); } spin_unlock(&po->bind_lock); synchronize_net(); err = -EBUSY; mutex_lock(&po->pg_vec_lock); if (closing || atomic_read(&po->mapped) == 0) { err = 0; spin_lock_bh(&rb_queue->lock); swap(rb->pg_vec, pg_vec); rb->frame_max = (req->tp_frame_nr - 1); rb->head = 0; rb->frame_size = req->tp_frame_size; spin_unlock_bh(&rb_queue->lock); swap(rb->pg_vec_order, order); swap(rb->pg_vec_len, req->tp_block_nr); rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE; po->prot_hook.func = (po->rx_ring.pg_vec) ? tpacket_rcv : packet_rcv; skb_queue_purge(rb_queue); if (atomic_read(&po->mapped)) pr_err("packet_mmap: vma is busy: %d\n", atomic_read(&po->mapped)); } mutex_unlock(&po->pg_vec_lock); spin_lock(&po->bind_lock); if (was_running) { po->num = num; register_prot_hook(sk); } spin_unlock(&po->bind_lock); if (closing && (po->tp_version > TPACKET_V2)) { /* Because we don't support block-based V3 on tx-ring */ if (!tx_ring) prb_shutdown_retire_blk_timer(po, rb_queue); } if (pg_vec) free_pg_vec(pg_vec, order, req->tp_block_nr); out: release_sock(sk); return err; }
166,909
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, AVFrame *picture) { int compno, reslevelno, bandno; int x, y; uint8_t *line; Jpeg2000T1Context t1; /* Loop on tile components */ for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; /* Loop on resolution levels */ for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) { Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; /* Loop on bands */ for (bandno = 0; bandno < rlevel->nbands; bandno++) { int nb_precincts, precno; Jpeg2000Band *band = rlevel->band + bandno; int cblkno = 0, bandpos; bandpos = bandno + (reslevelno > 0); if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y; /* Loop on precincts */ for (precno = 0; precno < nb_precincts; precno++) { Jpeg2000Prec *prec = band->prec + precno; /* Loop on codeblocks */ for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) { int x, y; Jpeg2000Cblk *cblk = prec->cblk + cblkno; decode_cblk(s, codsty, &t1, cblk, cblk->coord[0][1] - cblk->coord[0][0], cblk->coord[1][1] - cblk->coord[1][0], bandpos); x = cblk->coord[0][0]; y = cblk->coord[1][0]; if (codsty->transform == FF_DWT97) dequantization_float(x, y, cblk, comp, &t1, band); else dequantization_int(x, y, cblk, comp, &t1, band); } /* end cblk */ } /*end prec */ } /* end band */ } /* end reslevel */ /* inverse DWT */ ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data); } /*end comp */ /* inverse MCT transformation */ if (tile->codsty[0].mct) mct_decode(s, tile); if (s->cdef[0] < 0) { for (x = 0; x < s->ncomponents; x++) s->cdef[x] = x + 1; if ((s->ncomponents & 1) == 0) s->cdef[s->ncomponents-1] = 0; } if (s->precision <= 8) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; line = picture->data[plane] + y * picture->linesize[plane]; for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint8_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = line + x * pixelsize + compno*!planar; if (codsty->transform == FF_DWT97) { for (; x < w; x += s->cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s->cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); i_datap++; dst += pixelsize; } } line += picture->linesize[plane]; } } } else { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; uint16_t *linel; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; linel = (uint16_t *)picture->data[plane] + y * (picture->linesize[plane] >> 1); for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint16_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = linel + (x * pixelsize + compno*!planar); if (codsty->transform == FF_DWT97) { for (; x < w; x += s-> cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s-> cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); i_datap++; dst += pixelsize; } } linel += picture->linesize[plane] >> 1; } } } return 0; } Commit Message: avcodec/jpeg2000dec: prevent out of array accesses in pixel addressing Fixes Ticket2921 Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, AVFrame *picture) { int compno, reslevelno, bandno; int x, y; uint8_t *line; Jpeg2000T1Context t1; /* Loop on tile components */ for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; /* Loop on resolution levels */ for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) { Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; /* Loop on bands */ for (bandno = 0; bandno < rlevel->nbands; bandno++) { int nb_precincts, precno; Jpeg2000Band *band = rlevel->band + bandno; int cblkno = 0, bandpos; bandpos = bandno + (reslevelno > 0); if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y; /* Loop on precincts */ for (precno = 0; precno < nb_precincts; precno++) { Jpeg2000Prec *prec = band->prec + precno; /* Loop on codeblocks */ for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) { int x, y; Jpeg2000Cblk *cblk = prec->cblk + cblkno; decode_cblk(s, codsty, &t1, cblk, cblk->coord[0][1] - cblk->coord[0][0], cblk->coord[1][1] - cblk->coord[1][0], bandpos); x = cblk->coord[0][0]; y = cblk->coord[1][0]; if (codsty->transform == FF_DWT97) dequantization_float(x, y, cblk, comp, &t1, band); else dequantization_int(x, y, cblk, comp, &t1, band); } /* end cblk */ } /*end prec */ } /* end band */ } /* end reslevel */ /* inverse DWT */ ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data); } /*end comp */ /* inverse MCT transformation */ if (tile->codsty[0].mct) mct_decode(s, tile); if (s->cdef[0] < 0) { for (x = 0; x < s->ncomponents; x++) s->cdef[x] = x + 1; if ((s->ncomponents & 1) == 0) s->cdef[s->ncomponents-1] = 0; } if (s->precision <= 8) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; line = picture->data[plane] + y / s->cdy[compno] * picture->linesize[plane]; for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint8_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = line + x / s->cdx[compno] * pixelsize + compno*!planar; if (codsty->transform == FF_DWT97) { for (; x < w; x += s->cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s->cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); i_datap++; dst += pixelsize; } } line += picture->linesize[plane]; } } } else { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; uint16_t *linel; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; linel = (uint16_t *)picture->data[plane] + y / s->cdy[compno] * (picture->linesize[plane] >> 1); for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint16_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = linel + (x / s->cdx[compno] * pixelsize + compno*!planar); if (codsty->transform == FF_DWT97) { for (; x < w; x += s-> cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s-> cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); i_datap++; dst += pixelsize; } } linel += picture->linesize[plane] >> 1; } } } return 0; }
165,913
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gstd_accept(int fd, char **display_creds, char **export_name, char **mech) { gss_name_t client; gss_OID mech_oid; struct gstd_tok *tok; gss_ctx_id_t ctx = GSS_C_NO_CONTEXT; gss_buffer_desc in, out; OM_uint32 maj, min; int ret; *display_creds = NULL; *export_name = NULL; out.length = 0; in.length = 0; read_packet(fd, &in, 60000, 1); again: while ((ret = read_packet(fd, &in, 60000, 0)) == -2) ; if (ret < 1) return NULL; maj = gss_accept_sec_context(&min, &ctx, GSS_C_NO_CREDENTIAL, &in, GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_oid, &out, NULL, NULL, NULL); if (out.length && write_packet(fd, &out)) { gss_release_buffer(&min, &out); return NULL; } GSTD_GSS_ERROR(maj, min, NULL, "gss_accept_sec_context"); if (maj & GSS_S_CONTINUE_NEEDED) goto again; *display_creds = gstd_get_display_name(client); *export_name = gstd_get_export_name(client); *mech = gstd_get_mech(mech_oid); gss_release_name(&min, &client); SETUP_GSTD_TOK(tok, ctx, fd, "gstd_accept"); return tok; } Commit Message: knc: fix a couple of memory leaks. One of these can be remotely triggered during the authentication phase which leads to a remote DoS possibility. Pointed out by: Imre Rad <[email protected]> CWE ID: CWE-400
gstd_accept(int fd, char **display_creds, char **export_name, char **mech) { gss_name_t client; gss_OID mech_oid; struct gstd_tok *tok; gss_ctx_id_t ctx = GSS_C_NO_CONTEXT; gss_buffer_desc in, out; OM_uint32 maj, min; int ret; *display_creds = NULL; *export_name = NULL; out.length = 0; in.length = 0; read_packet(fd, &in, 60000, 1); again: while ((ret = read_packet(fd, &in, 60000, 0)) == -2) ; if (ret < 1) return NULL; maj = gss_accept_sec_context(&min, &ctx, GSS_C_NO_CREDENTIAL, &in, GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_oid, &out, NULL, NULL, NULL); gss_release_buffer(&min, &in); if (out.length && write_packet(fd, &out)) { gss_release_buffer(&min, &out); return NULL; } gss_release_buffer(&min, &out); GSTD_GSS_ERROR(maj, min, NULL, "gss_accept_sec_context"); if (maj & GSS_S_CONTINUE_NEEDED) goto again; *display_creds = gstd_get_display_name(client); *export_name = gstd_get_export_name(client); *mech = gstd_get_mech(mech_oid); gss_release_name(&min, &client); SETUP_GSTD_TOK(tok, ctx, fd, "gstd_accept"); return tok; }
169,432
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ExtensionTtsController::SpeakNextUtterance() { while (!utterance_queue_.empty() && !current_utterance_) { Utterance* utterance = utterance_queue_.front(); utterance_queue_.pop(); SpeakNow(utterance); } } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionTtsController::SpeakNextUtterance() {
170,387
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_module_is_block_mode) { MCRYPT_GET_MODE_DIR_ARGS(modes_dir) if (mcrypt_module_is_block_mode(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_is_block_mode) { MCRYPT_GET_MODE_DIR_ARGS(modes_dir) if (mcrypt_module_is_block_mode(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } }
167,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { q = (const uint8_t *)(const void *) ((const char *)(const void *)p + CDF_GETUINT32(p, (i << 1) + 1)) - 2 * sizeof(uint32_t); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, CDF_GETUINT32(p, (i << 1) + 1))); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_FLOAT: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); u32 = CDF_TOLE4(u32); memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f)); break; case CDF_DOUBLE: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); u64 = CDF_TOLE8((uint64_t)u64); memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d)); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %" SIZE_T_FORMAT "u, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); if (l & 1) l++; o += l >> 1; if (q + o >= e) goto out; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); return -1; } Commit Message: Fix bounds checks again. CWE ID: CWE-119
cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { size_t ofs = CDF_GETUINT32(p, (i << 1) + 1); q = (const uint8_t *)(const void *) ((const char *)(const void *)p + ofs - 2 * sizeof(uint32_t)); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_FLOAT: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); u32 = CDF_TOLE4(u32); memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f)); break; case CDF_DOUBLE: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); u64 = CDF_TOLE8((uint64_t)u64); memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d)); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %" SIZE_T_FORMAT "u, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); if (l & 1) l++; o += l >> 1; if (q + o >= e) goto out; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); return -1; }
165,623
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static byte parseHexByte(const char * &str) { byte b = parseHexChar(str[0]); if (str[1] == ':' || str[1] == '\0') { str += 2; return b; } else { b = b << 4 | parseHexChar(str[1]); str += 3; return b; } } Commit Message: Deal correctly with short strings The parseMacAddress function anticipates only properly formed MAC addresses (6 hexadecimal octets separated by ":"). This change properly deals with situations where the string is shorter than expected, making sure that the passed in char* reference in parseHexByte never exceeds the end of the string. BUG: 28164077 TEST: Added a main function: int main(int argc, char **argv) { unsigned char addr[6]; if (argc > 1) { memset(addr, 0, sizeof(addr)); parseMacAddress(argv[1], addr); printf("Result: %02x:%02x:%02x:%02x:%02x:%02x\n", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); } } Tested with "", "a" "ab" "ab:c" "abxc". Change-Id: I0db8d0037e48b62333d475296a45b22ab0efe386 CWE ID: CWE-200
static byte parseHexByte(const char * &str) { if (str[0] == '\0') { ALOGE("Passed an empty string"); return 0; } byte b = parseHexChar(str[0]); if (str[1] == '\0' || str[1] == ':') { str ++; } else { b = b << 4 | parseHexChar(str[1]); str += 2; } // Skip trailing delimiter if not at the end of the string. if (str[0] != '\0') { str++; } return b; }
173,500