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: BluetoothDeviceChromeOS::BluetoothDeviceChromeOS( BluetoothAdapterChromeOS* adapter, const dbus::ObjectPath& object_path) : adapter_(adapter), object_path_(object_path), num_connecting_calls_(0), pairing_delegate_(NULL), pairing_delegate_used_(false), weak_ptr_factory_(this) { } 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:
BluetoothDeviceChromeOS::BluetoothDeviceChromeOS( BluetoothAdapterChromeOS* adapter, const dbus::ObjectPath& object_path) : adapter_(adapter), object_path_(object_path), num_connecting_calls_(0), weak_ptr_factory_(this) { }
171,217
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: MediaGalleriesCustomBindings::MediaGalleriesCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetMediaFileSystemObject", base::Bind(&MediaGalleriesCustomBindings::GetMediaFileSystemObject, base::Unretained(this))); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
MediaGalleriesCustomBindings::MediaGalleriesCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetMediaFileSystemObject", "mediaGalleries", base::Bind(&MediaGalleriesCustomBindings::GetMediaFileSystemObject, base::Unretained(this))); }
173,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: x11_open_helper(Buffer *b) { u_char *ucp; u_int proto_len, data_len; u_char *ucp; u_int proto_len, data_len; /* Check if the fixed size part of the packet is in buffer. */ if (buffer_len(b) < 12) return 0; debug2("Initial X11 packet contains bad byte order byte: 0x%x", ucp[0]); return -1; } Commit Message: CWE ID: CWE-264
x11_open_helper(Buffer *b) { u_char *ucp; u_int proto_len, data_len; u_char *ucp; u_int proto_len, data_len; /* Is this being called after the refusal deadline? */ if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) { verbose("Rejected X11 connection after ForwardX11Timeout " "expired"); return -1; } /* Check if the fixed size part of the packet is in buffer. */ if (buffer_len(b) < 12) return 0; debug2("Initial X11 packet contains bad byte order byte: 0x%x", ucp[0]); return -1; }
164,666
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::string* GetTestingDMToken() { static std::string dm_token; return &dm_token; } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <domfc@chromium.org> Reviewed-by: Tien Mai <tienmai@chromium.org> Reviewed-by: Daniel Rubery <drubery@chromium.org> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20
std::string* GetTestingDMToken() { const char** GetTestingDMTokenStorage() { static const char* dm_token = ""; return &dm_token; }
172,354
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 tls1_set_server_sigalgs(SSL *s) { int al; size_t i; /* Clear any shared sigtnature algorithms */ if (s->cert->shared_sigalgs) { OPENSSL_free(s->cert->shared_sigalgs); s->cert->shared_sigalgs = NULL; } /* Clear certificate digests and validity flags */ for (i = 0; i < SSL_PKEY_NUM; i++) { s->cert->pkeys[i].valid_flags = 0; } /* If sigalgs received process it. */ if (s->cert->peer_sigalgs) { if (!tls1_process_sigalgs(s)) { SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE); al = SSL_AD_INTERNAL_ERROR; goto err; } /* Fatal error is no shared signature algorithms */ if (!s->cert->shared_sigalgs) { SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, SSL_R_NO_SHARED_SIGATURE_ALGORITHMS); al = SSL_AD_ILLEGAL_PARAMETER; goto err; } } else ssl_cert_set_default_md(s->cert); return 1; err: ssl3_send_alert(s, SSL3_AL_FATAL, al); return 0; } Commit Message: CWE ID:
int tls1_set_server_sigalgs(SSL *s) { int al; size_t i; /* Clear any shared sigtnature algorithms */ if (s->cert->shared_sigalgs) { OPENSSL_free(s->cert->shared_sigalgs); s->cert->shared_sigalgs = NULL; s->cert->shared_sigalgslen = 0; } /* Clear certificate digests and validity flags */ for (i = 0; i < SSL_PKEY_NUM; i++) { s->cert->pkeys[i].valid_flags = 0; } /* If sigalgs received process it. */ if (s->cert->peer_sigalgs) { if (!tls1_process_sigalgs(s)) { SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE); al = SSL_AD_INTERNAL_ERROR; goto err; } /* Fatal error is no shared signature algorithms */ if (!s->cert->shared_sigalgs) { SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, SSL_R_NO_SHARED_SIGATURE_ALGORITHMS); al = SSL_AD_ILLEGAL_PARAMETER; goto err; } } else ssl_cert_set_default_md(s->cert); return 1; err: ssl3_send_alert(s, SSL3_AL_FATAL, al); return 0; }
164,804
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 handle_emulation_failure(struct kvm_vcpu *vcpu) { ++vcpu->stat.insn_emulation_fail; trace_kvm_emulate_insn_failed(vcpu); vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION; vcpu->run->internal.ndata = 0; kvm_queue_exception(vcpu, UD_VECTOR); return EMULATE_FAIL; } Commit Message: KVM: X86: Don't report L2 emulation failures to user-space This patch prevents that emulation failures which result from emulating an instruction for an L2-Guest results in being reported to userspace. Without this patch a malicious L2-Guest would be able to kill the L1 by triggering a race-condition between an vmexit and the instruction emulator. With this patch the L2 will most likely only kill itself in this situation. Signed-off-by: Joerg Roedel <joerg.roedel@amd.com> Signed-off-by: Marcelo Tosatti <mtosatti@redhat.com> CWE ID: CWE-362
static int handle_emulation_failure(struct kvm_vcpu *vcpu) { int r = EMULATE_DONE; ++vcpu->stat.insn_emulation_fail; trace_kvm_emulate_insn_failed(vcpu); if (!is_guest_mode(vcpu)) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION; vcpu->run->internal.ndata = 0; r = EMULATE_FAIL; } kvm_queue_exception(vcpu, UD_VECTOR); return r; }
166,558
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 NormalPageArena::expandObject(HeapObjectHeader* header, size_t newSize) { ASSERT(header->checkHeader()); if (header->payloadSize() >= newSize) return true; size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize); ASSERT(allocationSize > header->size()); size_t expandSize = allocationSize - header->size(); if (isObjectAllocatedAtAllocationPoint(header) && expandSize <= m_remainingAllocationSize) { m_currentAllocationPoint += expandSize; ASSERT(m_remainingAllocationSize >= expandSize); setRemainingAllocationSize(m_remainingAllocationSize - expandSize); SET_MEMORY_ACCESSIBLE(header->payloadEnd(), expandSize); header->setSize(allocationSize); ASSERT(findPageFromAddress(header->payloadEnd() - 1)); return true; } return false; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
bool NormalPageArena::expandObject(HeapObjectHeader* header, size_t newSize) { header->checkHeader(); if (header->payloadSize() >= newSize) return true; size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize); ASSERT(allocationSize > header->size()); size_t expandSize = allocationSize - header->size(); if (isObjectAllocatedAtAllocationPoint(header) && expandSize <= m_remainingAllocationSize) { m_currentAllocationPoint += expandSize; ASSERT(m_remainingAllocationSize >= expandSize); setRemainingAllocationSize(m_remainingAllocationSize - expandSize); SET_MEMORY_ACCESSIBLE(header->payloadEnd(), expandSize); header->setSize(allocationSize); ASSERT(findPageFromAddress(header->payloadEnd() - 1)); return true; } return false; }
172,710
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: _pyfribidi_log2vis (PyObject * self, PyObject * args, PyObject * kw) { PyObject *logical = NULL; /* input unicode or string object */ FriBidiParType base = FRIBIDI_TYPE_RTL; /* optional direction */ const char *encoding = "utf-8"; /* optional input string encoding */ int clean = 0; /* optional flag to clean the string */ int reordernsm = 1; /* optional flag to allow reordering of non spacing marks*/ static char *kwargs[] = { "logical", "base_direction", "encoding", "clean", "reordernsm", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kw, "O|isii", kwargs, &logical, &base, &encoding, &clean, &reordernsm)) return NULL; /* Validate base */ if (!(base == FRIBIDI_TYPE_RTL || base == FRIBIDI_TYPE_LTR || base == FRIBIDI_TYPE_ON)) return PyErr_Format (PyExc_ValueError, "invalid value %d: use either RTL, LTR or ON", base); /* Check object type and delegate to one of the log2vis functions */ if (PyUnicode_Check (logical)) return log2vis_unicode (logical, base, clean, reordernsm); else if (PyString_Check (logical)) return log2vis_encoded_string (logical, encoding, base, clean, reordernsm); else return PyErr_Format (PyExc_TypeError, "expected unicode or str, not %s", logical->ob_type->tp_name); } Commit Message: refactor pyfribidi.c module pyfribidi.c is now compiled as _pyfribidi. This module only handles unicode internally and doesn't use the fribidi_utf8_to_unicode function (which can't handle 4 byte utf-8 sequences). This fixes the buffer overflow in issue #2. The code is now also much simpler: pyfribidi.c is down from 280 to 130 lines of code. We now ship a pure python pyfribidi that handles the case when non-unicode strings are passed in. We now also adapt the size of the output string if clean=True is passed. CWE ID: CWE-119
_pyfribidi_log2vis (PyObject * self, PyObject * args, PyObject * kw) unicode_log2vis (PyUnicodeObject* string, FriBidiParType base_direction, int clean, int reordernsm) { int i; int length = string->length; FriBidiChar *logical = NULL; /* input fribidi unicode buffer */ FriBidiChar *visual = NULL; /* output fribidi unicode buffer */ FriBidiStrIndex new_len = 0; /* length of the UTF-8 buffer */ PyUnicodeObject *result = NULL; /* Allocate fribidi unicode buffers TODO - Don't copy strings if sizeof(FriBidiChar) == sizeof(Py_UNICODE) */ logical = PyMem_New (FriBidiChar, length + 1); if (logical == NULL) { PyErr_NoMemory(); goto cleanup; } visual = PyMem_New (FriBidiChar, length + 1); if (visual == NULL) { PyErr_NoMemory(); goto cleanup; } for (i=0; i<length; ++i) { logical[i] = string->str[i]; } /* Convert to unicode and order visually */ fribidi_set_reorder_nsm(reordernsm); if (!fribidi_log2vis (logical, length, &base_direction, visual, NULL, NULL, NULL)) { PyErr_SetString (PyExc_RuntimeError, "fribidi failed to order string"); goto cleanup; } /* Cleanup the string if requested */ if (clean) { length = fribidi_remove_bidi_marks (visual, length, NULL, NULL, NULL); } result = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, length); if (result == NULL) { goto cleanup; } for (i=0; i<length; ++i) { result->str[i] = visual[i]; } cleanup: /* Delete unicode buffers */ PyMem_Del (logical); PyMem_Del (visual); return (PyObject *)result; }
165,638
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 btsock_thread_remove_fd_and_close(int thread_handle, int fd) { if (thread_handle < 0 || thread_handle >= MAX_THREAD) { APPL_TRACE_ERROR("%s invalid thread handle: %d", __func__, thread_handle); return false; } if (fd == -1) { APPL_TRACE_ERROR("%s invalid file descriptor.", __func__); return false; } sock_cmd_t cmd = {CMD_REMOVE_FD, fd, 0, 0, 0}; return send(ts[thread_handle].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd); } 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
bool btsock_thread_remove_fd_and_close(int thread_handle, int fd) { if (thread_handle < 0 || thread_handle >= MAX_THREAD) { APPL_TRACE_ERROR("%s invalid thread handle: %d", __func__, thread_handle); return false; } if (fd == -1) { APPL_TRACE_ERROR("%s invalid file descriptor.", __func__); return false; } sock_cmd_t cmd = {CMD_REMOVE_FD, fd, 0, 0, 0}; return TEMP_FAILURE_RETRY(send(ts[thread_handle].cmd_fdw, &cmd, sizeof(cmd), 0)) == sizeof(cmd); }
173,463
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: Chapters::Edition::~Edition() { } 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
Chapters::Edition::~Edition() Chapters::Atom::~Atom() {} unsigned long long Chapters::Atom::GetUID() const { return m_uid; } const char* Chapters::Atom::GetStringUID() const { return m_string_uid; } long long Chapters::Atom::GetStartTimecode() const { return m_start_timecode; } long long Chapters::Atom::GetStopTimecode() const { return m_stop_timecode; } long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const { return GetTime(pChapters, m_start_timecode); }
174,466
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 StopInputMethodProcess() { if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "StopInputMethodProcess: IBus connection is not alive"; return false; } ibus_bus_exit_async(ibus_, FALSE /* do not restart */, -1 /* timeout */, NULL /* cancellable */, NULL /* callback */, NULL /* user_data */); if (ibus_config_) { g_object_unref(ibus_config_); ibus_config_ = NULL; } return true; } 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
bool StopInputMethodProcess() { // IBusController override. virtual bool StopInputMethodProcess() { if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "StopInputMethodProcess: IBus connection is not alive"; return false; } ibus_bus_exit_async(ibus_, FALSE /* do not restart */, -1 /* timeout */, NULL /* cancellable */, NULL /* callback */, NULL /* user_data */); if (ibus_config_) { g_object_unref(ibus_config_); ibus_config_ = NULL; } return true; }
170,549
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::string GetUploadData(const std::string& brand) { DCHECK(!brand.empty()); std::string data(kPostXml); const std::string placeholder("__BRANDCODE_PLACEHOLDER__"); size_t placeholder_pos = data.find(placeholder); DCHECK(placeholder_pos != std::string::npos); data.replace(placeholder_pos, placeholder.size(), brand); return data; } Commit Message: Use install_static::GetAppGuid instead of the hardcoded string in BrandcodeConfigFetcher. Bug: 769756 Change-Id: Ifdcb0a5145ffad1d563562e2b2ea2390ff074cdc Reviewed-on: https://chromium-review.googlesource.com/1213178 Reviewed-by: Dominic Battré <battre@chromium.org> Commit-Queue: Vasilii Sukhanov <vasilii@chromium.org> Cr-Commit-Position: refs/heads/master@{#590275} CWE ID: CWE-79
std::string GetUploadData(const std::string& brand) { std::string app_id(kDefaultAppID); #if defined(OS_WIN) app_id = install_static::UTF16ToUTF8(install_static::GetAppGuid()); #endif // defined(OS_WIN) DCHECK(!brand.empty()); return base::StringPrintf(kPostXml, app_id.c_str(), brand.c_str()); }
172,278
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 wdm_post_reset(struct usb_interface *intf) { struct wdm_device *desc = wdm_find_device(intf); int rv; clear_bit(WDM_RESETTING, &desc->flags); rv = recover_from_urb_loss(desc); mutex_unlock(&desc->wlock); mutex_unlock(&desc->rlock); return 0; } Commit Message: USB: cdc-wdm: fix buffer overflow The buffer for responses must not overflow. If this would happen, set a flag, drop the data and return an error after user space has read all remaining data. Signed-off-by: Oliver Neukum <oliver@neukum.org> CC: stable@kernel.org Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-119
static int wdm_post_reset(struct usb_interface *intf) { struct wdm_device *desc = wdm_find_device(intf); int rv; clear_bit(WDM_OVERFLOW, &desc->flags); clear_bit(WDM_RESETTING, &desc->flags); rv = recover_from_urb_loss(desc); mutex_unlock(&desc->wlock); mutex_unlock(&desc->rlock); return 0; }
166,104
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 Chapters::Display::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 == 0x05) // ChapterString ID { status = UnserializeString(pReader, pos, size, m_string); if (status) return status; } else if (id == 0x037C) // ChapterLanguage ID { status = UnserializeString(pReader, pos, size, m_language); if (status) return status; } else if (id == 0x037E) // ChapterCountry ID { status = UnserializeString(pReader, pos, size, m_country); if (status) return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Chapters::Display::Parse(
174,403
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 inet6_destroy_sock(struct sock *sk) { struct ipv6_pinfo *np = inet6_sk(sk); struct sk_buff *skb; struct ipv6_txoptions *opt; /* Release rx options */ skb = xchg(&np->pktoptions, NULL); if (skb) kfree_skb(skb); skb = xchg(&np->rxpmtu, NULL); if (skb) kfree_skb(skb); /* Free flowlabels */ fl6_free_socklist(sk); /* Free tx options */ opt = xchg(&np->opt, NULL); if (opt) sock_kfree_s(sk, opt, opt->tot_len); } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-416
void inet6_destroy_sock(struct sock *sk) { struct ipv6_pinfo *np = inet6_sk(sk); struct sk_buff *skb; struct ipv6_txoptions *opt; /* Release rx options */ skb = xchg(&np->pktoptions, NULL); if (skb) kfree_skb(skb); skb = xchg(&np->rxpmtu, NULL); if (skb) kfree_skb(skb); /* Free flowlabels */ fl6_free_socklist(sk); /* Free tx options */ opt = xchg((__force struct ipv6_txoptions **)&np->opt, NULL); if (opt) { atomic_sub(opt->tot_len, &sk->sk_omem_alloc); txopt_put(opt); } }
167,327
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 inode_init_owner(struct inode *inode, const struct inode *dir, umode_t mode) { inode->i_uid = current_fsuid(); if (dir && dir->i_mode & S_ISGID) { inode->i_gid = dir->i_gid; if (S_ISDIR(mode)) mode |= S_ISGID; } else inode->i_gid = current_fsgid(); inode->i_mode = mode; } Commit Message: Fix up non-directory creation in SGID directories sgid directories have special semantics, making newly created files in the directory belong to the group of the directory, and newly created subdirectories will also become sgid. This is historically used for group-shared directories. But group directories writable by non-group members should not imply that such non-group members can magically join the group, so make sure to clear the sgid bit on non-directories for non-members (but remember that sgid without group execute means "mandatory locking", just to confuse things even more). Reported-by: Jann Horn <jannh@google.com> Cc: Andy Lutomirski <luto@kernel.org> Cc: Al Viro <viro@zeniv.linux.org.uk> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-269
void inode_init_owner(struct inode *inode, const struct inode *dir, umode_t mode) { inode->i_uid = current_fsuid(); if (dir && dir->i_mode & S_ISGID) { inode->i_gid = dir->i_gid; /* Directories are special, and always inherit S_ISGID */ if (S_ISDIR(mode)) mode |= S_ISGID; else if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP) && !in_group_p(inode->i_gid) && !capable_wrt_inode_uidgid(dir, CAP_FSETID)) mode &= ~S_ISGID; } else inode->i_gid = current_fsgid(); inode->i_mode = mode; }
169,153
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 long mem_seek(jas_stream_obj_t *obj, long offset, int origin) { jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; long newpos; JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin)); switch (origin) { case SEEK_SET: newpos = offset; break; case SEEK_END: newpos = m->len_ - offset; break; case SEEK_CUR: newpos = m->pos_ + offset; break; default: abort(); break; } if (newpos < 0) { return -1; } m->pos_ = newpos; return m->pos_; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190
static long mem_seek(jas_stream_obj_t *obj, long offset, int origin) { jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; size_t newpos; JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin)); switch (origin) { case SEEK_SET: newpos = offset; break; case SEEK_END: newpos = m->len_ - offset; break; case SEEK_CUR: newpos = m->pos_ + offset; break; default: abort(); break; } if (newpos < 0) { return -1; } m->pos_ = newpos; return m->pos_; }
168,751
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 SynchronousCompositorOutputSurface::InvokeComposite( const gfx::Transform& transform, gfx::Rect viewport, gfx::Rect clip, gfx::Rect viewport_rect_for_tile_priority, gfx::Transform transform_for_tile_priority, bool hardware_draw) { DCHECK(!frame_holder_.get()); gfx::Transform adjusted_transform = transform; adjusted_transform.matrix().postTranslate(-viewport.x(), -viewport.y(), 0); SetExternalDrawConstraints(adjusted_transform, viewport, clip, viewport_rect_for_tile_priority, transform_for_tile_priority, !hardware_draw); if (!hardware_draw || next_hardware_draw_needs_damage_) { next_hardware_draw_needs_damage_ = false; SetNeedsRedrawRect(gfx::Rect(viewport.size())); } client_->OnDraw(); if (hardware_draw) { cached_hw_transform_ = adjusted_transform; cached_hw_viewport_ = viewport; cached_hw_clip_ = clip; cached_hw_viewport_rect_for_tile_priority_ = viewport_rect_for_tile_priority; cached_hw_transform_for_tile_priority_ = transform_for_tile_priority; } else { bool resourceless_software_draw = false; SetExternalDrawConstraints(cached_hw_transform_, cached_hw_viewport_, cached_hw_clip_, cached_hw_viewport_rect_for_tile_priority_, cached_hw_transform_for_tile_priority_, resourceless_software_draw); next_hardware_draw_needs_damage_ = true; } if (frame_holder_.get()) client_->DidSwapBuffersComplete(); } 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 SynchronousCompositorOutputSurface::InvokeComposite( const gfx::Transform& transform, const gfx::Rect& viewport, const gfx::Rect& clip, const gfx::Rect& viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority, bool hardware_draw) { DCHECK(!frame_holder_.get()); gfx::Transform adjusted_transform = transform; adjusted_transform.matrix().postTranslate(-viewport.x(), -viewport.y(), 0); SetExternalDrawConstraints(adjusted_transform, viewport, clip, viewport_rect_for_tile_priority, transform_for_tile_priority, !hardware_draw); if (!hardware_draw || next_hardware_draw_needs_damage_) { next_hardware_draw_needs_damage_ = false; SetNeedsRedrawRect(gfx::Rect(viewport.size())); } client_->OnDraw(); if (hardware_draw) { cached_hw_transform_ = adjusted_transform; cached_hw_viewport_ = viewport; cached_hw_clip_ = clip; cached_hw_viewport_rect_for_tile_priority_ = viewport_rect_for_tile_priority; cached_hw_transform_for_tile_priority_ = transform_for_tile_priority; } else { bool resourceless_software_draw = false; SetExternalDrawConstraints(cached_hw_transform_, cached_hw_viewport_, cached_hw_clip_, cached_hw_viewport_rect_for_tile_priority_, cached_hw_transform_for_tile_priority_, resourceless_software_draw); next_hardware_draw_needs_damage_ = true; } if (frame_holder_.get()) client_->DidSwapBuffersComplete(); }
171,622
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long Cluster::CreateBlock(long long id, long long pos, // absolute pos of payload long long size, long long discard_padding) { assert((id == 0x20) || (id == 0x23)); // BlockGroup or SimpleBlock if (m_entries_count < 0) { // haven't parsed anything yet assert(m_entries == NULL); assert(m_entries_size == 0); m_entries_size = 1024; m_entries = new BlockEntry* [m_entries_size]; m_entries_count = 0; } else { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (m_entries_count >= m_entries_size) { const long entries_size = 2 * m_entries_size; BlockEntry** const entries = new BlockEntry* [entries_size]; assert(entries); BlockEntry** src = m_entries; BlockEntry** const src_end = src + m_entries_count; BlockEntry** dst = entries; while (src != src_end) *dst++ = *src++; delete[] m_entries; m_entries = entries; m_entries_size = entries_size; } } if (id == 0x20) // BlockGroup ID return CreateBlockGroup(pos, size, discard_padding); else // SimpleBlock ID return CreateSimpleBlock(pos, size); } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Cluster::CreateBlock(long long id, long long pos, // absolute pos of payload long long size, long long discard_padding) { assert((id == 0x20) || (id == 0x23)); // BlockGroup or SimpleBlock if (m_entries_count < 0) { // haven't parsed anything yet assert(m_entries == NULL); assert(m_entries_size == 0); m_entries_size = 1024; m_entries = new (std::nothrow) BlockEntry*[m_entries_size]; if (m_entries == NULL) return -1; m_entries_count = 0; } else { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (m_entries_count >= m_entries_size) { const long entries_size = 2 * m_entries_size; BlockEntry** const entries = new (std::nothrow) BlockEntry*[entries_size]; if (entries == NULL) return -1; BlockEntry** src = m_entries; BlockEntry** const src_end = src + m_entries_count; BlockEntry** dst = entries; while (src != src_end) *dst++ = *src++; delete[] m_entries; m_entries = entries; m_entries_size = entries_size; } } if (id == 0x20) // BlockGroup ID return CreateBlockGroup(pos, size, discard_padding); else // SimpleBlock ID return CreateSimpleBlock(pos, size); }
173,805
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 PageFormAnalyserLogger::Flush() { std::string text; for (ConsoleLevel level : {kError, kWarning, kVerbose}) { for (LogEntry& entry : node_buffer_[level]) { text.clear(); text += "[DOM] "; text += entry.message; for (unsigned i = 0; i < entry.nodes.size(); ++i) text += " %o"; blink::WebConsoleMessage message(level, blink::WebString::FromUTF8(text)); message.nodes = std::move(entry.nodes); // avoids copying node vectors. frame_->AddMessageToConsole(message); } } node_buffer_.clear(); } Commit Message: [AF] Prevent Logging Password Values to Console Before sending over to be logged by DevTools, filter out DOM nodes that have a type attribute equal to "password", and that are not empty. Bug: 934609 Change-Id: I147ad0c2bad13cc50394f4b5ff2f4bfb7293114b Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1506498 Commit-Queue: Sebastien Lalancette <seblalancette@chromium.org> Reviewed-by: Vadym Doroshenko <dvadym@chromium.org> Reviewed-by: Mathieu Perreault <mathp@chromium.org> Cr-Commit-Position: refs/heads/master@{#638615} CWE ID: CWE-119
void PageFormAnalyserLogger::Flush() { std::string text; for (ConsoleLevel level : {kError, kWarning, kVerbose}) { for (LogEntry& entry : node_buffer_[level]) { text.clear(); text += "[DOM] "; text += entry.message; std::vector<blink::WebNode> nodesToLog; for (unsigned i = 0; i < entry.nodes.size(); ++i) { if (entry.nodes[i].IsElementNode()) { const blink::WebElement element = entry.nodes[i].ToConst<blink::WebElement>(); const blink::WebInputElement* webInputElement = blink::ToWebInputElement(&element); // Filter out password inputs with values from being logged, as their // values are also logged. const bool shouldObfuscate = webInputElement && webInputElement->IsPasswordFieldForAutofill() && !webInputElement->Value().IsEmpty(); if (!shouldObfuscate) { text += " %o"; nodesToLog.push_back(element); } } } blink::WebConsoleMessage message(level, blink::WebString::FromUTF8(text)); message.nodes = std::move(nodesToLog); // avoids copying node vectors. frame_->AddMessageToConsole(message); } } node_buffer_.clear(); }
172,078
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 uipc_check_interrupt_locked(void) { if (SAFE_FD_ISSET(uipc_main.signal_fds[0], &uipc_main.read_set)) { char sig_recv = 0; recv(uipc_main.signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL); } } 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 uipc_check_interrupt_locked(void) { if (SAFE_FD_ISSET(uipc_main.signal_fds[0], &uipc_main.read_set)) { char sig_recv = 0; TEMP_FAILURE_RETRY(recv(uipc_main.signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL)); } }
173,496
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 trigger_fpga_config(void) { int ret = 0, init_l; /* approx 10ms */ u32 timeout = 10000; /* make sure the FPGA_can access the EEPROM */ toggle_fpga_eeprom_bus(false); /* assert CONF_SEL_L to be able to drive FPGA_PROG_L */ qrio_gpio_direction_output(GPIO_A, CONF_SEL_L, 0); /* trigger the config start */ qrio_gpio_direction_output(GPIO_A, FPGA_PROG_L, 0); /* small delay for INIT_L line */ udelay(10); /* wait for FPGA_INIT to be asserted */ do { init_l = qrio_get_gpio(GPIO_A, FPGA_INIT_L); if (timeout-- == 0) { printf("FPGA_INIT timeout\n"); ret = -EFAULT; break; } udelay(10); } while (init_l); /* deassert FPGA_PROG, config should start */ qrio_set_gpio(GPIO_A, FPGA_PROG_L, 1); return ret; } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
int trigger_fpga_config(void) { int ret = 0, init_l; /* approx 10ms */ u32 timeout = 10000; /* make sure the FPGA_can access the EEPROM */ toggle_fpga_eeprom_bus(false); /* assert CONF_SEL_L to be able to drive FPGA_PROG_L */ qrio_gpio_direction_output(QRIO_GPIO_A, CONF_SEL_L, 0); /* trigger the config start */ qrio_gpio_direction_output(QRIO_GPIO_A, FPGA_PROG_L, 0); /* small delay for INIT_L line */ udelay(10); /* wait for FPGA_INIT to be asserted */ do { init_l = qrio_get_gpio(QRIO_GPIO_A, FPGA_INIT_L); if (timeout-- == 0) { printf("FPGA_INIT timeout\n"); ret = -EFAULT; break; } udelay(10); } while (init_l); /* deassert FPGA_PROG, config should start */ qrio_set_gpio(QRIO_GPIO_A, FPGA_PROG_L, 1); return ret; }
169,635
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 mntput_no_expire(struct mount *mnt) { rcu_read_lock(); mnt_add_count(mnt, -1); if (likely(mnt->mnt_ns)) { /* shouldn't be the last one */ rcu_read_unlock(); return; } lock_mount_hash(); if (mnt_get_count(mnt)) { rcu_read_unlock(); unlock_mount_hash(); return; } if (unlikely(mnt->mnt.mnt_flags & MNT_DOOMED)) { rcu_read_unlock(); unlock_mount_hash(); return; } mnt->mnt.mnt_flags |= MNT_DOOMED; rcu_read_unlock(); list_del(&mnt->mnt_instance); unlock_mount_hash(); if (likely(!(mnt->mnt.mnt_flags & MNT_INTERNAL))) { struct task_struct *task = current; if (likely(!(task->flags & PF_KTHREAD))) { init_task_work(&mnt->mnt_rcu, __cleanup_mnt); if (!task_work_add(task, &mnt->mnt_rcu, true)) return; } if (llist_add(&mnt->mnt_llist, &delayed_mntput_list)) schedule_delayed_work(&delayed_mntput_work, 1); return; } cleanup_mnt(mnt); } Commit Message: mnt: Honor MNT_LOCKED when detaching mounts Modify umount(MNT_DETACH) to keep mounts in the hash table that are locked to their parent mounts, when the parent is lazily unmounted. In mntput_no_expire detach the children from the hash table, depending on mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children. In __detach_mounts if there are any mounts that have been unmounted but still are on the list of mounts of a mountpoint, remove their children from the mount hash table and those children to the unmounted list so they won't linger potentially indefinitely waiting for their final mntput, now that the mounts serve no purpose. Cc: stable@vger.kernel.org Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com> CWE ID: CWE-284
static void mntput_no_expire(struct mount *mnt) { rcu_read_lock(); mnt_add_count(mnt, -1); if (likely(mnt->mnt_ns)) { /* shouldn't be the last one */ rcu_read_unlock(); return; } lock_mount_hash(); if (mnt_get_count(mnt)) { rcu_read_unlock(); unlock_mount_hash(); return; } if (unlikely(mnt->mnt.mnt_flags & MNT_DOOMED)) { rcu_read_unlock(); unlock_mount_hash(); return; } mnt->mnt.mnt_flags |= MNT_DOOMED; rcu_read_unlock(); list_del(&mnt->mnt_instance); if (unlikely(!list_empty(&mnt->mnt_mounts))) { struct mount *p, *tmp; list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) { umount_mnt(p); } } unlock_mount_hash(); if (likely(!(mnt->mnt.mnt_flags & MNT_INTERNAL))) { struct task_struct *task = current; if (likely(!(task->flags & PF_KTHREAD))) { init_task_work(&mnt->mnt_rcu, __cleanup_mnt); if (!task_work_add(task, &mnt->mnt_rcu, true)) return; } if (llist_add(&mnt->mnt_llist, &delayed_mntput_list)) schedule_delayed_work(&delayed_mntput_work, 1); return; } cleanup_mnt(mnt); }
167,589
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 btif_hl_select_monitor_callback(fd_set *p_cur_set ,fd_set *p_org_set) { UNUSED(p_org_set); BTIF_TRACE_DEBUG("entering %s",__FUNCTION__); for (const list_node_t *node = list_begin(soc_queue); node != list_end(soc_queue); node = list_next(node)) { btif_hl_soc_cb_t *p_scb = list_node(node); if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_READ) { if (FD_ISSET(p_scb->socket_id[1], p_cur_set)) { BTIF_TRACE_DEBUG("read data state= BTIF_HL_SOC_STATE_W4_READ"); btif_hl_mdl_cb_t *p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx, p_scb->mcl_idx, p_scb->mdl_idx); assert(p_dcb != NULL); if (p_dcb->p_tx_pkt) { BTIF_TRACE_ERROR("Rcv new pkt but the last pkt is still not been" " sent tx_size=%d", p_dcb->tx_size); btif_hl_free_buf((void **) &p_dcb->p_tx_pkt); } p_dcb->p_tx_pkt = btif_hl_get_buf (p_dcb->mtu); if (p_dcb) { int r = (int)recv(p_scb->socket_id[1], p_dcb->p_tx_pkt, p_dcb->mtu, MSG_DONTWAIT); if (r > 0) { BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data r =%d", r); p_dcb->tx_size = r; BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data tx_size=%d", p_dcb->tx_size ); BTA_HlSendData(p_dcb->mdl_handle, p_dcb->tx_size); } else { BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback receive failed r=%d",r); BTA_HlDchClose(p_dcb->mdl_handle); } } } } } if (list_is_empty(soc_queue)) BTIF_TRACE_DEBUG("btif_hl_select_monitor_queue is empty"); BTIF_TRACE_DEBUG("leaving %s",__FUNCTION__); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
void btif_hl_select_monitor_callback(fd_set *p_cur_set ,fd_set *p_org_set) { UNUSED(p_org_set); BTIF_TRACE_DEBUG("entering %s",__FUNCTION__); for (const list_node_t *node = list_begin(soc_queue); node != list_end(soc_queue); node = list_next(node)) { btif_hl_soc_cb_t *p_scb = list_node(node); if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_READ) { if (FD_ISSET(p_scb->socket_id[1], p_cur_set)) { BTIF_TRACE_DEBUG("read data state= BTIF_HL_SOC_STATE_W4_READ"); btif_hl_mdl_cb_t *p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx, p_scb->mcl_idx, p_scb->mdl_idx); assert(p_dcb != NULL); if (p_dcb->p_tx_pkt) { BTIF_TRACE_ERROR("Rcv new pkt but the last pkt is still not been" " sent tx_size=%d", p_dcb->tx_size); btif_hl_free_buf((void **) &p_dcb->p_tx_pkt); } p_dcb->p_tx_pkt = btif_hl_get_buf (p_dcb->mtu); if (p_dcb) { int r = (int)TEMP_FAILURE_RETRY(recv(p_scb->socket_id[1], p_dcb->p_tx_pkt, p_dcb->mtu, MSG_DONTWAIT)); if (r > 0) { BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data r =%d", r); p_dcb->tx_size = r; BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data tx_size=%d", p_dcb->tx_size ); BTA_HlSendData(p_dcb->mdl_handle, p_dcb->tx_size); } else { BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback receive failed r=%d",r); BTA_HlDchClose(p_dcb->mdl_handle); } } } } } if (list_is_empty(soc_queue)) BTIF_TRACE_DEBUG("btif_hl_select_monitor_queue is empty"); BTIF_TRACE_DEBUG("leaving %s",__FUNCTION__); }
173,441
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 HostPortAllocatorSession::SendSessionRequest(const std::string& host, int port) { GURL url("https://" + host + ":" + base::IntToString(port) + GetSessionRequestUrl() + "&sn=1"); scoped_ptr<UrlFetcher> url_fetcher(new UrlFetcher(url, UrlFetcher::GET)); url_fetcher->SetRequestContext(url_context_); url_fetcher->SetHeader("X-Talk-Google-Relay-Auth", relay_token()); url_fetcher->SetHeader("X-Google-Relay-Auth", relay_token()); url_fetcher->SetHeader("X-Stream-Type", "chromoting"); url_fetcher->Start(base::Bind(&HostPortAllocatorSession::OnSessionRequestDone, base::Unretained(this), url_fetcher.get())); url_fetchers_.insert(url_fetcher.release()); } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void HostPortAllocatorSession::SendSessionRequest(const std::string& host, int port) { GURL url("https://" + host + ":" + base::IntToString(port) + GetSessionRequestUrl() + "&sn=1"); scoped_ptr<net::URLFetcher> url_fetcher( net::URLFetcher::Create(url, net::URLFetcher::GET, this)); url_fetcher->SetRequestContext(url_context_); url_fetcher->AddExtraRequestHeader( "X-Talk-Google-Relay-Auth: " + relay_token()); url_fetcher->AddExtraRequestHeader("X-Google-Relay-Auth: " + relay_token()); url_fetcher->AddExtraRequestHeader("X-Stream-Type: chromoting"); url_fetcher->Start(); url_fetchers_.insert(url_fetcher.release()); }
170,811
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 RenderViewHostManager::ShouldSwapProcessesForNavigation( const NavigationEntry* curr_entry, const NavigationEntryImpl* new_entry) const { DCHECK(new_entry); const GURL& current_url = (curr_entry) ? curr_entry->GetURL() : render_view_host_->GetSiteInstance()->GetSiteURL(); BrowserContext* browser_context = delegate_->GetControllerForRenderManager().GetBrowserContext(); if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL( browser_context, current_url)) { if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI( browser_context, new_entry->GetURL(), false)) { return true; } } else { if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL( browser_context, new_entry->GetURL())) { return true; } } if (GetContentClient()->browser()->ShouldSwapProcessesForNavigation( curr_entry ? curr_entry->GetURL() : GURL(), new_entry->GetURL())) { return true; } if (!curr_entry) return false; if (curr_entry->IsViewSourceMode() != new_entry->IsViewSourceMode()) return true; return false; } Commit Message: Ensure extensions and the Chrome Web Store are loaded in new BrowsingInstances. BUG=174943 TEST=Can't post message to CWS. See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/12301013 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184208 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool RenderViewHostManager::ShouldSwapProcessesForNavigation( const NavigationEntry* curr_entry, const NavigationEntryImpl* new_entry) const { DCHECK(new_entry); const GURL& current_url = (curr_entry) ? curr_entry->GetURL() : render_view_host_->GetSiteInstance()->GetSiteURL(); BrowserContext* browser_context = delegate_->GetControllerForRenderManager().GetBrowserContext(); if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL( browser_context, current_url)) { if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI( browser_context, new_entry->GetURL(), false)) { return true; } } else { if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL( browser_context, new_entry->GetURL())) { return true; } } if (GetContentClient()->browser()->ShouldSwapProcessesForNavigation( render_view_host_->GetSiteInstance(), curr_entry ? curr_entry->GetURL() : GURL(), new_entry->GetURL())) { return true; } if (!curr_entry) return false; if (curr_entry->IsViewSourceMode() != new_entry->IsViewSourceMode()) return true; return false; }
171,437
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 suffix_object( cJSON *prev, cJSON *item ) { prev->next = item; item->prev = prev; } 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
static void suffix_object( cJSON *prev, cJSON *item )
167,313
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION( locale_get_script ) { get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION( locale_get_script ) PHP_FUNCTION( locale_get_script ) { get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); }
167,182
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 Dispatcher::AddStatus(const std::string& pattern) { mg_set_uri_callback(context_, (root_ + pattern).c_str(), &SendStatus, NULL); } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void Dispatcher::AddStatus(const std::string& pattern) { void Dispatcher::AddHealthz(const std::string& pattern) { mg_set_uri_callback(context_, (root_ + pattern).c_str(), &SendHealthz, NULL); } void Dispatcher::AddLog(const std::string& pattern) { mg_set_uri_callback(context_, (root_ + pattern).c_str(), &SendLog, NULL); }
170,455
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 bmp_getint32(jas_stream_t *in, int_fast32_t *val) { int n; uint_fast32_t v; int c; for (n = 4, v = 0;;) { if ((c = jas_stream_getc(in)) == EOF) { return -1; } v |= (c << 24); if (--n <= 0) { break; } v >>= 8; } if (val) { *val = v; } return 0; } Commit Message: Fixed a sanitizer failure in the BMP codec. Also, added a --debug-level command line option to the imginfo command for debugging purposes. CWE ID: CWE-476
static int bmp_getint32(jas_stream_t *in, int_fast32_t *val) { int n; uint_fast32_t v; int c; for (n = 4, v = 0;;) { if ((c = jas_stream_getc(in)) == EOF) { return -1; } v |= (JAS_CAST(uint_fast32_t, c) << 24); if (--n <= 0) { break; } v >>= 8; } if (val) { *val = v; } return 0; }
168,763
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: header_put_be_int (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4) { psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_int */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_be_int (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = (x >> 24) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_be_int */
170,051
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: exsltFuncRegisterImportFunc (exsltFuncFunctionData *data, exsltFuncImportRegData *ch, const xmlChar *URI, const xmlChar *name, ATTRIBUTE_UNUSED const xmlChar *ignored) { exsltFuncFunctionData *func=NULL; if ((data == NULL) || (ch == NULL) || (URI == NULL) || (name == NULL)) return; if (ch->ctxt == NULL || ch->hash == NULL) return; /* Check if already present */ func = (exsltFuncFunctionData*)xmlHashLookup2(ch->hash, URI, name); if (func == NULL) { /* Not yet present - copy it in */ func = exsltFuncNewFunctionData(); memcpy(func, data, sizeof(exsltFuncFunctionData)); if (xmlHashAddEntry2(ch->hash, URI, name, func) < 0) { xsltGenericError(xsltGenericErrorContext, "Failed to register function {%s}%s\n", URI, name); } else { /* Do the registration */ xsltGenericDebug(xsltGenericDebugContext, "exsltFuncRegisterImportFunc: register {%s}%s\n", URI, name); xsltRegisterExtFunction(ch->ctxt, name, URI, exsltFuncFunctionFunction); } } } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
exsltFuncRegisterImportFunc (exsltFuncFunctionData *data, exsltFuncImportRegData *ch, const xmlChar *URI, const xmlChar *name, ATTRIBUTE_UNUSED const xmlChar *ignored) { exsltFuncFunctionData *func=NULL; if ((data == NULL) || (ch == NULL) || (URI == NULL) || (name == NULL)) return; if (ch->ctxt == NULL || ch->hash == NULL) return; /* Check if already present */ func = (exsltFuncFunctionData*)xmlHashLookup2(ch->hash, URI, name); if (func == NULL) { /* Not yet present - copy it in */ func = exsltFuncNewFunctionData(); if (func == NULL) return; memcpy(func, data, sizeof(exsltFuncFunctionData)); if (xmlHashAddEntry2(ch->hash, URI, name, func) < 0) { xsltGenericError(xsltGenericErrorContext, "Failed to register function {%s}%s\n", URI, name); } else { /* Do the registration */ xsltGenericDebug(xsltGenericDebugContext, "exsltFuncRegisterImportFunc: register {%s}%s\n", URI, name); xsltRegisterExtFunction(ch->ctxt, name, URI, exsltFuncFunctionFunction); } } }
173,294
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 RunFwdTxfm(int16_t *in, int16_t *out, int stride) { fwd_txfm_(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 RunFwdTxfm(int16_t *in, int16_t *out, int stride) { void RunFwdTxfm(int16_t *in, tran_low_t *out, int stride) { fwd_txfm_(in, out, stride, tx_type_); }
174,522
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 PreconnectManager::FinishPreresolveJob(PreresolveJobId job_id, bool success) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); PreresolveJob* job = preresolve_jobs_.Lookup(job_id); DCHECK(job); bool need_preconnect = success && job->need_preconnect(); if (need_preconnect) { PreconnectUrl(job->url, job->num_sockets, job->allow_credentials, job->network_isolation_key); } PreresolveInfo* info = job->info; if (info) info->stats->requests_stats.emplace_back(job->url, need_preconnect); preresolve_jobs_.Remove(job_id); --inflight_preresolves_count_; if (info) { DCHECK_LE(1u, info->inflight_count); --info->inflight_count; } if (info && info->is_done()) AllPreresolvesForUrlFinished(info); TryToLaunchPreresolveJobs(); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org> Reviewed-by: Alex Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void PreconnectManager::FinishPreresolveJob(PreresolveJobId job_id, bool success) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); PreresolveJob* job = preresolve_jobs_.Lookup(job_id); DCHECK(job); bool need_preconnect = success && job->need_preconnect(); if (need_preconnect) { PreconnectUrl(job->url, job->num_sockets, job->allow_credentials, job->network_isolation_key); } PreresolveInfo* info = job->info; if (info) { info->stats->requests_stats.emplace_back(url::Origin::Create(job->url), need_preconnect); } preresolve_jobs_.Remove(job_id); --inflight_preresolves_count_; if (info) { DCHECK_LE(1u, info->inflight_count); --info->inflight_count; } if (info && info->is_done()) AllPreresolvesForUrlFinished(info); TryToLaunchPreresolveJobs(); }
172,374
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 skcipher_release(void *private) { crypto_free_skcipher(private); } Commit Message: crypto: algif_skcipher - Require setkey before accept(2) Some cipher implementations will crash if you try to use them without calling setkey first. This patch adds a check so that the accept(2) call will fail with -ENOKEY if setkey hasn't been done on the socket yet. Cc: stable@vger.kernel.org Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> Tested-by: Dmitry Vyukov <dvyukov@google.com> CWE ID: CWE-476
static void skcipher_release(void *private) { struct skcipher_tfm *tfm = private; crypto_free_skcipher(tfm->skcipher); kfree(tfm); }
167,456
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 cdrom_ioctl_drive_status(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n"); if (!(cdi->ops->capability & CDC_DRIVE_STATUS)) return -ENOSYS; if (!CDROM_CAN(CDC_SELECT_DISC) || (arg == CDSL_CURRENT || arg == CDSL_NONE)) return cdi->ops->drive_status(cdi, CDSL_CURRENT); if (((int)arg >= cdi->capacity)) return -EINVAL; return cdrom_slot_status(cdi, arg); } Commit Message: cdrom: Fix info leak/OOB read in cdrom_ioctl_drive_status Like d88b6d04: "cdrom: information leak in cdrom_ioctl_media_changed()" There is another cast from unsigned long to int which causes a bounds check to fail with specially crafted input. The value is then used as an index in the slot array in cdrom_slot_status(). Signed-off-by: Scott Bauer <scott.bauer@intel.com> Signed-off-by: Scott Bauer <sbauer@plzdonthack.me> Cc: stable@vger.kernel.org Signed-off-by: Jens Axboe <axboe@kernel.dk> CWE ID: CWE-200
static int cdrom_ioctl_drive_status(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n"); if (!(cdi->ops->capability & CDC_DRIVE_STATUS)) return -ENOSYS; if (!CDROM_CAN(CDC_SELECT_DISC) || (arg == CDSL_CURRENT || arg == CDSL_NONE)) return cdi->ops->drive_status(cdi, CDSL_CURRENT); if (arg >= cdi->capacity) return -EINVAL; return cdrom_slot_status(cdi, arg); }
169,035
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 btif_hl_select_wake_reset(void){ char sig_recv = 0; BTIF_TRACE_DEBUG("btif_hl_select_wake_reset"); recv(signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL); return(int)sig_recv; } 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 inline int btif_hl_select_wake_reset(void){ char sig_recv = 0; BTIF_TRACE_DEBUG("btif_hl_select_wake_reset"); TEMP_FAILURE_RETRY(recv(signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL)); return(int)sig_recv; }
173,443
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 _moddeinit(module_unload_intent_t intent) { service_named_unbind_command("chanserv", &cs_flags); } Commit Message: chanserv/flags: make Anope FLAGS compatibility an option Previously, ChanServ FLAGS behavior could be modified by registering or dropping the keyword nicks "LIST", "CLEAR", and "MODIFY". Now, a configuration option is available that when turned on (default), disables registration of these keyword nicks and enables this compatibility feature. When turned off, registration of these keyword nicks is possible, and compatibility to Anope's FLAGS command is disabled. Fixes atheme/atheme#397 CWE ID: CWE-284
void _moddeinit(module_unload_intent_t intent) { service_named_unbind_command("chanserv", &cs_flags); hook_del_nick_can_register(check_registration_keywords); hook_del_user_can_register(check_registration_keywords); del_conf_item("ANOPE_FLAGS_COMPAT", &chansvs.me->conf_table); }
167,585
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 mk_request_free(struct session_request *sr) { if (sr->fd_file > 0) { mk_vhost_close(sr); } if (sr->headers.location) { mk_mem_free(sr->headers.location); } if (sr->uri_processed.data != sr->uri.data) { mk_ptr_free(&sr->uri_processed); } if (sr->real_path.data != sr->real_path_static) { mk_ptr_free(&sr->real_path); } } Commit Message: Request: new request session flag to mark those files opened by FDT This patch aims to fix a potential DDoS problem that can be caused in the server quering repetitive non-existent resources. When serving a static file, the core use Vhost FDT mechanism, but if it sends a static error page it does a direct open(2). When closing the resources for the same request it was just calling mk_vhost_close() which did not clear properly the file descriptor. This patch adds a new field on the struct session_request called 'fd_is_fdt', which contains MK_TRUE or MK_FALSE depending of how fd_file was opened. Thanks to Matthew Daley <mattd@bugfuzz.com> for report and troubleshoot this problem. Signed-off-by: Eduardo Silva <eduardo@monkey.io> CWE ID: CWE-20
void mk_request_free(struct session_request *sr) { if (sr->fd_file > 0) { if (sr->fd_is_fdt == MK_TRUE) { mk_vhost_close(sr); } else { close(sr->fd_file); } } if (sr->headers.location) { mk_mem_free(sr->headers.location); } if (sr->uri_processed.data != sr->uri.data) { mk_ptr_free(&sr->uri_processed); } if (sr->real_path.data != sr->real_path_static) { mk_ptr_free(&sr->real_path); } }
166,277
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: HostCache::HostCache(size_t max_entries) : max_entries_(max_entries), network_changes_(0) {} 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:
HostCache::HostCache(size_t max_entries)
172,007
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 uint16_t transmit_data(serial_data_type_t type, uint8_t *data, uint16_t length) { assert(data != NULL); assert(length > 0); if (type < DATA_TYPE_COMMAND || type > DATA_TYPE_SCO) { LOG_ERROR("%s invalid data type: %d", __func__, type); return 0; } --data; uint8_t previous_byte = *data; *(data) = type; ++length; uint16_t transmitted_length = 0; while (length > 0) { ssize_t ret = write(uart_fd, data + transmitted_length, length); switch (ret) { case -1: LOG_ERROR("In %s, error writing to the uart serial port: %s", __func__, strerror(errno)); goto done; case 0: goto done; default: transmitted_length += ret; length -= ret; break; } } done:; *(data) = previous_byte; if (transmitted_length > 0) --transmitted_length; return transmitted_length; } 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 uint16_t transmit_data(serial_data_type_t type, uint8_t *data, uint16_t length) { assert(data != NULL); assert(length > 0); if (type < DATA_TYPE_COMMAND || type > DATA_TYPE_SCO) { LOG_ERROR("%s invalid data type: %d", __func__, type); return 0; } --data; uint8_t previous_byte = *data; *(data) = type; ++length; uint16_t transmitted_length = 0; while (length > 0) { ssize_t ret = TEMP_FAILURE_RETRY(write(uart_fd, data + transmitted_length, length)); switch (ret) { case -1: LOG_ERROR("In %s, error writing to the uart serial port: %s", __func__, strerror(errno)); goto done; case 0: goto done; default: transmitted_length += ret; length -= ret; break; } } done:; *(data) = previous_byte; if (transmitted_length > 0) --transmitted_length; return transmitted_length; }
173,476
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 P2PQuicStreamImpl::Finish() { DCHECK(!fin_sent()); quic::QuicStream::WriteOrBufferData("", /*fin=*/true, nullptr); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <shampson@chromium.org> Reviewed-by: Henrik Boström <hbos@chromium.org> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
void P2PQuicStreamImpl::Finish() { void P2PQuicStreamImpl::WriteData(std::vector<uint8_t> data, bool fin) { // It is up to the delegate to not write more data than the // |write_buffer_size_|. DCHECK_GE(write_buffer_size_, data.size() + write_buffered_amount_); write_buffered_amount_ += data.size(); QuicStream::WriteOrBufferData( quic::QuicStringPiece(reinterpret_cast<const char*>(data.data()), data.size()), fin, nullptr); }
172,261
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(locale_get_display_region) { get_icu_disp_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION(locale_get_display_region) PHP_FUNCTION(locale_get_display_region) { get_icu_disp_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); }
167,188
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 CancelHandwriting(int n_strokes) { IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } ibus_input_context_cancel_hand_writing(context, n_strokes); g_object_unref(context); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void CancelHandwriting(int n_strokes) { // IBusController override. virtual void CancelHandwriting(int n_strokes) { IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } ibus_input_context_cancel_hand_writing(context, n_strokes); g_object_unref(context); }
170,518
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 PrintWebViewHelper::OnPrintPages() { blink::WebLocalFrame* frame; if (!GetPrintFrame(&frame)) return; auto plugin = delegate_->GetPdfElement(frame); Print(frame, plugin, false); } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
void PrintWebViewHelper::OnPrintPages() { CHECK_LE(ipc_nesting_level_, 1); blink::WebLocalFrame* frame; if (!GetPrintFrame(&frame)) return; auto plugin = delegate_->GetPdfElement(frame); Print(frame, plugin, false); }
171,875
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 FrameLoader::Trace(blink::Visitor* visitor) { visitor->Trace(frame_); visitor->Trace(progress_tracker_); visitor->Trace(document_loader_); visitor->Trace(provisional_document_loader_); } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <andypaicu@chromium.org> Reviewed-by: Mike West <mkwst@chromium.org> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20
void FrameLoader::Trace(blink::Visitor* visitor) { visitor->Trace(frame_); visitor->Trace(progress_tracker_); visitor->Trace(document_loader_); visitor->Trace(provisional_document_loader_); visitor->Trace(last_origin_document_); }
173,059
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 UINT drdynvc_process_data(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { UINT32 ChannelId; ChannelId = drdynvc_read_variable_uint(s, cbChId); WLog_Print(drdynvc->log, WLOG_TRACE, "process_data: Sp=%d cbChId=%d, ChannelId=%"PRIu32"", Sp, cbChId, ChannelId); return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s); } Commit Message: Fix for #4866: Added additional length checks CWE ID:
static UINT drdynvc_process_data(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { UINT32 ChannelId; if (Stream_GetRemainingLength(s) < drdynvc_cblen_to_bytes(cbChId)) return ERROR_INVALID_DATA; ChannelId = drdynvc_read_variable_uint(s, cbChId); WLog_Print(drdynvc->log, WLOG_TRACE, "process_data: Sp=%d cbChId=%d, ChannelId=%"PRIu32"", Sp, cbChId, ChannelId); return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s); }
168,937
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: SSH_PACKET_CALLBACK(ssh_packet_dh_reply){ int rc; (void)type; (void)user; SSH_LOG(SSH_LOG_PROTOCOL,"Received SSH_KEXDH_REPLY"); if(session->session_state!= SSH_SESSION_STATE_DH && session->dh_handshake_state != DH_STATE_INIT_SENT){ ssh_set_error(session,SSH_FATAL,"ssh_packet_dh_reply called in wrong state : %d:%d", session->session_state,session->dh_handshake_state); goto error; } switch(session->next_crypto->kex_type){ case SSH_KEX_DH_GROUP1_SHA1: case SSH_KEX_DH_GROUP14_SHA1: rc=ssh_client_dh_reply(session, packet); break; #ifdef HAVE_ECDH case SSH_KEX_ECDH_SHA2_NISTP256: rc = ssh_client_ecdh_reply(session, packet); break; #endif #ifdef HAVE_CURVE25519 case SSH_KEX_CURVE25519_SHA256_LIBSSH_ORG: rc = ssh_client_curve25519_reply(session, packet); break; #endif default: ssh_set_error(session,SSH_FATAL,"Wrong kex type in ssh_packet_dh_reply"); goto error; } if(rc==SSH_OK) { session->dh_handshake_state = DH_STATE_NEWKEYS_SENT; return SSH_PACKET_USED; } error: session->session_state=SSH_SESSION_STATE_ERROR; return SSH_PACKET_USED; } Commit Message: CWE ID:
SSH_PACKET_CALLBACK(ssh_packet_dh_reply){ int rc; (void)type; (void)user; SSH_LOG(SSH_LOG_PROTOCOL,"Received SSH_KEXDH_REPLY"); if (session->session_state != SSH_SESSION_STATE_DH || session->dh_handshake_state != DH_STATE_INIT_SENT){ ssh_set_error(session,SSH_FATAL,"ssh_packet_dh_reply called in wrong state : %d:%d", session->session_state,session->dh_handshake_state); goto error; } switch(session->next_crypto->kex_type){ case SSH_KEX_DH_GROUP1_SHA1: case SSH_KEX_DH_GROUP14_SHA1: rc=ssh_client_dh_reply(session, packet); break; #ifdef HAVE_ECDH case SSH_KEX_ECDH_SHA2_NISTP256: rc = ssh_client_ecdh_reply(session, packet); break; #endif #ifdef HAVE_CURVE25519 case SSH_KEX_CURVE25519_SHA256_LIBSSH_ORG: rc = ssh_client_curve25519_reply(session, packet); break; #endif default: ssh_set_error(session,SSH_FATAL,"Wrong kex type in ssh_packet_dh_reply"); goto error; } if(rc==SSH_OK) { session->dh_handshake_state = DH_STATE_NEWKEYS_SENT; return SSH_PACKET_USED; } error: session->session_state=SSH_SESSION_STATE_ERROR; return SSH_PACKET_USED; }
165,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: status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer); header->nFilledLen = rangeLength; header->nOffset = rangeOffset; BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); buffer_meta->CopyToOMX(header); return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer); } Commit Message: IOMX: Add buffer range check to emptyBuffer Bug: 20634516 Change-Id: If351dbd573bb4aeb6968bfa33f6d407225bc752c (cherry picked from commit d971df0eb300356b3c995d533289216f43aa60de) CWE ID: CWE-119
status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer); // rangeLength and rangeOffset must be a subset of the allocated data in the buffer. // corner case: we permit rangeOffset == end-of-buffer with rangeLength == 0. if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); buffer_meta->CopyToOMX(header); return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer); }
174,122
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 WebSocketJob::Wakeup() { if (!waiting_) return; waiting_ = false; DCHECK(callback_); MessageLoopForIO::current()->PostTask( FROM_HERE, NewRunnableMethod(this, &WebSocketJob::RetryPendingIO)); } Commit Message: Use ScopedRunnableMethodFactory in WebSocketJob Don't post SendPending if it is already posted. BUG=89795 TEST=none Review URL: http://codereview.chromium.org/7488007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93599 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void WebSocketJob::Wakeup() { if (!waiting_) return; waiting_ = false; DCHECK(callback_); MessageLoopForIO::current()->PostTask( FROM_HERE, method_factory_.NewRunnableMethod(&WebSocketJob::RetryPendingIO)); }
170,307
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 ClipboardMessageFilter::OnWriteObjectsAsync( const ui::Clipboard::ObjectMap& objects) { scoped_ptr<ui::Clipboard::ObjectMap> sanitized_objects( new ui::Clipboard::ObjectMap(objects)); sanitized_objects->erase(ui::Clipboard::CBF_SMBITMAP); #if defined(OS_WIN) BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &WriteObjectsOnUIThread, base::Owned(sanitized_objects.release()))); #else GetClipboard()->WriteObjects( ui::CLIPBOARD_TYPE_COPY_PASTE, *sanitized_objects.get()); #endif } Commit Message: Refactor ui::Clipboard::ObjectMap sanitization in ClipboardMsgFilter. BUG=352395 R=tony@chromium.org TBR=creis@chromium.org Review URL: https://codereview.chromium.org/200523004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@257164 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ClipboardMessageFilter::OnWriteObjectsAsync( const ui::Clipboard::ObjectMap& objects) { scoped_ptr<ui::Clipboard::ObjectMap> sanitized_objects( new ui::Clipboard::ObjectMap(objects)); SanitizeObjectMap(sanitized_objects.get(), kFilterBitmap); #if defined(OS_WIN) BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &WriteObjectsOnUIThread, base::Owned(sanitized_objects.release()))); #else GetClipboard()->WriteObjects( ui::CLIPBOARD_TYPE_COPY_PASTE, *sanitized_objects.get()); #endif }
171,691
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: tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller) { tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size); PrintOutParsingResult(res, 1, caller); return res; } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <yhindin@rehat.com> CWE ID: CWE-20
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller) tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, BOOLEAN verifyLength, LPCSTR caller) { tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size, verifyLength); PrintOutParsingResult(res, 1, caller); return res; }
170,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 MockRenderThread::RemoveRoute(int32 routing_id) { EXPECT_EQ(routing_id_, routing_id); widget_ = NULL; } 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
void MockRenderThread::RemoveRoute(int32 routing_id) { // We may hear this for views created from OnMsgCreateWindow as well, // in which case we don't want to track the new widget. if (routing_id_ == routing_id) widget_ = NULL; }
171,024
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 const char *check_secret(int module, const char *user, const char *group, const char *challenge, const char *pass) { char line[1024]; char pass2[MAX_DIGEST_LEN*2]; const char *fname = lp_secrets_file(module); STRUCT_STAT st; int fd, ok = 1; int user_len = strlen(user); int group_len = group ? strlen(group) : 0; char *err; if (!fname || !*fname || (fd = open(fname, O_RDONLY)) < 0) return "no secrets file"; if (do_fstat(fd, &st) == -1) { rsyserr(FLOG, errno, "fstat(%s)", fname); ok = 0; } else if (lp_strict_modes(module)) { rprintf(FLOG, "secrets file must not be other-accessible (see strict modes option)\n"); ok = 0; } else if (MY_UID() == 0 && st.st_uid != 0) { rprintf(FLOG, "secrets file must be owned by root when running as root (see strict modes)\n"); ok = 0; } } Commit Message: CWE ID: CWE-20
static const char *check_secret(int module, const char *user, const char *group, const char *challenge, const char *pass) { char line[1024]; char pass2[MAX_DIGEST_LEN*2]; const char *fname = lp_secrets_file(module); STRUCT_STAT st; int ok = 1; int user_len = strlen(user); int group_len = group ? strlen(group) : 0; char *err; FILE *fh; if (!fname || !*fname || (fh = fopen(fname, "r")) == NULL) return "no secrets file"; if (do_fstat(fileno(fh), &st) == -1) { rsyserr(FLOG, errno, "fstat(%s)", fname); ok = 0; } else if (lp_strict_modes(module)) { rprintf(FLOG, "secrets file must not be other-accessible (see strict modes option)\n"); ok = 0; } else if (MY_UID() == 0 && st.st_uid != 0) { rprintf(FLOG, "secrets file must be owned by root when running as root (see strict modes)\n"); ok = 0; } }
165,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 SpdyWriteQueue::RemovePendingWritesForStream( const base::WeakPtr<SpdyStream>& stream) { CHECK(!removing_writes_); removing_writes_ = true; RequestPriority priority = stream->priority(); CHECK_GE(priority, MINIMUM_PRIORITY); CHECK_LE(priority, MAXIMUM_PRIORITY); DCHECK(stream.get()); #if DCHECK_IS_ON for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) { if (priority == i) continue; for (std::deque<PendingWrite>::const_iterator it = queue_[i].begin(); it != queue_[i].end(); ++it) { DCHECK_NE(it->stream.get(), stream.get()); } } #endif std::deque<PendingWrite>* queue = &queue_[priority]; std::deque<PendingWrite>::iterator out_it = queue->begin(); for (std::deque<PendingWrite>::const_iterator it = queue->begin(); it != queue->end(); ++it) { if (it->stream.get() == stream.get()) { delete it->frame_producer; } else { *out_it = *it; ++out_it; } } queue->erase(out_it, queue->end()); removing_writes_ = false; } Commit Message: These can post callbacks which re-enter into SpdyWriteQueue. BUG=369539 Review URL: https://codereview.chromium.org/265933007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268730 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void SpdyWriteQueue::RemovePendingWritesForStream( const base::WeakPtr<SpdyStream>& stream) { CHECK(!removing_writes_); removing_writes_ = true; RequestPriority priority = stream->priority(); CHECK_GE(priority, MINIMUM_PRIORITY); CHECK_LE(priority, MAXIMUM_PRIORITY); DCHECK(stream.get()); #if DCHECK_IS_ON for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) { if (priority == i) continue; for (std::deque<PendingWrite>::const_iterator it = queue_[i].begin(); it != queue_[i].end(); ++it) { DCHECK_NE(it->stream.get(), stream.get()); } } #endif // Defer deletion until queue iteration is complete, as // SpdyBuffer::~SpdyBuffer() can result in callbacks into SpdyWriteQueue. std::vector<SpdyBufferProducer*> erased_buffer_producers; std::deque<PendingWrite>* queue = &queue_[priority]; std::deque<PendingWrite>::iterator out_it = queue->begin(); for (std::deque<PendingWrite>::const_iterator it = queue->begin(); it != queue->end(); ++it) { if (it->stream.get() == stream.get()) { erased_buffer_producers.push_back(it->frame_producer); } else { *out_it = *it; ++out_it; } } queue->erase(out_it, queue->end()); removing_writes_ = false; STLDeleteElements(&erased_buffer_producers); // Invokes callbacks. }
171,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: void BrowserEventRouter::TabUpdated(WebContents* contents, bool did_navigate) { TabEntry* entry = GetTabEntry(contents); DictionaryValue* changed_properties = NULL; DCHECK(entry); if (did_navigate) changed_properties = entry->DidNavigate(contents); else changed_properties = entry->UpdateLoadState(contents); if (changed_properties) DispatchTabUpdatedEvent(contents, changed_properties); } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void BrowserEventRouter::TabUpdated(WebContents* contents, bool did_navigate) { TabEntry* entry = GetTabEntry(contents); scoped_ptr<DictionaryValue> changed_properties; DCHECK(entry); if (did_navigate) changed_properties.reset(entry->DidNavigate(contents)); else changed_properties.reset(entry->UpdateLoadState(contents)); if (changed_properties) DispatchTabUpdatedEvent(contents, changed_properties.Pass()); }
171,452
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: InterstitialPage* WebContentsImpl::GetInterstitialPage() const { return GetRenderManager()->interstitial_page(); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
InterstitialPage* WebContentsImpl::GetInterstitialPage() const { return interstitial_page_; }
172,329
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: create_bits (pixman_format_code_t format, int width, int height, int * rowstride_bytes, pixman_bool_t clear) { int stride; size_t buf_size; int bpp; /* what follows is a long-winded way, avoiding any possibility of integer * overflows, of saying: * stride = ((width * bpp + 0x1f) >> 5) * sizeof (uint32_t); */ bpp = PIXMAN_FORMAT_BPP (format); if (_pixman_multiply_overflows_int (width, bpp)) return NULL; stride = width * bpp; if (_pixman_addition_overflows_int (stride, 0x1f)) return NULL; stride += 0x1f; stride >>= 5; stride *= sizeof (uint32_t); if (_pixman_multiply_overflows_size (height, stride)) return NULL; buf_size = height * stride; if (rowstride_bytes) *rowstride_bytes = stride; if (clear) return calloc (buf_size, 1); else return malloc (buf_size); } Commit Message: CWE ID: CWE-189
create_bits (pixman_format_code_t format, int width, int height, int * rowstride_bytes, pixman_bool_t clear) { int stride; size_t buf_size; int bpp; /* what follows is a long-winded way, avoiding any possibility of integer * overflows, of saying: * stride = ((width * bpp + 0x1f) >> 5) * sizeof (uint32_t); */ bpp = PIXMAN_FORMAT_BPP (format); if (_pixman_multiply_overflows_int (width, bpp)) return NULL; stride = width * bpp; if (_pixman_addition_overflows_int (stride, 0x1f)) return NULL; stride += 0x1f; stride >>= 5; stride *= sizeof (uint32_t); if (_pixman_multiply_overflows_size (height, stride)) return NULL; buf_size = (size_t)height * stride; if (rowstride_bytes) *rowstride_bytes = stride; if (clear) return calloc (buf_size, 1); else return malloc (buf_size); }
165,337
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 AppCacheBackendImpl::SelectCache( int host_id, const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { AppCacheHost* host = GetHost(host_id); if (!host || host->was_select_cache_called()) return false; host->SelectCache(document_url, cache_document_was_loaded_from, manifest_url); return true; } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
bool AppCacheBackendImpl::SelectCache( int host_id, const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { AppCacheHost* host = GetHost(host_id); if (!host) return false; return host->SelectCache(document_url, cache_document_was_loaded_from, manifest_url); }
171,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: MagickExport void *DetachBlob(BlobInfo *blob_info) { void *data; assert(blob_info != (BlobInfo *) NULL); if (blob_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (blob_info->mapped != MagickFalse) { (void) UnmapBlob(blob_info->data,blob_info->length); RelinquishMagickResource(MapResource,blob_info->length); } blob_info->mapped=MagickFalse; blob_info->length=0; blob_info->offset=0; blob_info->eof=MagickFalse; blob_info->error=0; blob_info->exempt=MagickFalse; blob_info->type=UndefinedStream; blob_info->file_info.file=(FILE *) NULL; data=blob_info->data; blob_info->data=(unsigned char *) NULL; blob_info->stream=(StreamHandler) NULL; blob_info->custom_stream=(CustomStreamInfo *) NULL; return(data); } Commit Message: https://github.com/ImageMagick/ImageMagick6/issues/43 CWE ID: CWE-416
MagickExport void *DetachBlob(BlobInfo *blob_info) { void *data; assert(blob_info != (BlobInfo *) NULL); if (blob_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (blob_info->mapped != MagickFalse) { (void) UnmapBlob(blob_info->data,blob_info->length); blob_info->data=NULL; RelinquishMagickResource(MapResource,blob_info->length); } blob_info->mapped=MagickFalse; blob_info->length=0; blob_info->offset=0; blob_info->eof=MagickFalse; blob_info->error=0; blob_info->exempt=MagickFalse; blob_info->type=UndefinedStream; blob_info->file_info.file=(FILE *) NULL; data=blob_info->data; blob_info->data=(unsigned char *) NULL; blob_info->stream=(StreamHandler) NULL; blob_info->custom_stream=(CustomStreamInfo *) NULL; return(data); }
170,190
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 ssize_t readAt(off64_t offset, void *buffer, size_t size) { Parcel data, reply; data.writeInterfaceToken( IMediaHTTPConnection::getInterfaceDescriptor()); data.writeInt64(offset); data.writeInt32(size); status_t err = remote()->transact(READ_AT, data, &reply); if (err != OK) { ALOGE("remote readAt failed"); return UNKNOWN_ERROR; } int32_t exceptionCode = reply.readExceptionCode(); if (exceptionCode) { return UNKNOWN_ERROR; } int32_t len = reply.readInt32(); if (len > 0) { memcpy(buffer, mMemory->pointer(), len); } return len; } Commit Message: Add some sanity checks Bug: 19400722 Change-Id: Ib3afdf73fd4647eeea5721c61c8b72dbba0647f6 CWE ID: CWE-119
virtual ssize_t readAt(off64_t offset, void *buffer, size_t size) { Parcel data, reply; data.writeInterfaceToken( IMediaHTTPConnection::getInterfaceDescriptor()); data.writeInt64(offset); data.writeInt32(size); status_t err = remote()->transact(READ_AT, data, &reply); if (err != OK) { ALOGE("remote readAt failed"); return UNKNOWN_ERROR; } int32_t exceptionCode = reply.readExceptionCode(); if (exceptionCode) { return UNKNOWN_ERROR; } size_t len = reply.readInt32(); if (len > size) { ALOGE("requested %zu, got %zu", size, len); return ERROR_OUT_OF_RANGE; } if (len > mMemory->size()) { ALOGE("got %zu, but memory has %zu", len, mMemory->size()); return ERROR_OUT_OF_RANGE; } memcpy(buffer, mMemory->pointer(), len); return len; }
173,365
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 ExtensionServiceBackend::LoadSingleExtension(const FilePath& path_in) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath extension_path = path_in; file_util::AbsolutePath(&extension_path); int flags = Extension::ShouldAlwaysAllowFileAccess(Extension::LOAD) ? Extension::ALLOW_FILE_ACCESS : Extension::NO_FLAGS; if (Extension::ShouldDoStrictErrorChecking(Extension::LOAD)) flags |= Extension::STRICT_ERROR_CHECKS; std::string error; scoped_refptr<const Extension> extension(extension_file_util::LoadExtension( extension_path, Extension::LOAD, flags, &error)); if (!extension) { if (!BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &ExtensionServiceBackend::ReportExtensionLoadError, extension_path, error))) NOTREACHED() << error; return; } if (!BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &ExtensionServiceBackend::OnExtensionInstalled, extension))) NOTREACHED(); } Commit Message: Unrevert: Show the install dialog for the initial load of an unpacked extension with plugins. First landing broke some browser tests. BUG=83273 TEST=in the extensions managmenet page, with developer mode enabled, Load an unpacked extension on an extension with NPAPI plugins. You should get an install dialog. TBR=mihaip git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87738 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionServiceBackend::LoadSingleExtension(const FilePath& path_in) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath extension_path = path_in; file_util::AbsolutePath(&extension_path); int flags = Extension::ShouldAlwaysAllowFileAccess(Extension::LOAD) ? Extension::ALLOW_FILE_ACCESS : Extension::NO_FLAGS; if (Extension::ShouldDoStrictErrorChecking(Extension::LOAD)) flags |= Extension::STRICT_ERROR_CHECKS; std::string error; scoped_refptr<const Extension> extension(extension_file_util::LoadExtension( extension_path, Extension::LOAD, flags, &error)); if (!extension) { if (!BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &ExtensionServiceBackend::ReportExtensionLoadError, extension_path, error))) NOTREACHED() << error; return; } if (!BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &ExtensionServiceBackend::OnLoadSingleExtension, extension))) NOTREACHED(); }
170,407
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: secret_core_crt (gcry_mpi_t M, gcry_mpi_t C, gcry_mpi_t D, unsigned int Nlimbs, gcry_mpi_t P, gcry_mpi_t Q, gcry_mpi_t U) { gcry_mpi_t m1 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t m2 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t h = mpi_alloc_secure ( Nlimbs + 1 ); /* m1 = c ^ (d mod (p-1)) mod p */ mpi_sub_ui ( h, P, 1 ); mpi_fdiv_r ( h, D, h ); mpi_powm ( m1, C, h, P ); /* m2 = c ^ (d mod (q-1)) mod q */ mpi_sub_ui ( h, Q, 1 ); mpi_fdiv_r ( h, D, h ); mpi_powm ( m2, C, h, Q ); /* h = u * ( m2 - m1 ) mod q */ mpi_sub ( h, m2, m1 ); /* Remove superfluous leading zeroes from INPUT. */ mpi_normalize (input); if (!skey->p || !skey->q || !skey->u) { secret_core_std (output, input, skey->d, skey->n); } else { secret_core_crt (output, input, skey->d, mpi_get_nlimbs (skey->n), skey->p, skey->q, skey->u); } } Commit Message: CWE ID: CWE-310
secret_core_crt (gcry_mpi_t M, gcry_mpi_t C, gcry_mpi_t D, unsigned int Nlimbs, gcry_mpi_t P, gcry_mpi_t Q, gcry_mpi_t U) { gcry_mpi_t m1 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t m2 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t h = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t D_blind = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t r; unsigned int r_nbits; r_nbits = mpi_get_nbits (P) / 4; if (r_nbits < 96) r_nbits = 96; r = mpi_alloc_secure ( (r_nbits + BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB ); /* d_blind = (d mod (p-1)) + (p-1) * r */ /* m1 = c ^ d_blind mod p */ _gcry_mpi_randomize (r, r_nbits, GCRY_WEAK_RANDOM); mpi_set_highbit (r, r_nbits - 1); mpi_sub_ui ( h, P, 1 ); mpi_mul ( D_blind, h, r ); mpi_fdiv_r ( h, D, h ); mpi_add ( D_blind, D_blind, h ); mpi_powm ( m1, C, D_blind, P ); /* d_blind = (d mod (q-1)) + (q-1) * r */ /* m2 = c ^ d_blind mod q */ _gcry_mpi_randomize (r, r_nbits, GCRY_WEAK_RANDOM); mpi_set_highbit (r, r_nbits - 1); mpi_sub_ui ( h, Q, 1 ); mpi_mul ( D_blind, h, r ); mpi_fdiv_r ( h, D, h ); mpi_add ( D_blind, D_blind, h ); mpi_powm ( m2, C, D_blind, Q ); mpi_free ( r ); mpi_free ( D_blind ); /* h = u * ( m2 - m1 ) mod q */ mpi_sub ( h, m2, m1 ); /* Remove superfluous leading zeroes from INPUT. */ mpi_normalize (input); if (!skey->p || !skey->q || !skey->u) { secret_core_std (output, input, skey->d, skey->n); } else { secret_core_crt (output, input, skey->d, mpi_get_nlimbs (skey->n), skey->p, skey->q, skey->u); } }
165,456
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 DownloadUIAdapterDelegate::OpenItem(const OfflineItem& item, int64_t offline_id) { JNIEnv* env = AttachCurrentThread(); Java_OfflinePageDownloadBridge_openItem( env, ConvertUTF8ToJavaString(env, item.page_url.spec()), offline_id); } Commit Message: Open Offline Pages in CCT from Downloads Home. When the respective feature flag is enabled, offline pages opened from the Downloads Home will use CCT instead of normal tabs. Bug: 824807 Change-Id: I6d968b8b0c51aaeb7f26332c7ada9f927e151a65 Reviewed-on: https://chromium-review.googlesource.com/977321 Commit-Queue: Carlos Knippschild <carlosk@chromium.org> Reviewed-by: Ted Choc <tedchoc@chromium.org> Reviewed-by: Bernhard Bauer <bauerb@chromium.org> Reviewed-by: Jian Li <jianli@chromium.org> Cr-Commit-Position: refs/heads/master@{#546545} CWE ID: CWE-264
void DownloadUIAdapterDelegate::OpenItem(const OfflineItem& item, int64_t offline_id) { JNIEnv* env = AttachCurrentThread(); Java_OfflinePageDownloadBridge_openItem( env, ConvertUTF8ToJavaString(env, item.page_url.spec()), offline_id, offline_pages::ShouldOfflinePagesInDownloadHomeOpenInCct()); }
171,751
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: yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, void *yyscanner, RE_LEX_ENVIRONMENT *lex_env) { YYUSE (yyvaluep); YYUSE (yyscanner); YYUSE (lex_env); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN switch (yytype) { case 6: /* _CLASS_ */ #line 96 "re_grammar.y" /* yacc.c:1257 */ { yr_free(((*yyvaluep).class_vector)); } #line 1045 "re_grammar.c" /* yacc.c:1257 */ break; case 26: /* alternative */ #line 97 "re_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1051 "re_grammar.c" /* yacc.c:1257 */ break; case 27: /* concatenation */ #line 98 "re_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1057 "re_grammar.c" /* yacc.c:1257 */ break; case 28: /* repeat */ #line 99 "re_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1063 "re_grammar.c" /* yacc.c:1257 */ break; case 29: /* single */ #line 100 "re_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1069 "re_grammar.c" /* yacc.c:1257 */ break; default: break; } YY_IGNORE_MAYBE_UNINITIALIZED_END } Commit Message: Fix issue #674. Move regexp limits to limits.h. CWE ID: CWE-674
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, void *yyscanner, RE_LEX_ENVIRONMENT *lex_env) { YYUSE (yyvaluep); YYUSE (yyscanner); YYUSE (lex_env); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN switch (yytype) { case 6: /* _CLASS_ */ #line 104 "re_grammar.y" /* yacc.c:1257 */ { yr_free(((*yyvaluep).class_vector)); } #line 1053 "re_grammar.c" /* yacc.c:1257 */ break; case 26: /* alternative */ #line 105 "re_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1059 "re_grammar.c" /* yacc.c:1257 */ break; case 27: /* concatenation */ #line 106 "re_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1065 "re_grammar.c" /* yacc.c:1257 */ break; case 28: /* repeat */ #line 107 "re_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1071 "re_grammar.c" /* yacc.c:1257 */ break; case 29: /* single */ #line 108 "re_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1077 "re_grammar.c" /* yacc.c:1257 */ break; default: break; } YY_IGNORE_MAYBE_UNINITIALIZED_END }
168,103
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 ExtensionService::IsDownloadFromGallery(const GURL& download_url, const GURL& referrer_url) { if (IsDownloadFromMiniGallery(download_url) && StartsWithASCII(referrer_url.spec(), extension_urls::kMiniGalleryBrowsePrefix, false)) { return true; } const Extension* download_extension = GetExtensionByWebExtent(download_url); const Extension* referrer_extension = GetExtensionByWebExtent(referrer_url); const Extension* webstore_app = GetWebStoreApp(); bool referrer_valid = (referrer_extension == webstore_app); bool download_valid = (download_extension == webstore_app); GURL store_url = GURL(CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kAppsGalleryURL)); if (!store_url.is_empty()) { std::string store_tld = net::RegistryControlledDomainService::GetDomainAndRegistry(store_url); if (!referrer_valid) { std::string referrer_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( referrer_url); referrer_valid = referrer_url.is_empty() || (referrer_tld == store_tld); } if (!download_valid) { std::string download_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( download_url); download_valid = (download_tld == store_tld); } } return (referrer_valid && download_valid); } Commit Message: Limit extent of webstore app to just chrome.google.com/webstore. BUG=93497 TEST=Try installing extensions and apps from the webstore, starting both being initially logged in, and not. Review URL: http://codereview.chromium.org/7719003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97986 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool ExtensionService::IsDownloadFromGallery(const GURL& download_url, const GURL& referrer_url) { if (IsDownloadFromMiniGallery(download_url) && StartsWithASCII(referrer_url.spec(), extension_urls::kMiniGalleryBrowsePrefix, false)) { return true; } const Extension* download_extension = GetExtensionByWebExtent(download_url); const Extension* referrer_extension = GetExtensionByWebExtent(referrer_url); const Extension* webstore_app = GetWebStoreApp(); bool referrer_valid = (referrer_extension == webstore_app); bool download_valid = (download_extension == webstore_app); // We also allow the download to be from a small set of trusted paths. if (!download_valid) { for (size_t i = 0; i < arraysize(kAllowedDownloadURLPatterns); i++) { URLPattern pattern(URLPattern::SCHEME_HTTPS, kAllowedDownloadURLPatterns[i]); if (pattern.MatchesURL(download_url)) { download_valid = true; break; } } } GURL store_url = GURL(CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kAppsGalleryURL)); if (!store_url.is_empty()) { std::string store_tld = net::RegistryControlledDomainService::GetDomainAndRegistry(store_url); if (!referrer_valid) { std::string referrer_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( referrer_url); referrer_valid = referrer_url.is_empty() || (referrer_tld == store_tld); } if (!download_valid) { std::string download_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( download_url); download_valid = (download_tld == store_tld); } } return (referrer_valid && download_valid); }
170,320
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: BufferMeta(const sp<IMemory> &mem, bool is_backup = false) : mMem(mem), mIsBackup(is_backup) { } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
BufferMeta(const sp<IMemory> &mem, bool is_backup = false) BufferMeta(const sp<IMemory> &mem, OMX_U32 portIndex, bool is_backup = false) : mMem(mem), mIsBackup(is_backup), mPortIndex(portIndex) { }
173,521
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int SoundPool::load(const char* path, int priority __unused) { ALOGV("load: path=%s, priority=%d", path, priority); Mutex::Autolock lock(&mLock); sp<Sample> sample = new Sample(++mNextSampleID, path); mSamples.add(sample->sampleID(), sample); doLoad(sample); return sample->sampleID(); } Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread Sample decoding still occurs in SoundPoolThread without holding the SoundPool lock. Bug: 25781119 Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8 CWE ID: CWE-264
int SoundPool::load(const char* path, int priority __unused) { ALOGV("load: path=%s, priority=%d", path, priority); int sampleID; { Mutex::Autolock lock(&mLock); sampleID = ++mNextSampleID; sp<Sample> sample = new Sample(sampleID, path); mSamples.add(sampleID, sample); sample->startLoad(); } // mDecodeThread->loadSample() must be called outside of mLock. // mDecodeThread->loadSample() may block on mDecodeThread message queue space; // the message queue emptying may block on SoundPool::findSample(). // // It theoretically possible that sample loads might decode out-of-order. mDecodeThread->loadSample(sampleID); return sampleID; }
173,961
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: emit_string(const char *str, FILE *out) /* Print a string with spaces replaced by '_' and non-printing characters by * an octal escape. */ { for (; *str; ++str) if (isgraph(UCHAR_MAX & *str)) putc(*str, out); else if (isspace(UCHAR_MAX & *str)) putc('_', out); else fprintf(out, "\\%.3o", *str); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
emit_string(const char *str, FILE *out) /* Print a string with spaces replaced by '_' and non-printing characters by * an octal escape. */ { for (; *str; ++str) if (isgraph(UCHAR_MAX & *str)) putc(*str, out); else if (isspace(UCHAR_MAX & *str)) putc('_', out); else fprintf(out, "\\%.3o", *str); }
173,731
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 DatabaseImpl::IDBThreadHelper::CreateTransaction( int64_t transaction_id, const std::vector<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode) { DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; connection_->database()->CreateTransaction(transaction_id, connection_.get(), object_store_ids, mode); } Commit Message: [IndexedDB] Fixed transaction use-after-free vuln Bug: 725032 Change-Id: I689ded6c74d5563403587b149c3f3e02e807e4aa Reviewed-on: https://chromium-review.googlesource.com/518483 Reviewed-by: Joshua Bell <jsbell@chromium.org> Commit-Queue: Daniel Murphy <dmurph@chromium.org> Cr-Commit-Position: refs/heads/master@{#475952} CWE ID: CWE-416
void DatabaseImpl::IDBThreadHelper::CreateTransaction( int64_t transaction_id, const std::vector<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode) { DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; // Can't call BadMessage as we're no longer on the IO thread. So ignore. if (connection_->GetTransaction(transaction_id)) return; connection_->database()->CreateTransaction(transaction_id, connection_.get(), object_store_ids, mode); }
172,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: void DCTStream::reset() { int row_stride; str->reset(); if (row_buffer) { jpeg_destroy_decompress(&cinfo); init(); } bool startFound = false; int c = 0, c2 = 0; while (!startFound) { if (!c) if (c == -1) { error(-1, "Could not find start of jpeg data"); src.abort = true; return; } if (c != 0xFF) c = 0; return; } if (c != 0xFF) c = 0; } Commit Message: CWE ID: CWE-20
void DCTStream::reset() { int row_stride; str->reset(); if (row_buffer) { jpeg_destroy_decompress(&cinfo); init(); } bool startFound = false; int c = 0, c2 = 0; while (!startFound) { if (!c) if (c == -1) { error(-1, "Could not find start of jpeg data"); return; } if (c != 0xFF) c = 0; return; } if (c != 0xFF) c = 0; }
165,394
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 PluginServiceImpl::GetPluginInfo(int render_process_id, int render_view_id, ResourceContext* context, const GURL& url, const GURL& page_url, const std::string& mime_type, bool allow_wildcard, bool* is_stale, webkit::WebPluginInfo* info, std::string* actual_mime_type) { std::vector<webkit::WebPluginInfo> plugins; std::vector<std::string> mime_types; bool stale = GetPluginInfoArray( url, mime_type, allow_wildcard, &plugins, &mime_types); if (is_stale) *is_stale = stale; for (size_t i = 0; i < plugins.size(); ++i) { if (!filter_ || filter_->IsPluginEnabled(render_process_id, render_view_id, context, url, page_url, &plugins[i])) { *info = plugins[i]; if (actual_mime_type) *actual_mime_type = mime_types[i]; return true; } } return false; } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287
bool PluginServiceImpl::GetPluginInfo(int render_process_id, int render_view_id, ResourceContext* context, const GURL& url, const GURL& page_url, const std::string& mime_type, bool allow_wildcard, bool* is_stale, webkit::WebPluginInfo* info, std::string* actual_mime_type) { std::vector<webkit::WebPluginInfo> plugins; std::vector<std::string> mime_types; bool stale = GetPluginInfoArray( url, mime_type, allow_wildcard, &plugins, &mime_types); if (is_stale) *is_stale = stale; for (size_t i = 0; i < plugins.size(); ++i) { if (!filter_ || filter_->IsPluginAvailable(render_process_id, render_view_id, context, url, page_url, &plugins[i])) { *info = plugins[i]; if (actual_mime_type) *actual_mime_type = mime_types[i]; return true; } } return false; }
171,475
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static ssize_t bat_socket_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct socket_client *socket_client = file->private_data; struct socket_packet *socket_packet; size_t packet_len; int error; if ((file->f_flags & O_NONBLOCK) && (socket_client->queue_len == 0)) return -EAGAIN; if ((!buf) || (count < sizeof(struct icmp_packet))) return -EINVAL; if (!access_ok(VERIFY_WRITE, buf, count)) return -EFAULT; error = wait_event_interruptible(socket_client->queue_wait, socket_client->queue_len); if (error) return error; spin_lock_bh(&socket_client->lock); socket_packet = list_first_entry(&socket_client->queue_list, struct socket_packet, list); list_del(&socket_packet->list); socket_client->queue_len--; spin_unlock_bh(&socket_client->lock); error = copy_to_user(buf, &socket_packet->icmp_packet, socket_packet->icmp_len); packet_len = socket_packet->icmp_len; kfree(socket_packet); if (error) return -EFAULT; return packet_len; } Commit Message: batman-adv: Only write requested number of byte to user buffer Don't write more than the requested number of bytes of an batman-adv icmp packet to the userspace buffer. Otherwise unrelated userspace memory might get overridden by the kernel. Signed-off-by: Sven Eckelmann <sven@narfation.org> Signed-off-by: Marek Lindner <lindner_marek@yahoo.de> CWE ID: CWE-119
static ssize_t bat_socket_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct socket_client *socket_client = file->private_data; struct socket_packet *socket_packet; size_t packet_len; int error; if ((file->f_flags & O_NONBLOCK) && (socket_client->queue_len == 0)) return -EAGAIN; if ((!buf) || (count < sizeof(struct icmp_packet))) return -EINVAL; if (!access_ok(VERIFY_WRITE, buf, count)) return -EFAULT; error = wait_event_interruptible(socket_client->queue_wait, socket_client->queue_len); if (error) return error; spin_lock_bh(&socket_client->lock); socket_packet = list_first_entry(&socket_client->queue_list, struct socket_packet, list); list_del(&socket_packet->list); socket_client->queue_len--; spin_unlock_bh(&socket_client->lock); packet_len = min(count, socket_packet->icmp_len); error = copy_to_user(buf, &socket_packet->icmp_packet, packet_len); kfree(socket_packet); if (error) return -EFAULT; return packet_len; }
166,207
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 AcceleratedStaticBitmapImage::CheckThread() { if (detach_thread_at_next_check_) { thread_checker_.DetachFromThread(); detach_thread_at_next_check_ = false; } CHECK(thread_checker_.CalledOnValidThread()); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <gab@chromium.org> Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Fernando Serboncini <fserb@chromium.org> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
void AcceleratedStaticBitmapImage::CheckThread() {
172,590
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 GLES2DecoderPassthroughImpl::IsEmulatedQueryTarget(GLenum target) const { switch (target) { case GL_COMMANDS_COMPLETED_CHROMIUM: case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: case GL_COMMANDS_ISSUED_CHROMIUM: case GL_LATENCY_QUERY_CHROMIUM: case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: case GL_GET_ERROR_QUERY_CHROMIUM: return true; default: return false; } } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
bool GLES2DecoderPassthroughImpl::IsEmulatedQueryTarget(GLenum target) const { switch (target) { case GL_COMMANDS_COMPLETED_CHROMIUM: case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: case GL_COMMANDS_ISSUED_CHROMIUM: case GL_LATENCY_QUERY_CHROMIUM: case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: case GL_GET_ERROR_QUERY_CHROMIUM: case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM: return true; default: return false; } }
172,530
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum) { #define AlignedExtent(size,alignment) \ (((size)+((alignment)-1)) & ~((alignment)-1)) size_t alignment, extent, size; void *memory; if (CheckMemoryOverflow(count,quantum) != MagickFalse) return((void *) NULL); memory=NULL; alignment=CACHE_LINE_SIZE; size=count*quantum; extent=AlignedExtent(size,alignment); if ((size == 0) || (alignment < sizeof(void *)) || (extent < size)) return((void *) NULL); #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN) if (posix_memalign(&memory,alignment,extent) != 0) memory=NULL; #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC) memory=_aligned_malloc(extent,alignment); #else { void *p; extent=(size+alignment-1)+sizeof(void *); if (extent > size) { p=malloc(extent); if (p != NULL) { memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment); *((void **) memory-1)=p; } } } #endif return(memory); } Commit Message: Suspend exception processing if there are too many exceptions CWE ID: CWE-119
MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum) { #define AlignedExtent(size,alignment) \ (((size)+((alignment)-1)) & ~((alignment)-1)) size_t alignment, extent, size; void *memory; if (HeapOverflowSanityCheck(count,quantum) != MagickFalse) return((void *) NULL); memory=NULL; alignment=CACHE_LINE_SIZE; size=count*quantum; extent=AlignedExtent(size,alignment); if ((size == 0) || (alignment < sizeof(void *)) || (extent < size)) return((void *) NULL); #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN) if (posix_memalign(&memory,alignment,extent) != 0) memory=NULL; #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC) memory=_aligned_malloc(extent,alignment); #else { void *p; extent=(size+alignment-1)+sizeof(void *); if (extent > size) { p=malloc(extent); if (p != NULL) { memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment); *((void **) memory-1)=p; } } } #endif return(memory); }
168,542
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 verify_source_vc(char **ret_path, const char *src_vc) { _cleanup_close_ int fd = -1; char *path; int r; fd = open_terminal(src_vc, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) return log_error_errno(fd, "Failed to open %s: %m", src_vc); r = verify_vc_device(fd); if (r < 0) return log_error_errno(r, "Device %s is not a virtual console: %m", src_vc); r = verify_vc_allocation_byfd(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not allocated: %m", src_vc); r = verify_vc_kbmode(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", src_vc); path = strdup(src_vc); if (!path) return log_oom(); *ret_path = path; return TAKE_FD(fd); } Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check VT kbd reset check CWE ID: CWE-255
static int verify_source_vc(char **ret_path, const char *src_vc) { _cleanup_close_ int fd = -1; char *path; int r; fd = open_terminal(src_vc, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) return log_error_errno(fd, "Failed to open %s: %m", src_vc); r = verify_vc_device(fd); if (r < 0) return log_error_errno(r, "Device %s is not a virtual console: %m", src_vc); r = verify_vc_allocation_byfd(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not allocated: %m", src_vc); r = vt_verify_kbmode(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", src_vc); path = strdup(src_vc); if (!path) return log_oom(); *ret_path = path; return TAKE_FD(fd); }
169,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: jbig2_decode_gray_scale_image(Jbig2Ctx *ctx, Jbig2Segment *segment, const byte *data, const size_t size, bool GSMMR, uint32_t GSW, uint32_t GSH, uint32_t GSBPP, bool GSUSESKIP, Jbig2Image *GSKIP, int GSTEMPLATE, Jbig2ArithCx *GB_stats) { uint8_t **GSVALS = NULL; size_t consumed_bytes = 0; int i, j, code, stride; int x, y; Jbig2Image **GSPLANES; Jbig2GenericRegionParams rparams; Jbig2WordStream *ws = NULL; Jbig2ArithState *as = NULL; /* allocate GSPLANES */ GSPLANES = jbig2_new(ctx, Jbig2Image *, GSBPP); if (GSPLANES == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %d bytes for GSPLANES", GSBPP); return NULL; } for (i = 0; i < GSBPP; ++i) { GSPLANES[i] = jbig2_image_new(ctx, GSW, GSH); if (GSPLANES[i] == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %dx%d image for GSPLANES", GSW, GSH); /* free already allocated */ for (j = i - 1; j >= 0; --j) { jbig2_image_release(ctx, GSPLANES[j]); } jbig2_free(ctx->allocator, GSPLANES); return NULL; } } } Commit Message: CWE ID: CWE-119
jbig2_decode_gray_scale_image(Jbig2Ctx *ctx, Jbig2Segment *segment, const byte *data, const size_t size, bool GSMMR, uint32_t GSW, uint32_t GSH, uint32_t GSBPP, bool GSUSESKIP, Jbig2Image *GSKIP, int GSTEMPLATE, Jbig2ArithCx *GB_stats) { uint8_t **GSVALS = NULL; size_t consumed_bytes = 0; uint32_t i, j, stride, x, y; int code; Jbig2Image **GSPLANES; Jbig2GenericRegionParams rparams; Jbig2WordStream *ws = NULL; Jbig2ArithState *as = NULL; /* allocate GSPLANES */ GSPLANES = jbig2_new(ctx, Jbig2Image *, GSBPP); if (GSPLANES == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %d bytes for GSPLANES", GSBPP); return NULL; } for (i = 0; i < GSBPP; ++i) { GSPLANES[i] = jbig2_image_new(ctx, GSW, GSH); if (GSPLANES[i] == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %dx%d image for GSPLANES", GSW, GSH); /* free already allocated */ for (j = i; j > 0;) jbig2_image_release(ctx, GSPLANES[--j]); jbig2_free(ctx->allocator, GSPLANES); return NULL; } } }
165,487
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: const SegmentInfo* Segment::GetInfo() const { return m_pInfo; } 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
const SegmentInfo* Segment::GetInfo() const Chapters::~Chapters() { while (m_editions_count > 0) { Edition& e = m_editions[--m_editions_count]; e.Clear(); } }
174,330
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 GpuChannel::OnChannelConnected(int32 peer_pid) { renderer_pid_ = peer_pid; } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuChannel::OnChannelConnected(int32 peer_pid) {
170,932
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: header_put_be_short (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 2) { psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_short */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_be_short (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_be_short */
170,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: IndexedDBTransaction::IndexedDBTransaction( int64_t id, IndexedDBConnection* connection, const std::set<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) : id_(id), object_store_ids_(object_store_ids), mode_(mode), connection_(connection), transaction_(backing_store_transaction), ptr_factory_(this) { IDB_ASYNC_TRACE_BEGIN("IndexedDBTransaction::lifetime", this); callbacks_ = connection_->callbacks(); database_ = connection_->database(); diagnostics_.tasks_scheduled = 0; diagnostics_.tasks_completed = 0; diagnostics_.creation_time = base::Time::Now(); } Commit Message: [IndexedDB] Fixing early destruction of connection during forceclose Patch is as small as possible for merging. Bug: 842990 Change-Id: I9968ffee1bf3279e61e1ec13e4d541f713caf12f Reviewed-on: https://chromium-review.googlesource.com/1062935 Commit-Queue: Daniel Murphy <dmurph@chromium.org> Commit-Queue: Victor Costan <pwnall@chromium.org> Reviewed-by: Victor Costan <pwnall@chromium.org> Cr-Commit-Position: refs/heads/master@{#559383} CWE ID:
IndexedDBTransaction::IndexedDBTransaction( int64_t id, IndexedDBConnection* connection, const std::set<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) : id_(id), object_store_ids_(object_store_ids), mode_(mode), connection_(connection->GetWeakPtr()), transaction_(backing_store_transaction), ptr_factory_(this) { IDB_ASYNC_TRACE_BEGIN("IndexedDBTransaction::lifetime", this); callbacks_ = connection_->callbacks(); database_ = connection_->database(); diagnostics_.tasks_scheduled = 0; diagnostics_.tasks_completed = 0; diagnostics_.creation_time = base::Time::Now(); }
173,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: gfx::Size LauncherView::GetPreferredSize() { IdealBounds ideal_bounds; CalculateIdealBounds(&ideal_bounds); if (is_horizontal_alignment()) { if (view_model_->view_size() >= 2) { return gfx::Size(view_model_->ideal_bounds(1).right() + kLeadingInset, kLauncherPreferredSize); } return gfx::Size(kLauncherPreferredSize * 2 + kLeadingInset * 2, kLauncherPreferredSize); } if (view_model_->view_size() >= 2) { return gfx::Size(kLauncherPreferredSize, view_model_->ideal_bounds(1).bottom() + kLeadingInset); } return gfx::Size(kLauncherPreferredSize, kLauncherPreferredSize * 2 + kLeadingInset * 2); } 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
gfx::Size LauncherView::GetPreferredSize() { IdealBounds ideal_bounds; CalculateIdealBounds(&ideal_bounds); const int app_list_index = view_model_->view_size() - 1; const int last_button_index = is_overflow_mode() ? last_visible_index_ : app_list_index; const gfx::Rect last_button_bounds = last_button_index >= first_visible_index_ ? view_model_->view_at(last_button_index)->bounds() : gfx::Rect(gfx::Size(kLauncherPreferredSize, kLauncherPreferredSize)); if (is_horizontal_alignment()) { return gfx::Size(last_button_bounds.right() + leading_inset(), kLauncherPreferredSize); } return gfx::Size(kLauncherPreferredSize, last_button_bounds.bottom() + leading_inset()); }
170,889
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: png_zalloc(voidpf png_ptr, uInt items, uInt size) { png_voidp ptr; png_structp p=(png_structp)png_ptr; png_uint_32 save_flags=p->flags; png_uint_32 num_bytes; if (png_ptr == NULL) return (NULL); if (items > PNG_UINT_32_MAX/size) { png_warning (p, "Potential overflow in png_zalloc()"); return (NULL); } num_bytes = (png_uint_32)items * size; p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK; ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes); p->flags=save_flags; #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO) if (ptr == NULL) return ((voidpf)ptr); if (num_bytes > (png_uint_32)0x8000L) { png_memset(ptr, 0, (png_size_t)0x8000L); png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0, (png_size_t)(num_bytes - (png_uint_32)0x8000L)); } else { png_memset(ptr, 0, (png_size_t)num_bytes); } #endif return ((voidpf)ptr); } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_zalloc(voidpf png_ptr, uInt items, uInt size) { png_voidp ptr; png_structp p; png_uint_32 save_flags; png_uint_32 num_bytes; if (png_ptr == NULL) return (NULL); p=(png_structp)png_ptr; save_flags=p->flags; if (items > PNG_UINT_32_MAX/size) { png_warning (p, "Potential overflow in png_zalloc()"); return (NULL); } num_bytes = (png_uint_32)items * size; p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK; ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes); p->flags=save_flags; #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO) if (ptr == NULL) return ((voidpf)ptr); if (num_bytes > (png_uint_32)0x8000L) { png_memset(ptr, 0, (png_size_t)0x8000L); png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0, (png_size_t)(num_bytes - (png_uint_32)0x8000L)); } else { png_memset(ptr, 0, (png_size_t)num_bytes); } #endif return ((voidpf)ptr); }
172,164
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 ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) { if (fields) { if (fields->Buffer) { free(fields->Buffer); fields->Len = 0; fields->MaxLen = 0; fields->Buffer = NULL; fields->BufferOffset = 0; } } } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) static void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) { if (fields) { if (fields->Buffer) { free(fields->Buffer); fields->Len = 0; fields->MaxLen = 0; fields->Buffer = NULL; fields->BufferOffset = 0; } } }
169,272
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 StopCast() { CastConfigDelegate* cast_config = Shell::GetInstance()->system_tray_delegate()->GetCastConfigDelegate(); if (cast_config && cast_config->HasCastExtension()) { cast_config->GetReceiversAndActivities( base::Bind(&StopCastCallback, cast_config)); } } Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods. BUG=489445 Review URL: https://codereview.chromium.org/1145833003 Cr-Commit-Position: refs/heads/master@{#330663} CWE ID: CWE-79
void StopCast() {
171,625
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 WorkerProcessLauncherTest::KillProcess(DWORD exit_code) { exit_code_ = exit_code; BOOL result = SetEvent(process_exit_event_); EXPECT_TRUE(result); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void WorkerProcessLauncherTest::KillProcess(DWORD exit_code) { BOOL result = SetEvent(process_exit_event_); EXPECT_TRUE(result); }
171,550
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: CastStreamingNativeHandler::CastStreamingNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context), last_transport_id_(1), weak_factory_(this) { RouteFunction("CreateSession", base::Bind(&CastStreamingNativeHandler::CreateCastSession, weak_factory_.GetWeakPtr())); RouteFunction("DestroyCastRtpStream", base::Bind(&CastStreamingNativeHandler::DestroyCastRtpStream, weak_factory_.GetWeakPtr())); RouteFunction( "GetSupportedParamsCastRtpStream", base::Bind(&CastStreamingNativeHandler::GetSupportedParamsCastRtpStream, weak_factory_.GetWeakPtr())); RouteFunction("StartCastRtpStream", base::Bind(&CastStreamingNativeHandler::StartCastRtpStream, weak_factory_.GetWeakPtr())); RouteFunction("StopCastRtpStream", base::Bind(&CastStreamingNativeHandler::StopCastRtpStream, weak_factory_.GetWeakPtr())); RouteFunction("DestroyCastUdpTransport", base::Bind(&CastStreamingNativeHandler::DestroyCastUdpTransport, weak_factory_.GetWeakPtr())); RouteFunction( "SetDestinationCastUdpTransport", base::Bind(&CastStreamingNativeHandler::SetDestinationCastUdpTransport, weak_factory_.GetWeakPtr())); RouteFunction( "SetOptionsCastUdpTransport", base::Bind(&CastStreamingNativeHandler::SetOptionsCastUdpTransport, weak_factory_.GetWeakPtr())); RouteFunction("ToggleLogging", base::Bind(&CastStreamingNativeHandler::ToggleLogging, weak_factory_.GetWeakPtr())); RouteFunction("GetRawEvents", base::Bind(&CastStreamingNativeHandler::GetRawEvents, weak_factory_.GetWeakPtr())); RouteFunction("GetStats", base::Bind(&CastStreamingNativeHandler::GetStats, weak_factory_.GetWeakPtr())); RouteFunction("StartCastRtpReceiver", base::Bind(&CastStreamingNativeHandler::StartCastRtpReceiver, weak_factory_.GetWeakPtr())); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
CastStreamingNativeHandler::CastStreamingNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context), last_transport_id_(1), weak_factory_(this) { RouteFunction("CreateSession", "cast.streaming.session", base::Bind(&CastStreamingNativeHandler::CreateCastSession, weak_factory_.GetWeakPtr())); RouteFunction("DestroyCastRtpStream", "cast.streaming.rtpStream", base::Bind(&CastStreamingNativeHandler::DestroyCastRtpStream, weak_factory_.GetWeakPtr())); RouteFunction( "GetSupportedParamsCastRtpStream", "cast.streaming.rtpStream", base::Bind(&CastStreamingNativeHandler::GetSupportedParamsCastRtpStream, weak_factory_.GetWeakPtr())); RouteFunction("StartCastRtpStream", "cast.streaming.rtpStream", base::Bind(&CastStreamingNativeHandler::StartCastRtpStream, weak_factory_.GetWeakPtr())); RouteFunction("StopCastRtpStream", "cast.streaming.rtpStream", base::Bind(&CastStreamingNativeHandler::StopCastRtpStream, weak_factory_.GetWeakPtr())); RouteFunction("DestroyCastUdpTransport", "cast.streaming.udpTransport", base::Bind(&CastStreamingNativeHandler::DestroyCastUdpTransport, weak_factory_.GetWeakPtr())); RouteFunction( "SetDestinationCastUdpTransport", "cast.streaming.udpTransport", base::Bind(&CastStreamingNativeHandler::SetDestinationCastUdpTransport, weak_factory_.GetWeakPtr())); RouteFunction( "SetOptionsCastUdpTransport", "cast.streaming.udpTransport", base::Bind(&CastStreamingNativeHandler::SetOptionsCastUdpTransport, weak_factory_.GetWeakPtr())); RouteFunction("ToggleLogging", "cast.streaming.rtpStream", base::Bind(&CastStreamingNativeHandler::ToggleLogging, weak_factory_.GetWeakPtr())); RouteFunction("GetRawEvents", "cast.streaming.rtpStream", base::Bind(&CastStreamingNativeHandler::GetRawEvents, weak_factory_.GetWeakPtr())); RouteFunction("GetStats", "cast.streaming.rtpStream", base::Bind(&CastStreamingNativeHandler::GetStats, weak_factory_.GetWeakPtr())); RouteFunction("StartCastRtpReceiver", "cast.streaming.receiverSession", base::Bind(&CastStreamingNativeHandler::StartCastRtpReceiver, weak_factory_.GetWeakPtr())); }
173,270
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 EBMLHeader::Init() { m_version = 1; m_readVersion = 1; m_maxIdLength = 4; m_maxSizeLength = 8; if (m_docType) { delete[] m_docType; m_docType = NULL; } m_docTypeVersion = 1; m_docTypeReadVersion = 1; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void EBMLHeader::Init() long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) { assert(pReader); long long total, available;
174,389
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SchedulerObject::suspend(std::string key, std::string &/*reason*/, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } scheduler.enqueueActOnJobMyself(id,JA_SUSPEND_JOBS,true); return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::suspend(std::string key, std::string &/*reason*/, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } scheduler.enqueueActOnJobMyself(id,JA_SUSPEND_JOBS,true); return true; }
164,836
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 PermissionsRequestFunction::InstallUIAbort(bool user_initiated) { results_ = Request::Results::Create(false); SendResponse(true); Release(); // Balanced in RunImpl(). } Commit Message: Check prefs before allowing extension file access in the permissions API. R=mpcomplete@chromium.org BUG=169632 Review URL: https://chromiumcodereview.appspot.com/11884008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void PermissionsRequestFunction::InstallUIAbort(bool user_initiated) { SendResponse(true); Release(); // Balanced in RunImpl(). }
171,441
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 AutoFillQueryXmlParser::StartElement(buzz::XmlParseContext* context, const char* name, const char** attrs) { buzz::QName qname = context->ResolveQName(name, false); const std::string &element = qname.LocalPart(); if (element.compare("autofillqueryresponse") == 0) { *upload_required_ = USE_UPLOAD_RATES; if (*attrs) { buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string &attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("uploadrequired") == 0) { if (strcmp(attrs[1], "true") == 0) *upload_required_ = UPLOAD_REQUIRED; else if (strcmp(attrs[1], "false") == 0) *upload_required_ = UPLOAD_NOT_REQUIRED; } } } else if (element.compare("field") == 0) { if (!attrs[0]) { context->RaiseError(XML_ERROR_ABORTED); return; } AutoFillFieldType field_type = UNKNOWN_TYPE; buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string &attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("autofilltype") == 0) { int value = GetIntValue(context, attrs[1]); field_type = static_cast<AutoFillFieldType>(value); if (field_type < 0 || field_type > MAX_VALID_FIELD_TYPE) { field_type = NO_SERVER_DATA; } } field_types_->push_back(field_type); } } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AutoFillQueryXmlParser::StartElement(buzz::XmlParseContext* context, const char* name, const char** attrs) { buzz::QName qname = context->ResolveQName(name, false); const std::string& element = qname.LocalPart(); if (element.compare("autofillqueryresponse") == 0) { // We check for the upload required attribute below, but if it's not // present, we use the default upload rates. Likewise, by default we assume // an empty experiment id. *upload_required_ = USE_UPLOAD_RATES; *experiment_id_ = std::string(); // |attrs| is a NULL-terminated list of (attribute, value) pairs. while (*attrs) { buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string& attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("uploadrequired") == 0) { if (strcmp(attrs[1], "true") == 0) *upload_required_ = UPLOAD_REQUIRED; else if (strcmp(attrs[1], "false") == 0) *upload_required_ = UPLOAD_NOT_REQUIRED; } else if (attribute_name.compare("experimentid") == 0) { *experiment_id_ = attrs[1]; } // Advance to the next (attribute, value) pair. attrs += 2; } } else if (element.compare("field") == 0) { if (!attrs[0]) { context->RaiseError(XML_ERROR_ABORTED); return; } AutoFillFieldType field_type = UNKNOWN_TYPE; buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string& attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("autofilltype") == 0) { int value = GetIntValue(context, attrs[1]); field_type = static_cast<AutoFillFieldType>(value); if (field_type < 0 || field_type > MAX_VALID_FIELD_TYPE) { field_type = NO_SERVER_DATA; } } field_types_->push_back(field_type); } }
170,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: my_object_many_uppercase (MyObject *obj, const char * const *in, char ***out, GError **error) { int len; int i; len = g_strv_length ((char**) in); *out = g_new0 (char *, len + 1); for (i = 0; i < len; i++) { (*out)[i] = g_ascii_strup (in[i], -1); } (*out)[i] = NULL; return TRUE; } Commit Message: CWE ID: CWE-264
my_object_many_uppercase (MyObject *obj, const char * const *in, char ***out, GError **error)
165,113
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(mcrypt_ofb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ofb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_ofb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ofb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); }
167,110
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 SeekHead::GetCount() const { return m_entry_count; } 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
int SeekHead::GetCount() const const SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const { if (idx < 0) return 0; if (idx >= m_void_element_count) return 0; return m_void_elements + idx; }
174,297
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 ChromeMockRenderThread::print_preview_pages_remaining() { return print_preview_pages_remaining_; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
int ChromeMockRenderThread::print_preview_pages_remaining() { int ChromeMockRenderThread::print_preview_pages_remaining() const { return print_preview_pages_remaining_; }
170,855
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 scoped_refptr<ui::Texture> CreateTransportClient( const gfx::Size& size, float device_scale_factor, uint64 transport_handle) { if (!shared_context_.get()) return NULL; scoped_refptr<ImageTransportClientTexture> image( new ImageTransportClientTexture(shared_context_.get(), size, device_scale_factor, transport_handle)); return image; } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
virtual scoped_refptr<ui::Texture> CreateTransportClient( const gfx::Size& size, float device_scale_factor, const std::string& mailbox_name) { if (!shared_context_.get()) return NULL; scoped_refptr<ImageTransportClientTexture> image( new ImageTransportClientTexture(shared_context_.get(), size, device_scale_factor, mailbox_name)); return image; }
171,361
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 signed short ReadPropertyMSBShort(const unsigned char **p, size_t *length) { union { unsigned short unsigned_value; signed short signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[2]; unsigned short value; if (*length < 2) return((unsigned short) ~0); for (i=0; i < 2; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(unsigned short) (buffer[0] << 8); value|=buffer[1]; quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125
static inline signed short ReadPropertyMSBShort(const unsigned char **p, size_t *length) { union { unsigned short unsigned_value; signed short signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[2]; unsigned short value; if (*length < 2) return((unsigned short) ~0); for (i=0; i < 2; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); }
169,953
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static ssize_t aio_setup_single_vector(struct kiocb *kiocb, int rw, char __user *buf, unsigned long *nr_segs, struct iovec *iovec) { if (unlikely(!access_ok(!rw, buf, kiocb->ki_nbytes))) return -EFAULT; iovec->iov_base = buf; iovec->iov_len = kiocb->ki_nbytes; *nr_segs = 1; return 0; } Commit Message: AIO: properly check iovec sizes In Linus's tree, the iovec code has been reworked massively, but in older kernels the AIO layer should be checking this before passing the request on to other layers. Many thanks to Ben Hawkes of Google Project Zero for pointing out the issue. Reported-by: Ben Hawkes <hawkes@google.com> Acked-by: Benjamin LaHaise <bcrl@kvack.org> Tested-by: Willy Tarreau <w@1wt.eu> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID:
static ssize_t aio_setup_single_vector(struct kiocb *kiocb, int rw, char __user *buf, unsigned long *nr_segs, struct iovec *iovec) { size_t len = kiocb->ki_nbytes; if (len > MAX_RW_COUNT) len = MAX_RW_COUNT; if (unlikely(!access_ok(!rw, buf, len))) return -EFAULT; iovec->iov_base = buf; iovec->iov_len = len; *nr_segs = 1; return 0; }
167,493
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 preproc_mount_mnt_dir(void) { if (!tmpfs_mounted) { if (arg_debug) printf("Mounting tmpfs on %s directory\n", RUN_MNT_DIR); if (mount("tmpfs", RUN_MNT_DIR, "tmpfs", MS_NOSUID | MS_STRICTATIME, "mode=755,gid=0") < 0) errExit("mounting /run/firejail/mnt"); tmpfs_mounted = 1; fs_logger2("tmpfs", RUN_MNT_DIR); #ifdef HAVE_SECCOMP if (arg_seccomp_block_secondary) copy_file(PATH_SECCOMP_BLOCK_SECONDARY, RUN_SECCOMP_BLOCK_SECONDARY, getuid(), getgid(), 0644); // root needed else { copy_file(PATH_SECCOMP_32, RUN_SECCOMP_32, getuid(), getgid(), 0644); // root needed } if (arg_allow_debuggers) copy_file(PATH_SECCOMP_DEFAULT_DEBUG, RUN_SECCOMP_CFG, getuid(), getgid(), 0644); // root needed else copy_file(PATH_SECCOMP_DEFAULT, RUN_SECCOMP_CFG, getuid(), getgid(), 0644); // root needed if (arg_memory_deny_write_execute) copy_file(PATH_SECCOMP_MDWX, RUN_SECCOMP_MDWX, getuid(), getgid(), 0644); // root needed create_empty_file_as_root(RUN_SECCOMP_PROTOCOL, 0644); if (set_perms(RUN_SECCOMP_PROTOCOL, getuid(), getgid(), 0644)) errExit("set_perms"); create_empty_file_as_root(RUN_SECCOMP_POSTEXEC, 0644); if (set_perms(RUN_SECCOMP_POSTEXEC, getuid(), getgid(), 0644)) errExit("set_perms"); #endif } } Commit Message: mount runtime seccomp files read-only (#2602) avoid creating locations in the file system that are both writable and executable (in this case for processes with euid of the user). for the same reason also remove user owned libfiles when it is not needed any more CWE ID: CWE-284
void preproc_mount_mnt_dir(void) { if (!tmpfs_mounted) { if (arg_debug) printf("Mounting tmpfs on %s directory\n", RUN_MNT_DIR); if (mount("tmpfs", RUN_MNT_DIR, "tmpfs", MS_NOSUID | MS_STRICTATIME, "mode=755,gid=0") < 0) errExit("mounting /run/firejail/mnt"); tmpfs_mounted = 1; fs_logger2("tmpfs", RUN_MNT_DIR); #ifdef HAVE_SECCOMP create_empty_dir_as_root(RUN_SECCOMP_DIR, 0755); if (arg_seccomp_block_secondary) copy_file(PATH_SECCOMP_BLOCK_SECONDARY, RUN_SECCOMP_BLOCK_SECONDARY, getuid(), getgid(), 0644); // root needed else { copy_file(PATH_SECCOMP_32, RUN_SECCOMP_32, getuid(), getgid(), 0644); // root needed } if (arg_allow_debuggers) copy_file(PATH_SECCOMP_DEFAULT_DEBUG, RUN_SECCOMP_CFG, getuid(), getgid(), 0644); // root needed else copy_file(PATH_SECCOMP_DEFAULT, RUN_SECCOMP_CFG, getuid(), getgid(), 0644); // root needed if (arg_memory_deny_write_execute) copy_file(PATH_SECCOMP_MDWX, RUN_SECCOMP_MDWX, getuid(), getgid(), 0644); // root needed create_empty_file_as_root(RUN_SECCOMP_PROTOCOL, 0644); if (set_perms(RUN_SECCOMP_PROTOCOL, getuid(), getgid(), 0644)) errExit("set_perms"); create_empty_file_as_root(RUN_SECCOMP_POSTEXEC, 0644); if (set_perms(RUN_SECCOMP_POSTEXEC, getuid(), getgid(), 0644)) errExit("set_perms"); #endif } }
169,658