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: void TargetHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { auto_attacher_.SetRenderFrameHost(frame_host); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void TargetHandler::SetRenderer(RenderProcessHost* process_host, void TargetHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { auto_attacher_.SetRenderFrameHost(frame_host); }
172,780
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 UDPSocketLibevent::DoBind(const IPEndPoint& address) { SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_ADDRESS_INVALID; int rv = bind(socket_, storage.addr, storage.addr_len); if (rv == 0) return OK; int last_error = errno; UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketBindErrorFromPosix", last_error); return MapSystemError(last_error); } Commit Message: Map posix error codes in bind better, and fix one windows mapping. r=wtc BUG=330233 Review URL: https://codereview.chromium.org/101193008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
int UDPSocketLibevent::DoBind(const IPEndPoint& address) { SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_ADDRESS_INVALID; int rv = bind(socket_, storage.addr, storage.addr_len); if (rv == 0) return OK; int last_error = errno; UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketBindErrorFromPosix", last_error); #if defined(OS_CHROMEOS) if (last_error == EINVAL) return ERR_ADDRESS_IN_USE; #elif defined(OS_MACOSX) if (last_error == EADDRNOTAVAIL) return ERR_ADDRESS_IN_USE; #endif return MapSystemError(last_error); }
171,315
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 long Cluster::GetFirstTime() const { const BlockEntry* pEntry; const long status = GetFirst(pEntry); if (status < 0) //error return status; if (pEntry == NULL) //empty cluster return GetTime(); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); return pBlock->GetTime(this); } 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 long Cluster::GetFirstTime() const
174,323
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: l2tp_proto_ver_print(netdissect_options *ndo, const uint16_t *dat) { ND_PRINT((ndo, "%u.%u", (EXTRACT_16BITS(dat) >> 8), (EXTRACT_16BITS(dat) & 0xff))); } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_proto_ver_print(netdissect_options *ndo, const uint16_t *dat) l2tp_proto_ver_print(netdissect_options *ndo, const uint16_t *dat, u_int length) { if (length < 2) { ND_PRINT((ndo, "AVP too short")); return; } ND_PRINT((ndo, "%u.%u", (EXTRACT_16BITS(dat) >> 8), (EXTRACT_16BITS(dat) & 0xff))); }
167,898
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: entry_guard_obeys_restriction(const entry_guard_t *guard, const entry_guard_restriction_t *rst) { tor_assert(guard); if (! rst) return 1; // No restriction? No problem. return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN); } Commit Message: Consider the exit family when applying guard restrictions. When the new path selection logic went into place, I accidentally dropped the code that considered the _family_ of the exit node when deciding if the guard was usable, and we didn't catch that during code review. This patch makes the guard_restriction_t code consider the exit family as well, and adds some (hopefully redundant) checks for the case where we lack a node_t for a guard but we have a bridge_info_t for it. Fixes bug 22753; bugfix on 0.3.0.1-alpha. Tracked as TROVE-2016-006 and CVE-2017-0377. CWE ID: CWE-200
entry_guard_obeys_restriction(const entry_guard_t *guard, const entry_guard_restriction_t *rst) { tor_assert(guard); if (! rst) return 1; // No restriction? No problem. // Only one kind of restriction exists right now: excluding an exit // ID and all of its family. const node_t *node = node_get_by_id((const char*)rst->exclude_id); if (node && guard_in_node_family(guard, node)) return 0; return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN); }
168,450
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 nfsd_mountpoint(struct dentry *dentry, struct svc_export *exp) { if (d_mountpoint(dentry)) return 1; if (nfsd4_is_junction(dentry)) return 1; if (!(exp->ex_flags & NFSEXP_V4ROOT)) return 0; return d_inode(dentry) != NULL; } 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
int nfsd_mountpoint(struct dentry *dentry, struct svc_export *exp) { if (!d_inode(dentry)) return 0; if (exp->ex_flags & NFSEXP_V4ROOT) return 1; if (nfsd4_is_junction(dentry)) return 1; if (d_mountpoint(dentry)) /* * Might only be a mountpoint in a different namespace, * but we need to check. */ return 2; return 0; }
168,154
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 struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev, struct ib_udata *udata) { int ret = 0; struct hns_roce_ucontext *context; struct hns_roce_ib_alloc_ucontext_resp resp; struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); resp.qp_tab_size = hr_dev->caps.num_qps; context = kmalloc(sizeof(*context), GFP_KERNEL); if (!context) return ERR_PTR(-ENOMEM); ret = hns_roce_uar_alloc(hr_dev, &context->uar); if (ret) goto error_fail_uar_alloc; if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) { INIT_LIST_HEAD(&context->page_list); mutex_init(&context->page_mutex); } ret = ib_copy_to_udata(udata, &resp, sizeof(resp)); if (ret) goto error_fail_copy_to_udata; return &context->ibucontext; error_fail_copy_to_udata: hns_roce_uar_free(hr_dev, &context->uar); error_fail_uar_alloc: kfree(context); return ERR_PTR(ret); } Commit Message: RDMA/hns: Fix init resp when alloc ucontext The data in resp will be copied from kernel to userspace, thus it needs to be initialized to zeros to avoid copying uninited stack memory. Reported-by: Dan Carpenter <dan.carpenter@oracle.com> Fixes: e088a685eae9 ("RDMA/hns: Support rq record doorbell for the user space") Signed-off-by: Yixian Liu <liuyixian@huawei.com> Signed-off-by: Jason Gunthorpe <jgg@mellanox.com> CWE ID: CWE-665
static struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev, struct ib_udata *udata) { int ret = 0; struct hns_roce_ucontext *context; struct hns_roce_ib_alloc_ucontext_resp resp = {}; struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); resp.qp_tab_size = hr_dev->caps.num_qps; context = kmalloc(sizeof(*context), GFP_KERNEL); if (!context) return ERR_PTR(-ENOMEM); ret = hns_roce_uar_alloc(hr_dev, &context->uar); if (ret) goto error_fail_uar_alloc; if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) { INIT_LIST_HEAD(&context->page_list); mutex_init(&context->page_mutex); } ret = ib_copy_to_udata(udata, &resp, sizeof(resp)); if (ret) goto error_fail_copy_to_udata; return &context->ibucontext; error_fail_copy_to_udata: hns_roce_uar_free(hr_dev, &context->uar); error_fail_uar_alloc: kfree(context); return ERR_PTR(ret); }
169,504
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 BrowserCommandController::RemoveInterstitialObservers( TabContents* contents) { registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED, content::Source<WebContents>(contents->web_contents())); registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_DETACHED, content::Source<WebContents>(contents->web_contents())); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void BrowserCommandController::RemoveInterstitialObservers( WebContents* contents) { registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED, content::Source<WebContents>(contents)); registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_DETACHED, content::Source<WebContents>(contents)); }
171,510
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::hasContentEditableAttributeSet() const { const AtomicString& contentEditableValue = getAttribute(contenteditableAttr); if (contentEditableValue.isNull()) return false; return contentEditableValue.isEmpty() || equalIgnoringCase(contentEditableValue, "true"); } 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::hasContentEditableAttributeSet() const { const AtomicString& contentEditableValue = getAttribute(contenteditableAttr); if (contentEditableValue.isNull()) return false; return contentEditableValue.isEmpty() || equalIgnoringASCIICase(contentEditableValue, "true"); }
171,913
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 ChromeRenderProcessObserver::OnWriteTcmallocHeapProfile( const FilePath::StringType& filename) { #if !defined(OS_WIN) if (!IsHeapProfilerRunning()) return; char* profile = GetHeapProfile(); if (!profile) { LOG(WARNING) << "Unable to get heap profile."; return; } std::string result(profile); delete profile; RenderThread::Get()->Send( new ChromeViewHostMsg_WriteTcmallocHeapProfile_ACK(filename, result)); #endif } Commit Message: Disable tcmalloc profile files. BUG=154983 TBR=darin@chromium.org NOTRY=true Review URL: https://chromiumcodereview.appspot.com/11087041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void ChromeRenderProcessObserver::OnWriteTcmallocHeapProfile(
170,667
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: ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," n len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!ike_show_somedata(ndo, (const u_char *)(const uint8_t *)(ext + 1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } Commit Message: CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data. The closest thing to a specification for the contents of the payload data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it is ever a complete ISAKMP message, so don't dissect types we don't have specific code for as a complete ISAKMP message. While we're at it, fix a comment, and clean up printing of V1 Nonce, V2 Authentication payloads, and v2 Notice payloads. This fixes an infinite loop 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-835
ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; }
167,925
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 inline void encode_openhdr(struct xdr_stream *xdr, const struct nfs_openargs *arg) { __be32 *p; /* * opcode 4, seqid 4, share_access 4, share_deny 4, clientid 8, ownerlen 4, * owner 4 = 32 */ RESERVE_SPACE(8); WRITE32(OP_OPEN); WRITE32(arg->seqid->sequence->counter); encode_share_access(xdr, arg->open_flags); RESERVE_SPACE(28); WRITE64(arg->clientid); WRITE32(16); WRITEMEM("open id:", 8); WRITE64(arg->id); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
static inline void encode_openhdr(struct xdr_stream *xdr, const struct nfs_openargs *arg) { __be32 *p; /* * opcode 4, seqid 4, share_access 4, share_deny 4, clientid 8, ownerlen 4, * owner 4 = 32 */ RESERVE_SPACE(8); WRITE32(OP_OPEN); WRITE32(arg->seqid->sequence->counter); encode_share_access(xdr, arg->fmode); RESERVE_SPACE(28); WRITE64(arg->clientid); WRITE32(16); WRITEMEM("open id:", 8); WRITE64(arg->id); }
165,714
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 Parcel::readUtf8FromUtf16(std::string* str) const { size_t utf16Size = 0; const char16_t* src = readString16Inplace(&utf16Size); if (!src) { return UNEXPECTED_NULL; } if (utf16Size == 0u) { str->clear(); return NO_ERROR; } ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size); if (utf8Size < 0) { return BAD_VALUE; } str->resize(utf8Size + 1); utf16_to_utf8(src, utf16Size, &((*str)[0])); str->resize(utf8Size); return NO_ERROR; } Commit Message: Add bound checks to utf16_to_utf8 Bug: 29250543 Change-Id: I518e7b2fe10aaa3f1c1987586a09b1110aff7e1a (cherry picked from commit 7e93b2ddcb49b5365fbe1dab134ffb38e6f1c719) CWE ID: CWE-119
status_t Parcel::readUtf8FromUtf16(std::string* str) const { size_t utf16Size = 0; const char16_t* src = readString16Inplace(&utf16Size); if (!src) { return UNEXPECTED_NULL; } if (utf16Size == 0u) { str->clear(); return NO_ERROR; } // Allow for closing '\0' ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size) + 1; if (utf8Size < 1) { return BAD_VALUE; } // spare byte around for the trailing null, we still pass the size including the trailing null str->resize(utf8Size); utf16_to_utf8(src, utf16Size, &((*str)[0]), utf8Size); str->resize(utf8Size - 1); return NO_ERROR; }
174,158
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 get_socket_name(SingleInstData* data, char* buf, int len) { const char* dpy = g_getenv("DISPLAY"); char* host = NULL; int dpynum; if(dpy) { const char* p = strrchr(dpy, ':'); host = g_strndup(dpy, (p - dpy)); dpynum = atoi(p + 1); } else dpynum = 0; g_snprintf(buf, len, "%s/.%s-socket-%s-%d-%s", g_get_tmp_dir(), data->prog_name, host ? host : "", dpynum, g_get_user_name()); } Commit Message: CWE ID: CWE-20
static void get_socket_name(SingleInstData* data, char* buf, int len) { const char* dpy = g_getenv("DISPLAY"); char* host = NULL; int dpynum; if(dpy) { const char* p = strrchr(dpy, ':'); host = g_strndup(dpy, (p - dpy)); dpynum = atoi(p + 1); } else dpynum = 0; #if GLIB_CHECK_VERSION(2, 28, 0) g_snprintf(buf, len, "%s/%s-socket-%s-%d", g_get_user_runtime_dir(), data->prog_name, host ? host : "", dpynum); #else g_snprintf(buf, len, "%s/.%s-socket-%s-%d-%s", g_get_tmp_dir(), data->prog_name, host ? host : "", dpynum, g_get_user_name()); #endif }
164,816
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: XcursorImageCreate (int width, int height) { XcursorImage *image; image = malloc (sizeof (XcursorImage) + width * height * sizeof (XcursorPixel)); if (!image) image->height = height; image->delay = 0; return image; } Commit Message: CWE ID: CWE-190
XcursorImageCreate (int width, int height) { XcursorImage *image; if (width < 0 || height < 0) return NULL; if (width > XCURSOR_IMAGE_MAX_SIZE || height > XCURSOR_IMAGE_MAX_SIZE) return NULL; image = malloc (sizeof (XcursorImage) + width * height * sizeof (XcursorPixel)); if (!image) image->height = height; image->delay = 0; return image; }
164,626
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: explicit ElementsAccessorBase(const char* name) : ElementsAccessor(name) { } 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
explicit ElementsAccessorBase(const char* name)
174,095
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 InspectorHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { host_ = frame_host; } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void InspectorHandler::SetRenderer(RenderProcessHost* process_host, void InspectorHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { host_ = frame_host; }
172,748
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 BlockEntry::EOS() const { return (GetKind() == kBlockEOS); } 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 BlockEntry::EOS() const
174,271
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: PP_Bool LaunchSelLdr(PP_Instance instance, const char* alleged_url, int socket_count, void* imc_handles) { std::vector<nacl::FileDescriptor> sockets; IPC::Sender* sender = content::RenderThread::Get(); if (sender == NULL) sender = g_background_thread_sender.Pointer()->get(); IPC::ChannelHandle channel_handle; if (!sender->Send(new ChromeViewHostMsg_LaunchNaCl( GURL(alleged_url), socket_count, &sockets, &channel_handle))) { return PP_FALSE; } bool invalid_handle = channel_handle.name.empty(); #if defined(OS_POSIX) if (!invalid_handle) invalid_handle = (channel_handle.socket.fd == -1); #endif if (!invalid_handle) g_channel_handle_map.Get()[instance] = channel_handle; CHECK(static_cast<int>(sockets.size()) == socket_count); for (int i = 0; i < socket_count; i++) { static_cast<nacl::Handle*>(imc_handles)[i] = nacl::ToNativeHandle(sockets[i]); } return PP_TRUE; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
PP_Bool LaunchSelLdr(PP_Instance instance, const char* alleged_url, int socket_count, void* imc_handles) { std::vector<nacl::FileDescriptor> sockets; IPC::Sender* sender = content::RenderThread::Get(); if (sender == NULL) sender = g_background_thread_sender.Pointer()->get(); if (!sender->Send(new ChromeViewHostMsg_LaunchNaCl( GURL(alleged_url), socket_count, &sockets))) return PP_FALSE; CHECK(static_cast<int>(sockets.size()) == socket_count); for (int i = 0; i < socket_count; i++) { static_cast<nacl::Handle*>(imc_handles)[i] = nacl::ToNativeHandle(sockets[i]); } return PP_TRUE; }
170,736
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: media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() { if (!media_service_factory_) { mojo::InterfacePtr<mojo::Shell> shell_ptr; GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&shell_ptr)); mojo::ServiceProviderPtr service_provider; mojo::URLRequestPtr request(mojo::URLRequest::New()); request->url = mojo::String::From("mojo:media"); shell_ptr->ConnectToApplication(request.Pass(), GetProxy(&service_provider), nullptr, nullptr); mojo::ConnectToService(service_provider.get(), &media_service_factory_); media_service_factory_.set_connection_error_handler( base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError, base::Unretained(this))); } return media_service_factory_.get(); } Commit Message: Connect WebUSB client interface to the devices app This provides a basic WebUSB client interface in content/renderer. Most of the interface is unimplemented, but this CL hooks up navigator.usb.getDevices() to the browser's Mojo devices app to enumerate available USB devices. BUG=492204 Review URL: https://codereview.chromium.org/1293253002 Cr-Commit-Position: refs/heads/master@{#344881} CWE ID: CWE-399
media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() { if (!media_service_factory_) { mojo::ServiceProviderPtr service_provider = ConnectToApplication(GURL("mojo:media")); mojo::ConnectToService(service_provider.get(), &media_service_factory_); media_service_factory_.set_connection_error_handler( base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError, base::Unretained(this))); } return media_service_factory_.get(); }
171,696
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 inline void AllocatePixelCachePixels(CacheInfo *cache_info) { cache_info->mapped=MagickFalse; cache_info->pixels=(PixelPacket *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); if (cache_info->pixels == (PixelPacket *) NULL) { cache_info->mapped=MagickTrue; cache_info->pixels=(PixelPacket *) MapBlob(-1,IOMode,0,(size_t) cache_info->length); } } Commit Message: http://www.imagemagick.org/discourse-server/viewtopic.php?f=2&t=28946 CWE ID: CWE-399
static inline void AllocatePixelCachePixels(CacheInfo *cache_info)
168,787
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_AddItemToObject( cJSON *object, const char *string, cJSON *item ) { if ( ! item ) return; if ( item->string ) cJSON_free( item->string ); item->string = cJSON_strdup( string ); cJSON_AddItemToArray( object, item ); } 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_AddItemToObject( cJSON *object, const char *string, cJSON *item )
167,268
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 ExtensionTtsPlatformImplWin::Speak( const std::string& src_utterance, const std::string& language, const std::string& gender, double rate, double pitch, double volume) { std::wstring utterance = UTF8ToUTF16(src_utterance); if (!speech_synthesizer_) return false; if (rate >= 0.0) { speech_synthesizer_->SetRate(static_cast<int32>(rate * 20 - 10)); } if (pitch >= 0.0) { std::wstring pitch_value = base::IntToString16(static_cast<int>(pitch * 20 - 10)); utterance = L"<pitch absmiddle=\"" + pitch_value + L"\">" + utterance + L"</pitch>"; } if (volume >= 0.0) { speech_synthesizer_->SetVolume(static_cast<uint16>(volume * 100)); } if (paused_) { speech_synthesizer_->Resume(); paused_ = false; } speech_synthesizer_->Speak( utterance.c_str(), SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL); return true; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool ExtensionTtsPlatformImplWin::Speak( int utterance_id, const std::string& src_utterance, const std::string& lang, const UtteranceContinuousParameters& params) { std::wstring prefix; std::wstring suffix; if (!speech_synthesizer_) return false; // TODO(dmazzoni): support languages other than the default: crbug.com/88059 if (params.rate >= 0.0) { // Map our multiplicative range of 0.1x to 10.0x onto Microsoft's // linear range of -10 to 10: // 0.1 -> -10 // 1.0 -> 0 // 10.0 -> 10 speech_synthesizer_->SetRate(static_cast<int32>(10 * log10(params.rate))); } if (params.pitch >= 0.0) { std::wstring pitch_value = base::IntToString16(static_cast<int>(params.pitch * 10 - 10)); prefix = L"<pitch absmiddle=\"" + pitch_value + L"\">"; suffix = L"</pitch>"; } if (params.volume >= 0.0) { speech_synthesizer_->SetVolume(static_cast<uint16>(params.volume * 100)); } if (paused_) { speech_synthesizer_->Resume(); paused_ = false; } // TODO(dmazzoni): convert SSML to SAPI xml. http://crbug.com/88072 utterance_ = UTF8ToWide(src_utterance); utterance_id_ = utterance_id; char_position_ = 0; std::wstring merged_utterance = prefix + utterance_ + suffix; prefix_len_ = prefix.size(); HRESULT result = speech_synthesizer_->Speak( merged_utterance.c_str(), SPF_ASYNC | SPF_PURGEBEFORESPEAK, &stream_number_); return (result == S_OK); }
170,402
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 msleep(uint64_t ms) { usleep(ms * 1000); } 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 void msleep(uint64_t ms) { TEMP_FAILURE_RETRY(usleep(ms * 1000)); }
173,489
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 inline int hpel_motion(MpegEncContext *s, uint8_t *dest, uint8_t *src, int src_x, int src_y, op_pixels_func *pix_op, int motion_x, int motion_y) { int dxy = 0; int emu = 0; src_x += motion_x >> 1; src_y += motion_y >> 1; /* WARNING: do no forget half pels */ src_x = av_clip(src_x, -16, s->width); // FIXME unneeded for emu? if (src_x != s->width) dxy |= motion_x & 1; src_y = av_clip(src_y, -16, s->height); if (src_y != s->height) dxy |= (motion_y & 1) << 1; src += src_y * s->linesize + src_x; if (s->unrestricted_mv) { if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) || (unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) { s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src, s->linesize, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos); src = s->sc.edge_emu_buffer; emu = 1; } } pix_op[dxy](dest, src, s->linesize, 8); return emu; } Commit Message: CWE ID: CWE-476
static inline int hpel_motion(MpegEncContext *s, uint8_t *dest, uint8_t *src, int src_x, int src_y, op_pixels_func *pix_op, int motion_x, int motion_y) { int dxy = 0; int emu = 0; src_x += motion_x >> 1; src_y += motion_y >> 1; /* WARNING: do no forget half pels */ src_x = av_clip(src_x, -16, s->width); // FIXME unneeded for emu? if (src_x != s->width) dxy |= motion_x & 1; src_y = av_clip(src_y, -16, s->height); if (src_y != s->height) dxy |= (motion_y & 1) << 1; src += src_y * s->linesize + src_x; if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) || (unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) { s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src, s->linesize, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos); src = s->sc.edge_emu_buffer; emu = 1; } pix_op[dxy](dest, src, s->linesize, 8); return emu; }
164,927
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 long Chapters::Atom::GetStopTime(const Chapters* pChapters) const { return GetTime(pChapters, m_stop_timecode); } 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 long Chapters::Atom::GetStopTime(const Chapters* pChapters) const
174,357
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 RunCoeffCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) input_block[j] = rnd.Rand8() - rnd.Rand8(); fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_); REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) EXPECT_EQ(output_block[j], output_ref_block[j]); } } 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
void RunCoeffCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED(16, int16_t, input_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]); for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_, mask_]. for (int j = 0; j < kNumCoeffs; ++j) input_block[j] = (rnd.Rand16() & mask_) - (rnd.Rand16() & mask_); fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_); ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) EXPECT_EQ(output_block[j], output_ref_block[j]); } }
174,520
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 inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly) { ASSERT(&topResolver.runs() == &bidiRuns); ASSERT(topResolver.position() != endOfRuns); RenderObject* currentRoot = topResolver.position().root(); topResolver.createBidiRunsForLine(endOfRuns, override, previousLineBrokeCleanly); while (!topResolver.isolatedRuns().isEmpty()) { BidiRun* isolatedRun = topResolver.isolatedRuns().last(); topResolver.isolatedRuns().removeLast(); RenderObject* startObj = isolatedRun->object(); RenderInline* isolatedInline = toRenderInline(containingIsolate(startObj, currentRoot)); InlineBidiResolver isolatedResolver; EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi(); TextDirection direction = isolatedInline->style()->direction(); if (unicodeBidi == Plaintext) direction = determinePlaintextDirectionality(isolatedInline, startObj); else { ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride); direction = isolatedInline->style()->direction(); } isolatedResolver.setStatus(statusWithDirection(direction, isOverride(unicodeBidi))); setupResolverToResumeInIsolate(isolatedResolver, isolatedInline, startObj); InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start); isolatedResolver.setPositionIgnoringNestedIsolates(iter); isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly); if (isolatedResolver.runs().runCount()) bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs()); if (!isolatedResolver.isolatedRuns().isEmpty()) { topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns()); isolatedResolver.isolatedRuns().clear(); currentRoot = isolatedInline; } } } Commit Message: Update containtingIsolate to go back all the way to top isolate from current root, rather than stopping at the first isolate it finds. This works because the current root is always updated with each isolate run. BUG=279277 Review URL: https://chromiumcodereview.appspot.com/23972003 git-svn-id: svn://svn.chromium.org/blink/trunk@157268 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly) { ASSERT(&topResolver.runs() == &bidiRuns); ASSERT(topResolver.position() != endOfRuns); RenderObject* currentRoot = topResolver.position().root(); topResolver.createBidiRunsForLine(endOfRuns, override, previousLineBrokeCleanly); while (!topResolver.isolatedRuns().isEmpty()) { BidiRun* isolatedRun = topResolver.isolatedRuns().last(); topResolver.isolatedRuns().removeLast(); RenderObject* startObj = isolatedRun->object(); RenderInline* isolatedInline = toRenderInline(highestContainingIsolateWithinRoot(startObj, currentRoot)); ASSERT(isolatedInline); InlineBidiResolver isolatedResolver; EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi(); TextDirection direction = isolatedInline->style()->direction(); if (unicodeBidi == Plaintext) direction = determinePlaintextDirectionality(isolatedInline, startObj); else { ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride); direction = isolatedInline->style()->direction(); } isolatedResolver.setStatus(statusWithDirection(direction, isOverride(unicodeBidi))); setupResolverToResumeInIsolate(isolatedResolver, isolatedInline, startObj); InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start); isolatedResolver.setPositionIgnoringNestedIsolates(iter); isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly); if (isolatedResolver.runs().runCount()) bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs()); if (!isolatedResolver.isolatedRuns().isEmpty()) { topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns()); isolatedResolver.isolatedRuns().clear(); currentRoot = isolatedInline; } } }
171,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: int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset, int len) { int r; unsigned long addr; addr = gfn_to_hva(kvm, gfn); if (kvm_is_error_hva(addr)) return -EFAULT; r = copy_from_user(data, (void __user *)addr + offset, len); if (r) return -EFAULT; return 0; } Commit Message: KVM: Validate userspace_addr of memslot when registered This way, we can avoid checking the user space address many times when we read the guest memory. Although we can do the same for write if we check which slots are writable, we do not care write now: reading the guest memory happens more often than writing. [avi: change VERIFY_READ to VERIFY_WRITE] Signed-off-by: Takuya Yoshikawa <yoshikawa.takuya@oss.ntt.co.jp> Signed-off-by: Avi Kivity <avi@redhat.com> CWE ID: CWE-20
int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset, int len) { int r; unsigned long addr; addr = gfn_to_hva(kvm, gfn); if (kvm_is_error_hva(addr)) return -EFAULT; r = __copy_from_user(data, (void __user *)addr + offset, len); if (r) return -EFAULT; return 0; }
166,100
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: HistogramBase* SparseHistogram::FactoryGet(const std::string& name, int32_t flags) { HistogramBase* histogram = StatisticsRecorder::FindHistogram(name); if (!histogram) { PersistentMemoryAllocator::Reference histogram_ref = 0; std::unique_ptr<HistogramBase> tentative_histogram; PersistentHistogramAllocator* allocator = GlobalHistogramAllocator::Get(); if (allocator) { tentative_histogram = allocator->AllocateHistogram( SPARSE_HISTOGRAM, name, 0, 0, nullptr, flags, &histogram_ref); } if (!tentative_histogram) { DCHECK(!histogram_ref); // Should never have been set. DCHECK(!allocator); // Shouldn't have failed. flags &= ~HistogramBase::kIsPersistent; tentative_histogram.reset(new SparseHistogram(name)); tentative_histogram->SetFlags(flags); } const void* tentative_histogram_ptr = tentative_histogram.get(); histogram = StatisticsRecorder::RegisterOrDeleteDuplicate( tentative_histogram.release()); if (histogram_ref) { allocator->FinalizeHistogram(histogram_ref, histogram == tentative_histogram_ptr); } ReportHistogramActivity(*histogram, HISTOGRAM_CREATED); } else { ReportHistogramActivity(*histogram, HISTOGRAM_LOOKUP); } DCHECK_EQ(SPARSE_HISTOGRAM, histogram->GetHistogramType()); return histogram; } Commit Message: Convert DCHECKs to CHECKs for histogram types When a histogram is looked up by name, there is currently a DCHECK that verifies the type of the stored histogram matches the expected type. A mismatch represents a significant problem because the returned HistogramBase is cast to a Histogram in ValidateRangeChecksum, potentially causing a crash. This CL converts the DCHECK to a CHECK to prevent the possibility of type confusion in release builds. BUG=651443 R=isherman@chromium.org Review-Url: https://codereview.chromium.org/2381893003 Cr-Commit-Position: refs/heads/master@{#421929} CWE ID: CWE-476
HistogramBase* SparseHistogram::FactoryGet(const std::string& name, int32_t flags) { HistogramBase* histogram = StatisticsRecorder::FindHistogram(name); if (!histogram) { PersistentMemoryAllocator::Reference histogram_ref = 0; std::unique_ptr<HistogramBase> tentative_histogram; PersistentHistogramAllocator* allocator = GlobalHistogramAllocator::Get(); if (allocator) { tentative_histogram = allocator->AllocateHistogram( SPARSE_HISTOGRAM, name, 0, 0, nullptr, flags, &histogram_ref); } if (!tentative_histogram) { DCHECK(!histogram_ref); // Should never have been set. DCHECK(!allocator); // Shouldn't have failed. flags &= ~HistogramBase::kIsPersistent; tentative_histogram.reset(new SparseHistogram(name)); tentative_histogram->SetFlags(flags); } const void* tentative_histogram_ptr = tentative_histogram.get(); histogram = StatisticsRecorder::RegisterOrDeleteDuplicate( tentative_histogram.release()); if (histogram_ref) { allocator->FinalizeHistogram(histogram_ref, histogram == tentative_histogram_ptr); } ReportHistogramActivity(*histogram, HISTOGRAM_CREATED); } else { ReportHistogramActivity(*histogram, HISTOGRAM_LOOKUP); } CHECK_EQ(SPARSE_HISTOGRAM, histogram->GetHistogramType()); return histogram; }
172,494
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 CloudPolicySubsystem::StopAutoRetry() { cloud_policy_controller_->StopAutoRetry(); device_token_fetcher_->StopAutoRetry(); data_store_->Reset(); } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void CloudPolicySubsystem::StopAutoRetry() { void CloudPolicySubsystem::Reset() { data_store_->Reset(); cloud_policy_cache_->Reset(); cloud_policy_controller_->Reset(); device_token_fetcher_->Reset(); }
170,283
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 EnterpriseEnrollmentScreen::OnAuthCancelled() { UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentCancelled, policy::kMetricEnrollmentSize); auth_fetcher_.reset(); registrar_.reset(); g_browser_process->browser_policy_connector()->DeviceStopAutoRetry(); get_screen_observer()->OnExit( ScreenObserver::ENTERPRISE_ENROLLMENT_CANCELLED); } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void EnterpriseEnrollmentScreen::OnAuthCancelled() { UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentCancelled, policy::kMetricEnrollmentSize); auth_fetcher_.reset(); registrar_.reset(); g_browser_process->browser_policy_connector()->ResetDevicePolicy(); get_screen_observer()->OnExit( ScreenObserver::ENTERPRISE_ENROLLMENT_CANCELLED); }
170,276
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 HostCache::ClearForHosts( const base::Callback<bool(const std::string&)>& host_filter) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (host_filter.is_null()) { clear(); return; } base::TimeTicks now = base::TimeTicks::Now(); for (EntryMap::iterator it = entries_.begin(); it != entries_.end();) { EntryMap::iterator next_it = std::next(it); if (host_filter.Run(it->first.hostname)) { RecordErase(ERASE_CLEAR, now, it->second); entries_.erase(it); } it = next_it; } } Commit Message: Add PersistenceDelegate to HostCache PersistenceDelegate is a new interface for persisting the contents of the HostCache. This commit includes the interface itself, the logic in HostCache for interacting with it, and a mock implementation of the interface for testing. It does not include support for immediate data removal since that won't be needed for the currently planned use case. BUG=605149 Review-Url: https://codereview.chromium.org/2943143002 Cr-Commit-Position: refs/heads/master@{#481015} CWE ID:
void HostCache::ClearForHosts( const base::Callback<bool(const std::string&)>& host_filter) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (host_filter.is_null()) { clear(); return; } bool changed = false; base::TimeTicks now = base::TimeTicks::Now(); for (EntryMap::iterator it = entries_.begin(); it != entries_.end();) { EntryMap::iterator next_it = std::next(it); if (host_filter.Run(it->first.hostname)) { RecordErase(ERASE_CLEAR, now, it->second); entries_.erase(it); changed = true; } it = next_it; } if (delegate_ && changed) delegate_->ScheduleWrite(); }
172,006
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 PPB_Widget_Impl::Invalidate(const PP_Rect* dirty) { const PPP_Widget_Dev* widget = static_cast<const PPP_Widget_Dev*>( instance()->module()->GetPluginInterface(PPP_WIDGET_DEV_INTERFACE)); if (!widget) return; ScopedResourceId resource(this); widget->Invalidate(instance()->pp_instance(), resource.id, dirty); } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PPB_Widget_Impl::Invalidate(const PP_Rect* dirty) { if (!instance()) return; const PPP_Widget_Dev* widget = static_cast<const PPP_Widget_Dev*>( instance()->module()->GetPluginInterface(PPP_WIDGET_DEV_INTERFACE)); if (!widget) return; ScopedResourceId resource(this); widget->Invalidate(instance()->pp_instance(), resource.id, dirty); }
170,412
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: size_t compile_tree(struct filter_op **fop) { int i = 1; struct filter_op *array = NULL; struct unfold_elm *ue; BUG_IF(tree_root == NULL); fprintf(stdout, " Unfolding the meta-tree "); fflush(stdout); /* start the recursion on the tree */ unfold_blk(&tree_root); fprintf(stdout, " done.\n\n"); /* substitute the virtual labels with real offsets */ labels_to_offsets(); /* convert the tailq into an array */ TAILQ_FOREACH(ue, &unfolded_tree, next) { /* label == 0 means a real instruction */ if (ue->label == 0) { SAFE_REALLOC(array, i * sizeof(struct filter_op)); memcpy(&array[i - 1], &ue->fop, sizeof(struct filter_op)); i++; } } /* always append the exit function to a script */ SAFE_REALLOC(array, i * sizeof(struct filter_op)); array[i - 1].opcode = FOP_EXIT; /* return the pointer to the array */ *fop = array; return (i); } Commit Message: Exit gracefully in case of corrupted filters (Closes issue #782) CWE ID: CWE-125
size_t compile_tree(struct filter_op **fop) { int i = 1; struct filter_op *array = NULL; struct unfold_elm *ue; // invalid file if (tree_root == NULL) return 0; fprintf(stdout, " Unfolding the meta-tree "); fflush(stdout); /* start the recursion on the tree */ unfold_blk(&tree_root); fprintf(stdout, " done.\n\n"); /* substitute the virtual labels with real offsets */ labels_to_offsets(); /* convert the tailq into an array */ TAILQ_FOREACH(ue, &unfolded_tree, next) { /* label == 0 means a real instruction */ if (ue->label == 0) { SAFE_REALLOC(array, i * sizeof(struct filter_op)); memcpy(&array[i - 1], &ue->fop, sizeof(struct filter_op)); i++; } } /* always append the exit function to a script */ SAFE_REALLOC(array, i * sizeof(struct filter_op)); array[i - 1].opcode = FOP_EXIT; /* return the pointer to the array */ *fop = array; return (i); }
168,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: static inline int file_list_cpu(struct file *file) { #ifdef CONFIG_SMP return file->f_sb_list_cpu; #else return smp_processor_id(); #endif } 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
static inline int file_list_cpu(struct file *file)
166,797
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: find_auth_end (FlatpakProxyClient *client, Buffer *buffer) { guchar *match; int i; /* First try to match any leftover at the start */ if (client->auth_end_offset > 0) { gsize left = strlen (AUTH_END_STRING) - client->auth_end_offset; gsize to_match = MIN (left, buffer->pos); /* Matched at least up to to_match */ if (memcmp (buffer->data, &AUTH_END_STRING[client->auth_end_offset], to_match) == 0) { client->auth_end_offset += to_match; /* Matched all */ if (client->auth_end_offset == strlen (AUTH_END_STRING)) return to_match; /* Matched to end of buffer */ return -1; } /* Did not actually match at start */ client->auth_end_offset = -1; } /* Look for whole match inside buffer */ match = memmem (buffer, buffer->pos, AUTH_END_STRING, strlen (AUTH_END_STRING)); if (match != NULL) return match - buffer->data + strlen (AUTH_END_STRING); /* Record longest prefix match at the end */ for (i = MIN (strlen (AUTH_END_STRING) - 1, buffer->pos); i > 0; i--) { if (memcmp (buffer->data + buffer->pos - i, AUTH_END_STRING, i) == 0) { client->auth_end_offset = i; break; } } return -1; } Commit Message: Fix vulnerability in dbus proxy During the authentication all client data is directly forwarded to the dbus daemon as is, until we detect the BEGIN command after which we start filtering the binary dbus protocol. Unfortunately the detection of the BEGIN command in the proxy did not exactly match the detection in the dbus daemon. A BEGIN followed by a space or tab was considered ok in the daemon but not by the proxy. This could be exploited to send arbitrary dbus messages to the host, which can be used to break out of the sandbox. This was noticed by Gabriel Campana of The Google Security Team. This fix makes the detection of the authentication phase end match the dbus code. In addition we duplicate the authentication line validation from dbus, which includes ensuring all data is ASCII, and limiting the size of a line to 16k. In fact, we add some extra stringent checks, disallowing ASCII control chars and requiring that auth lines start with a capital letter. CWE ID: CWE-436
find_auth_end (FlatpakProxyClient *client, Buffer *buffer) { goffset offset = 0; gsize original_size = client->auth_buffer->len; /* Add the new data to the remaining data from last iteration */ g_byte_array_append (client->auth_buffer, buffer->data, buffer->pos); while (TRUE) { guint8 *line_start = client->auth_buffer->data + offset; gsize remaining_data = client->auth_buffer->len - offset; guint8 *line_end; line_end = memmem (line_start, remaining_data, AUTH_LINE_SENTINEL, strlen (AUTH_LINE_SENTINEL)); if (line_end) /* Found end of line */ { offset = (line_end + strlen (AUTH_LINE_SENTINEL) - line_start); if (!auth_line_is_valid (line_start, line_end)) return FIND_AUTH_END_ABORT; *line_end = 0; if (auth_line_is_begin (line_start)) return offset - original_size; /* continue with next line */ } else { /* No end-of-line in this buffer */ g_byte_array_remove_range (client->auth_buffer, 0, offset); /* Abort if more than 16k before newline, similar to what dbus-daemon does */ if (client->auth_buffer->len >= 16*1024) return FIND_AUTH_END_ABORT; return FIND_AUTH_END_CONTINUE; } } }
169,340
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: raptor_rss_parse_start(raptor_parser *rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int n; /* base URI required for RSS */ if(!uri) return 1; for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++) rss_parser->nspaces_seen[n] = 'N'; /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rss_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rss_parser->sax2, uri); return 0; } Commit Message: CVE-2012-0037 Enforce entity loading policy in raptor_libxml_resolveEntity and raptor_libxml_getEntity by checking for file URIs and network URIs. Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for turning on loading of XML external entity loading, disabled by default. This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and aliases) and rdfa. CWE ID: CWE-200
raptor_rss_parse_start(raptor_parser *rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int n; /* base URI required for RSS */ if(!uri) return 1; for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++) rss_parser->nspaces_seen[n] = 'N'; /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rss_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rss_parser->sax2, uri); return 0; }
165,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: LazyBackgroundPageNativeHandler::LazyBackgroundPageNativeHandler( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "IncrementKeepaliveCount", base::Bind(&LazyBackgroundPageNativeHandler::IncrementKeepaliveCount, base::Unretained(this))); RouteFunction( "DecrementKeepaliveCount", base::Bind(&LazyBackgroundPageNativeHandler::DecrementKeepaliveCount, base::Unretained(this))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
LazyBackgroundPageNativeHandler::LazyBackgroundPageNativeHandler( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "IncrementKeepaliveCount", "tts", base::Bind(&LazyBackgroundPageNativeHandler::IncrementKeepaliveCount, base::Unretained(this))); RouteFunction( "DecrementKeepaliveCount", "tts", base::Bind(&LazyBackgroundPageNativeHandler::DecrementKeepaliveCount, base::Unretained(this))); }
172,250
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: MediaElementAudioSourceHandler::MediaElementAudioSourceHandler( AudioNode& node, HTMLMediaElement& media_element) : AudioHandler(kNodeTypeMediaElementAudioSource, node, node.context()->sampleRate()), media_element_(media_element), source_number_of_channels_(0), source_sample_rate_(0), passes_current_src_cors_access_check_( PassesCurrentSrcCORSAccessCheck(media_element.currentSrc())), maybe_print_cors_message_(!passes_current_src_cors_access_check_), current_src_string_(media_element.currentSrc().GetString()) { DCHECK(IsMainThread()); AddOutput(2); if (Context()->GetExecutionContext()) { task_runner_ = Context()->GetExecutionContext()->GetTaskRunner( TaskType::kMediaElementEvent); } Initialize(); } 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
MediaElementAudioSourceHandler::MediaElementAudioSourceHandler( AudioNode& node, HTMLMediaElement& media_element) : AudioHandler(kNodeTypeMediaElementAudioSource, node, node.context()->sampleRate()), media_element_(media_element), source_number_of_channels_(0), source_sample_rate_(0), is_origin_tainted_(false) { DCHECK(IsMainThread()); AddOutput(2); if (Context()->GetExecutionContext()) { task_runner_ = Context()->GetExecutionContext()->GetTaskRunner( TaskType::kMediaElementEvent); } Initialize(); }
173,144
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 PromoResourceService::PostNotification(int64 delay_ms) { if (web_resource_update_scheduled_) return; if (delay_ms > 0) { web_resource_update_scheduled_ = true; MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PromoResourceService::PromoResourceStateChange, weak_ptr_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(delay_ms)); } else if (delay_ms == 0) { PromoResourceStateChange(); } } Commit Message: Refresh promo notifications as they're fetched The "guard" existed for notification scheduling was preventing "turn-off a promo" and "update a promo" scenarios. Yet I do not believe it was adding any actual safety: if things on a server backend go wrong, the clients will be affected one way or the other, and it is better to have an option to shut the malformed promo down "as quickly as possible" (~in 12-24 hours). BUG= TEST= Review URL: https://chromiumcodereview.appspot.com/10696204 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void PromoResourceService::PostNotification(int64 delay_ms) { // Note that this could cause re-issuing a notification every time // we receive an update from a server if something goes wrong. // Given that this couldn't happen more frequently than every // kCacheUpdateDelay milliseconds, we should be fine. if (delay_ms > 0) { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PromoResourceService::PromoResourceStateChange, weak_ptr_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(delay_ms)); } else if (delay_ms == 0) { PromoResourceStateChange(); } }
170,781
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: LauncherView::LauncherView(LauncherModel* model, LauncherDelegate* delegate, ShelfLayoutManager* shelf_layout_manager) : model_(model), delegate_(delegate), view_model_(new views::ViewModel), last_visible_index_(-1), overflow_button_(NULL), dragging_(false), drag_view_(NULL), drag_offset_(0), start_drag_index_(-1), context_menu_id_(0), alignment_(SHELF_ALIGNMENT_BOTTOM) { DCHECK(model_); bounds_animator_.reset(new views::BoundsAnimator(this)); bounds_animator_->AddObserver(this); set_context_menu_controller(this); focus_search_.reset(new LauncherFocusSearch(view_model_.get())); tooltip_.reset(new LauncherTooltipManager(alignment_, shelf_layout_manager)); } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
LauncherView::LauncherView(LauncherModel* model, LauncherDelegate* delegate, ShelfLayoutManager* shelf_layout_manager) : model_(model), delegate_(delegate), view_model_(new views::ViewModel), first_visible_index_(0), last_visible_index_(-1), overflow_button_(NULL), dragging_(false), drag_view_(NULL), drag_offset_(0), start_drag_index_(-1), context_menu_id_(0), alignment_(SHELF_ALIGNMENT_BOTTOM), leading_inset_(kDefaultLeadingInset) { DCHECK(model_); bounds_animator_.reset(new views::BoundsAnimator(this)); bounds_animator_->AddObserver(this); set_context_menu_controller(this); focus_search_.reset(new LauncherFocusSearch(view_model_.get())); tooltip_.reset(new LauncherTooltipManager(alignment_, shelf_layout_manager)); }
170,892
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 output_quantization_factor(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { if (out_depth == 16 && in_depth != 16 && pm->calculations_use_input_precision) return 257; else return 1; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static int output_quantization_factor(PNG_CONST png_modifier *pm, int in_depth, static int output_quantization_factor(const png_modifier *pm, int in_depth, int out_depth) { if (out_depth == 16 && in_depth != 16 && pm->calculations_use_input_precision) return 257; else return 1; }
173,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: static int tsc210x_load(QEMUFile *f, void *opaque, int version_id) { TSC210xState *s = (TSC210xState *) opaque; int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL); int i; s->x = qemu_get_be16(f); s->y = qemu_get_be16(f); s->pressure = qemu_get_byte(f); s->state = qemu_get_byte(f); s->page = qemu_get_byte(f); s->offset = qemu_get_byte(f); s->command = qemu_get_byte(f); s->irq = qemu_get_byte(f); qemu_get_be16s(f, &s->dav); timer_get(f, s->timer); s->enabled = qemu_get_byte(f); s->host_mode = qemu_get_byte(f); s->function = qemu_get_byte(f); s->nextfunction = qemu_get_byte(f); s->precision = qemu_get_byte(f); s->nextprecision = qemu_get_byte(f); s->filter = qemu_get_byte(f); s->pin_func = qemu_get_byte(f); s->ref = qemu_get_byte(f); qemu_get_be16s(f, &s->dac_power); for (i = 0; i < 0x14; i ++) qemu_get_be16s(f, &s->filter_data[i]); s->busy = timer_pending(s->timer); qemu_set_irq(s->pint, !s->irq); qemu_set_irq(s->davint, !s->dav); return 0; } Commit Message: CWE ID: CWE-119
static int tsc210x_load(QEMUFile *f, void *opaque, int version_id) { TSC210xState *s = (TSC210xState *) opaque; int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL); int i; s->x = qemu_get_be16(f); s->y = qemu_get_be16(f); s->pressure = qemu_get_byte(f); s->state = qemu_get_byte(f); s->page = qemu_get_byte(f); s->offset = qemu_get_byte(f); s->command = qemu_get_byte(f); s->irq = qemu_get_byte(f); qemu_get_be16s(f, &s->dav); timer_get(f, s->timer); s->enabled = qemu_get_byte(f); s->host_mode = qemu_get_byte(f); s->function = qemu_get_byte(f); if (s->function < 0 || s->function >= ARRAY_SIZE(mode_regs)) { return -EINVAL; } s->nextfunction = qemu_get_byte(f); if (s->nextfunction < 0 || s->nextfunction >= ARRAY_SIZE(mode_regs)) { return -EINVAL; } s->precision = qemu_get_byte(f); if (s->precision < 0 || s->precision >= ARRAY_SIZE(resolution)) { return -EINVAL; } s->nextprecision = qemu_get_byte(f); if (s->nextprecision < 0 || s->nextprecision >= ARRAY_SIZE(resolution)) { return -EINVAL; } s->filter = qemu_get_byte(f); s->pin_func = qemu_get_byte(f); s->ref = qemu_get_byte(f); qemu_get_be16s(f, &s->dac_power); for (i = 0; i < 0x14; i ++) qemu_get_be16s(f, &s->filter_data[i]); s->busy = timer_pending(s->timer); qemu_set_irq(s->pint, !s->irq); qemu_set_irq(s->davint, !s->dav); return 0; }
165,356
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 send_full_color_rect(VncState *vs, int x, int y, int w, int h) { int stream = 0; ssize_t bytes; #ifdef CONFIG_VNC_PNG if (tight_can_send_png_rect(vs, w, h)) { return send_png_rect(vs, x, y, w, h, NULL); } #endif tight_pack24(vs, vs->tight.tight.buffer, w * h, &vs->tight.tight.offset); bytes = 3; } else { bytes = vs->clientds.pf.bytes_per_pixel; } Commit Message: CWE ID: CWE-125
static int send_full_color_rect(VncState *vs, int x, int y, int w, int h) { int stream = 0; ssize_t bytes; #ifdef CONFIG_VNC_PNG if (tight_can_send_png_rect(vs, w, h)) { return send_png_rect(vs, x, y, w, h, NULL); } #endif tight_pack24(vs, vs->tight.tight.buffer, w * h, &vs->tight.tight.offset); bytes = 3; } else { bytes = vs->client_pf.bytes_per_pixel; }
165,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: cpStripToTile(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) *out++ = *in++; out += outskew; in += inskew; } } Commit Message: * tools/tiffcp.c: fix uint32 underflow/overflow that can cause heap-based buffer overflow. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2610 CWE ID: CWE-190
cpStripToTile(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int64 inskew) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) *out++ = *in++; out += outskew; in += inskew; } }
168,533
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 BlockGroup::Parse() { const long status = m_block.Parse(m_pCluster); if (status) return status; m_block.SetKey((m_prev > 0) && (m_next <= 0)); 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 BlockGroup::Parse()
174,411
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: ptaReadStream(FILE *fp) { char typestr[128]; l_int32 i, n, ix, iy, type, version; l_float32 x, y; PTA *pta; PROCNAME("ptaReadStream"); if (!fp) return (PTA *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, "\n Pta Version %d\n", &version) != 1) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (version != PTA_VERSION_NUMBER) return (PTA *)ERROR_PTR("invalid pta version", procName, NULL); if (fscanf(fp, " Number of pts = %d; format = %s\n", &n, typestr) != 2) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (!strcmp(typestr, "float")) type = 0; else /* typestr is "integer" */ type = 1; if ((pta = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("pta not made", procName, NULL); for (i = 0; i < n; i++) { if (type == 0) { /* data is float */ if (fscanf(fp, " (%f, %f)\n", &x, &y) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading floats", procName, NULL); } ptaAddPt(pta, x, y); } else { /* data is integer */ if (fscanf(fp, " (%d, %d)\n", &ix, &iy) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading ints", procName, NULL); } ptaAddPt(pta, ix, iy); } } return pta; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
ptaReadStream(FILE *fp) { char typestr[128]; /* hardcoded below in fscanf */ l_int32 i, n, ix, iy, type, version; l_float32 x, y; PTA *pta; PROCNAME("ptaReadStream"); if (!fp) return (PTA *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, "\n Pta Version %d\n", &version) != 1) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (version != PTA_VERSION_NUMBER) return (PTA *)ERROR_PTR("invalid pta version", procName, NULL); if (fscanf(fp, " Number of pts = %d; format = %127s\n", &n, typestr) != 2) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (!strcmp(typestr, "float")) type = 0; else /* typestr is "integer" */ type = 1; if ((pta = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("pta not made", procName, NULL); for (i = 0; i < n; i++) { if (type == 0) { /* data is float */ if (fscanf(fp, " (%f, %f)\n", &x, &y) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading floats", procName, NULL); } ptaAddPt(pta, x, y); } else { /* data is integer */ if (fscanf(fp, " (%d, %d)\n", &ix, &iy) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading ints", procName, NULL); } ptaAddPt(pta, ix, iy); } } return pta; }
169,328
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 BrowserViewRenderer::ScrollTo(gfx::Vector2d scroll_offset) { gfx::Vector2d max_offset = max_scroll_offset(); gfx::Vector2dF scroll_offset_dip; if (max_offset.x()) { scroll_offset_dip.set_x((scroll_offset.x() * max_scroll_offset_dip_.x()) / max_offset.x()); } if (max_offset.y()) { scroll_offset_dip.set_y((scroll_offset.y() * max_scroll_offset_dip_.y()) / max_offset.y()); } DCHECK_LE(0.f, scroll_offset_dip.x()); DCHECK_LE(0.f, scroll_offset_dip.y()); DCHECK(scroll_offset_dip.x() < max_scroll_offset_dip_.x() || scroll_offset_dip.x() - max_scroll_offset_dip_.x() < kEpsilon) << scroll_offset_dip.x() << " " << max_scroll_offset_dip_.x(); DCHECK(scroll_offset_dip.y() < max_scroll_offset_dip_.y() || scroll_offset_dip.y() - max_scroll_offset_dip_.y() < kEpsilon) << scroll_offset_dip.y() << " " << max_scroll_offset_dip_.y(); if (scroll_offset_dip_ == scroll_offset_dip) return; scroll_offset_dip_ = scroll_offset_dip; TRACE_EVENT_INSTANT2("android_webview", "BrowserViewRenderer::ScrollTo", TRACE_EVENT_SCOPE_THREAD, "x", scroll_offset_dip.x(), "y", scroll_offset_dip.y()); if (compositor_) { compositor_->DidChangeRootLayerScrollOffset( gfx::ScrollOffset(scroll_offset_dip_)); } } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399
void BrowserViewRenderer::ScrollTo(gfx::Vector2d scroll_offset) { void BrowserViewRenderer::ScrollTo(const gfx::Vector2d& scroll_offset) { gfx::Vector2d max_offset = max_scroll_offset(); gfx::Vector2dF scroll_offset_dip; if (max_offset.x()) { scroll_offset_dip.set_x((scroll_offset.x() * max_scroll_offset_dip_.x()) / max_offset.x()); } if (max_offset.y()) { scroll_offset_dip.set_y((scroll_offset.y() * max_scroll_offset_dip_.y()) / max_offset.y()); } DCHECK_LE(0.f, scroll_offset_dip.x()); DCHECK_LE(0.f, scroll_offset_dip.y()); DCHECK(scroll_offset_dip.x() < max_scroll_offset_dip_.x() || scroll_offset_dip.x() - max_scroll_offset_dip_.x() < kEpsilon) << scroll_offset_dip.x() << " " << max_scroll_offset_dip_.x(); DCHECK(scroll_offset_dip.y() < max_scroll_offset_dip_.y() || scroll_offset_dip.y() - max_scroll_offset_dip_.y() < kEpsilon) << scroll_offset_dip.y() << " " << max_scroll_offset_dip_.y(); if (scroll_offset_dip_ == scroll_offset_dip) return; scroll_offset_dip_ = scroll_offset_dip; TRACE_EVENT_INSTANT2("android_webview", "BrowserViewRenderer::ScrollTo", TRACE_EVENT_SCOPE_THREAD, "x", scroll_offset_dip.x(), "y", scroll_offset_dip.y()); if (compositor_) { compositor_->DidChangeRootLayerScrollOffset( gfx::ScrollOffset(scroll_offset_dip_)); } }
171,614
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: MockRenderThread::MockRenderThread() : routing_id_(0), surface_id_(0), opener_id_(0) { } 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
MockRenderThread::MockRenderThread() : routing_id_(0), surface_id_(0), opener_id_(0), new_window_routing_id_(0) { }
171,022
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: _asn1_extract_der_octet (asn1_node node, const unsigned char *der, int der_len, unsigned flags) { int len2, len3; int counter, counter_end; int result; len2 = asn1_get_length_der (der, der_len, &len3); if (len2 < -1) return ASN1_DER_ERROR; counter = len3 + 1; DECR_LEN(der_len, len3); if (len2 == -1) counter_end = der_len - 2; else counter_end = der_len; while (counter < counter_end) { DECR_LEN(der_len, 1); if (len2 >= 0) { DECR_LEN(der_len, len2+len3); _asn1_append_value (node, der + counter + len3, len2); } else { /* indefinite */ DECR_LEN(der_len, len3); result = _asn1_extract_der_octet (node, der + counter + len3, der_len, flags); if (result != ASN1_SUCCESS) return result; len2 = 0; } counter += len2 + len3 + 1; } return ASN1_SUCCESS; cleanup: return result; } Commit Message: CWE ID: CWE-399
_asn1_extract_der_octet (asn1_node node, const unsigned char *der, int der_len, unsigned flags) { int len2, len3; int counter, counter_end; int result; len2 = asn1_get_length_der (der, der_len, &len3); if (len2 < -1) return ASN1_DER_ERROR; counter = len3 + 1; DECR_LEN(der_len, len3); if (len2 == -1) { if (der_len < 2) return ASN1_DER_ERROR; counter_end = der_len - 2; } else counter_end = der_len; if (counter_end < counter) return ASN1_DER_ERROR; while (counter < counter_end) { DECR_LEN(der_len, 1); if (len2 >= 0) { DECR_LEN(der_len, len2+len3); _asn1_append_value (node, der + counter + len3, len2); } else { /* indefinite */ DECR_LEN(der_len, len3); result = _asn1_extract_der_octet (node, der + counter + len3, der_len, flags); if (result != ASN1_SUCCESS) return result; len2 = 0; } counter += len2 + len3 + 1; } return ASN1_SUCCESS; cleanup: return result; }
165,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: Blob::Blob() : m_size(0) { ScriptWrappable::init(this); OwnPtr<BlobData> blobData = BlobData::create(); m_internalURL = BlobURL::createInternalURL(); ThreadableBlobRegistry::registerBlobURL(m_internalURL, blobData.release()); } 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() : m_size(0) { ScriptWrappable::init(this); OwnPtr<BlobData> blobData = BlobData::create(); m_internalURL = BlobURL::createInternalURL(); BlobRegistry::registerBlobURL(m_internalURL, blobData.release()); }
170,674
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 mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, long long& val) { assert(pReader); assert(pos >= 0); long long total, available; const long status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); if (status < 0) return false; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); if ((unsigned long)id != id_) return false; pos += len; // consume id const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert(size <= 8); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); pos += len; // consume length of size of payload val = UnserializeUInt(pReader, pos, size); assert(val >= 0); pos += size; // consume size of payload return true; } 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
bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, bool Match(IMkvReader* pReader, long long& pos, unsigned long expected_id, long long& val) { if (!pReader || pos < 0) return false; long long total = 0; long long available = 0; const long status = pReader->Length(&total, &available); if (status < 0 || (total >= 0 && available > total)) return false; long len = 0; const long long id = ReadID(pReader, pos, len); if (id < 0 || (available - pos) > len) return false; if (static_cast<unsigned long>(id) != expected_id) return false; pos += len; // consume id const long long size = ReadUInt(pReader, pos, len); if (size < 0 || size > 8 || len < 1 || len > 8 || (available - pos) > len) return false; pos += len; // consume length of size of payload val = UnserializeUInt(pReader, pos, size); if (val < 0) return false; pos += size; // consume size of payload return true; }
173,832
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_check(PNG_CONST png_store* ps, png_const_structp pp, int iImage) { png_const_bytep image = ps->image; if (image[-1] != 0xed || image[ps->cb_image] != 0xfe) png_error(pp, "image overwrite"); else { png_size_t cbRow = ps->cb_row; png_uint_32 rows = ps->image_h; image += iImage * (cbRow+5) * ps->image_h; image += 2; /* skip image first row markers */ while (rows-- > 0) { if (image[-2] != 190 || image[-1] != 239) png_error(pp, "row start overwritten"); if (image[cbRow] != 222 || image[cbRow+1] != 173 || image[cbRow+2] != 17) png_error(pp, "row end overwritten"); image += cbRow+5; } } } 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_check(PNG_CONST png_store* ps, png_const_structp pp, int iImage) store_image_check(const png_store* ps, png_const_structp pp, int iImage) { png_const_bytep image = ps->image; if (image[-1] != 0xed || image[ps->cb_image] != 0xfe) png_error(pp, "image overwrite"); else { png_size_t cbRow = ps->cb_row; png_uint_32 rows = ps->image_h; image += iImage * (cbRow+5) * ps->image_h; image += 2; /* skip image first row markers */ while (rows-- > 0) { if (image[-2] != 190 || image[-1] != 239) png_error(pp, "row start overwritten"); if (image[cbRow] != 222 || image[cbRow+1] != 173 || image[cbRow+2] != 17) png_error(pp, "row end overwritten"); image += cbRow+5; } } }
173,704
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 fht8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { vp9_fht8x8_c(in, out, stride, tx_type); } 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
void fht8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { void reference_8x8_dct_2d(const int16_t input[kNumCoeffs], double output[kNumCoeffs]) { // First transform columns for (int i = 0; i < 8; ++i) { double temp_in[8], temp_out[8]; for (int j = 0; j < 8; ++j) temp_in[j] = input[j*8 + i]; reference_8x8_dct_1d(temp_in, temp_out, 1); for (int j = 0; j < 8; ++j) output[j * 8 + i] = temp_out[j]; } // Then transform rows for (int i = 0; i < 8; ++i) { double temp_in[8], temp_out[8]; for (int j = 0; j < 8; ++j) temp_in[j] = output[j + i*8]; reference_8x8_dct_1d(temp_in, temp_out, 1); // Scale by some magic number for (int j = 0; j < 8; ++j) output[j + i * 8] = temp_out[j] * 2; } } void fdct8x8_ref(const int16_t *in, tran_low_t *out, int stride, int tx_type) { vpx_fdct8x8_c(in, out, stride); } void fht8x8_ref(const int16_t *in, tran_low_t *out, int stride, int tx_type) { vp9_fht8x8_c(in, out, stride, tx_type); }
174,565
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: monitor_init(void) { struct ssh *ssh = active_state; /* XXX */ struct monitor *mon; mon = xcalloc(1, sizeof(*mon)); monitor_openfds(mon, 1); /* Used to share zlib space across processes */ if (options.compression) { mon->m_zback = mm_create(NULL, MM_MEMSIZE); mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE); /* Compression needs to share state across borders */ ssh_packet_set_compress_hooks(ssh, mon->m_zlib, (ssh_packet_comp_alloc_func *)mm_zalloc, (ssh_packet_comp_free_func *)mm_zfree); } return mon; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
monitor_init(void) { struct monitor *mon; mon = xcalloc(1, sizeof(*mon)); monitor_openfds(mon, 1); return mon; }
168,649
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 sum_update(const char *p, int32 len) { switch (cursum_type) { case CSUM_MD5: md5_update(&md, (uchar *)p, len); break; case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: if (len + sumresidue < CSUM_CHUNK) { memcpy(md.buffer + sumresidue, p, len); sumresidue += len; } if (sumresidue) { int32 i = CSUM_CHUNK - sumresidue; memcpy(md.buffer + sumresidue, p, i); mdfour_update(&md, (uchar *)md.buffer, CSUM_CHUNK); len -= i; p += i; } while (len >= CSUM_CHUNK) { mdfour_update(&md, (uchar *)p, CSUM_CHUNK); len -= CSUM_CHUNK; p += CSUM_CHUNK; } sumresidue = len; if (sumresidue) memcpy(md.buffer, p, sumresidue); break; case CSUM_NONE: break; } } Commit Message: CWE ID: CWE-354
void sum_update(const char *p, int32 len) { switch (cursum_type) { case CSUM_MD5: md5_update(&md, (uchar *)p, len); break; case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: case CSUM_MD4_ARCHAIC: if (len + sumresidue < CSUM_CHUNK) { memcpy(md.buffer + sumresidue, p, len); sumresidue += len; } if (sumresidue) { int32 i = CSUM_CHUNK - sumresidue; memcpy(md.buffer + sumresidue, p, i); mdfour_update(&md, (uchar *)md.buffer, CSUM_CHUNK); len -= i; p += i; } while (len >= CSUM_CHUNK) { mdfour_update(&md, (uchar *)p, CSUM_CHUNK); len -= CSUM_CHUNK; p += CSUM_CHUNK; } sumresidue = len; if (sumresidue) memcpy(md.buffer, p, sumresidue); break; case CSUM_NONE: break; } }
164,640
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 ext4_end_io_dio(struct kiocb *iocb, loff_t offset, ssize_t size, void *private) { ext4_io_end_t *io_end = iocb->private; struct workqueue_struct *wq; /* if not async direct IO or dio with 0 bytes write, just return */ if (!io_end || !size) return; ext_debug("ext4_end_io_dio(): io_end 0x%p" "for inode %lu, iocb 0x%p, offset %llu, size %llu\n", iocb->private, io_end->inode->i_ino, iocb, offset, size); /* if not aio dio with unwritten extents, just free io and return */ if (io_end->flag != EXT4_IO_UNWRITTEN){ ext4_free_io_end(io_end); iocb->private = NULL; return; } io_end->offset = offset; io_end->size = size; wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq; /* queue the work to convert unwritten extents to written */ queue_work(wq, &io_end->work); /* Add the io_end to per-inode completed aio dio list*/ list_add_tail(&io_end->list, &EXT4_I(io_end->inode)->i_completed_io_list); iocb->private = NULL; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <jiayingz@google.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> CWE ID:
static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset, ssize_t size, void *private) { ext4_io_end_t *io_end = iocb->private; struct workqueue_struct *wq; unsigned long flags; struct ext4_inode_info *ei; /* if not async direct IO or dio with 0 bytes write, just return */ if (!io_end || !size) return; ext_debug("ext4_end_io_dio(): io_end 0x%p" "for inode %lu, iocb 0x%p, offset %llu, size %llu\n", iocb->private, io_end->inode->i_ino, iocb, offset, size); /* if not aio dio with unwritten extents, just free io and return */ if (io_end->flag != EXT4_IO_UNWRITTEN){ ext4_free_io_end(io_end); iocb->private = NULL; return; } io_end->offset = offset; io_end->size = size; io_end->flag = EXT4_IO_UNWRITTEN; wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq; /* queue the work to convert unwritten extents to written */ queue_work(wq, &io_end->work); /* Add the io_end to per-inode completed aio dio list*/ ei = EXT4_I(io_end->inode); spin_lock_irqsave(&ei->i_completed_io_lock, flags); list_add_tail(&io_end->list, &ei->i_completed_io_list); spin_unlock_irqrestore(&ei->i_completed_io_lock, flags); iocb->private = NULL; }
167,540
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: sshkey_load_file(int fd, struct sshbuf *blob) { u_char buf[1024]; size_t len; struct stat st; int r; if (fstat(fd, &st) < 0) return SSH_ERR_SYSTEM_ERROR; if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && st.st_size > MAX_KEY_FILE_SIZE) return SSH_ERR_INVALID_FORMAT; for (;;) { if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) { if (errno == EPIPE) break; r = SSH_ERR_SYSTEM_ERROR; goto out; } if ((r = sshbuf_put(blob, buf, len)) != 0) goto out; if (sshbuf_len(blob) > MAX_KEY_FILE_SIZE) { r = SSH_ERR_INVALID_FORMAT; goto out; } } if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && st.st_size != (off_t)sshbuf_len(blob)) { r = SSH_ERR_FILE_CHANGED; goto out; } r = 0; out: explicit_bzero(buf, sizeof(buf)); if (r != 0) sshbuf_reset(blob); return r; } Commit Message: use sshbuf_allocate() to pre-allocate the buffer used for loading keys. This avoids implicit realloc inside the buffer code, which might theoretically leave fragments of the key on the heap. This doesn't appear to happen in practice for normal sized keys, but was observed for novelty oversize ones. Pointed out by Jann Horn of Project Zero; ok markus@ CWE ID: CWE-320
sshkey_load_file(int fd, struct sshbuf *blob) { u_char buf[1024]; size_t len; struct stat st; int r, dontmax = 0; if (fstat(fd, &st) < 0) return SSH_ERR_SYSTEM_ERROR; if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && st.st_size > MAX_KEY_FILE_SIZE) return SSH_ERR_INVALID_FORMAT; /* * Pre-allocate the buffer used for the key contents and clamp its * maximum size. This ensures that key contents are never leaked via * implicit realloc() in the sshbuf code. */ if ((st.st_mode & S_IFREG) == 0 || st.st_size <= 0) { st.st_size = 64*1024; /* 64k should be enough for anyone :) */ dontmax = 1; } if ((r = sshbuf_allocate(blob, st.st_size)) != 0 || (dontmax && (r = sshbuf_set_max_size(blob, st.st_size)) != 0)) return r; for (;;) { if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) { if (errno == EPIPE) break; r = SSH_ERR_SYSTEM_ERROR; goto out; } if ((r = sshbuf_put(blob, buf, len)) != 0) goto out; if (sshbuf_len(blob) > MAX_KEY_FILE_SIZE) { r = SSH_ERR_INVALID_FORMAT; goto out; } } if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && st.st_size != (off_t)sshbuf_len(blob)) { r = SSH_ERR_FILE_CHANGED; goto out; } r = 0; out: explicit_bzero(buf, sizeof(buf)); if (r != 0) sshbuf_reset(blob); return r; }
168,660
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 processInputBuffer(client *c) { server.current_client = c; /* Keep processing while there is something in the input buffer */ while(sdslen(c->querybuf)) { /* Return if clients are paused. */ if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break; /* Immediately abort if the client is in the middle of something. */ if (c->flags & CLIENT_BLOCKED) break; /* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is * written to the client. Make sure to not let the reply grow after * this flag has been set (i.e. don't process more commands). */ if (c->flags & CLIENT_CLOSE_AFTER_REPLY) break; /* Determine request type when unknown. */ if (!c->reqtype) { if (c->querybuf[0] == '*') { c->reqtype = PROTO_REQ_MULTIBULK; } else { c->reqtype = PROTO_REQ_INLINE; } } if (c->reqtype == PROTO_REQ_INLINE) { if (processInlineBuffer(c) != C_OK) break; } else if (c->reqtype == PROTO_REQ_MULTIBULK) { if (processMultibulkBuffer(c) != C_OK) break; } else { serverPanic("Unknown request type"); } /* Multibulk processing could see a <= 0 length. */ if (c->argc == 0) { resetClient(c); } else { /* Only reset the client when the command was executed. */ if (processCommand(c) == C_OK) resetClient(c); /* freeMemoryIfNeeded may flush slave output buffers. This may result * into a slave, that may be the active client, to be freed. */ if (server.current_client == NULL) break; } } server.current_client = NULL; } Commit Message: Security: Cross Protocol Scripting protection. This is an attempt at mitigating problems due to cross protocol scripting, an attack targeting services using line oriented protocols like Redis that can accept HTTP requests as valid protocol, by discarding the invalid parts and accepting the payloads sent, for example, via a POST request. For this to be effective, when we detect POST and Host: and terminate the connection asynchronously, the networking code was modified in order to never process further input. It was later verified that in a pipelined request containing a POST command, the successive commands are not executed. CWE ID: CWE-254
void processInputBuffer(client *c) { server.current_client = c; /* Keep processing while there is something in the input buffer */ while(sdslen(c->querybuf)) { /* Return if clients are paused. */ if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break; /* Immediately abort if the client is in the middle of something. */ if (c->flags & CLIENT_BLOCKED) break; /* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is * written to the client. Make sure to not let the reply grow after * this flag has been set (i.e. don't process more commands). * * The same applies for clients we want to terminate ASAP. */ if (c->flags & (CLIENT_CLOSE_AFTER_REPLY|CLIENT_CLOSE_ASAP)) break; /* Determine request type when unknown. */ if (!c->reqtype) { if (c->querybuf[0] == '*') { c->reqtype = PROTO_REQ_MULTIBULK; } else { c->reqtype = PROTO_REQ_INLINE; } } if (c->reqtype == PROTO_REQ_INLINE) { if (processInlineBuffer(c) != C_OK) break; } else if (c->reqtype == PROTO_REQ_MULTIBULK) { if (processMultibulkBuffer(c) != C_OK) break; } else { serverPanic("Unknown request type"); } /* Multibulk processing could see a <= 0 length. */ if (c->argc == 0) { resetClient(c); } else { /* Only reset the client when the command was executed. */ if (processCommand(c) == C_OK) resetClient(c); /* freeMemoryIfNeeded may flush slave output buffers. This may result * into a slave, that may be the active client, to be freed. */ if (server.current_client == NULL) break; } } server.current_client = NULL; }
168,453
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 br_mdb_dump(struct sk_buff *skb, struct netlink_callback *cb) { struct net_device *dev; struct net *net = sock_net(skb->sk); struct nlmsghdr *nlh = NULL; int idx = 0, s_idx; s_idx = cb->args[0]; rcu_read_lock(); /* In theory this could be wrapped to 0... */ cb->seq = net->dev_base_seq + br_mdb_rehash_seq; for_each_netdev_rcu(net, dev) { if (dev->priv_flags & IFF_EBRIDGE) { struct br_port_msg *bpm; if (idx < s_idx) goto skip; nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, RTM_GETMDB, sizeof(*bpm), NLM_F_MULTI); if (nlh == NULL) break; bpm = nlmsg_data(nlh); bpm->ifindex = dev->ifindex; if (br_mdb_fill_info(skb, cb, dev) < 0) goto out; if (br_rports_fill_info(skb, cb, dev) < 0) goto out; cb->args[1] = 0; nlmsg_end(skb, nlh); skip: idx++; } } out: if (nlh) nlmsg_end(skb, nlh); rcu_read_unlock(); cb->args[0] = idx; return skb->len; } Commit Message: bridge: fix mdb info leaks The bridging code discloses heap and stack bytes via the RTM_GETMDB netlink interface and via the notify messages send to group RTNLGRP_MDB afer a successful add/del. Fix both cases by initializing all unset members/padding bytes with memset(0). Cc: Stephen Hemminger <stephen@networkplumber.org> Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
static int br_mdb_dump(struct sk_buff *skb, struct netlink_callback *cb) { struct net_device *dev; struct net *net = sock_net(skb->sk); struct nlmsghdr *nlh = NULL; int idx = 0, s_idx; s_idx = cb->args[0]; rcu_read_lock(); /* In theory this could be wrapped to 0... */ cb->seq = net->dev_base_seq + br_mdb_rehash_seq; for_each_netdev_rcu(net, dev) { if (dev->priv_flags & IFF_EBRIDGE) { struct br_port_msg *bpm; if (idx < s_idx) goto skip; nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, RTM_GETMDB, sizeof(*bpm), NLM_F_MULTI); if (nlh == NULL) break; bpm = nlmsg_data(nlh); memset(bpm, 0, sizeof(*bpm)); bpm->ifindex = dev->ifindex; if (br_mdb_fill_info(skb, cb, dev) < 0) goto out; if (br_rports_fill_info(skb, cb, dev) < 0) goto out; cb->args[1] = 0; nlmsg_end(skb, nlh); skip: idx++; } } out: if (nlh) nlmsg_end(skb, nlh); rcu_read_unlock(); cb->args[0] = idx; return skb->len; }
166,052
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: DrawingBuffer::ScopedStateRestorer::~ScopedStateRestorer() { DCHECK_EQ(drawing_buffer_->state_restorer_, this); drawing_buffer_->state_restorer_ = previous_state_restorer_; Client* client = drawing_buffer_->client_; if (!client) return; if (clear_state_dirty_) { client->DrawingBufferClientRestoreScissorTest(); client->DrawingBufferClientRestoreMaskAndClearValues(); } if (pixel_pack_alignment_dirty_) client->DrawingBufferClientRestorePixelPackAlignment(); if (texture_binding_dirty_) client->DrawingBufferClientRestoreTexture2DBinding(); if (renderbuffer_binding_dirty_) client->DrawingBufferClientRestoreRenderbufferBinding(); if (framebuffer_binding_dirty_) client->DrawingBufferClientRestoreFramebufferBinding(); if (pixel_unpack_buffer_binding_dirty_) client->DrawingBufferClientRestorePixelUnpackBufferBinding(); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test R=kbr@chromium.org,piman@chromium.org Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <piman@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
DrawingBuffer::ScopedStateRestorer::~ScopedStateRestorer() { DCHECK_EQ(drawing_buffer_->state_restorer_, this); drawing_buffer_->state_restorer_ = previous_state_restorer_; Client* client = drawing_buffer_->client_; if (!client) return; if (clear_state_dirty_) { client->DrawingBufferClientRestoreScissorTest(); client->DrawingBufferClientRestoreMaskAndClearValues(); } if (pixel_pack_parameters_dirty_) client->DrawingBufferClientRestorePixelPackParameters(); if (texture_binding_dirty_) client->DrawingBufferClientRestoreTexture2DBinding(); if (renderbuffer_binding_dirty_) client->DrawingBufferClientRestoreRenderbufferBinding(); if (framebuffer_binding_dirty_) client->DrawingBufferClientRestoreFramebufferBinding(); if (pixel_unpack_buffer_binding_dirty_) client->DrawingBufferClientRestorePixelUnpackBufferBinding(); if (pixel_pack_buffer_binding_dirty_) client->DrawingBufferClientRestorePixelPackBufferBinding(); }
172,296
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 GM2TabStyle::PaintTabBackground(gfx::Canvas* canvas, bool active, int fill_id, int y_inset, const SkPath* clip) const { DCHECK(!y_inset || fill_id); const SkColor active_color = tab_->controller()->GetTabBackgroundColor(TAB_ACTIVE); const SkColor inactive_color = tab_->GetThemeProvider()->GetDisplayProperty( ThemeProperties::SHOULD_FILL_BACKGROUND_TAB_COLOR) ? tab_->controller()->GetTabBackgroundColor(TAB_INACTIVE) : SK_ColorTRANSPARENT; const SkColor stroke_color = tab_->controller()->GetToolbarTopSeparatorColor(); const bool paint_hover_effect = !active && IsHoverActive(); const float stroke_thickness = GetStrokeThickness(active); PaintTabBackgroundFill(canvas, active, paint_hover_effect, active_color, inactive_color, fill_id, y_inset); if (stroke_thickness > 0) { gfx::ScopedCanvas scoped_canvas(clip ? canvas : nullptr); if (clip) canvas->sk_canvas()->clipPath(*clip, SkClipOp::kDifference, true); PaintBackgroundStroke(canvas, active, stroke_color); } PaintSeparators(canvas); } Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <bsep@chromium.org> Reviewed-by: Taylor Bergquist <tbergquist@chromium.org> Cr-Commit-Position: refs/heads/master@{#660498} CWE ID: CWE-20
void GM2TabStyle::PaintTabBackground(gfx::Canvas* canvas, TabState active_state, int fill_id, int y_inset, const SkPath* clip) const { DCHECK(!y_inset || fill_id); const SkColor stroke_color = tab_->controller()->GetToolbarTopSeparatorColor(); const bool paint_hover_effect = active_state == TAB_INACTIVE && IsHoverActive(); const float stroke_thickness = GetStrokeThickness(active_state == TAB_ACTIVE); PaintTabBackgroundFill(canvas, active_state, paint_hover_effect, fill_id, y_inset); if (stroke_thickness > 0) { gfx::ScopedCanvas scoped_canvas(clip ? canvas : nullptr); if (clip) canvas->sk_canvas()->clipPath(*clip, SkClipOp::kDifference, true); PaintBackgroundStroke(canvas, active_state, stroke_color); } PaintSeparators(canvas); }
172,525
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: le64addr_string(netdissect_options *ndo, const u_char *ep) { const unsigned int len = 8; register u_int i; register char *cp; register struct enamemem *tp; char buf[BUFSIZE]; tp = lookup_bytestring(ndo, ep, len); if (tp->e_name) return (tp->e_name); cp = buf; for (i = len; i > 0 ; --i) { *cp++ = hex[*(ep + i - 1) >> 4]; *cp++ = hex[*(ep + i - 1) & 0xf]; *cp++ = ':'; } cp --; *cp = '\0'; tp->e_name = strdup(buf); if (tp->e_name == NULL) (*ndo->ndo_error)(ndo, "le64addr_string: strdup(buf)"); return (tp->e_name); } Commit Message: CVE-2017-12894/In lookup_bytestring(), take the length of the byte string into account. Otherwise, if, in our search of the hash table, we come across a byte string that's shorter than the string we're looking for, we'll search past the end of the string in the hash table. 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
le64addr_string(netdissect_options *ndo, const u_char *ep) { const unsigned int len = 8; register u_int i; register char *cp; register struct bsnamemem *tp; char buf[BUFSIZE]; tp = lookup_bytestring(ndo, ep, len); if (tp->bs_name) return (tp->bs_name); cp = buf; for (i = len; i > 0 ; --i) { *cp++ = hex[*(ep + i - 1) >> 4]; *cp++ = hex[*(ep + i - 1) & 0xf]; *cp++ = ':'; } cp --; *cp = '\0'; tp->bs_name = strdup(buf); if (tp->bs_name == NULL) (*ndo->ndo_error)(ndo, "le64addr_string: strdup(buf)"); return (tp->bs_name); }
167,958
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 SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) { List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); BufferInfo *outInfo = *outQueue.begin(); outQueue.erase(outQueue.begin()); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; OMX_BUFFERHEADERTYPE *header = mPicToHeaderMap.valueFor(picId); outHeader->nTimeStamp = header->nTimeStamp; outHeader->nFlags = header->nFlags; outHeader->nFilledLen = mWidth * mHeight * 3 / 2; uint8_t *dst = outHeader->pBuffer + outHeader->nOffset; const uint8_t *srcY = data; const uint8_t *srcU = srcY + mWidth * mHeight; const uint8_t *srcV = srcU + mWidth * mHeight / 4; size_t srcYStride = mWidth; size_t srcUStride = mWidth / 2; size_t srcVStride = srcUStride; copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride); mPicToHeaderMap.removeItem(picId); delete header; outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); } Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec Bug: 27833616 Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0 CWE ID: CWE-20
void SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) { bool SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) { List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; OMX_U32 frameSize = mWidth * mHeight * 3 / 2; if (outHeader->nAllocLen - outHeader->nOffset < frameSize) { android_errorWriteLog(0x534e4554, "27833616"); return false; } outQueue.erase(outQueue.begin()); OMX_BUFFERHEADERTYPE *header = mPicToHeaderMap.valueFor(picId); outHeader->nTimeStamp = header->nTimeStamp; outHeader->nFlags = header->nFlags; outHeader->nFilledLen = frameSize; uint8_t *dst = outHeader->pBuffer + outHeader->nOffset; const uint8_t *srcY = data; const uint8_t *srcU = srcY + mWidth * mHeight; const uint8_t *srcV = srcU + mWidth * mHeight / 4; size_t srcYStride = mWidth; size_t srcUStride = mWidth / 2; size_t srcVStride = srcUStride; copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride); mPicToHeaderMap.removeItem(picId); delete header; outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return true; }
174,177
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 LauncherView::ShowOverflowMenu() { #if !defined(OS_MACOSX) if (!delegate_) return; std::vector<LauncherItem> items; GetOverflowItems(&items); if (items.empty()) return; MenuDelegateImpl menu_delegate; ui::SimpleMenuModel menu_model(&menu_delegate); for (size_t i = 0; i < items.size(); ++i) menu_model.AddItem(static_cast<int>(i), delegate_->GetTitle(items[i])); views::MenuModelAdapter menu_adapter(&menu_model); overflow_menu_runner_.reset(new views::MenuRunner(menu_adapter.CreateMenu())); gfx::Rect bounds(overflow_button_->size()); gfx::Point origin; ConvertPointToScreen(overflow_button_, &origin); if (overflow_menu_runner_->RunMenuAt(GetWidget(), NULL, gfx::Rect(origin, size()), views::MenuItemView::TOPLEFT, 0) == views::MenuRunner::MENU_DELETED) return; Shell::GetInstance()->UpdateShelfVisibility(); if (menu_delegate.activated_command_id() == -1) return; LauncherID activated_id = items[menu_delegate.activated_command_id()].id; LauncherItems::const_iterator window_iter = model_->ItemByID(activated_id); if (window_iter == model_->items().end()) return; // Window was deleted while menu was up. delegate_->ItemClicked(*window_iter, ui::EF_NONE); #endif // !defined(OS_MACOSX) } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void LauncherView::ShowOverflowMenu() { void LauncherView::ShowOverflowBubble() { int first_overflow_index = last_visible_index_ + 1; DCHECK_LT(first_overflow_index, view_model_->view_size() - 1); if (!overflow_bubble_.get()) overflow_bubble_.reset(new OverflowBubble()); overflow_bubble_->Show(delegate_, model_, overflow_button_, alignment_, first_overflow_index); Shell::GetInstance()->UpdateShelfVisibility(); }
170,896
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 FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { searchpath_t *search; long len; if(!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); for(search = fs_searchpaths; search; search = search->next) { len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse); if(file == NULL) { if(len > 0) return len; } else { if(len >= 0 && *file) return len; } } #ifdef FS_MISSING if(missingFiles) fprintf(missingFiles, "%s\n", filename); #endif if(file) { *file = 0; return -1; } else { return 0; } } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269
long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { searchpath_t *search; long len; qboolean isLocalConfig; if(!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); isLocalConfig = !strcmp(filename, "autoexec.cfg") || !strcmp(filename, Q3CONFIG_CFG); for(search = fs_searchpaths; search; search = search->next) { // autoexec.cfg and wolfconfig_mp.cfg can only be loaded outside of pk3 files. if (isLocalConfig && search->pack) continue; len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse); if(file == NULL) { if(len > 0) return len; } else { if(len >= 0 && *file) return len; } } #ifdef FS_MISSING if(missingFiles) fprintf(missingFiles, "%s\n", filename); #endif if(file) { *file = 0; return -1; } else { return 0; } }
170,083
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 TestPlaybackRate(double playback_rate) { static const int kDefaultBufferSize = kSamplesPerSecond / 10; static const int kDefaultFramesRequested = 5 * kSamplesPerSecond; TestPlaybackRate(playback_rate, kDefaultBufferSize, kDefaultFramesRequested); } Commit Message: Protect AudioRendererAlgorithm from invalid step sizes. BUG=165430 TEST=unittests and asan pass. Review URL: https://codereview.chromium.org/11573023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void TestPlaybackRate(double playback_rate) { const int kDefaultBufferSize = algorithm_.samples_per_second() / 10; const int kDefaultFramesRequested = 2 * algorithm_.samples_per_second(); TestPlaybackRate(playback_rate, kDefaultBufferSize, kDefaultFramesRequested); }
171,535
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 const ImePropertyList& current_ime_properties() const { return current_ime_properties_; } 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 const ImePropertyList& current_ime_properties() const { virtual const input_method::ImePropertyList& current_ime_properties() const { return current_ime_properties_; }
170,511
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 IBusBusNameOwnerChangedCallback( IBusBus* bus, const gchar* name, const gchar* old_name, const gchar* new_name, gpointer user_data) { DCHECK(name); DCHECK(old_name); DCHECK(new_name); DLOG(INFO) << "Name owner is changed: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; if (name != std::string("org.freedesktop.IBus.Config")) { return; } const std::string empty_string; if (old_name != empty_string || new_name == empty_string) { LOG(WARNING) << "Unexpected name owner change: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; return; } LOG(INFO) << "IBus config daemon is started. Recovering ibus_config_"; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } 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
static void IBusBusNameOwnerChangedCallback( void IBusBusNameOwnerChanged(IBusBus* bus, const gchar* name, const gchar* old_name, const gchar* new_name) { DCHECK(name); DCHECK(old_name); DCHECK(new_name); VLOG(1) << "Name owner is changed: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; if (name != std::string("org.freedesktop.IBus.Config")) { return; } const std::string empty_string; if (old_name != empty_string || new_name == empty_string) { LOG(WARNING) << "Unexpected name owner change: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; // |OnConnectionChange| with false here to allow Chrome to return; } VLOG(1) << "IBus config daemon is started. Recovering ibus_config_"; // successfully created, |OnConnectionChange| will be called to MaybeRestoreConnections(); }
170,539
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: checked_xcalloc (size_t num, size_t size) { alloc_limit_assert ("checked_xcalloc", (num *size)); return xcalloc (num, size); } Commit Message: Fix integer overflows and harden memory allocator. CWE ID: CWE-190
checked_xcalloc (size_t num, size_t size) { size_t res; if (check_mul_overflow(num, size, &res)) abort(); alloc_limit_assert ("checked_xcalloc", (res)); return xcalloc (num, size); }
168,356
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 WebviewInfo::IsResourceWebviewAccessible( const Extension* extension, const std::string& partition_id, const std::string& relative_path) { if (!extension) return false; const WebviewInfo* info = GetResourcesInfo(*extension); if (!info) return false; bool partition_is_privileged = false; for (size_t i = 0; i < info->webview_privileged_partitions_.size(); ++i) { if (MatchPattern(partition_id, info->webview_privileged_partitions_[i])) { partition_is_privileged = true; break; } } return partition_is_privileged && extension->ResourceMatches( info->webview_accessible_resources_, relative_path); } Commit Message: <webview>: Update format for local file access in manifest.json The new format is: "webview" : { "partitions" : [ { "name" : "foo*", "accessible_resources" : ["a.html", "b.html"] }, { "name" : "bar", "accessible_resources" : ["a.html", "c.html"] } ] } BUG=340291 Review URL: https://codereview.chromium.org/151923005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@249640 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool WebviewInfo::IsResourceWebviewAccessible( const Extension* extension, const std::string& partition_id, const std::string& relative_path) { if (!extension) return false; const WebviewInfo* info = GetResourcesInfo(*extension); if (!info) return false; for (size_t i = 0; i < info->partition_items_.size(); ++i) { const PartitionItem* const item = info->partition_items_[i]; if (item->Matches(partition_id) && extension->ResourceMatches(item->accessible_resources(), relative_path)) { return true; } } return false; } void WebviewInfo::AddPartitionItem(scoped_ptr<PartitionItem> item) { partition_items_.push_back(item.release()); }
171,208
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 * calloc(size_t n, size_t lb) { # if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */ /* libpthread allocated some memory that is only pointed to by */ /* mmapped thread stacks. Make sure it's not collectable. */ { static GC_bool lib_bounds_set = FALSE; ptr_t caller = (ptr_t)__builtin_return_address(0); /* This test does not need to ensure memory visibility, since */ /* the bounds will be set when/if we create another thread. */ if (!EXPECT(lib_bounds_set, TRUE)) { GC_init_lib_bounds(); lib_bounds_set = TRUE; } if (((word)caller >= (word)GC_libpthread_start && (word)caller < (word)GC_libpthread_end) || ((word)caller >= (word)GC_libld_start && (word)caller < (word)GC_libld_end)) return GC_malloc_uncollectable(n*lb); /* The two ranges are actually usually adjacent, so there may */ /* be a way to speed this up. */ } # endif return((void *)REDIRECT_MALLOC(n*lb)); } Commit Message: Fix calloc() overflow * malloc.c (calloc): Check multiplication overflow in calloc(), assuming REDIRECT_MALLOC. CWE ID: CWE-189
void * calloc(size_t n, size_t lb) { if (lb && n > SIZE_MAX / lb) return NULL; # if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */ /* libpthread allocated some memory that is only pointed to by */ /* mmapped thread stacks. Make sure it's not collectable. */ { static GC_bool lib_bounds_set = FALSE; ptr_t caller = (ptr_t)__builtin_return_address(0); /* This test does not need to ensure memory visibility, since */ /* the bounds will be set when/if we create another thread. */ if (!EXPECT(lib_bounds_set, TRUE)) { GC_init_lib_bounds(); lib_bounds_set = TRUE; } if (((word)caller >= (word)GC_libpthread_start && (word)caller < (word)GC_libpthread_end) || ((word)caller >= (word)GC_libld_start && (word)caller < (word)GC_libld_end)) return GC_malloc_uncollectable(n*lb); /* The two ranges are actually usually adjacent, so there may */ /* be a way to speed this up. */ } # endif return((void *)REDIRECT_MALLOC(n*lb)); }
165,592
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: _dbus_header_byteswap (DBusHeader *header, int new_order) { if (header->byte_order == new_order) return; _dbus_marshal_byteswap (&_dbus_header_signature_str, 0, header->byte_order, new_order, &header->data, 0); header->byte_order = new_order; } Commit Message: CWE ID: CWE-20
_dbus_header_byteswap (DBusHeader *header, int new_order) { unsigned char byte_order; if (header->byte_order == new_order) return; byte_order = _dbus_string_get_byte (&header->data, BYTE_ORDER_OFFSET); _dbus_assert (header->byte_order == byte_order); _dbus_marshal_byteswap (&_dbus_header_signature_str, 0, header->byte_order, new_order, &header->data, 0); _dbus_string_set_byte (&header->data, BYTE_ORDER_OFFSET, new_order); header->byte_order = new_order; }
164,686
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: ztype(i_ctx_t *i_ctx_p) { os_ptr op = osp; ref tnref; int code = array_get(imemory, op, (long)r_btype(op - 1), &tnref); if (code < 0) return code; if (!r_has_type(&tnref, t_name)) { /* Must be either a stack underflow or a t_[a]struct. */ check_op(2); { /* Get the type name from the structure. */ if (op[-1].value.pstruct != 0x00) { const char *sname = gs_struct_type_name_string(gs_object_type(imemory, op[-1].value.pstruct)); int code = name_ref(imemory, (const byte *)sname, strlen(sname), (ref *) (op - 1), 0); if (code < 0) return code; } else return_error(gs_error_stackunderflow); } r_set_attrs(op - 1, a_executable); } else { ref_assign(op - 1, &tnref); } pop(1); return 0; } Commit Message: CWE ID: CWE-704
ztype(i_ctx_t *i_ctx_p) { os_ptr op = osp; ref tnref; int code = array_get(imemory, op, (long)r_btype(op - 1), &tnref); if (code < 0) return code; if (!r_has_type(&tnref, t_name)) { /* Must be either a stack underflow or a t_[a]struct. */ check_op(2); { /* Get the type name from the structure. */ if ((r_has_type(&op[-1], t_struct) || r_has_type(&op[-1], t_astruct)) && op[-1].value.pstruct != 0x00) { const char *sname = gs_struct_type_name_string(gs_object_type(imemory, op[-1].value.pstruct)); int code = name_ref(imemory, (const byte *)sname, strlen(sname), (ref *) (op - 1), 0); if (code < 0) return code; } else return_error(gs_error_stackunderflow); } r_set_attrs(op - 1, a_executable); } else { ref_assign(op - 1, &tnref); } pop(1); return 0; }
164,698
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::useBuffer( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { Mutex::Autolock autoLock(mLock); if (allottedSize > params->size()) { return BAD_VALUE; } BufferMeta *buffer_meta = new BufferMeta(params); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_UseBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize, static_cast<OMX_U8 *>(params->pointer())); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER( portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT( *buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer())); return OK; } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
status_t OMXNodeInstance::useBuffer( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { Mutex::Autolock autoLock(mLock); if (allottedSize > params->size()) { return BAD_VALUE; } BufferMeta *buffer_meta = new BufferMeta(params, portIndex); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_UseBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize, static_cast<OMX_U8 *>(params->pointer())); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER( portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT( *buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer())); return OK; }
173,533
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 IsTraceEventArgsWhitelisted(const char* category_group_name, const char* event_name) { if (base::MatchPattern(category_group_name, "toplevel") && base::MatchPattern(event_name, "*")) { return true; } return false; } Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments R=dsinclair,shatch BUG=546093 Review URL: https://codereview.chromium.org/1415013003 Cr-Commit-Position: refs/heads/master@{#356690} CWE ID: CWE-399
bool IsTraceEventArgsWhitelisted(const char* category_group_name, const char* event_name, ArgumentNameFilterPredicate* arg_filter) { if (base::MatchPattern(category_group_name, "toplevel") && base::MatchPattern(event_name, "*")) { return true; } if (base::MatchPattern(category_group_name, "benchmark") && base::MatchPattern(event_name, "granularly_whitelisted")) { *arg_filter = base::Bind(&IsArgNameWhitelisted); return true; } return false; }
171,679
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: CheckClientDownloadRequest( content::DownloadItem* item, const CheckDownloadCallback& callback, DownloadProtectionService* service, const scoped_refptr<SafeBrowsingDatabaseManager>& database_manager, BinaryFeatureExtractor* binary_feature_extractor) : item_(item), url_chain_(item->GetUrlChain()), referrer_url_(item->GetReferrerUrl()), tab_url_(item->GetTabUrl()), tab_referrer_url_(item->GetTabReferrerUrl()), zipped_executable_(false), callback_(callback), service_(service), binary_feature_extractor_(binary_feature_extractor), database_manager_(database_manager), pingback_enabled_(service_->enabled()), finished_(false), type_(ClientDownloadRequest::WIN_EXECUTABLE), start_time_(base::TimeTicks::Now()), weakptr_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); item_->AddObserver(this); } Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService. BUG=496898,464083 R=isherman@chromium.org, kenrb@chromium.org, mattm@chromium.org, thestig@chromium.org Review URL: https://codereview.chromium.org/1299223006 . Cr-Commit-Position: refs/heads/master@{#344876} CWE ID:
CheckClientDownloadRequest( content::DownloadItem* item, const CheckDownloadCallback& callback, DownloadProtectionService* service, const scoped_refptr<SafeBrowsingDatabaseManager>& database_manager, BinaryFeatureExtractor* binary_feature_extractor) : item_(item), url_chain_(item->GetUrlChain()), referrer_url_(item->GetReferrerUrl()), tab_url_(item->GetTabUrl()), tab_referrer_url_(item->GetTabReferrerUrl()), archived_executable_(false), callback_(callback), service_(service), binary_feature_extractor_(binary_feature_extractor), database_manager_(database_manager), pingback_enabled_(service_->enabled()), finished_(false), type_(ClientDownloadRequest::WIN_EXECUTABLE), start_time_(base::TimeTicks::Now()), weakptr_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); item_->AddObserver(this); }
171,712
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_http_url_t *php_http_url_parse(const char *str, size_t len, unsigned flags TSRMLS_DC) { size_t maxlen = 3 * len; struct parse_state *state = ecalloc(1, sizeof(*state) + maxlen); state->end = str + len; state->ptr = str; state->flags = flags; state->maxlen = maxlen; TSRMLS_SET_CTX(state->ts); if (!parse_scheme(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL scheme: '%s'", state->ptr); efree(state); return NULL; } if (!parse_hier(state)) { efree(state); return NULL; } if (!parse_query(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL query: '%s'", state->ptr); efree(state); return NULL; } if (!parse_fragment(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL fragment: '%s'", state->ptr); efree(state); return NULL; } return (php_http_url_t *) state; } Commit Message: fix bug #71719 (Buffer overflow in HTTP url parsing functions) The parser's offset was not reset when we softfail in scheme parsing and continue to parse a path. Thanks to hlt99 at blinkenshell dot org for the report. CWE ID: CWE-119
php_http_url_t *php_http_url_parse(const char *str, size_t len, unsigned flags TSRMLS_DC) { size_t maxlen = 3 * len + 8 /* null bytes for all components */; struct parse_state *state = ecalloc(1, sizeof(*state) + maxlen); state->end = str + len; state->ptr = str; state->flags = flags; state->maxlen = maxlen; TSRMLS_SET_CTX(state->ts); if (!parse_scheme(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL scheme: '%s'", state->ptr); efree(state); return NULL; } if (!parse_hier(state)) { efree(state); return NULL; } if (!parse_query(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL query: '%s'", state->ptr); efree(state); return NULL; } if (!parse_fragment(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL fragment: '%s'", state->ptr); efree(state); return NULL; } return (php_http_url_t *) state; }
168,834
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 NsGetParameter(preproc_effect_t *effect, void *pParam, uint32_t *pValueSize, void *pValue) { int status = 0; return status; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
int NsGetParameter(preproc_effect_t *effect, int NsGetParameter(preproc_effect_t *effect __unused, void *pParam __unused, uint32_t *pValueSize __unused, void *pValue __unused) { int status = 0; return status; }
173,351
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: matchCurrentInput( const InString *input, int pos, const widechar *passInstructions, int passIC) { int k; int kk = pos; for (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++) if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++]) return 0; return 1; } Commit Message: Fix a buffer overflow Fixes #635 Thanks to HongxuChen for reporting it CWE ID: CWE-125
matchCurrentInput( const InString *input, int pos, const widechar *passInstructions, int passIC) { int k; int kk = pos; for (k = passIC + 2; ((k < passIC + 2 + passInstructions[passIC + 1]) && (kk < input->length)); k++) if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++]) return 0; return 1; }
169,022
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, fputcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0, ret; zval *fields = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|sss", &fields, &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 4: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 3: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 2: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 1: case 0: break; } ret = php_fputcsv(intern->u.file.stream, fields, delimiter, enclosure, escape TSRMLS_CC); RETURN_LONG(ret); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, fputcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0, ret; zval *fields = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|sss", &fields, &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 4: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 3: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 2: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 1: case 0: break; } ret = php_fputcsv(intern->u.file.stream, fields, delimiter, enclosure, escape TSRMLS_CC); RETURN_LONG(ret); } }
167,062
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: ImageLoader::ImageLoader(Element* element) : m_element(element), m_derefElementTimer(this, &ImageLoader::timerFired), m_hasPendingLoadEvent(false), m_hasPendingErrorEvent(false), m_imageComplete(true), m_loadingImageDocument(false), m_elementIsProtected(false), m_suppressErrorEvents(false) { RESOURCE_LOADING_DVLOG(1) << "new ImageLoader " << this; } Commit Message: Move ImageLoader timer to frame-specific TaskRunnerTimer. Move ImageLoader timer m_derefElementTimer to frame-specific TaskRunnerTimer. This associates it with the frame's Networking timer task queue. BUG=624694 Review-Url: https://codereview.chromium.org/2642103002 Cr-Commit-Position: refs/heads/master@{#444927} CWE ID:
ImageLoader::ImageLoader(Element* element) : m_element(element), m_derefElementTimer(TaskRunnerHelper::get(TaskType::Networking, element->document().frame()), this, &ImageLoader::timerFired), m_hasPendingLoadEvent(false), m_hasPendingErrorEvent(false), m_imageComplete(true), m_loadingImageDocument(false), m_elementIsProtected(false), m_suppressErrorEvents(false) { RESOURCE_LOADING_DVLOG(1) << "new ImageLoader " << this; }
171,974
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 AXARIAGridCell::isAriaRowHeader() const { const AtomicString& role = getAttribute(HTMLNames::roleAttr); return equalIgnoringCase(role, "rowheader"); } 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 AXARIAGridCell::isAriaRowHeader() const { const AtomicString& role = getAttribute(HTMLNames::roleAttr); return equalIgnoringASCIICase(role, "rowheader"); }
171,902
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 registerBlobURLFromTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->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:
static void registerBlobURLFromTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); if (WebBlobRegistry* registry = blobRegistry()) registry->registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL); }
170,686
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::ExpandEditionsArray() { if (m_editions_size > m_editions_count) return true; // nothing else to do const int size = (m_editions_size == 0) ? 1 : 2 * m_editions_size; Edition* const editions = new (std::nothrow) Edition[size]; if (editions == NULL) return false; for (int idx = 0; idx < m_editions_count; ++idx) { m_editions[idx].ShallowCopy(editions[idx]); } delete[] m_editions; m_editions = editions; m_editions_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::ExpandEditionsArray() Edition& e = m_editions[m_editions_count++]; e.Init(); return e.Parse(m_pSegment->m_pReader, pos, size); } Chapters::Edition::Edition() {} Chapters::Edition::~Edition() {} int Chapters::Edition::GetAtomCount() const { return m_atoms_count; } const Chapters::Atom* Chapters::Edition::GetAtom(int index) const { if (index < 0) return NULL; if (index >= m_atoms_count) return NULL; return m_atoms + index; } void Chapters::Edition::Init() { m_atoms = NULL; m_atoms_size = 0; m_atoms_count = 0; } void Chapters::Edition::ShallowCopy(Edition& rhs) const { rhs.m_atoms = m_atoms; rhs.m_atoms_size = m_atoms_size; rhs.m_atoms_count = m_atoms_count; } void Chapters::Edition::Clear() { while (m_atoms_count > 0) { Atom& a = m_atoms[--m_atoms_count]; a.Clear(); } delete[] m_atoms; m_atoms = NULL; m_atoms_size = 0; } long Chapters::Edition::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) { // Atom ID status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; }
174,276
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: fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count = cc; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); assert((cc%(bps*stride))==0); if (!tmp) return; while (count > stride) { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++) count -= stride; } _TIFFmemcpy(tmp, cp0, cc); cp = (uint8 *) cp0; for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[bps * count + byte] = tmp[byte * wc + count]; #else cp[bps * count + byte] = tmp[(bps - byte - 1) * wc + count]; #endif } } _TIFFfree(tmp); } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count = cc; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if(cc%(bps*stride)!=0) { TIFFErrorExt(tif->tif_clientdata, "fpAcc", "%s", "cc%(bps*stride))!=0"); return 0; } if (!tmp) return 0; while (count > stride) { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++) count -= stride; } _TIFFmemcpy(tmp, cp0, cc); cp = (uint8 *) cp0; for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[bps * count + byte] = tmp[byte * wc + count]; #else cp[bps * count + byte] = tmp[(bps - byte - 1) * wc + count]; #endif } } _TIFFfree(tmp); return 1; }
166,880
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 _nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state) { struct nfs_delegation *delegation; struct nfs4_opendata *opendata; int delegation_type = 0; int status; opendata = nfs4_open_recoverdata_alloc(ctx, state); if (IS_ERR(opendata)) return PTR_ERR(opendata); opendata->o_arg.claim = NFS4_OPEN_CLAIM_PREVIOUS; opendata->o_arg.fh = NFS_FH(state->inode); rcu_read_lock(); delegation = rcu_dereference(NFS_I(state->inode)->delegation); if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) != 0) delegation_type = delegation->type; rcu_read_unlock(); opendata->o_arg.u.delegation_type = delegation_type; status = nfs4_open_recover(opendata, state); nfs4_opendata_put(opendata); return status; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
static int _nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state) { struct nfs_delegation *delegation; struct nfs4_opendata *opendata; fmode_t delegation_type = 0; int status; opendata = nfs4_open_recoverdata_alloc(ctx, state); if (IS_ERR(opendata)) return PTR_ERR(opendata); opendata->o_arg.claim = NFS4_OPEN_CLAIM_PREVIOUS; opendata->o_arg.fh = NFS_FH(state->inode); rcu_read_lock(); delegation = rcu_dereference(NFS_I(state->inode)->delegation); if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) != 0) delegation_type = delegation->type; rcu_read_unlock(); opendata->o_arg.u.delegation_type = delegation_type; status = nfs4_open_recover(opendata, state); nfs4_opendata_put(opendata); return status; }
165,685
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 do_devinfo_ioctl(struct comedi_device *dev, struct comedi_devinfo __user *arg, struct file *file) { struct comedi_devinfo devinfo; const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_subdevice *read_subdev = comedi_get_read_subdevice(dev_file_info); struct comedi_subdevice *write_subdev = comedi_get_write_subdevice(dev_file_info); memset(&devinfo, 0, sizeof(devinfo)); /* fill devinfo structure */ devinfo.version_code = COMEDI_VERSION_CODE; devinfo.n_subdevs = dev->n_subdevices; memcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN); memcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN); if (read_subdev) devinfo.read_subdevice = read_subdev - dev->subdevices; else devinfo.read_subdevice = -1; if (write_subdev) devinfo.write_subdevice = write_subdev - dev->subdevices; else devinfo.write_subdevice = -1; if (copy_to_user(arg, &devinfo, sizeof(struct comedi_devinfo))) return -EFAULT; return 0; } Commit Message: staging: comedi: fix infoleak to userspace driver_name and board_name are pointers to strings, not buffers of size COMEDI_NAMELEN. Copying COMEDI_NAMELEN bytes of a string containing less than COMEDI_NAMELEN-1 bytes would leak some unrelated bytes. Signed-off-by: Vasiliy Kulikov <segoon@openwall.com> Cc: stable <stable@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de> CWE ID: CWE-200
static int do_devinfo_ioctl(struct comedi_device *dev, struct comedi_devinfo __user *arg, struct file *file) { struct comedi_devinfo devinfo; const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_subdevice *read_subdev = comedi_get_read_subdevice(dev_file_info); struct comedi_subdevice *write_subdev = comedi_get_write_subdevice(dev_file_info); memset(&devinfo, 0, sizeof(devinfo)); /* fill devinfo structure */ devinfo.version_code = COMEDI_VERSION_CODE; devinfo.n_subdevs = dev->n_subdevices; strlcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN); strlcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN); if (read_subdev) devinfo.read_subdevice = read_subdev - dev->subdevices; else devinfo.read_subdevice = -1; if (write_subdev) devinfo.write_subdevice = write_subdev - dev->subdevices; else devinfo.write_subdevice = -1; if (copy_to_user(arg, &devinfo, sizeof(struct comedi_devinfo))) return -EFAULT; return 0; }
166,557
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 *ldb_dn_escape_value(TALLOC_CTX *mem_ctx, struct ldb_val value) { char *dst; if (!value.length) return NULL; /* allocate destination string, it will be at most 3 times the source */ dst = talloc_array(mem_ctx, char, value.length * 3 + 1); if ( ! dst) { talloc_free(dst); return NULL; } ldb_dn_escape_internal(dst, (const char *)value.data, value.length); dst = talloc_realloc(mem_ctx, dst, char, strlen(dst) + 1); return dst; } Commit Message: CWE ID: CWE-200
char *ldb_dn_escape_value(TALLOC_CTX *mem_ctx, struct ldb_val value) { char *dst; size_t len; if (!value.length) return NULL; /* allocate destination string, it will be at most 3 times the source */ dst = talloc_array(mem_ctx, char, value.length * 3 + 1); if ( ! dst) { talloc_free(dst); return NULL; } len = ldb_dn_escape_internal(dst, (const char *)value.data, value.length); dst = talloc_realloc(mem_ctx, dst, char, len + 1); if ( ! dst) { talloc_free(dst); return NULL; } dst[len] = '\0'; return dst; }
164,674
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::allocateBufferWithBackup( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size()) { return BAD_VALUE; } BufferMeta *buffer_meta = new BufferMeta(params, portIndex, true); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBufferWithBackup, err, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p", params->size(), params->pointer(), allottedSize, header->pBuffer)); return OK; } 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::allocateBufferWithBackup( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) { return BAD_VALUE; } // metadata buffers are not connected cross process; only copy if not meta bool copy = mMetadataType[portIndex] == kMetadataBufferTypeInvalid; BufferMeta *buffer_meta = new BufferMeta( params, portIndex, (portIndex == kPortIndexInput) && copy /* copyToOmx */, (portIndex == kPortIndexOutput) && copy /* copyFromOmx */, NULL /* data */); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBufferWithBackup, err, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); memset(header->pBuffer, 0, header->nAllocLen); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p", params->size(), params->pointer(), allottedSize, header->pBuffer)); return OK; }
174,130
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 php_stream_temp_close(php_stream *stream, int close_handle TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; int ret; assert(ts != NULL); if (ts->innerstream) { ret = php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE | (close_handle ? 0 : PHP_STREAM_FREE_PRESERVE_HANDLE)); } else { ret = 0; } if (ts->meta) { zval_ptr_dtor(&ts->meta); } efree(ts); return ret; } Commit Message: CWE ID: CWE-20
static int php_stream_temp_close(php_stream *stream, int close_handle TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; int ret; assert(ts != NULL); if (ts->innerstream) { ret = php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE | (close_handle ? 0 : PHP_STREAM_FREE_PRESERVE_HANDLE)); } else { ret = 0; } if (ts->meta) { zval_ptr_dtor(&ts->meta); } efree(ts); return ret; }
165,479
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 ReturnsValidPath(int dir_type) { base::FilePath path; bool result = PathService::Get(dir_type, &path); bool check_path_exists = true; #if defined(OS_POSIX) if (dir_type == base::DIR_CACHE) check_path_exists = false; #endif #if defined(OS_LINUX) if (dir_type == base::DIR_USER_DESKTOP) check_path_exists = false; #endif #if defined(OS_WIN) if (dir_type == base::DIR_DEFAULT_USER_QUICK_LAUNCH) { if (base::win::GetVersion() < base::win::VERSION_VISTA) { wchar_t default_profile_path[MAX_PATH]; DWORD size = arraysize(default_profile_path); return (result && ::GetDefaultUserProfileDirectory(default_profile_path, &size) && StartsWith(path.value(), default_profile_path, false)); } } else if (dir_type == base::DIR_TASKBAR_PINS) { if (base::win::GetVersion() < base::win::VERSION_WIN7) check_path_exists = false; } #endif #if defined(OS_MAC) if (dir_type != base::DIR_EXE && dir_type != base::DIR_MODULE && dir_type != base::FILE_EXE && dir_type != base::FILE_MODULE) { if (path.ReferencesParent()) return false; } #else if (path.ReferencesParent()) return false; #endif return result && !path.empty() && (!check_path_exists || file_util::PathExists(path)); } Commit Message: Fix OS_MACOS typos. Should be OS_MACOSX. BUG=163208 TEST=none Review URL: https://codereview.chromium.org/12829005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@189130 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool ReturnsValidPath(int dir_type) { base::FilePath path; bool result = PathService::Get(dir_type, &path); bool check_path_exists = true; #if defined(OS_POSIX) if (dir_type == base::DIR_CACHE) check_path_exists = false; #endif #if defined(OS_LINUX) if (dir_type == base::DIR_USER_DESKTOP) check_path_exists = false; #endif #if defined(OS_WIN) if (dir_type == base::DIR_DEFAULT_USER_QUICK_LAUNCH) { if (base::win::GetVersion() < base::win::VERSION_VISTA) { wchar_t default_profile_path[MAX_PATH]; DWORD size = arraysize(default_profile_path); return (result && ::GetDefaultUserProfileDirectory(default_profile_path, &size) && StartsWith(path.value(), default_profile_path, false)); } } else if (dir_type == base::DIR_TASKBAR_PINS) { if (base::win::GetVersion() < base::win::VERSION_WIN7) check_path_exists = false; } #endif #if defined(OS_MACOSX) if (dir_type != base::DIR_EXE && dir_type != base::DIR_MODULE && dir_type != base::FILE_EXE && dir_type != base::FILE_MODULE) { if (path.ReferencesParent()) return false; } #else if (path.ReferencesParent()) return false; #endif return result && !path.empty() && (!check_path_exists || file_util::PathExists(path)); }
171,539
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 BluetoothDeviceChromeOS::ConfirmPairing() { if (!agent_.get() || confirmation_callback_.is_null()) return; confirmation_callback_.Run(SUCCESS); confirmation_callback_.Reset(); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::ConfirmPairing() { if (!pairing_context_.get()) return; pairing_context_->ConfirmPairing(); }
171,220
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 g2m_init_buffers(G2MContext *c) { int aligned_height; if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) { c->framebuf_stride = FFALIGN(c->width * 3, 16); aligned_height = FFALIGN(c->height, 16); av_free(c->framebuf); c->framebuf = av_mallocz(c->framebuf_stride * aligned_height); if (!c->framebuf) return AVERROR(ENOMEM); } if (!c->synth_tile || !c->jpeg_tile || c->old_tile_w < c->tile_width || c->old_tile_h < c->tile_height) { c->tile_stride = FFALIGN(c->tile_width, 16) * 3; aligned_height = FFALIGN(c->tile_height, 16); av_free(c->synth_tile); av_free(c->jpeg_tile); av_free(c->kempf_buf); av_free(c->kempf_flags); c->synth_tile = av_mallocz(c->tile_stride * aligned_height); c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height); c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height + FF_INPUT_BUFFER_PADDING_SIZE); c->kempf_flags = av_mallocz( c->tile_width * aligned_height); if (!c->synth_tile || !c->jpeg_tile || !c->kempf_buf || !c->kempf_flags) return AVERROR(ENOMEM); } return 0; } Commit Message: avcodec/g2meet: Fix framebuf size Currently the code can in some cases draw tiles that hang outside the allocated buffer. This patch increases the buffer size to avoid out of array accesses. An alternative would be to fail if such tiles are encountered. I do not know if any valid files use such hanging tiles. Fixes Ticket2971 Found-by: ami_stuff Signed-off-by: Michael Niedermayer <michaelni@gmx.at> CWE ID: CWE-119
static int g2m_init_buffers(G2MContext *c) { int aligned_height; if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) { c->framebuf_stride = FFALIGN(c->width + 15, 16) * 3; aligned_height = c->height + 15; av_free(c->framebuf); c->framebuf = av_mallocz(c->framebuf_stride * aligned_height); if (!c->framebuf) return AVERROR(ENOMEM); } if (!c->synth_tile || !c->jpeg_tile || c->old_tile_w < c->tile_width || c->old_tile_h < c->tile_height) { c->tile_stride = FFALIGN(c->tile_width, 16) * 3; aligned_height = FFALIGN(c->tile_height, 16); av_free(c->synth_tile); av_free(c->jpeg_tile); av_free(c->kempf_buf); av_free(c->kempf_flags); c->synth_tile = av_mallocz(c->tile_stride * aligned_height); c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height); c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height + FF_INPUT_BUFFER_PADDING_SIZE); c->kempf_flags = av_mallocz( c->tile_width * aligned_height); if (!c->synth_tile || !c->jpeg_tile || !c->kempf_buf || !c->kempf_flags) return AVERROR(ENOMEM); } return 0; }
165,915
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: image_transform_png_set_rgb_to_gray_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return (colour_type & PNG_COLOR_MASK_COLOR) != 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_rgb_to_gray_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return (colour_type & PNG_COLOR_MASK_COLOR) != 0; }
173,641
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 BluetoothDeviceChromeOS::RequestPinCode( const dbus::ObjectPath& device_path, const PinCodeCallback& callback) { DCHECK(agent_.get()); DCHECK(device_path == object_path_); VLOG(1) << object_path_.value() << ": RequestPinCode"; UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_REQUEST_PINCODE, UMA_PAIRING_METHOD_COUNT); DCHECK(pairing_delegate_); DCHECK(pincode_callback_.is_null()); pincode_callback_ = callback; pairing_delegate_->RequestPinCode(this); pairing_delegate_used_ = true; } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::RequestPinCode(
171,237
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: file_ms_alloc(int flags) { struct magic_set *ms; size_t i, len; if ((ms = CAST(struct magic_set *, calloc((size_t)1, sizeof(struct magic_set)))) == NULL) return NULL; if (magic_setflags(ms, flags) == -1) { errno = EINVAL; goto free; } ms->o.buf = ms->o.pbuf = NULL; len = (ms->c.len = 10) * sizeof(*ms->c.li); if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL) goto free; ms->event_flags = 0; ms->error = -1; for (i = 0; i < MAGIC_SETS; i++) ms->mlist[i] = NULL; ms->file = "unknown"; ms->line = 0; ms->indir_max = FILE_INDIR_MAX; ms->name_max = FILE_NAME_MAX; ms->elf_shnum_max = FILE_ELF_SHNUM_MAX; ms->elf_phnum_max = FILE_ELF_PHNUM_MAX; return ms; free: free(ms); return NULL; } Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander Cherepanov) - Restructure ELF note printing so that we don't print the same message multiple times on repeated notes of the same kind. CWE ID: CWE-399
file_ms_alloc(int flags) { struct magic_set *ms; size_t i, len; if ((ms = CAST(struct magic_set *, calloc((size_t)1, sizeof(struct magic_set)))) == NULL) return NULL; if (magic_setflags(ms, flags) == -1) { errno = EINVAL; goto free; } ms->o.buf = ms->o.pbuf = NULL; len = (ms->c.len = 10) * sizeof(*ms->c.li); if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL) goto free; ms->event_flags = 0; ms->error = -1; for (i = 0; i < MAGIC_SETS; i++) ms->mlist[i] = NULL; ms->file = "unknown"; ms->line = 0; ms->indir_max = FILE_INDIR_MAX; ms->name_max = FILE_NAME_MAX; ms->elf_shnum_max = FILE_ELF_SHNUM_MAX; ms->elf_phnum_max = FILE_ELF_PHNUM_MAX; ms->elf_notes_max = FILE_ELF_NOTES_MAX; return ms; free: free(ms); return NULL; }
166,773
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 omx_vdec::release_output_done(void) { bool bRet = false; unsigned i=0,j=0; DEBUG_PRINT_LOW("Value of m_out_mem_ptr %p",m_inp_mem_ptr); if (m_out_mem_ptr) { for (; j < drv_ctx.op_buf.actualcount ; j++) { if (BITMASK_PRESENT(&m_out_bm_count,j)) { break; } } if (j == drv_ctx.op_buf.actualcount) { m_out_bm_count = 0; bRet = true; } } else { m_out_bm_count = 0; bRet = true; } return bRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: add safety checks for freeing buffers Allow only up to 64 buffers on input/output port (since the allocation bitmap is only 64-wide). Do not allow changing theactual buffer count while still holding allocation (Client can technically negotiate buffer count on a free/disabled port) Add safety checks to free only as many buffers were allocated. Fixes: Security Vulnerability - Heap Overflow and Possible Local Privilege Escalation in MediaServer (libOmxVdec problem #3) Bug: 27532282 27661749 Change-Id: I06dd680d43feaef3efdc87311e8a6703e234b523 CWE ID: CWE-119
bool omx_vdec::release_output_done(void) { bool bRet = false; unsigned i=0,j=0; DEBUG_PRINT_LOW("Value of m_out_mem_ptr %p",m_out_mem_ptr); if (m_out_mem_ptr) { for (; j < drv_ctx.op_buf.actualcount ; j++) { if (BITMASK_PRESENT(&m_out_bm_count,j)) { break; } } if (j == drv_ctx.op_buf.actualcount) { m_out_bm_count = 0; bRet = true; } } else { m_out_bm_count = 0; bRet = true; } return bRet; }
173,786
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 php_snmp_object_free_storage(void *object TSRMLS_DC) { php_snmp_object *intern = (php_snmp_object *)object; if (!intern) { return; } netsnmp_session_free(&(intern->session)); zend_object_std_dtor(&intern->zo TSRMLS_CC); efree(intern); } Commit Message: CWE ID: CWE-416
static void php_snmp_object_free_storage(void *object TSRMLS_DC) { php_snmp_object *intern = (php_snmp_object *)object; if (!intern) { return; } netsnmp_session_free(&(intern->session)); zend_object_std_dtor(&intern->zo TSRMLS_CC); efree(intern); }
164,977