instruction
stringclasses
1 value
input
stringlengths
93
3.53k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: IDAT_list_extend(struct IDAT_list *tail) { /* Use the previous cached value if available. */ struct IDAT_list *next = tail->next; if (next == NULL) { /* Insert a new, malloc'ed, block of IDAT information buffers, this * one twice as large as the previous one: */ unsigned int length = 2 * tail->length; if (length < tail->length) /* arithmetic overflow */ length = tail->length; next = png_voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length))); CLEAR(*next); /* The caller must handle this: */ if (next == NULL) return NULL; next->next = NULL; next->length = length; tail->next = next; } return next; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
IDAT_list_extend(struct IDAT_list *tail) { /* Use the previous cached value if available. */ struct IDAT_list *next = tail->next; if (next == NULL) { /* Insert a new, malloc'ed, block of IDAT information buffers, this * one twice as large as the previous one: */ unsigned int length = 2 * tail->length; if (length < tail->length) /* arithmetic overflow */ length = tail->length; next = voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length))); CLEAR(*next); /* The caller must handle this: */ if (next == NULL) return NULL; next->next = NULL; next->length = length; tail->next = next; } return next; }
173,728
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: GF_Err urn_Read(GF_Box *s, GF_BitStream *bs) { u32 i, to_read; char *tmpName; GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s; if (! ptr->size ) return GF_OK; to_read = (u32) ptr->size; tmpName = (char*)gf_malloc(sizeof(char) * to_read); if (!tmpName) return GF_OUT_OF_MEM; gf_bs_read_data(bs, tmpName, to_read); i = 0; while ( (tmpName[i] != 0) && (i < to_read) ) { i++; } if (i == to_read) { gf_free(tmpName); return GF_ISOM_INVALID_FILE; } if (i == to_read - 1) { ptr->nameURN = tmpName; ptr->location = NULL; return GF_OK; } ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1)); if (!ptr->nameURN) { gf_free(tmpName); return GF_OUT_OF_MEM; } ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1)); if (!ptr->location) { gf_free(tmpName); gf_free(ptr->nameURN); ptr->nameURN = NULL; return GF_OUT_OF_MEM; } memcpy(ptr->nameURN, tmpName, i + 1); memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1)); gf_free(tmpName); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125
GF_Err urn_Read(GF_Box *s, GF_BitStream *bs) { u32 i, to_read; char *tmpName; GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s; if (! ptr->size ) return GF_OK; to_read = (u32) ptr->size; tmpName = (char*)gf_malloc(sizeof(char) * to_read); if (!tmpName) return GF_OUT_OF_MEM; gf_bs_read_data(bs, tmpName, to_read); i = 0; while ( (i < to_read) && (tmpName[i] != 0) ) { i++; } if (i == to_read) { gf_free(tmpName); return GF_ISOM_INVALID_FILE; } if (i == to_read - 1) { ptr->nameURN = tmpName; ptr->location = NULL; return GF_OK; } ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1)); if (!ptr->nameURN) { gf_free(tmpName); return GF_OUT_OF_MEM; } ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1)); if (!ptr->location) { gf_free(tmpName); gf_free(ptr->nameURN); ptr->nameURN = NULL; return GF_OUT_OF_MEM; } memcpy(ptr->nameURN, tmpName, i + 1); memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1)); gf_free(tmpName); return GF_OK; }
169,167
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static sent_status_t send_data_to_app(int fd, BT_HDR *p_buf) { if (p_buf->len == 0) return SENT_ALL; ssize_t sent = send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT); if (sent == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return SENT_NONE; LOG_ERROR("%s error writing RFCOMM data back to app: %s", __func__, strerror(errno)); return SENT_FAILED; } if (sent == 0) return SENT_FAILED; if (sent == p_buf->len) return SENT_ALL; p_buf->offset += sent; p_buf->len -= sent; return SENT_PARTIAL; } 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 sent_status_t send_data_to_app(int fd, BT_HDR *p_buf) { if (p_buf->len == 0) return SENT_ALL; ssize_t sent = TEMP_FAILURE_RETRY(send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT)); if (sent == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return SENT_NONE; LOG_ERROR("%s error writing RFCOMM data back to app: %s", __func__, strerror(errno)); return SENT_FAILED; } if (sent == 0) return SENT_FAILED; if (sent == p_buf->len) return SENT_ALL; p_buf->offset += sent; p_buf->len -= sent; return SENT_PARTIAL; }
173,458
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WebContentsAndroid::OpenURL(JNIEnv* env, jobject obj, jstring url, jboolean user_gesture, jboolean is_renderer_initiated) { GURL gurl(base::android::ConvertJavaStringToUTF8(env, url)); OpenURLParams open_params(gurl, Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_LINK, is_renderer_initiated); open_params.user_gesture = user_gesture; web_contents_->OpenURL(open_params); } Commit Message: Revert "Load web contents after tab is created." This reverts commit 4c55f398def3214369aefa9f2f2e8f5940d3799d. BUG=432562 TBR=tedchoc@chromium.org,jbudorick@chromium.org,sky@chromium.org Review URL: https://codereview.chromium.org/894003005 Cr-Commit-Position: refs/heads/master@{#314469} CWE ID: CWE-399
void WebContentsAndroid::OpenURL(JNIEnv* env,
171,138
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static Maybe<bool> CollectValuesOrEntriesImpl( Isolate* isolate, Handle<JSObject> object, Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items, PropertyFilter filter) { int count = 0; KeyAccumulator accumulator(isolate, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES); Subclass::CollectElementIndicesImpl( object, handle(object->elements(), isolate), &accumulator); Handle<FixedArray> keys = accumulator.GetKeys(); for (int i = 0; i < keys->length(); ++i) { Handle<Object> key(keys->get(i), isolate); Handle<Object> value; uint32_t index; if (!key->ToUint32(&index)) continue; uint32_t entry = Subclass::GetEntryForIndexImpl( isolate, *object, object->elements(), index, filter); if (entry == kMaxUInt32) continue; PropertyDetails details = Subclass::GetDetailsImpl(*object, entry); if (details.kind() == kData) { value = Subclass::GetImpl(isolate, object->elements(), entry); } else { LookupIterator it(isolate, object, index, LookupIterator::OWN); ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, value, Object::GetProperty(&it), Nothing<bool>()); } if (get_entries) { value = MakeEntryPair(isolate, index, value); } values_or_entries->set(count++, *value); } *nof_items = count; return Just(true); } Commit Message: Backport: Fix Object.entries/values with changing elements Bug: 111274046 Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \ /data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb (cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99) CWE ID: CWE-704
static Maybe<bool> CollectValuesOrEntriesImpl( Isolate* isolate, Handle<JSObject> object, Handle<FixedArray> values_or_entries, bool get_entries, int* nof_items, PropertyFilter filter) { DCHECK_EQ(*nof_items, 0); KeyAccumulator accumulator(isolate, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES); Subclass::CollectElementIndicesImpl( object, handle(object->elements(), isolate), &accumulator); Handle<FixedArray> keys = accumulator.GetKeys(); int count = 0; int i = 0; Handle<Map> original_map(object->map(), isolate); for (; i < keys->length(); ++i) { Handle<Object> key(keys->get(i), isolate); uint32_t index; if (!key->ToUint32(&index)) continue; DCHECK_EQ(object->map(), *original_map); uint32_t entry = Subclass::GetEntryForIndexImpl( isolate, *object, object->elements(), index, filter); if (entry == kMaxUInt32) continue; PropertyDetails details = Subclass::GetDetailsImpl(*object, entry); Handle<Object> value; if (details.kind() == kData) { value = Subclass::GetImpl(isolate, object->elements(), entry); } else { // This might modify the elements and/or change the elements kind. LookupIterator it(isolate, object, index, LookupIterator::OWN); ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, value, Object::GetProperty(&it), Nothing<bool>()); } if (get_entries) value = MakeEntryPair(isolate, index, value); values_or_entries->set(count++, *value); if (object->map() != *original_map) break; } // Slow path caused by changes in elements kind during iteration. for (; i < keys->length(); i++) { Handle<Object> key(keys->get(i), isolate); uint32_t index; if (!key->ToUint32(&index)) continue; if (filter & ONLY_ENUMERABLE) { InternalElementsAccessor* accessor = reinterpret_cast<InternalElementsAccessor*>( object->GetElementsAccessor()); uint32_t entry = accessor->GetEntryForIndex(isolate, *object, object->elements(), index); if (entry == kMaxUInt32) continue; PropertyDetails details = accessor->GetDetails(*object, entry); if (!details.IsEnumerable()) continue; } Handle<Object> value; LookupIterator it(isolate, object, index, LookupIterator::OWN); ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, value, Object::GetProperty(&it), Nothing<bool>()); if (get_entries) value = MakeEntryPair(isolate, index, value); values_or_entries->set(count++, *value); } *nof_items = count; return Just(true); }
174,094
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ContainerNode::parserInsertBefore(PassRefPtrWillBeRawPtr<Node> newChild, Node& nextChild) { ASSERT(newChild); ASSERT(nextChild.parentNode() == this); ASSERT(!newChild->isDocumentFragment()); ASSERT(!isHTMLTemplateElement(this)); if (nextChild.previousSibling() == newChild || &nextChild == newChild) // nothing to do return; if (!checkParserAcceptChild(*newChild)) return; RefPtrWillBeRawPtr<Node> protect(this); while (RefPtrWillBeRawPtr<ContainerNode> parent = newChild->parentNode()) parent->parserRemoveChild(*newChild); if (document() != newChild->document()) document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION); { EventDispatchForbiddenScope assertNoEventDispatch; ScriptForbiddenScope forbidScript; treeScope().adoptIfNeeded(*newChild); insertBeforeCommon(nextChild, *newChild); newChild->updateAncestorConnectedSubframeCountForInsertion(); ChildListMutationScope(*this).childAdded(*newChild); } notifyNodeInserted(*newChild, ChildrenChangeSourceParser); } Commit Message: parserInsertBefore: Bail out if the parent no longer contains the child. nextChild may be removed from the DOM tree during the |parserRemoveChild(*newChild)| call which triggers unload events of newChild's descendant iframes. In order to maintain the integrity of the DOM tree, the insertion of newChild must be aborted in this case. This patch adds a return statement that rectifies the behavior in this edge case. BUG=519558 Review URL: https://codereview.chromium.org/1283263002 git-svn-id: svn://svn.chromium.org/blink/trunk@200690 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264
void ContainerNode::parserInsertBefore(PassRefPtrWillBeRawPtr<Node> newChild, Node& nextChild) { ASSERT(newChild); ASSERT(nextChild.parentNode() == this); ASSERT(!newChild->isDocumentFragment()); ASSERT(!isHTMLTemplateElement(this)); if (nextChild.previousSibling() == newChild || &nextChild == newChild) // nothing to do return; if (!checkParserAcceptChild(*newChild)) return; RefPtrWillBeRawPtr<Node> protect(this); while (RefPtrWillBeRawPtr<ContainerNode> parent = newChild->parentNode()) parent->parserRemoveChild(*newChild); if (nextChild.parentNode() != this) return; if (document() != newChild->document()) document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION); { EventDispatchForbiddenScope assertNoEventDispatch; ScriptForbiddenScope forbidScript; treeScope().adoptIfNeeded(*newChild); insertBeforeCommon(nextChild, *newChild); newChild->updateAncestorConnectedSubframeCountForInsertion(); ChildListMutationScope(*this).childAdded(*newChild); } notifyNodeInserted(*newChild, ChildrenChangeSourceParser); }
171,850
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: store_image_row(PNG_CONST png_store* ps, png_const_structp pp, int nImage, png_uint_32 y) { png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2; if (ps->image == NULL) png_error(pp, "no allocated image"); if (coffset + ps->cb_row + 3 > ps->cb_image) png_error(pp, "image too small"); return ps->image + coffset; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
store_image_row(PNG_CONST png_store* ps, png_const_structp pp, int nImage, store_image_row(const png_store* ps, png_const_structp pp, int nImage, png_uint_32 y) { png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2; if (ps->image == NULL) png_error(pp, "no allocated image"); if (coffset + ps->cb_row + 3 > ps->cb_image) png_error(pp, "image too small"); return ps->image + coffset; }
173,705
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long Segment::Load() { assert(m_clusters == NULL); assert(m_clusterSize == 0); assert(m_clusterCount == 0); const long long header_status = ParseHeaders(); if (header_status < 0) // error return static_cast<long>(header_status); if (header_status > 0) // underflow return E_BUFFER_NOT_FULL; assert(m_pInfo); assert(m_pTracks); for (;;) { const int status = LoadCluster(); if (status < 0) // error return status; if (status >= 1) // no more clusters return 0; } } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Segment::Load() { assert(m_clusters == NULL); assert(m_clusterSize == 0); assert(m_clusterCount == 0); const long long header_status = ParseHeaders(); if (header_status < 0) // error return static_cast<long>(header_status); if (header_status > 0) // underflow return E_BUFFER_NOT_FULL; if (m_pInfo == NULL || m_pTracks == NULL) return E_FILE_FORMAT_INVALID; for (;;) { const int status = LoadCluster(); if (status < 0) // error return status; if (status >= 1) // no more clusters return 0; } }
173,828
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void fput(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { struct task_struct *task = current; file_sb_list_del(file); if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) { init_task_work(&file->f_u.fu_rcuhead, ____fput); if (!task_work_add(task, &file->f_u.fu_rcuhead, true)) return; /* * After this task has run exit_task_work(), * task_work_add() will fail. Fall through to delayed * fput to avoid leaking *file. */ } if (llist_add(&file->f_u.fu_llist, &delayed_fput_list)) schedule_work(&delayed_fput_work); } } Commit Message: get rid of s_files and files_lock The only thing we need it for is alt-sysrq-r (emergency remount r/o) and these days we can do just as well without going through the list of files. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-17
void fput(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { struct task_struct *task = current; if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) { init_task_work(&file->f_u.fu_rcuhead, ____fput); if (!task_work_add(task, &file->f_u.fu_rcuhead, true)) return; /* * After this task has run exit_task_work(), * task_work_add() will fail. Fall through to delayed * fput to avoid leaking *file. */ } if (llist_add(&file->f_u.fu_llist, &delayed_fput_list)) schedule_work(&delayed_fput_work); } }
166,801
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info("problem id: '%s'", problem_id); return problem_id; } Commit Message: make the dump directories owned by root by default It was discovered that the abrt event scripts create a user-readable copy of a sosreport file in abrt problem directories, and include excerpts of /var/log/messages selected by the user-controlled process name, leading to an information disclosure. This issue was discovered by Florian Weimer of Red Hat Product Security. Related: #1212868 Signed-off-by: Jakub Filak <jfilak@redhat.com> CWE ID: CWE-200
char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = NULL; if (g_settings_privatereports) dd = create_dump_dir_from_problem_data_ext(pd, g_settings_dump_location, 0); else dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info("problem id: '%s'", problem_id); return problem_id; }
170,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem ) { cJSON *c = array->child; while ( c && which > 0 ) { c = c->next; --which; } if ( ! c ) return; newitem->next = c->next; newitem->prev = c->prev; if ( newitem->next ) newitem->next->prev = newitem; if ( c == array->child ) array->child = newitem; else newitem->prev->next = newitem; c->next = c->prev = 0; cJSON_Delete( c ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
void cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem )
167,295
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: xsltFindTemplate(xsltTransformContextPtr ctxt, const xmlChar *name, const xmlChar *nameURI) { xsltTemplatePtr cur; xsltStylesheetPtr style; if ((ctxt == NULL) || (name == NULL)) return(NULL); style = ctxt->style; while (style != NULL) { cur = style->templates; while (cur != NULL) { if (xmlStrEqual(name, cur->name)) { if (((nameURI == NULL) && (cur->nameURI == NULL)) || ((nameURI != NULL) && (cur->nameURI != NULL) && (xmlStrEqual(nameURI, cur->nameURI)))) { return(cur); } } cur = cur->next; } style = xsltNextImport(style); } return(NULL); } 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
xsltFindTemplate(xsltTransformContextPtr ctxt, const xmlChar *name, const xmlChar *nameURI) { xsltTemplatePtr cur; xsltStylesheetPtr style; if ((ctxt == NULL) || (name == NULL)) return(NULL); style = ctxt->style; while (style != NULL) { if (style->namedTemplates != NULL) { cur = (xsltTemplatePtr) xmlHashLookup2(style->namedTemplates, name, nameURI); if (cur != NULL) return(cur); } style = xsltNextImport(style); } return(NULL); }
173,303
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void qrio_cpuwd_flag(bool flag) { u8 reason1; void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE; reason1 = in_8(qrio_base + REASON1_OFF); if (flag) reason1 |= REASON1_CPUWD; else reason1 &= ~REASON1_CPUWD; out_8(qrio_base + REASON1_OFF, reason1); } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
void qrio_cpuwd_flag(bool flag) { u8 reason1; void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE; reason1 = in_8(qrio_base + REASON1_OFF); if (flag) reason1 |= REASON1_CPUWD; else reason1 &= ~REASON1_CPUWD; out_8(qrio_base + REASON1_OFF, reason1); }
169,624
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WebContentsImpl::AttachInterstitialPage( InterstitialPageImpl* interstitial_page) { DCHECK(interstitial_page); GetRenderManager()->set_interstitial_page(interstitial_page); CancelActiveAndPendingDialogs(); for (auto& observer : observers_) observer.DidAttachInterstitialPage(); if (frame_tree_.IsLoading()) LoadingStateChanged(true, true, nullptr); if (node_.OuterContentsFrameTreeNode()) { if (GetRenderManager()->GetProxyToOuterDelegate()) { DCHECK( static_cast<RenderWidgetHostViewBase*>(interstitial_page->GetView()) ->IsRenderWidgetHostViewChildFrame()); RenderWidgetHostViewChildFrame* view = static_cast<RenderWidgetHostViewChildFrame*>( interstitial_page->GetView()); GetRenderManager()->SetRWHViewForInnerContents(view); } } } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
void WebContentsImpl::AttachInterstitialPage( InterstitialPageImpl* interstitial_page) { DCHECK(!interstitial_page_ && interstitial_page); interstitial_page_ = interstitial_page; CancelActiveAndPendingDialogs(); for (auto& observer : observers_) observer.DidAttachInterstitialPage(); if (frame_tree_.IsLoading()) LoadingStateChanged(true, true, nullptr); if (node_.OuterContentsFrameTreeNode()) { if (GetRenderManager()->GetProxyToOuterDelegate()) { DCHECK( static_cast<RenderWidgetHostViewBase*>(interstitial_page->GetView()) ->IsRenderWidgetHostViewChildFrame()); RenderWidgetHostViewChildFrame* view = static_cast<RenderWidgetHostViewChildFrame*>( interstitial_page->GetView()); GetRenderManager()->SetRWHViewForInnerContents(view); } } }
172,324
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SchedulerObject::setAttribute(std::string key, std::string name, std::string value, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "SetAttribute: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (isSubmissionChange(name.c_str())) { text = "Changes to submission name not allowed"; return false; } if (isKeyword(name.c_str())) { text = "Attribute name is reserved: " + name; return false; } if (!isValidAttributeName(name,text)) { return false; } if (::SetAttribute(id.cluster, id.proc, name.c_str(), value.c_str())) { text = "Failed to set attribute " + name + " to " + value; return false; } return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::setAttribute(std::string key, std::string name, std::string value, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "SetAttribute: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (isSubmissionChange(name.c_str())) { text = "Changes to submission name not allowed"; return false; } if (isKeyword(name.c_str())) { text = "Attribute name is reserved: " + name; return false; } if (!isValidAttributeName(name,text)) { return false; } if (::SetAttribute(id.cluster, id.proc, name.c_str(), value.c_str())) { text = "Failed to set attribute " + name + " to " + value; return false; } return true; }
164,835
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool Chapters::Atom::ExpandDisplaysArray() { if (m_displays_size > m_displays_count) return true; // nothing else to do const int size = (m_displays_size == 0) ? 1 : 2 * m_displays_size; Display* const displays = new (std::nothrow) Display[size]; if (displays == NULL) return false; for (int idx = 0; idx < m_displays_count; ++idx) { m_displays[idx].ShallowCopy(displays[idx]); } delete[] m_displays; m_displays = displays; m_displays_size = size; 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 Chapters::Atom::ExpandDisplaysArray()
174,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ConnectIBusSignals() { if (!ibus_) { return; } g_signal_connect_after(ibus_, "connected", G_CALLBACK(IBusBusConnectedCallback), this); g_signal_connect(ibus_, "disconnected", G_CALLBACK(IBusBusDisconnectedCallback), this); g_signal_connect(ibus_, "global-engine-changed", G_CALLBACK(IBusBusGlobalEngineChangedCallback), this); g_signal_connect(ibus_, "name-owner-changed", G_CALLBACK(IBusBusNameOwnerChangedCallback), this); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void ConnectIBusSignals() { if (!ibus_) { return; } g_signal_connect_after(ibus_, "connected", G_CALLBACK(IBusBusConnectedThunk), this); g_signal_connect(ibus_, "disconnected", G_CALLBACK(IBusBusDisconnectedThunk), this); g_signal_connect(ibus_, "global-engine-changed", G_CALLBACK(IBusBusGlobalEngineChangedThunk), this); g_signal_connect(ibus_, "name-owner-changed", G_CALLBACK(IBusBusNameOwnerChangedThunk), this); }
170,529
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static uint32_t readU32(const uint8_t* data, size_t offset) { return data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]; } Commit Message: Avoid integer overflows in parsing fonts A malformed TTF can cause size calculations to overflow. This patch checks the maximum reasonable value so that the total size fits in 32 bits. It also adds some explicit casting to avoid possible technical undefined behavior when parsing sized unsigned values. Bug: 25645298 Change-Id: Id4716132041a6f4f1fbb73ec4e445391cf7d9616 (cherry picked from commit 183c9ec2800baa2ce099ee260c6cbc6121cf1274) CWE ID: CWE-19
static uint32_t readU32(const uint8_t* data, size_t offset) { return ((uint32_t)data[offset]) << 24 | ((uint32_t)data[offset + 1]) << 16 | ((uint32_t)data[offset + 2]) << 8 | ((uint32_t)data[offset + 3]); }
173,967
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void update_open_stateflags(struct nfs4_state *state, mode_t open_flags) { switch (open_flags) { case FMODE_WRITE: state->n_wronly++; break; case FMODE_READ: state->n_rdonly++; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr++; } nfs4_state_set_mode_locked(state, state->state | open_flags); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
static void update_open_stateflags(struct nfs4_state *state, mode_t open_flags) static void update_open_stateflags(struct nfs4_state *state, fmode_t fmode) { switch (fmode) { case FMODE_WRITE: state->n_wronly++; break; case FMODE_READ: state->n_rdonly++; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr++; } nfs4_state_set_mode_locked(state, state->state | fmode); }
165,707
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void ncq_err(NCQTransferState *ncq_tfs) { IDEState *ide_state = &ncq_tfs->drive->port.ifs[0]; ide_state->error = ABRT_ERR; ide_state->status = READY_STAT | ERR_STAT; ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag); } Commit Message: CWE ID:
static void ncq_err(NCQTransferState *ncq_tfs) { IDEState *ide_state = &ncq_tfs->drive->port.ifs[0]; ide_state->error = ABRT_ERR; ide_state->status = READY_STAT | ERR_STAT; ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag); ncq_tfs->used = 0; }
165,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int crypto_rng_reset(struct crypto_rng *tfm, const u8 *seed, unsigned int slen) { u8 *buf = NULL; int err; if (!seed && slen) { buf = kmalloc(slen, GFP_KERNEL); if (!buf) return -ENOMEM; get_random_bytes(buf, slen); seed = buf; } err = tfm->seed(tfm, seed, slen); kfree(buf); return err; } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-476
int crypto_rng_reset(struct crypto_rng *tfm, const u8 *seed, unsigned int slen) { u8 *buf = NULL; int err; if (!seed && slen) { buf = kmalloc(slen, GFP_KERNEL); if (!buf) return -ENOMEM; get_random_bytes(buf, slen); seed = buf; } err = crypto_rng_alg(tfm)->seed(tfm, seed, slen); kfree(buf); return err; }
167,732
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: FileEntrySync* DirectoryEntrySync::getFile(const String& path, const Dictionary& options, ExceptionState& exceptionState) { FileSystemFlags flags(options); RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create(); m_fileSystem->getFile(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); return static_cast<FileEntrySync*>(helper->getResult(exceptionState)); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
FileEntrySync* DirectoryEntrySync::getFile(const String& path, const Dictionary& options, ExceptionState& exceptionState) { FileSystemFlags flags(options); EntrySyncCallbackHelper* helper = EntrySyncCallbackHelper::create(); m_fileSystem->getFile(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); return static_cast<FileEntrySync*>(helper->getResult(exceptionState)); }
171,418
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: OMX_ERRORTYPE SoftAVC::setConfig( OMX_INDEXTYPE index, const OMX_PTR _params) { switch (index) { case OMX_IndexConfigVideoIntraVOPRefresh: { OMX_CONFIG_INTRAREFRESHVOPTYPE *params = (OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params; if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } mKeyFrameRequested = params->IntraRefreshVOP; return OMX_ErrorNone; } case OMX_IndexConfigVideoBitrate: { OMX_VIDEO_CONFIG_BITRATETYPE *params = (OMX_VIDEO_CONFIG_BITRATETYPE *)_params; if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } if (mBitrate != params->nEncodeBitrate) { mBitrate = params->nEncodeBitrate; mBitrateUpdated = true; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::setConfig(index, _params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAVC::setConfig( OMX_INDEXTYPE index, const OMX_PTR _params) { switch (index) { case OMX_IndexConfigVideoIntraVOPRefresh: { OMX_CONFIG_INTRAREFRESHVOPTYPE *params = (OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params; if (!isValidOMXParam(params)) { return OMX_ErrorBadParameter; } if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } mKeyFrameRequested = params->IntraRefreshVOP; return OMX_ErrorNone; } case OMX_IndexConfigVideoBitrate: { OMX_VIDEO_CONFIG_BITRATETYPE *params = (OMX_VIDEO_CONFIG_BITRATETYPE *)_params; if (!isValidOMXParam(params)) { return OMX_ErrorBadParameter; } if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } if (mBitrate != params->nEncodeBitrate) { mBitrate = params->nEncodeBitrate; mBitrateUpdated = true; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::setConfig(index, _params); } }
174,202
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ProcXFixesSetCursorName(ClientPtr client) { CursorPtr pCursor; char *tchar; REQUEST(xXFixesSetCursorNameReq); REQUEST(xXFixesSetCursorNameReq); Atom atom; REQUEST_AT_LEAST_SIZE(xXFixesSetCursorNameReq); VERIFY_CURSOR(pCursor, stuff->cursor, client, DixSetAttrAccess); tchar = (char *) &stuff[1]; atom = MakeAtom(tchar, stuff->nbytes, TRUE); return BadAlloc; pCursor->name = atom; return Success; } Commit Message: CWE ID: CWE-20
ProcXFixesSetCursorName(ClientPtr client) { CursorPtr pCursor; char *tchar; REQUEST(xXFixesSetCursorNameReq); REQUEST(xXFixesSetCursorNameReq); Atom atom; REQUEST_FIXED_SIZE(xXFixesSetCursorNameReq, stuff->nbytes); VERIFY_CURSOR(pCursor, stuff->cursor, client, DixSetAttrAccess); tchar = (char *) &stuff[1]; atom = MakeAtom(tchar, stuff->nbytes, TRUE); return BadAlloc; pCursor->name = atom; return Success; }
165,439
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec) { struct mrb_context *c = fiber_check(mrb, self); struct mrb_context *old_c = mrb->c; mrb_value value; fiber_check_cfunc(mrb, c); if (resume && c->status == MRB_FIBER_TRANSFERRED) { mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber"); } if (c->status == MRB_FIBER_RUNNING || c->status == MRB_FIBER_RESUMED) { mrb_raise(mrb, E_FIBER_ERROR, "double resume (fib)"); } if (c->status == MRB_FIBER_TERMINATED) { mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber"); } mrb->c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED; c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c); if (c->status == MRB_FIBER_CREATED) { mrb_value *b, *e; if (len >= c->stend - c->stack) { mrb_raise(mrb, E_FIBER_ERROR, "too many arguments to fiber"); } b = c->stack+1; e = b + len; while (b<e) { *b++ = *a++; } c->cibase->argc = (int)len; value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0]; } else { value = fiber_result(mrb, a, len); } fiber_switch_context(mrb, c); if (vmexec) { c->vmexec = TRUE; value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc); mrb->c = old_c; } else { MARK_CONTEXT_MODIFY(c); } return value; } Commit Message: Extend stack when pushing arguments that does not fit in; fix #4038 CWE ID: CWE-125
fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec) { struct mrb_context *c = fiber_check(mrb, self); struct mrb_context *old_c = mrb->c; enum mrb_fiber_state status; mrb_value value; fiber_check_cfunc(mrb, c); status = c->status; if (resume && status == MRB_FIBER_TRANSFERRED) { mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber"); } if (status == MRB_FIBER_RUNNING || status == MRB_FIBER_RESUMED) { mrb_raise(mrb, E_FIBER_ERROR, "double resume (fib)"); } if (status == MRB_FIBER_TERMINATED) { mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber"); } old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED; c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c); fiber_switch_context(mrb, c); if (status == MRB_FIBER_CREATED) { mrb_value *b, *e; mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */ b = c->stack+1; e = b + len; while (b<e) { *b++ = *a++; } c->cibase->argc = (int)len; value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0]; } else { value = fiber_result(mrb, a, len); } if (vmexec) { c->vmexec = TRUE; value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc); mrb->c = old_c; } else { MARK_CONTEXT_MODIFY(c); } return value; }
169,201
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: jp2_box_t *jp2_box_create(int type) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { return 0; } memset(box, 0, sizeof(jp2_box_t)); box->type = type; box->len = 0; if (!(boxinfo = jp2_boxinfolookup(type))) { return 0; } box->info = boxinfo; box->ops = &boxinfo->ops; return box; } Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems. CWE ID: CWE-476
jp2_box_t *jp2_box_create(int type) jp2_box_t *jp2_box_create0() { jp2_box_t *box; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { return 0; } memset(box, 0, sizeof(jp2_box_t)); box->type = 0; box->len = 0; // Mark the box data as never having been constructed // so that we will not errantly attempt to destroy it later. box->ops = &jp2_boxinfo_unk.ops; return box; } jp2_box_t *jp2_box_create(int type) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; if (!(box = jp2_box_create0())) { return 0; } box->type = type; box->len = 0; if (!(boxinfo = jp2_boxinfolookup(type))) { return 0; } box->info = boxinfo; box->ops = &boxinfo->ops; return box; }
168,317
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(mcrypt_encrypt) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_string_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_ENCRYPT, return_value TSRMLS_CC); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_encrypt) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_string_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_ENCRYPT, return_value TSRMLS_CC); }
167,106
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static char *__filterShell(const char *arg) { r_return_val_if_fail (arg, NULL); char *a = malloc (strlen (arg) + 1); if (!a) { return NULL; } char *b = a; while (*arg) { switch (*arg) { case '@': case '`': case '|': case ';': case '\n': break; default: *b++ = *arg; break; } arg++; } *b = 0; return a; } Commit Message: More fixes for the CVE-2019-14745 CWE ID: CWE-78
static char *__filterShell(const char *arg) { r_return_val_if_fail (arg, NULL); char *a = malloc (strlen (arg) + 1); if (!a) { return NULL; } char *b = a; while (*arg) { char ch = *arg; switch (ch) { case '@': case '`': case '|': case ';': case '=': case '\n': break; default: *b++ = ch; break; } arg++; } *b = 0; return a; }
170,185
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: my_object_async_increment (MyObject *obj, gint32 x, DBusGMethodInvocation *context) { IncrementData *data = g_new0 (IncrementData, 1); data->x = x; data->context = context; g_idle_add ((GSourceFunc)do_async_increment, data); } Commit Message: CWE ID: CWE-264
my_object_async_increment (MyObject *obj, gint32 x, DBusGMethodInvocation *context)
165,088
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: cid_parse_font_matrix( CID_Face face, CID_Parser* parser ) { CID_FaceDict dict; FT_Face root = (FT_Face)&face->root; FT_Fixed temp[6]; FT_Fixed temp_scale; if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts ) { FT_Matrix* matrix; FT_Vector* offset; dict = face->cid.font_dicts + parser->num_dict; matrix = &dict->font_matrix; offset = &dict->font_offset; (void)cid_parser_to_fixed_array( parser, 6, temp, 3 ); temp_scale = FT_ABS( temp[3] ); /* Set Units per EM based on FontMatrix values. We set the value to */ /* 1000 / temp_scale, because temp_scale was already multiplied by */ /* 1000 (in t1_tofixed, from psobjs.c). */ temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = 0x10000L; } matrix->xx = temp[0]; matrix->yx = temp[1]; matrix->xy = temp[2]; matrix->yy = temp[3]; temp[2] = FT_DivFix( temp[2], temp_scale ); temp[4] = FT_DivFix( temp[4], temp_scale ); temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = 0x10000L; } Commit Message: CWE ID: CWE-20
cid_parse_font_matrix( CID_Face face, CID_Parser* parser ) { CID_FaceDict dict; FT_Face root = (FT_Face)&face->root; FT_Fixed temp[6]; FT_Fixed temp_scale; if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts ) { FT_Matrix* matrix; FT_Vector* offset; FT_Int result; dict = face->cid.font_dicts + parser->num_dict; matrix = &dict->font_matrix; offset = &dict->font_offset; result = cid_parser_to_fixed_array( parser, 6, temp, 3 ); if ( result < 6 ) return FT_THROW( Invalid_File_Format ); temp_scale = FT_ABS( temp[3] ); if ( temp_scale == 0 ) { FT_ERROR(( "cid_parse_font_matrix: invalid font matrix\n" )); return FT_THROW( Invalid_File_Format ); } /* Set Units per EM based on FontMatrix values. We set the value to */ /* 1000 / temp_scale, because temp_scale was already multiplied by */ /* 1000 (in t1_tofixed, from psobjs.c). */ temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = 0x10000L; } matrix->xx = temp[0]; matrix->yx = temp[1]; matrix->xy = temp[2]; matrix->yy = temp[3]; temp[2] = FT_DivFix( temp[2], temp_scale ); temp[4] = FT_DivFix( temp[4], temp_scale ); temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L; }
165,341
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void finalizeStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().finalizeStream(blobRegistryContext->url); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static void finalizeStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); if (WebBlobRegistry* registry = blobRegistry()) registry->finalizeStream(blobRegistryContext->url); }
170,683
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index++; do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index++; do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } }
167,087
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(SplFileInfo, __construct) { spl_filesystem_object *intern; char *path; int len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); /* intern->type = SPL_FS_INFO; already set */ } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, __construct) { spl_filesystem_object *intern; char *path; int len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); /* intern->type = SPL_FS_INFO; already set */ }
167,038
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */
167,068
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PushMessagingServiceImpl::PushMessagingServiceImpl(Profile* profile) : profile_(profile), push_subscription_count_(0), pending_push_subscription_count_(0), notification_manager_(profile), push_messaging_service_observer_(PushMessagingServiceObserver::Create()), weak_factory_(this) { DCHECK(profile); HostContentSettingsMapFactory::GetForProfile(profile_)->AddObserver(this); registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, content::NotificationService::AllSources()); } Commit Message: Remove some senseless indirection from the Push API code Four files to call one Java function. Let's just call it directly. BUG= Change-Id: I6e988e9a000051dd7e3dd2b517a33a09afc2fff6 Reviewed-on: https://chromium-review.googlesource.com/749147 Reviewed-by: Anita Woodruff <awdf@chromium.org> Commit-Queue: Peter Beverloo <peter@chromium.org> Cr-Commit-Position: refs/heads/master@{#513464} CWE ID: CWE-119
PushMessagingServiceImpl::PushMessagingServiceImpl(Profile* profile) : profile_(profile), push_subscription_count_(0), pending_push_subscription_count_(0), notification_manager_(profile), weak_factory_(this) { DCHECK(profile); HostContentSettingsMapFactory::GetForProfile(profile_)->AddObserver(this); registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, content::NotificationService::AllSources()); }
172,942
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long Cluster::GetNext( const BlockEntry* pCurr, const BlockEntry*& pNext) const { assert(pCurr); assert(m_entries); assert(m_entries_count > 0); size_t idx = pCurr->GetIndex(); assert(idx < size_t(m_entries_count)); assert(m_entries[idx] == pCurr); ++idx; if (idx >= size_t(m_entries_count)) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) //error { pNext = NULL; return status; } if (status > 0) { pNext = NULL; return 0; } assert(m_entries); assert(m_entries_count > 0); assert(idx < size_t(m_entries_count)); } pNext = m_entries[idx]; assert(pNext); 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 Cluster::GetNext( size_t idx = pCurr->GetIndex(); assert(idx < size_t(m_entries_count)); assert(m_entries[idx] == pCurr); ++idx; if (idx >= size_t(m_entries_count)) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) { // error pNext = NULL; return status; } if (status > 0) { pNext = NULL; return 0; } assert(m_entries); assert(m_entries_count > 0); assert(idx < size_t(m_entries_count)); } pNext = m_entries[idx]; assert(pNext); return 0; }
174,345
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(RecursiveDirectoryIterator, getSubPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *sub_name; int len; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); RETURN_STRINGL(sub_name, len, 0); } else { RETURN_STRING(intern->u.dir.entry.d_name, 1); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(RecursiveDirectoryIterator, getSubPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *sub_name; int len; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); RETURN_STRINGL(sub_name, len, 0); } else { RETURN_STRING(intern->u.dir.entry.d_name, 1); } }
167,047
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_, long long size_) { const long long stop = start_ + size_; long long pos = start_; m_track = -1; m_pos = -1; m_block = 1; // default while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); // TODO assert((pos + len) <= stop); pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; // consume Size field assert((pos + size) <= stop); if (id == 0x77) // CueTrack ID m_track = UnserializeUInt(pReader, pos, size); else if (id == 0x71) // CueClusterPos ID m_pos = UnserializeUInt(pReader, pos, size); else if (id == 0x1378) // CueBlockNumber m_block = UnserializeUInt(pReader, pos, size); pos += size; // consume payload assert(pos <= stop); } assert(m_pos >= 0); assert(m_track > 0); } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
void CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_, bool CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_, long long size_) { const long long stop = start_ + size_; long long pos = start_; m_track = -1; m_pos = -1; m_block = 1; // default while (pos < stop) { long len; const long long id = ReadID(pReader, pos, len); if ((id < 0) || ((pos + len) > stop)) { return false; } pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); if ((size < 0) || ((pos + len) > stop)) { return false; } pos += len; // consume Size field if ((pos + size) > stop) { return false; } if (id == 0x77) // CueTrack ID m_track = UnserializeUInt(pReader, pos, size); else if (id == 0x71) // CueClusterPos ID m_pos = UnserializeUInt(pReader, pos, size); else if (id == 0x1378) // CueBlockNumber m_block = UnserializeUInt(pReader, pos, size); pos += size; // consume payload } if ((m_pos < 0) || (m_track <= 0)) { return false; } return true; }
173,837
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: nfs3svc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readdirargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->cookie); args->verf = p; p += 2; args->dircount = ~0; args->count = ntohl(*p++); args->count = min_t(u32, args->count, PAGE_SIZE); args->buffer = page_address(*(rqstp->rq_next_page++)); return xdr_argsize_check(rqstp, p); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfs3svc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readdirargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->cookie); args->verf = p; p += 2; args->dircount = ~0; args->count = ntohl(*p++); if (!xdr_argsize_check(rqstp, p)) return 0; args->count = min_t(u32, args->count, PAGE_SIZE); args->buffer = page_address(*(rqstp->rq_next_page++)); return 1; }
168,141
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: Blob::Blob(const KURL& srcURL, const String& type, long long size) : m_type(type) , m_size(size) { ScriptWrappable::init(this); m_internalURL = BlobURL::createInternalURL(); ThreadableBlobRegistry::registerBlobURL(0, m_internalURL, srcURL); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
Blob::Blob(const KURL& srcURL, const String& type, long long size) : m_type(type) , m_size(size) { ScriptWrappable::init(this); m_internalURL = BlobURL::createInternalURL(); BlobRegistry::registerBlobURL(0, m_internalURL, srcURL); }
170,676
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int btsock_thread_exit(int h) { if(h < 0 || h >= MAX_THREAD) { APPL_TRACE_ERROR("invalid bt thread handle:%d", h); return FALSE; } if(ts[h].cmd_fdw == -1) { APPL_TRACE_ERROR("cmd socket is not created"); return FALSE; } sock_cmd_t cmd = {CMD_EXIT, 0, 0, 0, 0}; if(send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd)) { pthread_join(ts[h].thread_id, 0); pthread_mutex_lock(&thread_slot_lock); free_thread_slot(h); pthread_mutex_unlock(&thread_slot_lock); return TRUE; } return FALSE; } 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
int btsock_thread_exit(int h) { if(h < 0 || h >= MAX_THREAD) { APPL_TRACE_ERROR("invalid bt thread handle:%d", h); return FALSE; } if(ts[h].cmd_fdw == -1) { APPL_TRACE_ERROR("cmd socket is not created"); return FALSE; } sock_cmd_t cmd = {CMD_EXIT, 0, 0, 0, 0}; if(TEMP_FAILURE_RETRY(send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0)) == sizeof(cmd)) { pthread_join(ts[h].thread_id, 0); pthread_mutex_lock(&thread_slot_lock); free_thread_slot(h); pthread_mutex_unlock(&thread_slot_lock); return TRUE; } return FALSE; }
173,461
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: foreach_nfs_shareopt(const char *shareopts, nfs_shareopt_callback_t callback, void *cookie) { char *shareopts_dup, *opt, *cur, *value; int was_nul, rc; if (shareopts == NULL) return (SA_OK); shareopts_dup = strdup(shareopts); if (shareopts_dup == NULL) return (SA_NO_MEMORY); opt = shareopts_dup; was_nul = 0; while (1) { cur = opt; while (*cur != ',' && *cur != '\0') cur++; if (*cur == '\0') was_nul = 1; *cur = '\0'; if (cur > opt) { value = strchr(opt, '='); if (value != NULL) { *value = '\0'; value++; } rc = callback(opt, value, cookie); if (rc != SA_OK) { free(shareopts_dup); return (rc); } } opt = cur + 1; if (was_nul) break; } free(shareopts_dup); return (0); } Commit Message: Move nfs.c:foreach_nfs_shareopt() to libshare.c:foreach_shareopt() so that it can be (re)used in other parts of libshare. CWE ID: CWE-200
foreach_nfs_shareopt(const char *shareopts,
170,133
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused) { ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d", fd, offset, length, priority); Mutex::Autolock lock(&mLock); sp<Sample> sample = new Sample(++mNextSampleID, fd, offset, length); mSamples.add(sample->sampleID(), sample); doLoad(sample); return sample->sampleID(); } Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread Sample decoding still occurs in SoundPoolThread without holding the SoundPool lock. Bug: 25781119 Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8 CWE ID: CWE-264
int SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused) { ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d", fd, offset, length, priority);
173,962
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void diff_bytes_c(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, int w){ long i; #if !HAVE_FAST_UNALIGNED if((long)src2 & (sizeof(long)-1)){ for(i=0; i+7<w; i+=8){ dst[i+0] = src1[i+0]-src2[i+0]; dst[i+1] = src1[i+1]-src2[i+1]; dst[i+2] = src1[i+2]-src2[i+2]; dst[i+3] = src1[i+3]-src2[i+3]; dst[i+4] = src1[i+4]-src2[i+4]; dst[i+5] = src1[i+5]-src2[i+5]; dst[i+6] = src1[i+6]-src2[i+6]; dst[i+7] = src1[i+7]-src2[i+7]; } }else #endif for(i=0; i<=w-sizeof(long); i+=sizeof(long)){ long a = *(long*)(src1+i); long b = *(long*)(src2+i); *(long*)(dst+i) = ((a|pb_80) - (b&pb_7f)) ^ ((a^b^pb_80)&pb_80); } for(; i<w; i++) dst[i+0] = src1[i+0]-src2[i+0]; } Commit Message: avcodec/dsputil: fix signedness in sizeof() comparissions Signed-off-by: Michael Niedermayer <michaelni@gmx.at> CWE ID: CWE-189
static void diff_bytes_c(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, int w){ long i; #if !HAVE_FAST_UNALIGNED if((long)src2 & (sizeof(long)-1)){ for(i=0; i+7<w; i+=8){ dst[i+0] = src1[i+0]-src2[i+0]; dst[i+1] = src1[i+1]-src2[i+1]; dst[i+2] = src1[i+2]-src2[i+2]; dst[i+3] = src1[i+3]-src2[i+3]; dst[i+4] = src1[i+4]-src2[i+4]; dst[i+5] = src1[i+5]-src2[i+5]; dst[i+6] = src1[i+6]-src2[i+6]; dst[i+7] = src1[i+7]-src2[i+7]; } }else #endif for(i=0; i<=w-(int)sizeof(long); i+=sizeof(long)){ long a = *(long*)(src1+i); long b = *(long*)(src2+i); *(long*)(dst+i) = ((a|pb_80) - (b&pb_7f)) ^ ((a^b^pb_80)&pb_80); } for(; i<w; i++) dst[i+0] = src1[i+0]-src2[i+0]; }
165,930
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WebPluginProxy::SetWindowlessPumpEvent(HANDLE pump_messages_event) { HANDLE pump_messages_event_for_renderer = NULL; DuplicateHandle(GetCurrentProcess(), pump_messages_event, channel_->renderer_handle(), &pump_messages_event_for_renderer, 0, FALSE, DUPLICATE_SAME_ACCESS); DCHECK(pump_messages_event_for_renderer != NULL); Send(new PluginHostMsg_SetWindowlessPumpEvent( route_id_, pump_messages_event_for_renderer)); } 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 WebPluginProxy::SetWindowlessPumpEvent(HANDLE pump_messages_event) { HANDLE pump_messages_event_for_renderer = NULL; sandbox::BrokerDuplicateHandle(pump_messages_event, channel_->peer_pid(), &pump_messages_event_for_renderer, SYNCHRONIZE | EVENT_MODIFY_STATE, 0); DCHECK(pump_messages_event_for_renderer != NULL); Send(new PluginHostMsg_SetWindowlessPumpEvent( route_id_, pump_messages_event_for_renderer)); }
170,953
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void MediaElementAudioSourceHandler::SetFormat(size_t number_of_channels, float source_sample_rate) { if (number_of_channels != source_number_of_channels_ || source_sample_rate != source_sample_rate_) { if (!number_of_channels || number_of_channels > BaseAudioContext::MaxNumberOfChannels() || !AudioUtilities::IsValidAudioBufferSampleRate(source_sample_rate)) { DLOG(ERROR) << "setFormat(" << number_of_channels << ", " << source_sample_rate << ") - unhandled format change"; Locker<MediaElementAudioSourceHandler> locker(*this); source_number_of_channels_ = 0; source_sample_rate_ = 0; return; } Locker<MediaElementAudioSourceHandler> locker(*this); source_number_of_channels_ = number_of_channels; source_sample_rate_ = source_sample_rate; if (source_sample_rate != Context()->sampleRate()) { double scale_factor = source_sample_rate / Context()->sampleRate(); multi_channel_resampler_ = std::make_unique<MultiChannelResampler>( scale_factor, number_of_channels); } else { multi_channel_resampler_.reset(); } { BaseAudioContext::GraphAutoLocker context_locker(Context()); Output(0).SetNumberOfChannels(number_of_channels); } } } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <rtoy@chromium.org> Reviewed-by: Yutaka Hirano <yhirano@chromium.org> Reviewed-by: Hongchan Choi <hongchan@chromium.org> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
void MediaElementAudioSourceHandler::SetFormat(size_t number_of_channels, float source_sample_rate) { bool is_tainted = WouldTaintOrigin(); if (is_tainted) { PrintCORSMessage(MediaElement()->currentSrc().GetString()); } if (number_of_channels != source_number_of_channels_ || source_sample_rate != source_sample_rate_) { if (!number_of_channels || number_of_channels > BaseAudioContext::MaxNumberOfChannels() || !AudioUtilities::IsValidAudioBufferSampleRate(source_sample_rate)) { DLOG(ERROR) << "setFormat(" << number_of_channels << ", " << source_sample_rate << ") - unhandled format change"; Locker<MediaElementAudioSourceHandler> locker(*this); source_number_of_channels_ = 0; source_sample_rate_ = 0; is_origin_tainted_ = is_tainted; return; } // Synchronize with process() to protect |source_number_of_channels_|, // |source_sample_rate_|, |multi_channel_resampler_|. and // |is_origin_tainted_|. Locker<MediaElementAudioSourceHandler> locker(*this); is_origin_tainted_ = is_tainted; source_number_of_channels_ = number_of_channels; source_sample_rate_ = source_sample_rate; if (source_sample_rate != Context()->sampleRate()) { double scale_factor = source_sample_rate / Context()->sampleRate(); multi_channel_resampler_ = std::make_unique<MultiChannelResampler>( scale_factor, number_of_channels); } else { multi_channel_resampler_.reset(); } { BaseAudioContext::GraphAutoLocker context_locker(Context()); Output(0).SetNumberOfChannels(number_of_channels); } } }
173,150
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=image->columns*quantum; if (quantum != (extent/image->columns)) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/110 CWE ID: CWE-369
MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=image->columns*quantum; if ((image->columns != 0) && (quantum != (extent/image->columns))) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); }
170,113
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx, Packet *p, Flow * const pflow) { PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP); /* cleanup pkt specific part of the patternmatcher */ PacketPatternCleanup(det_ctx); if (pflow != NULL) { /* update inspected tracker for raw reassembly */ if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL) { StreamReassembleRawUpdateProgress(pflow->protoctx, p, det_ctx->raw_stream_progress); DetectEngineCleanHCBDBuffers(det_ctx); } } PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP); SCReturn; } Commit Message: stream: fix false negative on bad RST If a bad RST was received the stream inspection would not happen for that packet, but it would still move the 'raw progress' tracker forward. Following good packets would then fail to detect anything before the 'raw progress' position. Bug #2770 Reported-by: Alexey Vishnyakov CWE ID: CWE-347
static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx, Packet *p, Flow * const pflow) { PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP); /* cleanup pkt specific part of the patternmatcher */ PacketPatternCleanup(det_ctx); if (pflow != NULL) { /* update inspected tracker for raw reassembly */ if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL && (p->flags & PKT_STREAM_EST)) { StreamReassembleRawUpdateProgress(pflow->protoctx, p, det_ctx->raw_stream_progress); DetectEngineCleanHCBDBuffers(det_ctx); } } PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP); SCReturn; }
169,475
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHPAPI char *php_unescape_html_entities(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset TSRMLS_DC) { size_t retlen; char *ret; enum entity_charset charset; const entity_ht *inverse_map = NULL; size_t new_size = TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen); if (all) { charset = determine_charset(hint_charset TSRMLS_CC); } else { charset = cs_8859_1; /* charset shouldn't matter, use ISO-8859-1 for performance */ } /* don't use LIMIT_ALL! */ if (oldlen > new_size) { /* overflow, refuse to do anything */ ret = estrndup((char*)old, oldlen); retlen = oldlen; goto empty_source; } ret = emalloc(new_size); *ret = '\0'; retlen = oldlen; if (retlen == 0) { goto empty_source; } inverse_map = unescape_inverse_map(all, flags); /* replace numeric entities */ traverse_for_entities(old, oldlen, ret, &retlen, all, flags, inverse_map, charset); empty_source: *newlen = retlen; return ret; } Commit Message: Fix bug #72135 - don't create strings with lengths outside int range CWE ID: CWE-190
PHPAPI char *php_unescape_html_entities(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset TSRMLS_DC) { size_t retlen; char *ret; enum entity_charset charset; const entity_ht *inverse_map = NULL; size_t new_size = TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen); if (all) { charset = determine_charset(hint_charset TSRMLS_CC); } else { charset = cs_8859_1; /* charset shouldn't matter, use ISO-8859-1 for performance */ } /* don't use LIMIT_ALL! */ if (oldlen > new_size) { /* overflow, refuse to do anything */ ret = estrndup((char*)old, oldlen); retlen = oldlen; goto empty_source; } ret = emalloc(new_size); *ret = '\0'; retlen = oldlen; if (retlen == 0) { goto empty_source; } inverse_map = unescape_inverse_map(all, flags); /* replace numeric entities */ traverse_for_entities(old, oldlen, ret, &retlen, all, flags, inverse_map, charset); empty_source: *newlen = retlen; return ret; }
167,176
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool AcceleratedStaticBitmapImage::CopyToTexture( gpu::gles2::GLES2Interface* dest_gl, GLenum dest_target, GLuint dest_texture_id, bool unpack_premultiply_alpha, bool unpack_flip_y, const IntPoint& dest_point, const IntRect& source_sub_rectangle) { CheckThread(); if (!IsValid()) return false; DCHECK(texture_holder_->IsCrossThread() || dest_gl != ContextProviderWrapper()->ContextProvider()->ContextGL()); EnsureMailbox(kUnverifiedSyncToken, GL_NEAREST); dest_gl->WaitSyncTokenCHROMIUM( texture_holder_->GetSyncToken().GetConstData()); GLuint source_texture_id = dest_gl->CreateAndConsumeTextureCHROMIUM( texture_holder_->GetMailbox().name); dest_gl->CopySubTextureCHROMIUM( source_texture_id, 0, dest_target, dest_texture_id, 0, dest_point.X(), dest_point.Y(), source_sub_rectangle.X(), source_sub_rectangle.Y(), source_sub_rectangle.Width(), source_sub_rectangle.Height(), unpack_flip_y ? GL_FALSE : GL_TRUE, GL_FALSE, unpack_premultiply_alpha ? GL_FALSE : GL_TRUE); dest_gl->DeleteTextures(1, &source_texture_id); gpu::SyncToken sync_token; dest_gl->GenUnverifiedSyncTokenCHROMIUM(sync_token.GetData()); texture_holder_->UpdateSyncToken(sync_token); return true; } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <gab@chromium.org> Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Fernando Serboncini <fserb@chromium.org> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
bool AcceleratedStaticBitmapImage::CopyToTexture( gpu::gles2::GLES2Interface* dest_gl, GLenum dest_target, GLuint dest_texture_id, bool unpack_premultiply_alpha, bool unpack_flip_y, const IntPoint& dest_point, const IntRect& source_sub_rectangle) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!IsValid()) return false; DCHECK(texture_holder_->IsCrossThread() || dest_gl != ContextProviderWrapper()->ContextProvider()->ContextGL()); EnsureMailbox(kUnverifiedSyncToken, GL_NEAREST); dest_gl->WaitSyncTokenCHROMIUM( texture_holder_->GetSyncToken().GetConstData()); GLuint source_texture_id = dest_gl->CreateAndConsumeTextureCHROMIUM( texture_holder_->GetMailbox().name); dest_gl->CopySubTextureCHROMIUM( source_texture_id, 0, dest_target, dest_texture_id, 0, dest_point.X(), dest_point.Y(), source_sub_rectangle.X(), source_sub_rectangle.Y(), source_sub_rectangle.Width(), source_sub_rectangle.Height(), unpack_flip_y ? GL_FALSE : GL_TRUE, GL_FALSE, unpack_premultiply_alpha ? GL_FALSE : GL_TRUE); dest_gl->DeleteTextures(1, &source_texture_id); gpu::SyncToken sync_token; dest_gl->GenUnverifiedSyncTokenCHROMIUM(sync_token.GetData()); texture_holder_->UpdateSyncToken(sync_token); return true; }
172,591
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: MagickExport void *ResizeQuantumMemory(void *memory,const size_t count, const size_t quantum) { size_t extent; if (CheckMemoryOverflow(count,quantum) != MagickFalse) { memory=RelinquishMagickMemory(memory); return((void *) NULL); } extent=count*quantum; return(ResizeMagickMemory(memory,extent)); } Commit Message: Suspend exception processing if there are too many exceptions CWE ID: CWE-119
MagickExport void *ResizeQuantumMemory(void *memory,const size_t count, const size_t quantum) { size_t extent; if (HeapOverflowSanityCheck(count,quantum) != MagickFalse) { memory=RelinquishMagickMemory(memory); return((void *) NULL); } extent=count*quantum; return(ResizeMagickMemory(memory,extent)); }
168,545
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function 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. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: v8::Local<v8::Value> PrivateScriptRunner::runDOMMethod(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* methodName, v8::Local<v8::Value> holder, int argc, v8::Local<v8::Value> argv[]) { v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> method; if (!classObject->Get(scriptState->context(), v8String(scriptState->isolate(), methodName)).ToLocal(&method) || !method->IsFunction()) { fprintf(stderr, "Private script error: Target DOM method was not found. (Class name = %s, Method name = %s)\n", className, methodName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::TryCatch block(scriptState->isolate()); v8::Local<v8::Value> result; if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(method), scriptState->getExecutionContext(), holder, argc, argv, scriptState->isolate()).ToLocal(&result)) { rethrowExceptionInPrivateScript(scriptState->isolate(), block, scriptStateInUserScript, ExceptionState::ExecutionContext, methodName, className); block.ReThrow(); return v8::Local<v8::Value>(); } return result; } Commit Message: Blink-in-JS should not run micro tasks If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug (see 645211 for concrete steps). This CL makes Blink-in-JS use callInternalFunction (instead of callFunction) to avoid running micro tasks after Blink-in-JS' callbacks. BUG=645211 Review-Url: https://codereview.chromium.org/2330843002 Cr-Commit-Position: refs/heads/master@{#417874} CWE ID: CWE-79
v8::Local<v8::Value> PrivateScriptRunner::runDOMMethod(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* methodName, v8::Local<v8::Value> holder, int argc, v8::Local<v8::Value> argv[]) { v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> method; if (!classObject->Get(scriptState->context(), v8String(scriptState->isolate(), methodName)).ToLocal(&method) || !method->IsFunction()) { fprintf(stderr, "Private script error: Target DOM method was not found. (Class name = %s, Method name = %s)\n", className, methodName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::TryCatch block(scriptState->isolate()); v8::Local<v8::Value> result; if (!V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(method), holder, argc, argv, scriptState->isolate()).ToLocal(&result)) { rethrowExceptionInPrivateScript(scriptState->isolate(), block, scriptStateInUserScript, ExceptionState::ExecutionContext, methodName, className); block.ReThrow(); return v8::Local<v8::Value>(); } return result; }
172,077
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Chapters::Atom::Clear() { delete[] m_string_uid; m_string_uid = NULL; while (m_displays_count > 0) { Display& d = m_displays[--m_displays_count]; d.Clear(); } delete[] m_displays; m_displays = NULL; m_displays_size = 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
void Chapters::Atom::Clear()
174,245
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void LogoService::GetLogo(search_provider_logos::LogoObserver* observer) { LogoCallbacks callbacks; callbacks.on_cached_decoded_logo_available = base::BindOnce(ObserverOnLogoAvailable, observer, true); callbacks.on_fresh_decoded_logo_available = base::BindOnce(ObserverOnLogoAvailable, observer, false); GetLogo(std::move(callbacks)); } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <sdefresne@chromium.org> Reviewed-by: Marc Treib <treib@chromium.org> Commit-Queue: Chris Pickel <sfiera@chromium.org> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
void LogoService::GetLogo(search_provider_logos::LogoObserver* observer) {
171,951
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: WebContents* PrintPreviewDialogController::CreatePrintPreviewDialog( WebContents* initiator) { base::AutoReset<bool> auto_reset(&is_creating_print_preview_dialog_, true); ConstrainedWebDialogDelegate* web_dialog_delegate = ShowConstrainedWebDialog(initiator->GetBrowserContext(), new PrintPreviewDialogDelegate(initiator), initiator); WebContents* preview_dialog = web_dialog_delegate->GetWebContents(); GURL print_url(chrome::kChromeUIPrintURL); content::HostZoomMap::Get(preview_dialog->GetSiteInstance()) ->SetZoomLevelForHostAndScheme(print_url.scheme(), print_url.host(), 0); PrintViewManager::CreateForWebContents(preview_dialog); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( preview_dialog); preview_dialog_map_[preview_dialog] = initiator; waiting_for_new_preview_page_ = true; task_manager::WebContentsTags::CreateForPrintingContents(preview_dialog); AddObservers(initiator); AddObservers(preview_dialog); return preview_dialog; } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. TBR=jzfeng@chromium.org BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <weili@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
WebContents* PrintPreviewDialogController::CreatePrintPreviewDialog( WebContents* initiator) { base::AutoReset<bool> auto_reset(&is_creating_print_preview_dialog_, true); ConstrainedWebDialogDelegate* web_dialog_delegate = ShowConstrainedWebDialog(initiator->GetBrowserContext(), new PrintPreviewDialogDelegate(initiator), initiator); WebContents* preview_dialog = web_dialog_delegate->GetWebContents(); GURL print_url(chrome::kChromeUIPrintURL); content::HostZoomMap::Get(preview_dialog->GetSiteInstance()) ->SetZoomLevelForHostAndScheme(print_url.scheme(), print_url.host(), 0); PrintViewManager::CreateForWebContents(preview_dialog); CreateCompositeClientIfNeeded(preview_dialog, true /* for_preview */); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( preview_dialog); preview_dialog_map_[preview_dialog] = initiator; waiting_for_new_preview_page_ = true; task_manager::WebContentsTags::CreateForPrintingContents(preview_dialog); AddObservers(initiator); AddObservers(preview_dialog); return preview_dialog; }
171,887
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static double digitize(double value, int depth, int do_round) { /* 'value' is in the range 0 to 1, the result is the same value rounded to a * multiple of the digitization factor - 8 or 16 bits depending on both the * sample depth and the 'assume' setting. Digitization is normally by * rounding and 'do_round' should be 1, if it is 0 the digitized value will * be truncated. */ PNG_CONST unsigned int digitization_factor = (1U << depth) -1; /* Limiting the range is done as a convenience to the caller - it's easier to * do it once here than every time at the call site. */ if (value <= 0) value = 0; else if (value >= 1) value = 1; value *= digitization_factor; if (do_round) value += .5; return floor(value)/digitization_factor; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static double digitize(double value, int depth, int do_round) { /* 'value' is in the range 0 to 1, the result is the same value rounded to a * multiple of the digitization factor - 8 or 16 bits depending on both the * sample depth and the 'assume' setting. Digitization is normally by * rounding and 'do_round' should be 1, if it is 0 the digitized value will * be truncated. */ const unsigned int digitization_factor = (1U << depth) -1; /* Limiting the range is done as a convenience to the caller - it's easier to * do it once here than every time at the call site. */ if (value <= 0) value = 0; else if (value >= 1) value = 1; value *= digitization_factor; if (do_round) value += .5; return floor(value)/digitization_factor; }
173,608
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int vcc_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct atm_vcc *vcc; int len; if (get_user(len, optlen)) return -EFAULT; if (__SO_LEVEL_MATCH(optname, level) && len != __SO_SIZE(optname)) return -EINVAL; vcc = ATM_SD(sock); switch (optname) { case SO_ATMQOS: if (!test_bit(ATM_VF_HASQOS, &vcc->flags)) return -EINVAL; return copy_to_user(optval, &vcc->qos, sizeof(vcc->qos)) ? -EFAULT : 0; case SO_SETCLP: return put_user(vcc->atm_options & ATM_ATMOPT_CLP ? 1 : 0, (unsigned long __user *)optval) ? -EFAULT : 0; case SO_ATMPVC: { struct sockaddr_atmpvc pvc; if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags)) return -ENOTCONN; pvc.sap_family = AF_ATMPVC; pvc.sap_addr.itf = vcc->dev->number; pvc.sap_addr.vpi = vcc->vpi; pvc.sap_addr.vci = vcc->vci; return copy_to_user(optval, &pvc, sizeof(pvc)) ? -EFAULT : 0; } default: if (level == SOL_SOCKET) return -EINVAL; break; } if (!vcc->dev || !vcc->dev->ops->getsockopt) return -EINVAL; return vcc->dev->ops->getsockopt(vcc, level, optname, optval, len); } Commit Message: atm: fix info leak in getsockopt(SO_ATMPVC) The ATM code fails to initialize the two padding bytes of struct sockaddr_atmpvc inserted for alignment. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
int vcc_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct atm_vcc *vcc; int len; if (get_user(len, optlen)) return -EFAULT; if (__SO_LEVEL_MATCH(optname, level) && len != __SO_SIZE(optname)) return -EINVAL; vcc = ATM_SD(sock); switch (optname) { case SO_ATMQOS: if (!test_bit(ATM_VF_HASQOS, &vcc->flags)) return -EINVAL; return copy_to_user(optval, &vcc->qos, sizeof(vcc->qos)) ? -EFAULT : 0; case SO_SETCLP: return put_user(vcc->atm_options & ATM_ATMOPT_CLP ? 1 : 0, (unsigned long __user *)optval) ? -EFAULT : 0; case SO_ATMPVC: { struct sockaddr_atmpvc pvc; if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags)) return -ENOTCONN; memset(&pvc, 0, sizeof(pvc)); pvc.sap_family = AF_ATMPVC; pvc.sap_addr.itf = vcc->dev->number; pvc.sap_addr.vpi = vcc->vpi; pvc.sap_addr.vci = vcc->vci; return copy_to_user(optval, &pvc, sizeof(pvc)) ? -EFAULT : 0; } default: if (level == SOL_SOCKET) return -EINVAL; break; } if (!vcc->dev || !vcc->dev->ops->getsockopt) return -EINVAL; return vcc->dev->ops->getsockopt(vcc, level, optname, optval, len); }
166,180
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool RenderWidgetHostViewAura::ShouldFastACK(uint64 surface_id) { ui::Texture* container = image_transport_clients_[surface_id]; DCHECK(container); if (can_lock_compositor_ == NO_PENDING_RENDERER_FRAME || can_lock_compositor_ == NO_PENDING_COMMIT || resize_locks_.empty()) return false; gfx::Size container_size = ConvertSizeToDIP(this, container->size()); ResizeLockList::iterator it = resize_locks_.begin(); while (it != resize_locks_.end()) { if ((*it)->expected_size() == container_size) break; ++it; } return it == resize_locks_.end() || ++it != resize_locks_.end(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool RenderWidgetHostViewAura::ShouldFastACK(uint64 surface_id) { bool RenderWidgetHostViewAura::ShouldSkipFrame(const gfx::Size& size) { if (can_lock_compositor_ == NO_PENDING_RENDERER_FRAME || can_lock_compositor_ == NO_PENDING_COMMIT || resize_locks_.empty()) return false; gfx::Size container_size = ConvertSizeToDIP(this, size); ResizeLockList::iterator it = resize_locks_.begin(); while (it != resize_locks_.end()) { if ((*it)->expected_size() == container_size) break; ++it; } return it == resize_locks_.end() || ++it != resize_locks_.end(); }
171,386
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int sysMapFD(int fd, MemMapping* pMap) { off_t start; size_t length; void* memPtr; assert(pMap != NULL); if (getFileStartAndLength(fd, &start, &length) < 0) return -1; memPtr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, start); if (memPtr == MAP_FAILED) { LOGW("mmap(%d, R, PRIVATE, %d, %d) failed: %s\n", (int) length, fd, (int) start, strerror(errno)); return -1; } pMap->addr = memPtr; pMap->length = length; pMap->range_count = 1; pMap->ranges = malloc(sizeof(MappedRange)); pMap->ranges[0].addr = memPtr; pMap->ranges[0].length = length; return 0; } Commit Message: Fix integer overflows in recovery procedure. Bug: 26960931 Change-Id: Ieae45caccfb4728fcf514f0d920976585d8e6caf (cherry picked from commit 4f2df162c6ab4a71ca86e4b38735b681729c353b) CWE ID: CWE-189
static int sysMapFD(int fd, MemMapping* pMap) { off_t start; size_t length; void* memPtr; assert(pMap != NULL); if (getFileStartAndLength(fd, &start, &length) < 0) return -1; memPtr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, start); if (memPtr == MAP_FAILED) { LOGW("mmap(%d, R, PRIVATE, %d, %d) failed: %s\n", (int) length, fd, (int) start, strerror(errno)); return -1; } pMap->addr = memPtr; pMap->length = length; pMap->range_count = 1; pMap->ranges = malloc(sizeof(MappedRange)); if (pMap->ranges == NULL) { LOGE("malloc failed: %s\n", strerror(errno)); munmap(memPtr, length); return -1; } pMap->ranges[0].addr = memPtr; pMap->ranges[0].length = length; return 0; }
173,904
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args) { if (args->flags & ~(KVM_IRQFD_FLAG_DEASSIGN | KVM_IRQFD_FLAG_RESAMPLE)) return -EINVAL; if (args->flags & KVM_IRQFD_FLAG_DEASSIGN) return kvm_irqfd_deassign(kvm, args); return kvm_irqfd_assign(kvm, args); } Commit Message: KVM: Don't accept obviously wrong gsi values via KVM_IRQFD We cannot add routes for gsi values >= KVM_MAX_IRQ_ROUTES -- see kvm_set_irq_routing(). Hence, there is no sense in accepting them via KVM_IRQFD. Prevent them from entering the system in the first place. Signed-off-by: Jan H. Schönherr <jschoenh@amazon.de> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-20
kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args) { if (args->flags & ~(KVM_IRQFD_FLAG_DEASSIGN | KVM_IRQFD_FLAG_RESAMPLE)) return -EINVAL; if (args->gsi >= KVM_MAX_IRQ_ROUTES) return -EINVAL; if (args->flags & KVM_IRQFD_FLAG_DEASSIGN) return kvm_irqfd_deassign(kvm, args); return kvm_irqfd_assign(kvm, args); }
167,620
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md) { X509_REQ *ret; X509_REQ_INFO *ri; int i; EVP_PKEY *pktmp; ret = X509_REQ_new(); if (ret == NULL) { X509err(X509_F_X509_TO_X509_REQ, ERR_R_MALLOC_FAILURE); goto err; } ri = ret->req_info; ri->version->length = 1; ri->version->data = (unsigned char *)OPENSSL_malloc(1); if (ri->version->data == NULL) goto err; ri->version->data[0] = 0; /* version == 0 */ if (!X509_REQ_set_subject_name(ret, X509_get_subject_name(x))) goto err; pktmp = X509_get_pubkey(x); i = X509_REQ_set_pubkey(ret, pktmp); EVP_PKEY_free(pktmp); if (!i) if (pkey != NULL) { if (!X509_REQ_sign(ret, pkey, md)) goto err; } return (ret); err: X509_REQ_free(ret); return (NULL); } Commit Message: CWE ID:
X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md) { X509_REQ *ret; X509_REQ_INFO *ri; int i; EVP_PKEY *pktmp; ret = X509_REQ_new(); if (ret == NULL) { X509err(X509_F_X509_TO_X509_REQ, ERR_R_MALLOC_FAILURE); goto err; } ri = ret->req_info; ri->version->length = 1; ri->version->data = (unsigned char *)OPENSSL_malloc(1); if (ri->version->data == NULL) goto err; ri->version->data[0] = 0; /* version == 0 */ if (!X509_REQ_set_subject_name(ret, X509_get_subject_name(x))) goto err; pktmp = X509_get_pubkey(x); if (pktmp == NULL) goto err; i = X509_REQ_set_pubkey(ret, pktmp); EVP_PKEY_free(pktmp); if (!i) if (pkey != NULL) { if (!X509_REQ_sign(ret, pkey, md)) goto err; } return (ret); err: X509_REQ_free(ret); return (NULL); }
164,809
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: sf_open_fd (int fd, int mode, SF_INFO *sfinfo, int close_desc) { SF_PRIVATE *psf ; if ((SF_CONTAINER (sfinfo->format)) == SF_FORMAT_SD2) { sf_errno = SFE_SD2_FD_DISALLOWED ; return NULL ; } ; if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; copy_filename (psf, "") ; psf->file.mode = mode ; psf_set_file (psf, fd) ; psf->is_pipe = psf_is_pipe (psf) ; psf->fileoffset = psf_ftell (psf) ; if (! close_desc) psf->file.do_not_close_descriptor = SF_TRUE ; return psf_open_file (psf, sfinfo) ; } /* sf_open_fd */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
sf_open_fd (int fd, int mode, SF_INFO *sfinfo, int close_desc) { SF_PRIVATE *psf ; if ((SF_CONTAINER (sfinfo->format)) == SF_FORMAT_SD2) { sf_errno = SFE_SD2_FD_DISALLOWED ; return NULL ; } ; if ((psf = psf_allocate ()) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; copy_filename (psf, "") ; psf->file.mode = mode ; psf_set_file (psf, fd) ; psf->is_pipe = psf_is_pipe (psf) ; psf->fileoffset = psf_ftell (psf) ; if (! close_desc) psf->file.do_not_close_descriptor = SF_TRUE ; return psf_open_file (psf, sfinfo) ; } /* sf_open_fd */
170,068
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: uint8_t smb2cli_session_security_mode(struct smbXcli_session *session) { struct smbXcli_conn *conn = session->conn; uint8_t security_mode = 0; if (conn == NULL) { return security_mode; } security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED; if (conn->mandatory_signing) { security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED; } return security_mode; } Commit Message: CWE ID: CWE-20
uint8_t smb2cli_session_security_mode(struct smbXcli_session *session) { struct smbXcli_conn *conn = session->conn; uint8_t security_mode = 0; if (conn == NULL) { return security_mode; } security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED; if (conn->mandatory_signing) { security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED; } if (session->smb2->should_sign) { security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED; } return security_mode; }
164,675
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void FrameFetchContext::DispatchDidBlockRequest( const ResourceRequest& resource_request, const FetchInitiatorInfo& fetch_initiator_info, ResourceRequestBlockedReason blocked_reason) const { if (IsDetached()) return; probe::didBlockRequest(GetFrame()->GetDocument(), resource_request, MasterDocumentLoader(), fetch_initiator_info, blocked_reason); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
void FrameFetchContext::DispatchDidBlockRequest( const ResourceRequest& resource_request, const FetchInitiatorInfo& fetch_initiator_info, ResourceRequestBlockedReason blocked_reason, Resource::Type resource_type) const { if (IsDetached()) return; probe::didBlockRequest(GetFrame()->GetDocument(), resource_request, MasterDocumentLoader(), fetch_initiator_info, blocked_reason, resource_type); }
172,473
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: UNCURL_EXPORT int32_t uncurl_ws_accept(struct uncurl_conn *ucc, char **origins, int32_t n_origins) { int32_t e; e = uncurl_read_header(ucc); if (e != UNCURL_OK) return e; uncurl_set_header_str(ucc, "Upgrade", "websocket"); uncurl_set_header_str(ucc, "Connection", "Upgrade"); char *origin = NULL; e = uncurl_get_header_str(ucc, "Origin", &origin); if (e != UNCURL_OK) return e; bool origin_ok = false; for (int32_t x = 0; x < n_origins; x++) if (strstr(origin, origins[x])) {origin_ok = true; break;} if (!origin_ok) return UNCURL_WS_ERR_ORIGIN; char *sec_key = NULL; e = uncurl_get_header_str(ucc, "Sec-WebSocket-Key", &sec_key); if (e != UNCURL_OK) return e; char *accept_key = ws_create_accept_key(sec_key); uncurl_set_header_str(ucc, "Sec-WebSocket-Accept", accept_key); free(accept_key); e = uncurl_write_header(ucc, "101", "Switching Protocols", UNCURL_RESPONSE); if (e != UNCURL_OK) return e; ucc->ws_mask = 0; return UNCURL_OK; } Commit Message: origin matching must come at str end CWE ID: CWE-352
UNCURL_EXPORT int32_t uncurl_ws_accept(struct uncurl_conn *ucc, char **origins, int32_t n_origins) { int32_t e; e = uncurl_read_header(ucc); if (e != UNCURL_OK) return e; uncurl_set_header_str(ucc, "Upgrade", "websocket"); uncurl_set_header_str(ucc, "Connection", "Upgrade"); char *origin = NULL; e = uncurl_get_header_str(ucc, "Origin", &origin); if (e != UNCURL_OK) return e; //the substring MUST came at the end of the origin header, thus a strstr AND a strcmp bool origin_ok = false; for (int32_t x = 0; x < n_origins; x++) { char *match = strstr(origin, origins[x]); if (match && !strcmp(match, origins[x])) {origin_ok = true; break;} } if (!origin_ok) return UNCURL_WS_ERR_ORIGIN; char *sec_key = NULL; e = uncurl_get_header_str(ucc, "Sec-WebSocket-Key", &sec_key); if (e != UNCURL_OK) return e; char *accept_key = ws_create_accept_key(sec_key); uncurl_set_header_str(ucc, "Sec-WebSocket-Accept", accept_key); free(accept_key); e = uncurl_write_header(ucc, "101", "Switching Protocols", UNCURL_RESPONSE); if (e != UNCURL_OK) return e; ucc->ws_mask = 0; return UNCURL_OK; }
169,336
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual InputMethodDescriptors* GetSupportedInputMethods() { if (!initialized_successfully_) { InputMethodDescriptors* result = new InputMethodDescriptors; result->push_back(input_method::GetFallbackInputMethodDescriptor()); return result; } return chromeos::GetSupportedInputMethodDescriptors(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual InputMethodDescriptors* GetSupportedInputMethods() { virtual input_method::InputMethodDescriptors* GetSupportedInputMethods() { if (!initialized_successfully_) { input_method::InputMethodDescriptors* result = new input_method::InputMethodDescriptors; result->push_back(input_method::GetFallbackInputMethodDescriptor()); return result; } return input_method::GetSupportedInputMethodDescriptors(); }
170,492
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return NULL; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp) { MP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]); if (MP4buffer) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp); return MP4buffer; } } return NULL; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return NULL; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp) { MP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]); if (MP4buffer) { if (mp4->filesize > mp4->metaoffsets[index]+mp4->metasizes[index]) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp); mp4->filepos = mp4->metaoffsets[index] + mp4->metasizes[index]; return MP4buffer; } } } return NULL; }
169,548
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { char *buf; size_t line_len = 0; long line_add = (intern->u.file.current_line || intern->u.file.current_zval) ? 1 : 0; spl_filesystem_file_free_line(intern TSRMLS_CC); if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (intern->u.file.max_line_len > 0) { buf = safe_emalloc((intern->u.file.max_line_len + 1), sizeof(char), 0); if (php_stream_get_line(intern->u.file.stream, buf, intern->u.file.max_line_len + 1, &line_len) == NULL) { efree(buf); buf = NULL; } else { buf[line_len] = '\0'; } } else { buf = php_stream_get_line(intern->u.file.stream, NULL, 0, &line_len); } if (!buf) { intern->u.file.current_line = estrdup(""); intern->u.file.current_line_len = 0; } else { if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_DROP_NEW_LINE)) { line_len = strcspn(buf, "\r\n"); buf[line_len] = '\0'; } intern->u.file.current_line = buf; intern->u.file.current_line_len = line_len; } intern->u.file.current_line_num += line_add; return SUCCESS; } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { char *buf; size_t line_len = 0; long line_add = (intern->u.file.current_line || intern->u.file.current_zval) ? 1 : 0; spl_filesystem_file_free_line(intern TSRMLS_CC); if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (intern->u.file.max_line_len > 0) { buf = safe_emalloc((intern->u.file.max_line_len + 1), sizeof(char), 0); if (php_stream_get_line(intern->u.file.stream, buf, intern->u.file.max_line_len + 1, &line_len) == NULL) { efree(buf); buf = NULL; } else { buf[line_len] = '\0'; } } else { buf = php_stream_get_line(intern->u.file.stream, NULL, 0, &line_len); } if (!buf) { intern->u.file.current_line = estrdup(""); intern->u.file.current_line_len = 0; } else { if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_DROP_NEW_LINE)) { line_len = strcspn(buf, "\r\n"); buf[line_len] = '\0'; } intern->u.file.current_line = buf; intern->u.file.current_line_len = line_len; } intern->u.file.current_line_num += line_add; return SUCCESS; } /* }}} */
167,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: OMX_ERRORTYPE SoftRaw::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.raw", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } mChannelCount = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftRaw::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_decoder.raw", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } mChannelCount = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,219
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_siz_t *siz = &ms->parms.siz; unsigned int i; uint_fast8_t tmp; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_getuint16(in, &siz->caps) || jpc_getuint32(in, &siz->width) || jpc_getuint32(in, &siz->height) || jpc_getuint32(in, &siz->xoff) || jpc_getuint32(in, &siz->yoff) || jpc_getuint32(in, &siz->tilewidth) || jpc_getuint32(in, &siz->tileheight) || jpc_getuint32(in, &siz->tilexoff) || jpc_getuint32(in, &siz->tileyoff) || jpc_getuint16(in, &siz->numcomps)) { return -1; } if (!siz->width || !siz->height || !siz->tilewidth || !siz->tileheight || !siz->numcomps) { return -1; } if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) { return -1; } for (i = 0; i < siz->numcomps; ++i) { if (jpc_getuint8(in, &tmp) || jpc_getuint8(in, &siz->comps[i].hsamp) || jpc_getuint8(in, &siz->comps[i].vsamp)) { jas_free(siz->comps); return -1; } siz->comps[i].sgnd = (tmp >> 7) & 1; siz->comps[i].prec = (tmp & 0x7f) + 1; } if (jas_stream_eof(in)) { jas_free(siz->comps); return -1; } return 0; } Commit Message: Added range check on XRsiz and YRsiz fields of SIZ marker segment. CWE ID: CWE-369
static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_siz_t *siz = &ms->parms.siz; unsigned int i; uint_fast8_t tmp; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_getuint16(in, &siz->caps) || jpc_getuint32(in, &siz->width) || jpc_getuint32(in, &siz->height) || jpc_getuint32(in, &siz->xoff) || jpc_getuint32(in, &siz->yoff) || jpc_getuint32(in, &siz->tilewidth) || jpc_getuint32(in, &siz->tileheight) || jpc_getuint32(in, &siz->tilexoff) || jpc_getuint32(in, &siz->tileyoff) || jpc_getuint16(in, &siz->numcomps)) { return -1; } if (!siz->width || !siz->height || !siz->tilewidth || !siz->tileheight || !siz->numcomps) { return -1; } if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) { return -1; } for (i = 0; i < siz->numcomps; ++i) { if (jpc_getuint8(in, &tmp) || jpc_getuint8(in, &siz->comps[i].hsamp) || jpc_getuint8(in, &siz->comps[i].vsamp)) { jas_free(siz->comps); return -1; } if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) { jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp); jas_free(siz->comps); return -1; } if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) { jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp); jas_free(siz->comps); return -1; } siz->comps[i].sgnd = (tmp >> 7) & 1; siz->comps[i].prec = (tmp & 0x7f) + 1; } if (jas_stream_eof(in)) { jas_free(siz->comps); return -1; } return 0; }
168,760
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int xfrm_dump_policy_done(struct netlink_callback *cb) { struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; struct net *net = sock_net(cb->skb->sk); xfrm_policy_walk_done(walk, net); return 0; } Commit Message: ipsec: Fix aborted xfrm policy dump crash An independent security researcher, Mohamed Ghannam, has reported this vulnerability to Beyond Security's SecuriTeam Secure Disclosure program. The xfrm_dump_policy_done function expects xfrm_dump_policy to have been called at least once or it will crash. This can be triggered if a dump fails because the target socket's receive buffer is full. This patch fixes it by using the cb->start mechanism to ensure that the initialisation is always done regardless of the buffer situation. Fixes: 12a169e7d8f4 ("ipsec: Put dumpers on the dump list") Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: Steffen Klassert <steffen.klassert@secunet.com> CWE ID: CWE-416
static int xfrm_dump_policy_done(struct netlink_callback *cb) { struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *)cb->args; struct net *net = sock_net(cb->skb->sk); xfrm_policy_walk_done(walk, net); return 0; }
167,663
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool IDNSpoofChecker::Check(base::StringPiece16 label) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), NULL, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII || (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string))) return true; if (non_ascii_latin_letters_.containsSome(label_string)) return false; if (!tls_index.initialized()) tls_index.Initialize(&OnThreadTermination); icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(tls_index.Get()); if (!dangerous_pattern) { dangerous_pattern = new icu::RegexMatcher( icu::UnicodeString( "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]" "[\\u30ce\\u30f3\\u30bd\\u30be]" "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]|" "[^\\p{scx=kana}\\p{scx=hira}]\\u30fc|" "\\u30fc[^\\p{scx=kana}\\p{scx=hira}]|" "^[\\p{scx=kana}]+[\\u3078-\\u307a][\\p{scx=kana}]+$|" "^[\\p{scx=hira}]+[\\u30d8-\\u30da][\\p{scx=hira}]+$|" "[a-z]\\u30fb|\\u30fb[a-z]|" "^[\\u0585\\u0581]+[a-z]|[a-z][\\u0585\\u0581]+$|" "[a-z][\\u0585\\u0581]+[a-z]|" "^[og]+[\\p{scx=armn}]|[\\p{scx=armn}][og]+$|" "[\\p{scx=armn}][og]+[\\p{scx=armn}]", -1, US_INV), 0, status); tls_index.Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); } Commit Message: Block domain labels made of Cyrillic letters that look alike Latin Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф. BUG=683314 TEST=components_unittests --gtest_filter=U*IDN* Review-Url: https://codereview.chromium.org/2683793010 Cr-Commit-Position: refs/heads/master@{#459226} CWE ID: CWE-20
bool IDNSpoofChecker::Check(base::StringPiece16 label) { bool IDNSpoofChecker::Check(base::StringPiece16 label, bool is_tld_ascii) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), NULL, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; // extra check unless it contains Kana letter exceptions or it's made entirely // of Cyrillic letters that look like Latin letters. Note that the following // combinations of scripts are treated as a 'logical' single script. result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII) return true; if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string)) { // Check Cyrillic confusable only for ASCII TLDs. return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); } if (non_ascii_latin_letters_.containsSome(label_string)) return false; if (!tls_index.initialized()) tls_index.Initialize(&OnThreadTermination); icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(tls_index.Get()); if (!dangerous_pattern) { dangerous_pattern = new icu::RegexMatcher( icu::UnicodeString( "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]" "[\\u30ce\\u30f3\\u30bd\\u30be]" "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]|" "[^\\p{scx=kana}\\p{scx=hira}]\\u30fc|" "\\u30fc[^\\p{scx=kana}\\p{scx=hira}]|" "^[\\p{scx=kana}]+[\\u3078-\\u307a][\\p{scx=kana}]+$|" "^[\\p{scx=hira}]+[\\u30d8-\\u30da][\\p{scx=hira}]+$|" "[a-z]\\u30fb|\\u30fb[a-z]|" "^[\\u0585\\u0581]+[a-z]|[a-z][\\u0585\\u0581]+$|" "[a-z][\\u0585\\u0581]+[a-z]|" "^[og]+[\\p{scx=armn}]|[\\p{scx=armn}][og]+$|" "[\\p{scx=armn}][og]+[\\p{scx=armn}]", -1, US_INV), 0, status); tls_index.Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); }
172,388
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: FilePath ExtensionPrefs::GetExtensionPath(const std::string& extension_id) { const DictionaryValue* dict = GetExtensionPref(extension_id); std::string path; if (!dict->GetString(kPrefPath, &path)) return FilePath(); return install_directory_.Append(FilePath::FromWStringHack(UTF8ToWide(path))); } Commit Message: Coverity: Add a missing NULL check. BUG=none TEST=none CID=16813 Review URL: http://codereview.chromium.org/7216034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89991 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
FilePath ExtensionPrefs::GetExtensionPath(const std::string& extension_id) { const DictionaryValue* dict = GetExtensionPref(extension_id); if (!dict) return FilePath(); std::string path; if (!dict->GetString(kPrefPath, &path)) return FilePath(); return install_directory_.Append(FilePath::FromWStringHack(UTF8ToWide(path))); }
170,309
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PluginChannel::PluginChannel() : renderer_handle_(0), renderer_id_(-1), in_send_(0), incognito_(false), filter_(new MessageFilter()) { set_send_unblocking_only_during_unblock_dispatch(); ChildProcess::current()->AddRefProcess(); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); } 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:
PluginChannel::PluginChannel() : renderer_id_(-1), in_send_(0), incognito_(false), filter_(new MessageFilter()) { set_send_unblocking_only_during_unblock_dispatch(); ChildProcess::current()->AddRefProcess(); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); }
170,950
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ui::ModalType ExtensionInstallDialogView::GetModalType() const { return ui::MODAL_TYPE_WINDOW; } Commit Message: Make the webstore inline install dialog be tab-modal Also clean up a few minor lint errors while I'm in here. BUG=550047 Review URL: https://codereview.chromium.org/1496033003 Cr-Commit-Position: refs/heads/master@{#363925} CWE ID: CWE-17
ui::ModalType ExtensionInstallDialogView::GetModalType() const { return prompt_->ShouldUseTabModalDialog() ? ui::MODAL_TYPE_CHILD : ui::MODAL_TYPE_WINDOW; }
172,206
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SchedulerObject::release(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Release: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!releaseJob(id.cluster, id.proc, reason.c_str(), true, // Always perform this action within a transaction false, // Do not email the user about this action false // Do not email admin about this action )) { text = "Failed to release job"; return false; } return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::release(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Release: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!releaseJob(id.cluster, id.proc, reason.c_str(), true, // Always perform this action within a transaction false, // Do not email the user about this action false // Do not email admin about this action )) { text = "Failed to release job"; return false; } return true; }
164,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int btpan_tap_open() { struct ifreq ifr; int fd, err; const char *clonedev = "/dev/tun"; /* open the clone device */ if ((fd = open(clonedev, O_RDWR)) < 0) { BTIF_TRACE_DEBUG("could not open %s, err:%d", clonedev, errno); return fd; } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; strncpy(ifr.ifr_name, TAP_IF_NAME, IFNAMSIZ); /* try to create the device */ if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0) { BTIF_TRACE_DEBUG("ioctl error:%d, errno:%s", err, strerror(errno)); close(fd); return err; } if (tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0) { int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags | O_NONBLOCK); return fd; } BTIF_TRACE_ERROR("can not bring up tap interface:%s", TAP_IF_NAME); close(fd); return INVALID_FD; } 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
int btpan_tap_open() { struct ifreq ifr; int fd, err; const char *clonedev = "/dev/tun"; /* open the clone device */ if ((fd = TEMP_FAILURE_RETRY(open(clonedev, O_RDWR))) < 0) { BTIF_TRACE_DEBUG("could not open %s, err:%d", clonedev, errno); return fd; } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; strncpy(ifr.ifr_name, TAP_IF_NAME, IFNAMSIZ); /* try to create the device */ if ((err = TEMP_FAILURE_RETRY(ioctl(fd, TUNSETIFF, (void *) &ifr))) < 0) { BTIF_TRACE_DEBUG("ioctl error:%d, errno:%s", err, strerror(errno)); close(fd); return err; } if (tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0) { int flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFL, 0)); TEMP_FAILURE_RETRY(fcntl(fd, F_SETFL, flags | O_NONBLOCK)); return fd; } BTIF_TRACE_ERROR("can not bring up tap interface:%s", TAP_IF_NAME); close(fd); return INVALID_FD; }
173,445
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BrowserGpuChannelHostFactory::EstablishRequest::EstablishRequest() : event(false, false), gpu_process_handle(base::kNullProcessHandle) { } 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:
BrowserGpuChannelHostFactory::EstablishRequest::EstablishRequest() : event(false, false) { }
170,918
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void SetUp() { url_util::AddStandardScheme("tabcontentstest"); old_browser_client_ = content::GetContentClient()->browser(); content::GetContentClient()->set_browser(&browser_client_); RenderViewHostTestHarness::SetUp(); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
virtual void SetUp() { url_util::AddStandardScheme("tabcontentstest"); old_client_ = content::GetContentClient(); content::SetContentClient(&client_); old_browser_client_ = content::GetContentClient()->browser(); content::GetContentClient()->set_browser(&browser_client_); RenderViewHostTestHarness::SetUp(); }
171,014
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int hashtable_init(hashtable_t *hashtable) { size_t i; hashtable->size = 0; hashtable->num_buckets = 0; /* index to primes[] */ hashtable->buckets = jsonp_malloc(num_buckets(hashtable) * sizeof(bucket_t)); if(!hashtable->buckets) return -1; list_init(&hashtable->list); for(i = 0; i < num_buckets(hashtable); i++) { hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list; } return 0; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
int hashtable_init(hashtable_t *hashtable) { size_t i; hashtable->size = 0; hashtable->order = 3; hashtable->buckets = jsonp_malloc(hashsize(hashtable->order) * sizeof(bucket_t)); if(!hashtable->buckets) return -1; list_init(&hashtable->list); for(i = 0; i < hashsize(hashtable->order); i++) { hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list; } return 0; }
166,531
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: UnacceleratedStaticBitmapImage::UnacceleratedStaticBitmapImage( sk_sp<SkImage> image) { CHECK(image); DCHECK(!image->isLazyGenerated()); paint_image_ = CreatePaintImageBuilder() .set_image(std::move(image), cc::PaintImage::GetNextContentId()) .TakePaintImage(); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <gab@chromium.org> Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Fernando Serboncini <fserb@chromium.org> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
UnacceleratedStaticBitmapImage::UnacceleratedStaticBitmapImage( sk_sp<SkImage> image) { CHECK(image); DCHECK(!image->isLazyGenerated()); paint_image_ = CreatePaintImageBuilder() .set_image(std::move(image), cc::PaintImage::GetNextContentId()) .TakePaintImage(); }
172,602
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int sdp_parse_fmtp_config_h264(AVFormatContext *s, AVStream *stream, PayloadContext *h264_data, const char *attr, const char *value) { AVCodecParameters *par = stream->codecpar; if (!strcmp(attr, "packetization-mode")) { av_log(s, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value)); h264_data->packetization_mode = atoi(value); /* * Packetization Mode: * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed) * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed. * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A), * and 29 (FU-B) are allowed. */ if (h264_data->packetization_mode > 1) av_log(s, AV_LOG_ERROR, "Interleaved RTP mode is not supported yet.\n"); } else if (!strcmp(attr, "profile-level-id")) { if (strlen(value) == 6) parse_profile_level_id(s, h264_data, value); } else if (!strcmp(attr, "sprop-parameter-sets")) { int ret; if (value[strlen(value) - 1] == ',') { av_log(s, AV_LOG_WARNING, "Missing PPS in sprop-parameter-sets, ignoring\n"); return 0; } par->extradata_size = 0; av_freep(&par->extradata); ret = ff_h264_parse_sprop_parameter_sets(s, &par->extradata, &par->extradata_size, value); av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)\n", par->extradata, par->extradata_size); return ret; } return 0; } Commit Message: avformat/rtpdec_h264: Fix heap-buffer-overflow Fixes: rtp_sdp/poc.sdp Found-by: Bingchang <l.bing.chang.bc@gmail.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-119
static int sdp_parse_fmtp_config_h264(AVFormatContext *s, AVStream *stream, PayloadContext *h264_data, const char *attr, const char *value) { AVCodecParameters *par = stream->codecpar; if (!strcmp(attr, "packetization-mode")) { av_log(s, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value)); h264_data->packetization_mode = atoi(value); /* * Packetization Mode: * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed) * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed. * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A), * and 29 (FU-B) are allowed. */ if (h264_data->packetization_mode > 1) av_log(s, AV_LOG_ERROR, "Interleaved RTP mode is not supported yet.\n"); } else if (!strcmp(attr, "profile-level-id")) { if (strlen(value) == 6) parse_profile_level_id(s, h264_data, value); } else if (!strcmp(attr, "sprop-parameter-sets")) { int ret; if (*value == 0 || value[strlen(value) - 1] == ',') { av_log(s, AV_LOG_WARNING, "Missing PPS in sprop-parameter-sets, ignoring\n"); return 0; } par->extradata_size = 0; av_freep(&par->extradata); ret = ff_h264_parse_sprop_parameter_sets(s, &par->extradata, &par->extradata_size, value); av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)\n", par->extradata, par->extradata_size); return ret; } return 0; }
167,744
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void reds_handle_ticket(void *opaque) { RedLinkInfo *link = (RedLinkInfo *)opaque; char password[SPICE_MAX_PASSWORD_LENGTH]; time_t ltime; time(&ltime); RSA_private_decrypt(link->tiTicketing.rsa_size, link->tiTicketing.encrypted_ticket.encrypted_data, (unsigned char *)password, link->tiTicketing.rsa, RSA_PKCS1_OAEP_PADDING); if (ticketing_enabled && !link->skip_auth) { int expired = taTicket.expiration_time < ltime; if (strlen(taTicket.password) == 0) { reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED); spice_warning("Ticketing is enabled, but no password is set. " "please set a ticket first"); reds_link_free(link); return; } if (expired || strncmp(password, taTicket.password, SPICE_MAX_PASSWORD_LENGTH) != 0) { if (expired) { spice_warning("Ticket has expired"); } else { spice_warning("Invalid password"); } reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED); reds_link_free(link); return; } } reds_handle_link(link); } Commit Message: CWE ID: CWE-119
static void reds_handle_ticket(void *opaque) { RedLinkInfo *link = (RedLinkInfo *)opaque; char *password; time_t ltime; int password_size; time(&ltime); if (RSA_size(link->tiTicketing.rsa) < SPICE_MAX_PASSWORD_LENGTH) { spice_warning("RSA modulus size is smaller than SPICE_MAX_PASSWORD_LENGTH (%d < %d), " "SPICE ticket sent from client may be truncated", RSA_size(link->tiTicketing.rsa), SPICE_MAX_PASSWORD_LENGTH); } password = g_malloc0(RSA_size(link->tiTicketing.rsa) + 1); password_size = RSA_private_decrypt(link->tiTicketing.rsa_size, link->tiTicketing.encrypted_ticket.encrypted_data, (unsigned char *)password, link->tiTicketing.rsa, RSA_PKCS1_OAEP_PADDING); if (password_size == -1) { spice_warning("failed to decrypt RSA encrypted password: %s", ERR_error_string(ERR_get_error(), NULL)); goto error; } password[password_size] = '\0'; if (ticketing_enabled && !link->skip_auth) { int expired = taTicket.expiration_time < ltime; if (strlen(taTicket.password) == 0) { spice_warning("Ticketing is enabled, but no password is set. " "please set a ticket first"); goto error; } if (expired || strcmp(password, taTicket.password) != 0) { if (expired) { spice_warning("Ticket has expired"); } else { spice_warning("Invalid password"); } goto error; } } reds_handle_link(link); goto end; error: reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED); reds_link_free(link); end: g_free(password); }
164,661
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: parse_field(netdissect_options *ndo, const char **pptr, int *len) { const char *s; if (*len <= 0 || !pptr || !*pptr) return NULL; if (*pptr > (const char *) ndo->ndo_snapend) return NULL; s = *pptr; while (*pptr <= (const char *) ndo->ndo_snapend && *len >= 0 && **pptr) { (*pptr)++; (*len)--; } (*pptr)++; (*len)--; if (*len < 0 || *pptr > (const char *) ndo->ndo_snapend) return NULL; return s; } Commit Message: CVE-2017-12902/Zephyr: Fix bounds checking. Use ND_TTEST() rather than comparing against ndo->ndo_snapend ourselves; it's easy to get the tests wrong. Check for running out of packet data before checking for running out of captured data, and distinguish between running out of packet data (which might just mean "no more strings") and running out of captured data (which means "truncated"). This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
parse_field(netdissect_options *ndo, const char **pptr, int *len) parse_field(netdissect_options *ndo, const char **pptr, int *len, int *truncated) { const char *s; /* Start of string */ s = *pptr; /* Scan for the NUL terminator */ for (;;) { if (*len == 0) { /* Ran out of packet data without finding it */ return NULL; } if (!ND_TTEST(**pptr)) { /* Ran out of captured data without finding it */ *truncated = 1; return NULL; } if (**pptr == '\0') { /* Found it */ break; } /* Keep scanning */ (*pptr)++; (*len)--; } /* Skip the NUL terminator */ (*pptr)++; (*len)--; return s; }
167,935
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: juniper_services_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_services_header { uint8_t svc_id; uint8_t flags_len; uint8_t svc_set_id[2]; uint8_t dir_iif[4]; }; const struct juniper_services_header *sh; l2info.pictype = DLT_JUNIPER_SERVICES; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; sh = (const struct juniper_services_header *)p; if (ndo->ndo_eflag) ND_PRINT((ndo, "service-id %u flags 0x%02x service-set-id 0x%04x iif %u: ", sh->svc_id, sh->flags_len, EXTRACT_16BITS(&sh->svc_set_id), EXTRACT_24BITS(&sh->dir_iif[1]))); /* no proto field - lets guess by first byte of IP header*/ ip_heuristic_guess (ndo, p, l2info.length); return l2info.header_len; } Commit Message: CVE-2017-12993/Juniper: Add more bounds checks. This fixes a buffer over-read discovered by Kamil Frankowicz. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125
juniper_services_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_services_header { uint8_t svc_id; uint8_t flags_len; uint8_t svc_set_id[2]; uint8_t dir_iif[4]; }; const struct juniper_services_header *sh; l2info.pictype = DLT_JUNIPER_SERVICES; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; sh = (const struct juniper_services_header *)p; ND_TCHECK(*sh); if (ndo->ndo_eflag) ND_PRINT((ndo, "service-id %u flags 0x%02x service-set-id 0x%04x iif %u: ", sh->svc_id, sh->flags_len, EXTRACT_16BITS(&sh->svc_set_id), EXTRACT_24BITS(&sh->dir_iif[1]))); /* no proto field - lets guess by first byte of IP header*/ ip_heuristic_guess (ndo, p, l2info.length); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; }
167,921
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int UDPSocketWin::InternalConnect(const IPEndPoint& address) { 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)) return ERR_ADDRESS_INVALID; rv = connect(socket_, storage.addr, storage.addr_len); if (rv < 0) { int result = MapSystemError(WSAGetLastError()); 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 UDPSocketWin::InternalConnect(const IPEndPoint& address) { 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)) return ERR_ADDRESS_INVALID; rv = connect(socket_, storage.addr, storage.addr_len); if (rv < 0) { int result = MapSystemError(WSAGetLastError()); Close(); return result; } remote_address_.reset(new IPEndPoint(address)); return rv; }
171,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void InitNavigateParams(FrameHostMsg_DidCommitProvisionalLoad_Params* params, int nav_entry_id, bool did_create_new_entry, const GURL& url, ui::PageTransition transition) { params->nav_entry_id = nav_entry_id; params->url = url; params->referrer = Referrer(); params->transition = transition; params->redirects = std::vector<GURL>(); params->should_update_history = false; params->searchable_form_url = GURL(); params->searchable_form_encoding = std::string(); params->did_create_new_entry = did_create_new_entry; params->gesture = NavigationGestureUser; params->was_within_same_document = false; params->method = "GET"; params->page_state = PageState::CreateFromURL(url); } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <iclelland@chromium.org> Reviewed-by: Charles Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254
void InitNavigateParams(FrameHostMsg_DidCommitProvisionalLoad_Params* params, int nav_entry_id, bool did_create_new_entry, const GURL& url, ui::PageTransition transition) { params->nav_entry_id = nav_entry_id; params->url = url; params->origin = url::Origin(url); params->referrer = Referrer(); params->transition = transition; params->redirects = std::vector<GURL>(); params->should_update_history = false; params->searchable_form_url = GURL(); params->searchable_form_encoding = std::string(); params->did_create_new_entry = did_create_new_entry; params->gesture = NavigationGestureUser; params->was_within_same_document = false; params->method = "GET"; params->page_state = PageState::CreateFromURL(url); }
171,965
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: XGetModifierMapping(register Display *dpy) { xGetModifierMappingReply rep; register xReq *req; unsigned long nbytes; XModifierKeymap *res; LockDisplay(dpy); GetEmptyReq(GetModifierMapping, req); (void) _XReply (dpy, (xReply *)&rep, 0, xFalse); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long)rep.length << 2; res = Xmalloc(sizeof (XModifierKeymap)); if (res) } else res = NULL; if ((! res) || (! res->modifiermap)) { Xfree(res); res = (XModifierKeymap *) NULL; _XEatDataWords(dpy, rep.length); } else { _XReadPad(dpy, (char *) res->modifiermap, (long) nbytes); res->max_keypermod = rep.numKeyPerModifier; } UnlockDisplay(dpy); SyncHandle(); return (res); } Commit Message: CWE ID: CWE-787
XGetModifierMapping(register Display *dpy) { xGetModifierMappingReply rep; register xReq *req; unsigned long nbytes; XModifierKeymap *res; LockDisplay(dpy); GetEmptyReq(GetModifierMapping, req); (void) _XReply (dpy, (xReply *)&rep, 0, xFalse); if (rep.length < (INT_MAX >> 2) && (rep.length >> 1) == rep.numKeyPerModifier) { nbytes = (unsigned long)rep.length << 2; res = Xmalloc(sizeof (XModifierKeymap)); if (res) } else res = NULL; if ((! res) || (! res->modifiermap)) { Xfree(res); res = (XModifierKeymap *) NULL; _XEatDataWords(dpy, rep.length); } else { _XReadPad(dpy, (char *) res->modifiermap, (long) nbytes); res->max_keypermod = rep.numKeyPerModifier; } UnlockDisplay(dpy); SyncHandle(); return (res); }
164,924
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static js_Ast *callexp(js_State *J) { js_Ast *a = newexp(J); loop: if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } if (jsP_accept(J, '(')) { a = EXP2(CALL, a, arguments(J)); jsP_expect(J, ')'); goto loop; } return a; } Commit Message: CWE ID: CWE-674
static js_Ast *callexp(js_State *J) { js_Ast *a = newexp(J); SAVEREC(); loop: INCREC(); if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } if (jsP_accept(J, '(')) { a = EXP2(CALL, a, arguments(J)); jsP_expect(J, ')'); goto loop; } POPREC(); return a; }
165,135
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: unsigned int SAD(unsigned int max_sad, int block_idx = 0) { unsigned int ret; const uint8_t* const reference = GetReference(block_idx); REGISTER_STATE_CHECK(ret = GET_PARAM(2)(source_data_, source_stride_, reference, reference_stride_, max_sad)); return ret; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
unsigned int SAD(unsigned int max_sad, int block_idx = 0) {
174,575
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int BrowserNonClientFrameViewAura::NonClientTopBorderHeight( bool force_restored) const { if (frame()->widget_delegate() && frame()->widget_delegate()->ShouldShowWindowTitle()) { return close_button_->bounds().bottom(); } if (!frame()->IsMaximized() || force_restored) return kTabstripTopSpacingRestored; return kTabstripTopSpacingMaximized; } Commit Message: Ash: Fix fullscreen window bounds I was computing the non-client frame top border height incorrectly for fullscreen windows, so it was trying to draw a few pixels of transparent non-client border. BUG=118774 TEST=visual Review URL: http://codereview.chromium.org/9810014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@128014 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
int BrowserNonClientFrameViewAura::NonClientTopBorderHeight( bool force_restored) const { if (force_restored) return kTabstripTopSpacingRestored; if (frame()->IsFullscreen()) return 0; if (frame()->IsMaximized()) return kTabstripTopSpacingMaximized; if (frame()->widget_delegate() && frame()->widget_delegate()->ShouldShowWindowTitle()) { return close_button_->bounds().bottom(); } return kTabstripTopSpacingRestored; }
171,004
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool AXNodeObject::isMultiSelectable() const { const AtomicString& ariaMultiSelectable = getAttribute(aria_multiselectableAttr); if (equalIgnoringCase(ariaMultiSelectable, "true")) return true; if (equalIgnoringCase(ariaMultiSelectable, "false")) return false; return isHTMLSelectElement(getNode()) && toHTMLSelectElement(*getNode()).isMultiple(); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool AXNodeObject::isMultiSelectable() const { const AtomicString& ariaMultiSelectable = getAttribute(aria_multiselectableAttr); if (equalIgnoringASCIICase(ariaMultiSelectable, "true")) return true; if (equalIgnoringASCIICase(ariaMultiSelectable, "false")) return false; return isHTMLSelectElement(getNode()) && toHTMLSelectElement(*getNode()).isMultiple(); }
171,917
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); if (end < start) { return false; } addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; } Commit Message: Add error logging on invalid cmap - DO NOT MERGE This patch logs instances of fonts with invalid cmap tables. Bug: 25645298 Bug: 26413177 Change-Id: I183985e9784a97a2b4307a22e036382b1fc90e5e CWE ID: CWE-20
static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { android_errorWriteLog(0x534e4554, "25645298"); return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); if (end < start) { android_errorWriteLog(0x534e4554, "26413177"); return false; } addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; }
173,895
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: AudioOutputDevice::AudioOutputDevice( AudioOutputIPC* ipc, const scoped_refptr<base::MessageLoopProxy>& io_loop) : ScopedLoopObserver(io_loop), input_channels_(0), callback_(NULL), ipc_(ipc), stream_id_(0), play_on_start_(true), is_started_(false), audio_thread_(new AudioDeviceThread()) { CHECK(ipc_); } Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call. I've kept my unit test changes intact but disabled until I get a proper fix. BUG=147499,150805 TBR=henrika Review URL: https://codereview.chromium.org/10946040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
AudioOutputDevice::AudioOutputDevice( AudioOutputIPC* ipc, const scoped_refptr<base::MessageLoopProxy>& io_loop) : ScopedLoopObserver(io_loop), input_channels_(0), callback_(NULL), ipc_(ipc), stream_id_(0), play_on_start_(true), is_started_(false) { CHECK(ipc_); }
170,703
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RenderWidgetHostViewGtk::AcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params, int gpu_host_id) { RenderWidgetHostImpl::AcknowledgeBufferPresent( params.route_id, gpu_host_id, true, 0); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewGtk::AcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params, int gpu_host_id) { RenderWidgetHostImpl::AcknowledgeBufferPresent( params.route_id, gpu_host_id, params.surface_handle, 0); }
171,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t OMXNodeInstance::setConfig( OMX_INDEXTYPE index, const void *params, size_t size) { Mutex::Autolock autoLock(mLock); OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index; CLOG_CONFIG(setConfig, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params); OMX_ERRORTYPE err = OMX_SetConfig( mHandle, index, const_cast<void *>(params)); CLOG_IF_ERROR(setConfig, err, "%s(%#x)", asString(extIndex), index); return StatusFromOMXError(err); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
status_t OMXNodeInstance::setConfig( OMX_INDEXTYPE index, const void *params, size_t size) { Mutex::Autolock autoLock(mLock); OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index; CLOG_CONFIG(setConfig, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params); if (isProhibitedIndex_l(index)) { android_errorWriteLog(0x534e4554, "29422020"); return BAD_INDEX; } OMX_ERRORTYPE err = OMX_SetConfig( mHandle, index, const_cast<void *>(params)); CLOG_IF_ERROR(setConfig, err, "%s(%#x)", asString(extIndex), index); return StatusFromOMXError(err); }
174,138
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: OMX_ERRORTYPE SoftMP3::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (const OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSamplingRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftMP3::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (const OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSamplingRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,212
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BrowserContextDestroyer::RenderProcessHostDestroyed( content::RenderProcessHost* host) { DCHECK_GT(pending_hosts_, 0U); if (--pending_hosts_ != 0) { return; } //// static if (content::RenderProcessHost::run_renderer_in_process()) { FinishDestroyContext(); } else { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&BrowserContextDestroyer::FinishDestroyContext, base::Unretained(this))); } } Commit Message: CWE ID: CWE-20
void BrowserContextDestroyer::RenderProcessHostDestroyed( content::RenderProcessHost* host) { DCHECK_GT(pending_host_ids_.size(), 0U); size_t erased = pending_host_ids_.erase(host->GetID()); DCHECK_GT(erased, 0U); MaybeScheduleFinishDestroyContext(host); } //// static void BrowserContextDestroyer::DestroyContext( std::unique_ptr<BrowserContext> context) { bool has_live_otr_context = false; uint32_t otr_contexts_pending_deletion = 0; if (!context->IsOffTheRecord()) { // If |context| is not an OTR BrowserContext, we need to keep track of how // many OTR BrowserContexts that were owned by it are scheduled for deletion // but still exist, as |context| must outlive these for (auto* destroyer : g_contexts_pending_deletion.Get()) { if (destroyer->context_->IsOffTheRecord() && destroyer->context_->GetOriginalContext() == context.get()) { ++otr_contexts_pending_deletion; } } // If |context| is not an OTR BrowserContext but currently owns a live OTR // BrowserContext, then we have to outlive that has_live_otr_context = context->HasOffTheRecordContext(); } else { // If |context| is an OTR BrowserContext and its owner has already been // scheduled for deletion, then we need to prevent the owner from being // deleted until after |context| BrowserContextDestroyer* orig_destroyer = GetForContext(context->GetOriginalContext()); if (orig_destroyer) { CHECK(!orig_destroyer->finish_destroy_scheduled_); ++orig_destroyer->otr_contexts_pending_deletion_; } } // Get all of the live RenderProcessHosts that are using |context| std::set<content::RenderProcessHost*> hosts = GetHostsForContext(context.get()); content::BrowserContext::NotifyWillBeDestroyed(context.get()); // |hosts| might not be empty if the application released its BrowserContext // too early, or if |context| is an OTR context or this application is single // process if (!hosts.empty() || otr_contexts_pending_deletion > 0 || has_live_otr_context) { // |context| is not safe to delete yet new BrowserContextDestroyer(std::move(context), hosts, otr_contexts_pending_deletion); } }
165,421
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::string SanitizeRemoteBase(const std::string& value) { GURL url(value); std::string path = url.path(); std::vector<std::string> parts = base::SplitString( path, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); std::string revision = parts.size() > 2 ? parts[2] : ""; revision = SanitizeRevision(revision); path = base::StringPrintf("/%s/%s/", kRemoteFrontendPath, revision.c_str()); return SanitizeFrontendURL(url, url::kHttpsScheme, kRemoteFrontendDomain, path, false).spec(); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
std::string SanitizeRemoteBase(const std::string& value) {
172,462