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: static void dtls1_clear_queues(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
dtls1_hm_fragment_free(frag);
pitem_free(item);
}
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
pqueue_free(s->d1->buffered_messages);
}
}
Commit Message:
CWE ID: CWE-399
|
static void dtls1_clear_queues(SSL *s)
{
dtls1_clear_received_buffer(s);
dtls1_clear_sent_buffer(s);
}
void dtls1_clear_received_buffer(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
dtls1_hm_fragment_free(frag);
pitem_free(item);
}
}
void dtls1_clear_sent_buffer(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
pqueue_free(s->d1->buffered_messages);
}
}
| 165,195
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 local_socket_close(asocket* s) {
adb_mutex_lock(&socket_list_lock);
local_socket_close_locked(s);
adb_mutex_unlock(&socket_list_lock);
}
Commit Message: adb: switch the socket list mutex to a recursive_mutex.
sockets.cpp was branching on whether a socket close function was
local_socket_close in order to avoid a potential deadlock if the socket
list lock was held while closing a peer socket.
Bug: http://b/28347842
Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3
(cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa)
CWE ID: CWE-264
|
static void local_socket_close(asocket* s) {
| 174,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 void copyIPv6IfDifferent(void * dest, const void * src)
{
if(dest != src) {
memcpy(dest, src, sizeof(struct in6_addr));
}
}
Commit Message: pcpserver.c: copyIPv6IfDifferent() check for NULL src argument
CWE ID: CWE-476
|
static void copyIPv6IfDifferent(void * dest, const void * src)
{
if(dest != src && src != NULL) {
memcpy(dest, src, sizeof(struct in6_addr));
}
}
| 169,665
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: struct file *get_empty_filp(void)
{
const struct cred *cred = current_cred();
static long old_max;
struct file *f;
int error;
/*
* Privileged users can go above max_files
*/
if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) {
/*
* percpu_counters are inaccurate. Do an expensive check before
* we go and fail.
*/
if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
goto over;
}
f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
if (unlikely(!f))
return ERR_PTR(-ENOMEM);
percpu_counter_inc(&nr_files);
f->f_cred = get_cred(cred);
error = security_file_alloc(f);
if (unlikely(error)) {
file_free(f);
return ERR_PTR(error);
}
INIT_LIST_HEAD(&f->f_u.fu_list);
atomic_long_set(&f->f_count, 1);
rwlock_init(&f->f_owner.lock);
spin_lock_init(&f->f_lock);
eventpoll_init_file(f);
/* f->f_version: 0 */
return f;
over:
/* Ran out of filps - report that */
if (get_nr_files() > old_max) {
pr_info("VFS: file-max limit %lu reached\n", get_max_files());
old_max = get_nr_files();
}
return ERR_PTR(-ENFILE);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-17
|
struct file *get_empty_filp(void)
{
const struct cred *cred = current_cred();
static long old_max;
struct file *f;
int error;
/*
* Privileged users can go above max_files
*/
if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) {
/*
* percpu_counters are inaccurate. Do an expensive check before
* we go and fail.
*/
if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
goto over;
}
f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
if (unlikely(!f))
return ERR_PTR(-ENOMEM);
percpu_counter_inc(&nr_files);
f->f_cred = get_cred(cred);
error = security_file_alloc(f);
if (unlikely(error)) {
file_free(f);
return ERR_PTR(error);
}
atomic_long_set(&f->f_count, 1);
rwlock_init(&f->f_owner.lock);
spin_lock_init(&f->f_lock);
eventpoll_init_file(f);
/* f->f_version: 0 */
return f;
over:
/* Ran out of filps - report that */
if (get_nr_files() > old_max) {
pr_info("VFS: file-max limit %lu reached\n", get_max_files());
old_max = get_nr_files();
}
return ERR_PTR(-ENFILE);
}
| 166,802
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int do_siocgstampns(struct net *net, struct socket *sock,
unsigned int cmd, void __user *up)
{
mm_segment_t old_fs = get_fs();
struct timespec kts;
int err;
set_fs(KERNEL_DS);
err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts);
set_fs(old_fs);
if (!err)
err = compat_put_timespec(up, &kts);
return err;
}
Commit Message: Fix order of arguments to compat_put_time[spec|val]
Commit 644595f89620 ("compat: Handle COMPAT_USE_64BIT_TIME in
net/socket.c") introduced a bug where the helper functions to take
either a 64-bit or compat time[spec|val] got the arguments in the wrong
order, passing the kernel stack pointer off as a user pointer (and vice
versa).
Because of the user address range check, that in turn then causes an
EFAULT due to the user pointer range checking failing for the kernel
address. Incorrectly resuling in a failed system call for 32-bit
processes with a 64-bit kernel.
On odder architectures like HP-PA (with separate user/kernel address
spaces), it can be used read kernel memory.
Signed-off-by: Mikulas Patocka <mpatocka@redhat.com>
Cc: stable@vger.kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-399
|
static int do_siocgstampns(struct net *net, struct socket *sock,
unsigned int cmd, void __user *up)
{
mm_segment_t old_fs = get_fs();
struct timespec kts;
int err;
set_fs(KERNEL_DS);
err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts);
set_fs(old_fs);
if (!err)
err = compat_put_timespec(&kts, up);
return err;
}
| 165,537
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: aodv_extension(netdissect_options *ndo,
const struct aodv_ext *ep, u_int length)
{
const struct aodv_hello *ah;
switch (ep->type) {
case AODV_EXT_HELLO:
ah = (const struct aodv_hello *)(const void *)ep;
ND_TCHECK(*ah);
if (length < sizeof(struct aodv_hello))
goto trunc;
ND_PRINT((ndo, "\n\text HELLO %ld ms",
(unsigned long)EXTRACT_32BITS(&ah->interval)));
break;
default:
ND_PRINT((ndo, "\n\text %u %u", ep->type, ep->length));
break;
}
return;
trunc:
ND_PRINT((ndo, " [|hello]"));
}
Commit Message: CVE-2017-13002/AODV: Add some missing bounds checks.
In aodv_extension() do a bounds check on the extension header before we
look at it.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s).
While we're at it, add the RFC number, and check the validity of the
length for the Hello extension.
CWE ID: CWE-125
|
aodv_extension(netdissect_options *ndo,
const struct aodv_ext *ep, u_int length)
{
const struct aodv_hello *ah;
ND_TCHECK(*ep);
switch (ep->type) {
case AODV_EXT_HELLO:
ah = (const struct aodv_hello *)(const void *)ep;
ND_TCHECK(*ah);
if (length < sizeof(struct aodv_hello))
goto trunc;
if (ep->length < 4) {
ND_PRINT((ndo, "\n\text HELLO - bad length %u", ep->length));
break;
}
ND_PRINT((ndo, "\n\text HELLO %ld ms",
(unsigned long)EXTRACT_32BITS(&ah->interval)));
break;
default:
ND_PRINT((ndo, "\n\text %u %u", ep->type, ep->length));
break;
}
return;
trunc:
ND_PRINT((ndo, " [|hello]"));
}
| 167,905
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: MediaRecorderHandler::~MediaRecorderHandler() {
DCHECK(main_render_thread_checker_.CalledOnValidThread());
if (client_)
client_->WriteData(
nullptr, 0u, true,
(TimeTicks::Now() - TimeTicks::UnixEpoch()).InMillisecondsF());
}
Commit Message: Check context is attached before creating MediaRecorder
Bug: 896736
Change-Id: I3ccfd2188fb15704af14c8af050e0a5667855d34
Reviewed-on: https://chromium-review.googlesource.com/c/1324231
Commit-Queue: Emircan Uysaler <emircan@chromium.org>
Reviewed-by: Miguel Casas <mcasas@chromium.org>
Cr-Commit-Position: refs/heads/master@{#606242}
CWE ID: CWE-119
|
MediaRecorderHandler::~MediaRecorderHandler() {
DCHECK(main_render_thread_checker_.CalledOnValidThread());
if (client_) {
client_->WriteData(
nullptr, 0u, true,
(TimeTicks::Now() - TimeTicks::UnixEpoch()).InMillisecondsF());
}
}
| 172,604
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 BlockEntry* Track::GetEOS() const
{
return &m_eos;
}
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 BlockEntry* Track::GetEOS() const
| 174,309
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int mem_resize(jas_stream_memobj_t *m, int bufsize)
{
unsigned char *buf;
assert(m->buf_);
assert(bufsize >= 0);
if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char)))) {
return -1;
}
m->buf_ = buf;
m->bufsize_ = bufsize;
return 0;
}
Commit Message: The memory stream interface allows for a buffer size of zero.
The case of a zero-sized buffer was not handled correctly, as it could
lead to a double free.
This problem has now been fixed (hopefully).
One might ask whether a zero-sized buffer should be allowed at all,
but this is a question for another day.
CWE ID: CWE-415
|
static int mem_resize(jas_stream_memobj_t *m, int bufsize)
{
unsigned char *buf;
//assert(m->buf_);
assert(bufsize >= 0);
if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) &&
bufsize) {
return -1;
}
m->buf_ = buf;
m->bufsize_ = bufsize;
return 0;
}
| 168,759
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) {
register const xmlChar *cmp = other;
register const xmlChar *in;
const xmlChar *ret;
GROW;
in = ctxt->input->cur;
while (*in != 0 && *in == *cmp) {
++in;
++cmp;
ctxt->input->col++;
}
if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) {
/* success */
ctxt->input->cur = in;
return (const xmlChar*) 1;
}
/* failure (or end of input buffer), check with full function */
ret = xmlParseName (ctxt);
/* strings coming from the dictionnary direct compare possible */
if (ret == other) {
return (const xmlChar*) 1;
}
return ret;
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) {
register const xmlChar *cmp = other;
register const xmlChar *in;
const xmlChar *ret;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
in = ctxt->input->cur;
while (*in != 0 && *in == *cmp) {
++in;
++cmp;
ctxt->input->col++;
}
if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) {
/* success */
ctxt->input->cur = in;
return (const xmlChar*) 1;
}
/* failure (or end of input buffer), check with full function */
ret = xmlParseName (ctxt);
/* strings coming from the dictionnary direct compare possible */
if (ret == other) {
return (const xmlChar*) 1;
}
return ret;
}
| 171,296
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool ChromeContentRendererClient::ShouldFork(WebFrame* frame,
const GURL& url,
bool is_initial_navigation,
bool* send_referrer) {
DCHECK(!frame->parent());
if (prerender_dispatcher_.get() && prerender_dispatcher_->IsPrerenderURL(url))
return true;
const ExtensionSet* extensions = extension_dispatcher_->extensions();
const Extension* new_url_extension = extensions::GetNonBookmarkAppExtension(
*extensions, ExtensionURLInfo(url));
bool is_extension_url = !!new_url_extension;
if (CrossesExtensionExtents(frame, url, *extensions, is_extension_url,
is_initial_navigation)) {
*send_referrer = true;
const Extension* extension =
extension_dispatcher_->extensions()->GetExtensionOrAppByURL(
ExtensionURLInfo(url));
if (extension && extension->is_app()) {
UMA_HISTOGRAM_ENUMERATION(
extension_misc::kAppLaunchHistogram,
extension_misc::APP_LAUNCH_CONTENT_NAVIGATION,
extension_misc::APP_LAUNCH_BUCKET_BOUNDARY);
}
return true;
}
if (frame->top()->document().url() == url) {
if (is_extension_url != extension_dispatcher_->is_extension_process())
return true;
}
if (url.SchemeIs(kChromeUIScheme))
return true;
return false;
}
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
|
bool ChromeContentRendererClient::ShouldFork(WebFrame* frame,
const GURL& url,
bool is_initial_navigation,
bool* send_referrer) {
DCHECK(!frame->parent());
if (prerender_dispatcher_.get() && prerender_dispatcher_->IsPrerenderURL(url))
return true;
const ExtensionSet* extensions = extension_dispatcher_->extensions();
const Extension* new_url_extension = extensions::GetNonBookmarkAppExtension(
*extensions, ExtensionURLInfo(url));
bool is_extension_url = !!new_url_extension;
if (CrossesExtensionExtents(frame, url, *extensions, is_extension_url,
is_initial_navigation)) {
*send_referrer = true;
const Extension* extension =
extension_dispatcher_->extensions()->GetExtensionOrAppByURL(
ExtensionURLInfo(url));
if (extension && extension->is_app()) {
UMA_HISTOGRAM_ENUMERATION(
extension_misc::kAppLaunchHistogram,
extension_misc::APP_LAUNCH_CONTENT_NAVIGATION,
extension_misc::APP_LAUNCH_BUCKET_BOUNDARY);
}
return true;
}
if (frame->top()->document().url() == url) {
if (is_extension_url != extension_dispatcher_->is_extension_process())
return true;
}
return false;
}
| 171,009
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 SADs(unsigned int *results) {
const uint8_t* refs[] = {GetReference(0), GetReference(1),
GetReference(2), GetReference(3)};
REGISTER_STATE_CHECK(GET_PARAM(2)(source_data_, source_stride_,
refs, reference_stride_,
results));
}
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 SADs(unsigned int *results) {
const uint8_t *references[] = {GetReference(0), GetReference(1),
GetReference(2), GetReference(3)};
ASM_REGISTER_STATE_CHECK(GET_PARAM(2)(source_data_, source_stride_,
references, reference_stride_,
results));
}
| 174,576
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 CanCommitURL(const GURL& url) {
SchemeMap::const_iterator judgment(scheme_policy_.find(url.scheme()));
if (judgment != scheme_policy_.end())
return judgment->second;
if (url.SchemeIs(url::kFileScheme)) {
base::FilePath path;
if (net::FileURLToFilePath(url, &path))
return ContainsKey(request_file_set_, path);
}
return false; // Unmentioned schemes are disallowed.
}
Commit Message: This patch implements a mechanism for more granular link URL permissions (filtering on scheme/host). This fixes the bug that allowed PDFs to have working links to any "chrome://" URLs.
BUG=528505,226927
Review URL: https://codereview.chromium.org/1362433002
Cr-Commit-Position: refs/heads/master@{#351705}
CWE ID: CWE-264
|
bool CanCommitURL(const GURL& url) {
// Having permission to a scheme implies permission to all of its URLs.
SchemeMap::const_iterator scheme_judgment(
scheme_policy_.find(url.scheme()));
if (scheme_judgment != scheme_policy_.end())
return scheme_judgment->second;
// Otherwise, check for permission for specific origin.
if (ContainsKey(origin_set_, url::Origin(url)))
return true;
if (url.SchemeIs(url::kFileScheme)) {
base::FilePath path;
if (net::FileURLToFilePath(url, &path))
return ContainsKey(request_file_set_, path);
}
return false; // Unmentioned schemes are disallowed.
}
| 171,775
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: image_transform_png_set_strip_alpha_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_strip_alpha(pp);
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_png_set_strip_alpha_set(PNG_CONST image_transform *this,
image_transform_png_set_strip_alpha_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_strip_alpha(pp);
this->next->set(this->next, that, pp, pi);
}
| 173,653
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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::fillBuffer(OMX::buffer_id buffer, int fenceFd) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer);
header->nFilledLen = 0;
header->nOffset = 0;
header->nFlags = 0;
status_t res = storeFenceInMeta_l(header, fenceFd, kPortIndexOutput);
if (res != OK) {
CLOG_ERROR(fillBuffer::storeFenceInMeta, res, EMPTY_BUFFER(buffer, header, fenceFd));
return res;
}
{
Mutex::Autolock _l(mDebugLock);
mOutputBuffersWithCodec.add(header);
CLOG_BUMPED_BUFFER(fillBuffer, WITH_STATS(EMPTY_BUFFER(buffer, header, fenceFd)));
}
OMX_ERRORTYPE err = OMX_FillThisBuffer(mHandle, header);
if (err != OMX_ErrorNone) {
CLOG_ERROR(fillBuffer, err, EMPTY_BUFFER(buffer, header, fenceFd));
Mutex::Autolock _l(mDebugLock);
mOutputBuffersWithCodec.remove(header);
}
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119
|
status_t OMXNodeInstance::fillBuffer(OMX::buffer_id buffer, int fenceFd) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexOutput);
if (header == NULL) {
return BAD_VALUE;
}
header->nFilledLen = 0;
header->nOffset = 0;
header->nFlags = 0;
status_t res = storeFenceInMeta_l(header, fenceFd, kPortIndexOutput);
if (res != OK) {
CLOG_ERROR(fillBuffer::storeFenceInMeta, res, EMPTY_BUFFER(buffer, header, fenceFd));
return res;
}
{
Mutex::Autolock _l(mDebugLock);
mOutputBuffersWithCodec.add(header);
CLOG_BUMPED_BUFFER(fillBuffer, WITH_STATS(EMPTY_BUFFER(buffer, header, fenceFd)));
}
OMX_ERRORTYPE err = OMX_FillThisBuffer(mHandle, header);
if (err != OMX_ErrorNone) {
CLOG_ERROR(fillBuffer, err, EMPTY_BUFFER(buffer, header, fenceFd));
Mutex::Autolock _l(mDebugLock);
mOutputBuffersWithCodec.remove(header);
}
return StatusFromOMXError(err);
}
| 173,527
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 DisconnectWindowLinux::Hide() {
NOTIMPLEMENTED();
}
Commit Message: Initial implementation of DisconnectWindow on Linux.
BUG=None
TEST=Manual
Review URL: http://codereview.chromium.org/7089016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88889 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void DisconnectWindowLinux::Hide() {
DCHECK(disconnect_window_);
gtk_widget_hide(disconnect_window_);
}
gboolean DisconnectWindowLinux::OnWindowDelete(GtkWidget* widget,
GdkEvent* event) {
// Don't allow the window to be closed.
return TRUE;
}
void DisconnectWindowLinux::OnDisconnectClicked(GtkButton* sender) {
DCHECK(host_);
host_->Shutdown();
}
| 170,473
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: scandir(const char *dir, struct dirent ***namelist,
int (*select) (const struct dirent *),
int (*compar) (const struct dirent **, const struct dirent **))
{
DIR *d = opendir(dir);
struct dirent *current;
struct dirent **names;
int count = 0;
int pos = 0;
int result = -1;
if (NULL == d)
return -1;
while (NULL != readdir(d))
count++;
names = malloc(sizeof (struct dirent *) * count);
closedir(d);
d = opendir(dir);
if (NULL == d)
return -1;
while (NULL != (current = readdir(d))) {
if (NULL == select || select(current)) {
struct dirent *copyentry = malloc(current->d_reclen);
memcpy(copyentry, current, current->d_reclen);
names[pos] = copyentry;
pos++;
}
}
result = closedir(d);
if (pos != count)
names = realloc(names, sizeof (struct dirent *) * pos);
*namelist = names;
return pos;
}
Commit Message: misc oom and possible memory leak fix
CWE ID:
|
scandir(const char *dir, struct dirent ***namelist,
int (*select) (const struct dirent *),
int (*compar) (const struct dirent **, const struct dirent **))
{
DIR *d = opendir(dir);
struct dirent *current;
struct dirent **names;
int count = 0;
int pos = 0;
int result = -1;
if (NULL == d)
return -1;
while (NULL != readdir(d))
count++;
closedir(d);
names = malloc(sizeof (struct dirent *) * count);
if (!names)
return -1;
d = opendir(dir);
if (NULL == d) {
free(names);
return -1;
}
while (NULL != (current = readdir(d))) {
if (NULL == select || select(current)) {
struct dirent *copyentry = malloc(current->d_reclen);
/* FIXME: OOM, silently skip it?*/
if (!copyentry)
continue;
memcpy(copyentry, current, current->d_reclen);
names[pos] = copyentry;
pos++;
}
}
result = closedir(d);
if (pos != count)
names = realloc(names, sizeof (struct dirent *) * pos);
*namelist = names;
return pos;
}
| 169,754
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 __init sit_init(void)
{
int err;
printk(KERN_INFO "IPv6 over IPv4 tunneling driver\n");
if (xfrm4_tunnel_register(&sit_handler, AF_INET6) < 0) {
printk(KERN_INFO "sit init: Can't add protocol\n");
return -EAGAIN;
}
err = register_pernet_device(&sit_net_ops);
if (err < 0)
xfrm4_tunnel_deregister(&sit_handler, AF_INET6);
return err;
}
Commit Message: tunnels: fix netns vs proto registration ordering
Same stuff as in ip_gre patch: receive hook can be called before netns
setup is done, oopsing in net_generic().
Signed-off-by: Alexey Dobriyan <adobriyan@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-362
|
static int __init sit_init(void)
{
int err;
printk(KERN_INFO "IPv6 over IPv4 tunneling driver\n");
err = register_pernet_device(&sit_net_ops);
if (err < 0)
return err;
err = xfrm4_tunnel_register(&sit_handler, AF_INET6);
if (err < 0) {
unregister_pernet_device(&sit_net_ops);
printk(KERN_INFO "sit init: Can't add protocol\n");
}
return err;
}
| 165,878
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 asf_read_marker(AVFormatContext *s, int64_t size)
{
AVIOContext *pb = s->pb;
ASFContext *asf = s->priv_data;
int i, count, name_len, ret;
char name[1024];
avio_rl64(pb); // reserved 16 bytes
avio_rl64(pb); // ...
count = avio_rl32(pb); // markers count
avio_rl16(pb); // reserved 2 bytes
name_len = avio_rl16(pb); // name length
for (i = 0; i < name_len; i++)
avio_r8(pb); // skip the name
for (i = 0; i < count; i++) {
int64_t pres_time;
int name_len;
avio_rl64(pb); // offset, 8 bytes
pres_time = avio_rl64(pb); // presentation time
pres_time -= asf->hdr.preroll * 10000;
avio_rl16(pb); // entry length
avio_rl32(pb); // send time
avio_rl32(pb); // flags
name_len = avio_rl32(pb); // name length
if ((ret = avio_get_str16le(pb, name_len * 2, name,
sizeof(name))) < name_len)
avio_skip(pb, name_len - ret);
avpriv_new_chapter(s, i, (AVRational) { 1, 10000000 }, pres_time,
AV_NOPTS_VALUE, name);
}
return 0;
}
Commit Message: avformat/asfdec: Fix DoS due to lack of eof check
Fixes: loop.asf
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-834
|
static int asf_read_marker(AVFormatContext *s, int64_t size)
{
AVIOContext *pb = s->pb;
ASFContext *asf = s->priv_data;
int i, count, name_len, ret;
char name[1024];
avio_rl64(pb); // reserved 16 bytes
avio_rl64(pb); // ...
count = avio_rl32(pb); // markers count
avio_rl16(pb); // reserved 2 bytes
name_len = avio_rl16(pb); // name length
avio_skip(pb, name_len);
for (i = 0; i < count; i++) {
int64_t pres_time;
int name_len;
if (avio_feof(pb))
return AVERROR_INVALIDDATA;
avio_rl64(pb); // offset, 8 bytes
pres_time = avio_rl64(pb); // presentation time
pres_time -= asf->hdr.preroll * 10000;
avio_rl16(pb); // entry length
avio_rl32(pb); // send time
avio_rl32(pb); // flags
name_len = avio_rl32(pb); // name length
if ((ret = avio_get_str16le(pb, name_len * 2, name,
sizeof(name))) < name_len)
avio_skip(pb, name_len - ret);
avpriv_new_chapter(s, i, (AVRational) { 1, 10000000 }, pres_time,
AV_NOPTS_VALUE, name);
}
return 0;
}
| 167,775
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: char *cJSON_PrintUnformatted( cJSON *item )
{
return print_value( item, 0, 0 );
}
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
|
char *cJSON_PrintUnformatted( cJSON *item )
char *cJSON_Print(cJSON *item) {return print_value(item,0,1,0);}
char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0,0);}
char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt)
{
printbuffer p;
p.buffer=(char*)cJSON_malloc(prebuffer);
p.length=prebuffer;
p.offset=0;
return print_value(item,0,fmt,&p);
}
| 167,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: SPL_METHOD(SplFileObject, fwrite)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *str;
int str_len;
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) {
return;
}
if (ZEND_NUM_ARGS() > 1) {
str_len = MAX(0, MIN(length, str_len));
}
if (!str_len) {
RETURN_LONG(0);
}
RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len));
} /* }}} */
SPL_METHOD(SplFileObject, fread)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) {
return;
}
if (length <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(length + 1);
Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
/* {{{ proto bool SplFileObject::fstat()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileObject, fwrite)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *str;
int str_len;
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) {
return;
}
if (ZEND_NUM_ARGS() > 1) {
str_len = MAX(0, MIN(length, str_len));
}
if (!str_len) {
RETURN_LONG(0);
}
RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len));
} /* }}} */
SPL_METHOD(SplFileObject, fread)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) {
return;
}
if (length <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
if (length > INT_MAX) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be no more than %d", INT_MAX);
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(length + 1);
Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
/* {{{ proto bool SplFileObject::fstat()
| 167,066
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 RemoveDuplicateLayers(Image **images,
ExceptionInfo *exception)
{
register Image
*curr,
*next;
RectangleInfo
bounds;
assert((*images) != (const Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
curr=GetFirstImageInList(*images);
for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next)
{
if ( curr->columns != next->columns || curr->rows != next->rows
|| curr->page.x != next->page.x || curr->page.y != next->page.y )
continue;
bounds=CompareImageBounds(curr,next,CompareAnyLayer,exception);
if ( bounds.x < 0 ) {
/*
the two images are the same, merge time delays and delete one.
*/
size_t time;
time = curr->delay*1000/curr->ticks_per_second;
time += next->delay*1000/next->ticks_per_second;
next->ticks_per_second = 100L;
next->delay = time*curr->ticks_per_second/1000;
next->iterations = curr->iterations;
*images = curr;
(void) DeleteImageFromList(images);
}
}
*images = GetFirstImageInList(*images);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1629
CWE ID: CWE-369
|
MagickExport void RemoveDuplicateLayers(Image **images,
MagickExport void RemoveDuplicateLayers(Image **images,ExceptionInfo *exception)
{
RectangleInfo
bounds;
register Image
*image,
*next;
assert((*images) != (const Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=GetFirstImageInList(*images);
for ( ; (next=GetNextImageInList(image)) != (Image *) NULL; image=next)
{
if ((image->columns != next->columns) || (image->rows != next->rows) ||
(image->page.x != next->page.x) || (image->page.y != next->page.y))
continue;
bounds=CompareImageBounds(image,next,CompareAnyLayer,exception);
if (bounds.x < 0)
{
/*
Two images are the same, merge time delays and delete one.
*/
size_t
time;
time=1000*image->delay*PerceptibleReciprocal(image->ticks_per_second);
time+=1000*next->delay*PerceptibleReciprocal(next->ticks_per_second);
next->ticks_per_second=100L;
next->delay=time*image->ticks_per_second/1000;
next->iterations=image->iterations;
*images=image;
(void) DeleteImageFromList(images);
}
}
*images=GetFirstImageInList(*images);
}
| 169,588
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 nick_hash_remove(CHANNEL_REC *channel, NICK_REC *nick)
{
NICK_REC *list;
list = g_hash_table_lookup(channel->nicks, nick->nick);
if (list == NULL)
return;
if (list == nick || list->next == NULL) {
g_hash_table_remove(channel->nicks, nick->nick);
if (list->next != NULL) {
g_hash_table_insert(channel->nicks, nick->next->nick,
nick->next);
}
} else {
while (list->next != nick)
list = list->next;
list->next = nick->next;
}
}
Commit Message: Merge branch 'security' into 'master'
Security
Closes #10
See merge request !17
CWE ID: CWE-416
|
static void nick_hash_remove(CHANNEL_REC *channel, NICK_REC *nick)
{
NICK_REC *list, *newlist;
list = g_hash_table_lookup(channel->nicks, nick->nick);
if (list == NULL)
return;
if (list == nick) {
newlist = nick->next;
} else {
newlist = list;
while (list->next != nick)
list = list->next;
list->next = nick->next;
}
g_hash_table_remove(channel->nicks, nick->nick);
if (newlist != NULL) {
g_hash_table_insert(channel->nicks, newlist->nick,
newlist);
}
}
| 168,057
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: NaClProcessHost::NaClProcessHost(const GURL& manifest_url, bool off_the_record)
: manifest_url_(manifest_url),
#if defined(OS_WIN)
process_launched_by_broker_(false),
#elif defined(OS_LINUX)
wait_for_nacl_gdb_(false),
#endif
reply_msg_(NULL),
#if defined(OS_WIN)
debug_exception_handler_requested_(false),
#endif
internal_(new NaClInternal()),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
enable_exception_handling_(false),
off_the_record_(off_the_record) {
process_.reset(content::BrowserChildProcessHost::Create(
content::PROCESS_TYPE_NACL_LOADER, this));
process_->SetName(net::FormatUrl(manifest_url_, std::string()));
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClExceptionHandling) ||
getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) {
enable_exception_handling_ = true;
}
enable_ipc_proxy_ = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClIPCProxy);
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
TBR=bbudge@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
NaClProcessHost::NaClProcessHost(const GURL& manifest_url, bool off_the_record)
: manifest_url_(manifest_url),
#if defined(OS_WIN)
process_launched_by_broker_(false),
#elif defined(OS_LINUX)
wait_for_nacl_gdb_(false),
#endif
reply_msg_(NULL),
#if defined(OS_WIN)
debug_exception_handler_requested_(false),
#endif
internal_(new NaClInternal()),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
enable_exception_handling_(false),
off_the_record_(off_the_record) {
process_.reset(content::BrowserChildProcessHost::Create(
content::PROCESS_TYPE_NACL_LOADER, this));
process_->SetName(net::FormatUrl(manifest_url_, std::string()));
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClExceptionHandling) ||
getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) {
enable_exception_handling_ = true;
}
}
| 170,724
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 LocalFileSystem::fileSystemNotAllowedInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
PassRefPtr<CallbackWrapper> callbacks)
{
context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR));
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
void LocalFileSystem::fileSystemNotAllowedInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
CallbackWrapper* callbacks)
{
context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR));
}
| 171,427
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 FILE *open_log_file(void)
{
if(log_fp) /* keep it open unless we rotate */
return log_fp;
log_fp = fopen(log_file, "a+");
if(log_fp == NULL) {
if (daemon_mode == FALSE) {
printf("Warning: Cannot open log file '%s' for writing\n", log_file);
}
return NULL;
}
(void)fcntl(fileno(log_fp), F_SETFD, FD_CLOEXEC);
return log_fp;
}
Commit Message: Merge branch 'maint'
CWE ID: CWE-264
|
static FILE *open_log_file(void)
{
int fh;
struct stat st;
if(log_fp) /* keep it open unless we rotate */
return log_fp;
if ((fh = open(log_file, O_RDWR|O_APPEND|O_CREAT|O_NOFOLLOW, S_IRUSR|S_IWUSR)) == -1) {
if (daemon_mode == FALSE)
printf("Warning: Cannot open log file '%s' for writing\n", log_file);
return NULL;
}
log_fp = fdopen(fh, "a+");
if(log_fp == NULL) {
if (daemon_mode == FALSE)
printf("Warning: Cannot open log file '%s' for writing\n", log_file);
return NULL;
}
if ((fstat(fh, &st)) == -1) {
log_fp = NULL;
close(fh);
if (daemon_mode == FALSE)
printf("Warning: Cannot fstat log file '%s'\n", log_file);
return NULL;
}
if (st.st_nlink != 1 || (st.st_mode & S_IFMT) != S_IFREG) {
log_fp = NULL;
close(fh);
if (daemon_mode == FALSE)
printf("Warning: log file '%s' has an invalid mode\n", log_file);
return NULL;
}
(void)fcntl(fileno(log_fp), F_SETFD, FD_CLOEXEC);
return log_fp;
}
| 166,860
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) {
LOG(WARNING) << "IBus connection is recovered.";
g_return_if_fail(user_data);
InputMethodStatusConnection* self
= static_cast<InputMethodStatusConnection*>(user_data);
self->MaybeRestoreConnections();
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
static void IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) {
void IBusBusConnected(IBusBus* bus) {
LOG(WARNING) << "IBus connection is recovered.";
MaybeRestoreConnections();
}
| 170,536
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 CoordinatorImpl::RequestGlobalMemoryDumpAndAppendToTrace(
MemoryDumpType dump_type,
MemoryDumpLevelOfDetail level_of_detail,
const RequestGlobalMemoryDumpAndAppendToTraceCallback& callback) {
auto adapter =
[](const RequestGlobalMemoryDumpAndAppendToTraceCallback& callback,
bool success, uint64_t dump_guid,
mojom::GlobalMemoryDumpPtr) { callback.Run(success, dump_guid); };
QueuedRequest::Args args(dump_type, level_of_detail, {},
true /* add_to_trace */, base::kNullProcessId);
RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback));
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <lalitm@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: oysteine <oysteine@chromium.org>
Reviewed-by: Albert J. Wong <ajwong@chromium.org>
Reviewed-by: Hector Dearman <hjd@chromium.org>
Cr-Commit-Position: refs/heads/master@{#529059}
CWE ID: CWE-269
|
void CoordinatorImpl::RequestGlobalMemoryDumpAndAppendToTrace(
MemoryDumpType dump_type,
MemoryDumpLevelOfDetail level_of_detail,
const RequestGlobalMemoryDumpAndAppendToTraceCallback& callback) {
// Don't allow arbitary processes to obtain VM regions. Only the heap profiler
// is allowed to obtain them using the special method on its own dedicated
// interface (HeapProfilingHelper).
if (level_of_detail ==
MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER) {
bindings_.ReportBadMessage(
"Requested global memory dump using level of detail reserved for the "
"heap profiler.");
return;
}
auto adapter =
[](const RequestGlobalMemoryDumpAndAppendToTraceCallback& callback,
bool success, uint64_t dump_guid,
mojom::GlobalMemoryDumpPtr) { callback.Run(success, dump_guid); };
QueuedRequest::Args args(dump_type, level_of_detail, {},
true /* add_to_trace */, base::kNullProcessId);
RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback));
}
| 172,916
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: GURL DevToolsUI::SanitizeFrontendURL(const GURL& url) {
return ::SanitizeFrontendURL(url, content::kChromeDevToolsScheme,
chrome::kChromeUIDevToolsHost, SanitizeFrontendPath(url.path()), true);
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200
|
GURL DevToolsUI::SanitizeFrontendURL(const GURL& url) {
| 172,461
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SetConstantInput(int value) {
memset(input_, value, kInputBufferSize);
}
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 SetConstantInput(int value) {
memset(input_, value, kInputBufferSize);
#if CONFIG_VP9_HIGHBITDEPTH
vpx_memset16(input16_, value, kInputBufferSize);
#endif
}
void CopyOutputToRef() {
memcpy(output_ref_, output_, kOutputBufferSize);
#if CONFIG_VP9_HIGHBITDEPTH
memcpy(output16_ref_, output16_, kOutputBufferSize);
#endif
}
| 174,504
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PixelBufferRasterWorkerPool::OnRasterTasksRequiredForActivationFinished() {
if (!should_notify_client_if_no_tasks_required_for_activation_are_pending_)
return;
CheckForCompletedRasterTasks();
}
Commit Message: cc: Simplify raster task completion notification logic
(Relanding after missing activation bug fixed in https://codereview.chromium.org/131763003/)
Previously the pixel buffer raster worker pool used a combination of
polling and explicit notifications from the raster worker pool to decide
when to tell the client about the completion of 1) all tasks or 2) the
subset of tasks required for activation. This patch simplifies the logic
by only triggering the notification based on the OnRasterTasksFinished
and OnRasterTasksRequiredForActivationFinished calls from the worker
pool.
BUG=307841,331534
Review URL: https://codereview.chromium.org/99873007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@243991 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void PixelBufferRasterWorkerPool::OnRasterTasksRequiredForActivationFinished() {
if (!should_notify_client_if_no_tasks_required_for_activation_are_pending_)
return;
raster_required_for_activation_finished_task_pending_ = false;
CheckForCompletedRasterTasks();
}
| 171,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: void CmdBufferImageTransportFactory::DestroySharedSurfaceHandle(
const gfx::GLSurfaceHandle& handle) {
if (!context_->makeContextCurrent()) {
NOTREACHED() << "Failed to make shared graphics context current";
return;
}
context_->deleteTexture(handle.parent_texture_id[0]);
context_->deleteTexture(handle.parent_texture_id[1]);
context_->finish();
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void CmdBufferImageTransportFactory::DestroySharedSurfaceHandle(
const gfx::GLSurfaceHandle& handle) {
if (!context_->makeContextCurrent()) {
NOTREACHED() << "Failed to make shared graphics context current";
return;
}
}
| 171,364
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int32 CommandBufferProxyImpl::CreateTransferBuffer(
size_t size, int32 id_request) {
if (last_state_.error != gpu::error::kNoError)
return -1;
scoped_ptr<base::SharedMemory> shm(
channel_->factory()->AllocateSharedMemory(size));
if (!shm.get())
return -1;
base::SharedMemoryHandle handle = shm->handle();
#if defined(OS_POSIX)
DCHECK(!handle.auto_close);
#endif
int32 id;
if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer(route_id_,
handle,
size,
id_request,
&id))) {
return -1;
}
return id;
}
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:
|
int32 CommandBufferProxyImpl::CreateTransferBuffer(
size_t size, int32 id_request) {
if (last_state_.error != gpu::error::kNoError)
return -1;
scoped_ptr<base::SharedMemory> shm(
channel_->factory()->AllocateSharedMemory(size));
if (!shm.get())
return -1;
base::SharedMemoryHandle handle = shm->handle();
#if defined(OS_WIN)
// Windows needs to explicitly duplicate the handle out to another process.
if (!sandbox::BrokerDuplicateHandle(handle, channel_->gpu_pid(),
&handle, FILE_MAP_WRITE, 0)) {
return -1;
}
#elif defined(OS_POSIX)
DCHECK(!handle.auto_close);
#endif
int32 id;
if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer(route_id_,
handle,
size,
id_request,
&id))) {
return -1;
}
return id;
}
| 170,926
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const
{
ParaNdis_CheckSumVerifyFlat(IpHeader,
EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum,
__FUNCTION__);
}
Commit Message: NetKVM: BZ#1169718: Checking the length only on read
Signed-off-by: Joseph Hindin <yhindin@rehat.com>
CWE ID: CWE-20
|
void CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const
{
ParaNdis_CheckSumVerifyFlat(IpHeader,
EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum, FALSE,
__FUNCTION__);
}
| 170,140
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ZEND_API void zend_ts_hash_graceful_destroy(TsHashTable *ht)
{
begin_write(ht);
zend_hash_graceful_destroy(TS_HASH(ht));
end_write(ht);
#ifdef ZTS
tsrm_mutex_free(ht->mx_reader);
tsrm_mutex_free(ht->mx_reader);
#endif
}
Commit Message:
CWE ID:
|
ZEND_API void zend_ts_hash_graceful_destroy(TsHashTable *ht)
{
begin_write(ht);
zend_hash_graceful_destroy(TS_HASH(ht));
end_write(ht);
#ifdef ZTS
tsrm_mutex_free(ht->mx_reader);
tsrm_mutex_free(ht->mx_writer);
#endif
}
| 164,883
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
tTcpIpPacketParsingResult res = _res;
ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader);
res.xxpStatus = ppresXxpIncomplete;
res.TcpUdp = ppresIsUDP;
res.XxpIpHeaderSize = udpDataStart;
if (len >= udpDataStart)
{
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
USHORT datagramLength = swap_short(pUdpHeader->udp_length);
res.xxpStatus = ppresXxpKnown;
DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength));
}
return res;
}
Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet
Signed-off-by: Joseph Hindin <yhindin@rehat.com>
CWE ID: CWE-20
|
ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
tTcpIpPacketParsingResult res = _res;
ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader);
res.TcpUdp = ppresIsUDP;
res.XxpIpHeaderSize = udpDataStart;
if (len >= udpDataStart)
{
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
USHORT datagramLength = swap_short(pUdpHeader->udp_length);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength));
}
else
{
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
}
| 168,890
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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_increment_val (MyObject *obj, GError **error)
{
obj->val++;
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_increment_val (MyObject *obj, GError **error)
| 165,108
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: BrowserContextImpl::~BrowserContextImpl() {
CHECK(!otr_context_);
}
Commit Message:
CWE ID: CWE-20
|
BrowserContextImpl::~BrowserContextImpl() {
| 165,417
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 AXLayoutObject::elementAttributeValue(
const QualifiedName& attributeName) const {
if (!m_layoutObject)
return false;
return equalIgnoringCase(getAttribute(attributeName), "true");
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
bool AXLayoutObject::elementAttributeValue(
const QualifiedName& attributeName) const {
if (!m_layoutObject)
return false;
return equalIgnoringASCIICase(getAttribute(attributeName), "true");
}
| 171,904
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: struct bpf_map *bpf_map_get_with_uref(u32 ufd)
{
struct fd f = fdget(ufd);
struct bpf_map *map;
map = __bpf_map_get(f);
if (IS_ERR(map))
return map;
bpf_map_inc(map, true);
fdput(f);
return map;
}
Commit Message: bpf: fix refcnt overflow
On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,
the malicious application may overflow 32-bit bpf program refcnt.
It's also possible to overflow map refcnt on 1Tb system.
Impose 32k hard limit which means that the same bpf program or
map cannot be shared by more than 32k processes.
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Reported-by: Jann Horn <jannh@google.com>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Acked-by: Daniel Borkmann <daniel@iogearbox.net>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID:
|
struct bpf_map *bpf_map_get_with_uref(u32 ufd)
{
struct fd f = fdget(ufd);
struct bpf_map *map;
map = __bpf_map_get(f);
if (IS_ERR(map))
return map;
map = bpf_map_inc(map, true);
fdput(f);
return map;
}
| 167,252
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: Metadata* EntrySync::getMetadata(ExceptionState& exceptionState)
{
RefPtr<MetadataSyncCallbackHelper> helper = MetadataSyncCallbackHelper::create();
m_fileSystem->getMetadata(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return helper->getResult(exceptionState);
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
Metadata* EntrySync::getMetadata(ExceptionState& exceptionState)
{
MetadataSyncCallbackHelper* helper = MetadataSyncCallbackHelper::create();
m_fileSystem->getMetadata(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return helper->getResult(exceptionState);
}
| 171,421
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
int chan = sa->rc_channel;
int err = 0;
BT_DBG("sk %p %pMR", sk, &sa->rc_bdaddr);
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
write_lock(&rfcomm_sk_list.lock);
if (chan && __rfcomm_get_listen_sock_by_addr(chan, &sa->rc_bdaddr)) {
err = -EADDRINUSE;
} else {
/* Save source address */
bacpy(&rfcomm_pi(sk)->src, &sa->rc_bdaddr);
rfcomm_pi(sk)->channel = chan;
sk->sk_state = BT_BOUND;
}
write_unlock(&rfcomm_sk_list.lock);
done:
release_sock(sk);
return err;
}
Commit Message: Bluetooth: Fix potential NULL dereference in RFCOMM bind callback
addr can be NULL and it should not be dereferenced before NULL checking.
Signed-off-by: Jaganath Kanakkassery <jaganath.k@samsung.com>
Signed-off-by: Marcel Holtmann <marcel@holtmann.org>
CWE ID: CWE-476
|
static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_rc sa;
struct sock *sk = sock->sk;
int len, err = 0;
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
memset(&sa, 0, sizeof(sa));
len = min_t(unsigned int, sizeof(sa), addr_len);
memcpy(&sa, addr, len);
BT_DBG("sk %p %pMR", sk, &sa.rc_bdaddr);
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
write_lock(&rfcomm_sk_list.lock);
if (sa.rc_channel &&
__rfcomm_get_listen_sock_by_addr(sa.rc_channel, &sa.rc_bdaddr)) {
err = -EADDRINUSE;
} else {
/* Save source address */
bacpy(&rfcomm_pi(sk)->src, &sa.rc_bdaddr);
rfcomm_pi(sk)->channel = sa.rc_channel;
sk->sk_state = BT_BOUND;
}
write_unlock(&rfcomm_sk_list.lock);
done:
release_sock(sk);
return err;
}
| 167,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: header_put_le_short (SF_PRIVATE *psf, int x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 2)
{ psf->header [psf->headindex++] = x ;
psf->header [psf->headindex++] = (x >> 8) ;
} ;
} /* header_put_le_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_le_short (SF_PRIVATE *psf, int x)
{ psf->header.ptr [psf->header.indx++] = x ;
psf->header.ptr [psf->header.indx++] = (x >> 8) ;
} /* header_put_le_short */
| 170,058
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 BaseMultipleFieldsDateAndTimeInputType::createShadowSubtree()
{
ASSERT(element()->shadow());
Document* document = element()->document();
ContainerNode* container = element()->userAgentShadowRoot();
RefPtr<DateTimeEditElement> dateTimeEditElement(DateTimeEditElement::create(document, *this));
m_dateTimeEditElement = dateTimeEditElement.get();
container->appendChild(m_dateTimeEditElement);
updateInnerTextValue();
RefPtr<ClearButtonElement> clearButton = ClearButtonElement::create(document, *this);
m_clearButton = clearButton.get();
container->appendChild(clearButton);
RefPtr<SpinButtonElement> spinButton = SpinButtonElement::create(document, *this);
m_spinButtonElement = spinButton.get();
container->appendChild(spinButton);
bool shouldAddPickerIndicator = false;
if (InputType::themeSupportsDataListUI(this))
shouldAddPickerIndicator = true;
RefPtr<RenderTheme> theme = document->page() ? document->page()->theme() : RenderTheme::defaultTheme();
if (theme->supportsCalendarPicker(formControlType())) {
shouldAddPickerIndicator = true;
m_pickerIndicatorIsAlwaysVisible = true;
}
if (shouldAddPickerIndicator) {
RefPtr<PickerIndicatorElement> pickerElement = PickerIndicatorElement::create(document, *this);
m_pickerIndicatorElement = pickerElement.get();
container->appendChild(m_pickerIndicatorElement);
m_pickerIndicatorIsVisible = true;
updatePickerIndicatorVisibility();
}
}
Commit Message: Setting input.x-webkit-speech should not cause focus change
In r150866, we introduced element()->focus() in destroyShadowSubtree()
to retain focus on <input> when its type attribute gets changed.
But when x-webkit-speech attribute is changed, the element is detached
before calling destroyShadowSubtree() and element()->focus() failed
This patch moves detach() after destroyShadowSubtree() to fix the
problem.
BUG=243818
TEST=fast/forms/input-type-change-focusout.html
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/16084005
git-svn-id: svn://svn.chromium.org/blink/trunk@151444 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
|
void BaseMultipleFieldsDateAndTimeInputType::createShadowSubtree()
{
ASSERT(element()->shadow());
// Element must not be attached here, because if it was attached
// DateTimeEditElement::customStyleForRenderer() is called in appendChild()
// before the field wrapper element is created.
ASSERT(!element()->attached());
Document* document = element()->document();
ContainerNode* container = element()->userAgentShadowRoot();
RefPtr<DateTimeEditElement> dateTimeEditElement(DateTimeEditElement::create(document, *this));
m_dateTimeEditElement = dateTimeEditElement.get();
container->appendChild(m_dateTimeEditElement);
updateInnerTextValue();
RefPtr<ClearButtonElement> clearButton = ClearButtonElement::create(document, *this);
m_clearButton = clearButton.get();
container->appendChild(clearButton);
RefPtr<SpinButtonElement> spinButton = SpinButtonElement::create(document, *this);
m_spinButtonElement = spinButton.get();
container->appendChild(spinButton);
bool shouldAddPickerIndicator = false;
if (InputType::themeSupportsDataListUI(this))
shouldAddPickerIndicator = true;
RefPtr<RenderTheme> theme = document->page() ? document->page()->theme() : RenderTheme::defaultTheme();
if (theme->supportsCalendarPicker(formControlType())) {
shouldAddPickerIndicator = true;
m_pickerIndicatorIsAlwaysVisible = true;
}
if (shouldAddPickerIndicator) {
RefPtr<PickerIndicatorElement> pickerElement = PickerIndicatorElement::create(document, *this);
m_pickerIndicatorElement = pickerElement.get();
container->appendChild(m_pickerIndicatorElement);
m_pickerIndicatorIsVisible = true;
updatePickerIndicatorVisibility();
}
}
| 171,264
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PPB_URLLoader_Impl::LastPluginRefWasDeleted(bool instance_destroyed) {
Resource::LastPluginRefWasDeleted(instance_destroyed);
if (instance_destroyed) {
loader_.reset();
}
}
Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed,
BUG=85808
Review URL: http://codereview.chromium.org/7196001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void PPB_URLLoader_Impl::LastPluginRefWasDeleted(bool instance_destroyed) {
void PPB_URLLoader_Impl::ClearInstance() {
Resource::ClearInstance();
loader_.reset();
}
| 170,411
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void queue_delete(struct snd_seq_queue *q)
{
/* stop and release the timer */
snd_seq_timer_stop(q->timer);
snd_seq_timer_close(q);
/* wait until access free */
snd_use_lock_sync(&q->use_lock);
/* release resources... */
snd_seq_prioq_delete(&q->tickq);
snd_seq_prioq_delete(&q->timeq);
snd_seq_timer_delete(&q->timer);
kfree(q);
}
Commit Message: ALSA: seq: Fix race at timer setup and close
ALSA sequencer code has an open race between the timer setup ioctl and
the close of the client. This was triggered by syzkaller fuzzer, and
a use-after-free was caught there as a result.
This patch papers over it by adding a proper queue->timer_mutex lock
around the timer-related calls in the relevant code path.
Reported-by: Dmitry Vyukov <dvyukov@google.com>
Tested-by: Dmitry Vyukov <dvyukov@google.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
CWE ID: CWE-362
|
static void queue_delete(struct snd_seq_queue *q)
{
/* stop and release the timer */
mutex_lock(&q->timer_mutex);
snd_seq_timer_stop(q->timer);
snd_seq_timer_close(q);
mutex_unlock(&q->timer_mutex);
/* wait until access free */
snd_use_lock_sync(&q->use_lock);
/* release resources... */
snd_seq_prioq_delete(&q->tickq);
snd_seq_prioq_delete(&q->timeq);
snd_seq_timer_delete(&q->timer);
kfree(q);
}
| 167,409
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 detect_allow_debuggers(int argc, char **argv) {
int i;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "--allow-debuggers") == 0) {
arg_allow_debuggers = 1;
break;
}
if (strcmp(argv[i], "--") == 0)
break;
if (strncmp(argv[i], "--", 2) != 0)
break;
}
}
Commit Message: security fix
CWE ID:
|
static void detect_allow_debuggers(int argc, char **argv) {
int i;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "--allow-debuggers") == 0) {
// check kernel version
struct utsname u;
int rv = uname(&u);
if (rv != 0)
errExit("uname");
int major;
int minor;
if (2 != sscanf(u.release, "%d.%d", &major, &minor)) {
fprintf(stderr, "Error: cannot extract Linux kernel version: %s\n", u.version);
exit(1);
}
if (major < 4 || (major == 4 && minor < 8)) {
fprintf(stderr, "Error: --allow-debuggers is disabled on Linux kernels prior to 4.8. "
"A bug in ptrace call allows a full bypass of the seccomp filter. "
"Your current kernel version is %d.%d.\n", major, minor);
exit(1);
}
arg_allow_debuggers = 1;
break;
}
if (strcmp(argv[i], "--") == 0)
break;
if (strncmp(argv[i], "--", 2) != 0)
break;
}
}
| 168,419
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 *gdImageJpegPtr (gdImagePtr im, int *size, int quality)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
gdImageJpegCtx (im, out, quality);
rv = gdDPExtractData (out, size);
out->gd_free (out);
return rv;
}
Commit Message: Sync with upstream
Even though libgd/libgd#492 is not a relevant bug fix for PHP, since
the binding doesn't use the `gdImage*Ptr()` functions at all, we're
porting the fix to stay in sync here.
CWE ID: CWE-415
|
void *gdImageJpegPtr (gdImagePtr im, int *size, int quality)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
if (!_gdImageJpegCtx(im, out, quality)) {
rv = gdDPExtractData(out, size);
} else {
rv = NULL;
}
out->gd_free (out);
return rv;
}
| 169,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: void UnacceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas,
const cc::PaintFlags& flags,
const FloatRect& dst_rect,
const FloatRect& src_rect,
RespectImageOrientationEnum,
ImageClampingMode clamp_mode,
ImageDecodingMode) {
StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect, clamp_mode,
PaintImageForCurrentFrame());
}
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 UnacceleratedStaticBitmapImage::Draw(cc::PaintCanvas* canvas,
const cc::PaintFlags& flags,
const FloatRect& dst_rect,
const FloatRect& src_rect,
RespectImageOrientationEnum,
ImageClampingMode clamp_mode,
ImageDecodingMode) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
StaticBitmapImage::DrawHelper(canvas, flags, dst_rect, src_rect, clamp_mode,
PaintImageForCurrentFrame());
}
| 172,600
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 SSLManager::OnSSLCertificateError(
base::WeakPtr<SSLErrorHandler::Delegate> delegate,
const content::GlobalRequestID& id,
const ResourceType::Type resource_type,
const GURL& url,
int render_process_id,
int render_view_id,
const net::SSLInfo& ssl_info,
bool fatal) {
DCHECK(delegate);
DVLOG(1) << "OnSSLCertificateError() cert_error: "
<< net::MapCertStatusToNetError(ssl_info.cert_status)
<< " id: " << id.child_id << "," << id.request_id
<< " resource_type: " << resource_type
<< " url: " << url.spec()
<< " render_process_id: " << render_process_id
<< " render_view_id: " << render_view_id
<< " cert_status: " << std::hex << ssl_info.cert_status;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&SSLCertErrorHandler::Dispatch,
new SSLCertErrorHandler(delegate,
id,
resource_type,
url,
render_process_id,
render_view_id,
ssl_info,
fatal)));
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void SSLManager::OnSSLCertificateError(
const base::WeakPtr<SSLErrorHandler::Delegate>& delegate,
const content::GlobalRequestID& id,
const ResourceType::Type resource_type,
const GURL& url,
int render_process_id,
int render_view_id,
const net::SSLInfo& ssl_info,
bool fatal) {
DCHECK(delegate);
DVLOG(1) << "OnSSLCertificateError() cert_error: "
<< net::MapCertStatusToNetError(ssl_info.cert_status)
<< " id: " << id.child_id << "," << id.request_id
<< " resource_type: " << resource_type
<< " url: " << url.spec()
<< " render_process_id: " << render_process_id
<< " render_view_id: " << render_view_id
<< " cert_status: " << std::hex << ssl_info.cert_status;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&SSLCertErrorHandler::Dispatch,
new SSLCertErrorHandler(delegate,
id,
resource_type,
url,
render_process_id,
render_view_id,
ssl_info,
fatal)));
}
| 170,996
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 DiscardTest(DiscardReason reason) {
const base::TimeTicks kDummyLastActiveTime =
base::TimeTicks() + kShortDelay;
LifecycleUnit* background_lifecycle_unit = nullptr;
LifecycleUnit* foreground_lifecycle_unit = nullptr;
CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit,
&foreground_lifecycle_unit);
content::WebContents* initial_web_contents =
tab_strip_model_->GetWebContentsAt(0);
content::WebContentsTester::For(initial_web_contents)
->SetLastActiveTime(kDummyLastActiveTime);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true));
background_lifecycle_unit->Discard(reason);
testing::Mock::VerifyAndClear(&tab_observer_);
TransitionFromPendingDiscardToDiscardedIfNeeded(reason,
background_lifecycle_unit);
EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0));
EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
EXPECT_EQ(kDummyLastActiveTime,
tab_strip_model_->GetWebContentsAt(0)->GetLastActiveTime());
source_->SetFocusedTabStripModelForTesting(nullptr);
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org>
Reviewed-by: François Doray <fdoray@chromium.org>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID:
|
void DiscardTest(DiscardReason reason) {
const base::TimeTicks kDummyLastActiveTime =
base::TimeTicks() + kShortDelay;
LifecycleUnit* background_lifecycle_unit = nullptr;
LifecycleUnit* foreground_lifecycle_unit = nullptr;
CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit,
&foreground_lifecycle_unit);
content::WebContents* initial_web_contents =
tab_strip_model_->GetWebContentsAt(0);
content::WebContentsTester::For(initial_web_contents)
->SetLastActiveTime(kDummyLastActiveTime);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true));
background_lifecycle_unit->Discard(reason);
::testing::Mock::VerifyAndClear(&tab_observer_);
TransitionFromPendingDiscardToDiscardedIfNeeded(reason,
background_lifecycle_unit);
EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0));
EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
EXPECT_EQ(kDummyLastActiveTime,
tab_strip_model_->GetWebContentsAt(0)->GetLastActiveTime());
source_->SetFocusedTabStripModelForTesting(nullptr);
}
| 172,226
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: receive_carbon(void **state)
{
prof_input("/carbons on");
prof_connect();
assert_true(stbbr_received(
"<iq id='*' type='set'><enable xmlns='urn:xmpp:carbons:2'/></iq>"
));
stbbr_send(
"<presence to='stabber@localhost' from='buddy1@localhost/mobile'>"
"<priority>10</priority>"
"<status>On my mobile</status>"
"</presence>"
);
assert_true(prof_output_exact("Buddy1 (mobile) is online, \"On my mobile\""));
prof_input("/msg Buddy1");
assert_true(prof_output_exact("unencrypted"));
stbbr_send(
"<message type='chat' to='stabber@localhost/profanity' from='buddy1@localhost'>"
"<received xmlns='urn:xmpp:carbons:2'>"
"<forwarded xmlns='urn:xmpp:forward:0'>"
"<message id='prof_msg_7' xmlns='jabber:client' type='chat' lang='en' to='stabber@localhost/profanity' from='buddy1@localhost/mobile'>"
"<body>test carbon from recipient</body>"
"</message>"
"</forwarded>"
"</received>"
"</message>"
);
assert_true(prof_output_regex("Buddy1/mobile: .+test carbon from recipient"));
}
Commit Message: Add carbons from check
CWE ID: CWE-346
|
receive_carbon(void **state)
{
prof_input("/carbons on");
prof_connect();
assert_true(stbbr_received(
"<iq id='*' type='set'><enable xmlns='urn:xmpp:carbons:2'/></iq>"
));
stbbr_send(
"<presence to='stabber@localhost' from='buddy1@localhost/mobile'>"
"<priority>10</priority>"
"<status>On my mobile</status>"
"</presence>"
);
assert_true(prof_output_exact("Buddy1 (mobile) is online, \"On my mobile\""));
prof_input("/msg Buddy1");
assert_true(prof_output_exact("unencrypted"));
stbbr_send(
"<message type='chat' to='stabber@localhost/profanity' from='stabber@localhost'>"
"<received xmlns='urn:xmpp:carbons:2'>"
"<forwarded xmlns='urn:xmpp:forward:0'>"
"<message id='prof_msg_7' xmlns='jabber:client' type='chat' lang='en' to='stabber@localhost/profanity' from='buddy1@localhost/mobile'>"
"<body>test carbon from recipient</body>"
"</message>"
"</forwarded>"
"</received>"
"</message>"
);
assert_true(prof_output_regex("Buddy1/mobile: .+test carbon from recipient"));
}
| 168,383
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
{
jpc_pchg_t *pchg;
int *prclyrno;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
assert(pi->prcno < pi->pirlvl->numprcs);
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
if (pi->lyrno >= *prclyrno) {
*prclyrno = pi->lyrno;
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
return 1;
}
Commit Message: Fixed numerous integer overflow problems in the code for packet iterators
in the JPC decoder.
CWE ID: CWE-125
|
static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
{
jpc_pchg_t *pchg;
int *prclyrno;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
assert(pi->prcno < pi->pirlvl->numprcs);
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls &&
pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) {
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno <
JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno,
++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
if (pi->lyrno >= *prclyrno) {
*prclyrno = pi->lyrno;
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
return 1;
}
| 169,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: long long Chapters::Atom::GetStartTimecode() const
{
return m_start_timecode;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long Chapters::Atom::GetStartTimecode() const
| 174,356
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SPL_METHOD(SplFileInfo, getFilename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
int path_len;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC);
if (path_len && path_len < intern->file_name_len) {
RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1);
} else {
RETURN_STRINGL(intern->file_name, intern->file_name_len, 1);
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileInfo, getFilename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
int path_len;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC);
if (path_len && path_len < intern->file_name_len) {
RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1);
} else {
RETURN_STRINGL(intern->file_name, intern->file_name_len, 1);
}
}
| 167,032
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 BaseMultipleFieldsDateAndTimeInputType::didFocusOnControl()
{
element()->setFocus(true);
}
Commit Message: Fix reentrance of BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree.
destroyShadowSubtree could dispatch 'blur' event unexpectedly because
element()->focused() had incorrect information. We make sure it has
correct information by checking if the UA shadow root contains the
focused element.
BUG=257353
Review URL: https://chromiumcodereview.appspot.com/19067004
git-svn-id: svn://svn.chromium.org/blink/trunk@154086 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
|
void BaseMultipleFieldsDateAndTimeInputType::didFocusOnControl()
{
if (!containsFocusedShadowElement())
return;
element()->setFocus(true);
}
| 171,212
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: P2PQuicStreamImpl* P2PQuicTransportImpl::CreateStreamInternal(
quic::QuicStreamId id) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(crypto_stream_);
DCHECK(IsEncryptionEstablished());
DCHECK(!IsClosed());
return new P2PQuicStreamImpl(id, this);
}
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
|
P2PQuicStreamImpl* P2PQuicTransportImpl::CreateStreamInternal(
quic::QuicStreamId id) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(crypto_stream_);
DCHECK(IsEncryptionEstablished());
DCHECK(!IsClosed());
return new P2PQuicStreamImpl(id, this, stream_write_buffer_size_);
}
| 172,265
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 CrosMock::SetSpeechSynthesisLibraryExpectations() {
InSequence s;
EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking())
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking())
.Times(AnyNumber())
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking())
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false))
.RetiresOnSaturation();
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void CrosMock::SetSpeechSynthesisLibraryExpectations() {
InSequence s;
EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking())
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, SetSpeakProperties(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking())
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking())
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, SetSpeakProperties(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false))
.RetiresOnSaturation();
}
| 170,372
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 BlobURLRegistry::unregisterURL(const KURL& url)
{
ThreadableBlobRegistry::unregisterBlobURL(url);
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
void BlobURLRegistry::unregisterURL(const KURL& url)
{
BlobRegistry::unregisterBlobURL(url);
}
| 170,678
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 OnGetDevicesOnServiceThread(
const std::vector<UsbDeviceFilter>& filters,
const base::Callback<void(mojo::Array<DeviceInfoPtr>)>& callback,
scoped_refptr<base::TaskRunner> callback_task_runner,
const std::vector<scoped_refptr<UsbDevice>>& devices) {
mojo::Array<DeviceInfoPtr> mojo_devices(0);
for (size_t i = 0; i < devices.size(); ++i) {
if (UsbDeviceFilter::MatchesAny(devices[i], filters))
mojo_devices.push_back(DeviceInfo::From(*devices[i]));
}
callback_task_runner->PostTask(
FROM_HERE, base::Bind(callback, base::Passed(&mojo_devices)));
}
Commit Message: Connect WebUSB client interface to the devices app
This provides a basic WebUSB client interface in
content/renderer. Most of the interface is unimplemented,
but this CL hooks up navigator.usb.getDevices() to the
browser's Mojo devices app to enumerate available USB
devices.
BUG=492204
Review URL: https://codereview.chromium.org/1293253002
Cr-Commit-Position: refs/heads/master@{#344881}
CWE ID: CWE-399
|
void OnGetDevicesOnServiceThread(
const std::vector<UsbDeviceFilter>& filters,
const base::Callback<void(mojo::Array<DeviceInfoPtr>)>& callback,
scoped_refptr<base::TaskRunner> callback_task_runner,
const std::vector<scoped_refptr<UsbDevice>>& devices) {
mojo::Array<DeviceInfoPtr> mojo_devices(0);
for (size_t i = 0; i < devices.size(); ++i) {
if (UsbDeviceFilter::MatchesAny(devices[i], filters) || filters.empty())
mojo_devices.push_back(DeviceInfo::From(*devices[i]));
}
callback_task_runner->PostTask(
FROM_HERE, base::Bind(callback, base::Passed(&mojo_devices)));
}
| 171,698
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: image_transform_png_set_scale_16_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_scale_16(pp);
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_png_set_scale_16_set(PNG_CONST image_transform *this,
image_transform_png_set_scale_16_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_scale_16(pp);
# if PNG_LIBPNG_VER < 10700
/* libpng will limit the gamma table size: */
that->max_gamma_8 = PNG_MAX_GAMMA_8;
# endif
this->next->set(this->next, that, pp, pi);
}
| 173,647
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 get_scl(void)
{
return qrio_get_gpio(DEBLOCK_PORT1, DEBLOCK_SCL1);
}
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 get_scl(void)
| 169,629
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BrowserContextDestroyer::DestroyContext(BrowserContext* context) {
CHECK(context->IsOffTheRecord() || !context->HasOffTheRecordContext());
content::BrowserContext::NotifyWillBeDestroyed(context);
std::set<content::RenderProcessHost*> hosts;
for (content::RenderProcessHost::iterator it =
content::RenderProcessHost::AllHostsIterator();
!it.IsAtEnd(); it.Advance()) {
content::RenderProcessHost* host = it.GetCurrentValue();
if (host->GetBrowserContext() != context) {
continue;
}
hosts.insert(host);
//// static
}
if (hosts.empty()) {
delete context;
} else {
new BrowserContextDestroyer(context, hosts);
}
}
Commit Message:
CWE ID: CWE-20
|
void BrowserContextDestroyer::DestroyContext(BrowserContext* context) {
void BrowserContextDestroyer::Shutdown() {
auto destroy_all_unused_contexts = []() {
auto it = g_contexts_pending_deletion.Get().begin();
while (it != g_contexts_pending_deletion.Get().end()) {
BrowserContextDestroyer* destroyer = *it;
++it;
if (!destroyer->finish_destroy_scheduled_) {
continue;
}
destroyer->FinishDestroyContext();
// |destroyer| is invalid now
}
};
// We make 2 passes over the list because the first pass can destroy an
// incognito BrowserContext that subsequently schedules its owner context for
// deletion
destroy_all_unused_contexts();
destroy_all_unused_contexts();
}
//// static
void BrowserContextDestroyer::RenderProcessHostAssignedToSiteInstance(
content::RenderProcessHost* host) {
BrowserContextDestroyer* destroyer = GetForContext(host->GetBrowserContext());
if (!destroyer) {
return;
}
CHECK(!destroyer->finish_destroy_scheduled_);
if (destroyer->pending_host_ids_.find(host->GetID()) !=
destroyer->pending_host_ids_.end()) {
return;
}
destroyer->ObserveHost(host);
}
| 165,419
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void HostCache::clear() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
RecordEraseAll(ERASE_CLEAR, base::TimeTicks::Now());
entries_.clear();
}
Commit Message: Add PersistenceDelegate to HostCache
PersistenceDelegate is a new interface for persisting the contents of
the HostCache. This commit includes the interface itself, the logic in
HostCache for interacting with it, and a mock implementation of the
interface for testing. It does not include support for immediate data
removal since that won't be needed for the currently planned use case.
BUG=605149
Review-Url: https://codereview.chromium.org/2943143002
Cr-Commit-Position: refs/heads/master@{#481015}
CWE ID:
|
void HostCache::clear() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
RecordEraseAll(ERASE_CLEAR, base::TimeTicks::Now());
// Don't bother scheduling a write if there's nothing to clear.
if (size() == 0)
return;
entries_.clear();
if (delegate_)
delegate_->ScheduleWrite();
}
| 172,010
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: init_copy(mrb_state *mrb, mrb_value dest, mrb_value obj)
{
switch (mrb_type(obj)) {
case MRB_TT_CLASS:
case MRB_TT_MODULE:
copy_class(mrb, dest, obj);
mrb_iv_copy(mrb, dest, obj);
mrb_iv_remove(mrb, dest, mrb_intern_lit(mrb, "__classname__"));
break;
case MRB_TT_OBJECT:
case MRB_TT_SCLASS:
case MRB_TT_HASH:
case MRB_TT_DATA:
case MRB_TT_EXCEPTION:
mrb_iv_copy(mrb, dest, obj);
break;
case MRB_TT_ISTRUCT:
mrb_istruct_copy(dest, obj);
break;
default:
break;
}
mrb_funcall(mrb, dest, "initialize_copy", 1, obj);
}
Commit Message: Should not call `initialize_copy` for `TT_ICLASS`; fix #4027
Since `TT_ICLASS` is a internal object that should never be revealed
to Ruby world.
CWE ID: CWE-824
|
init_copy(mrb_state *mrb, mrb_value dest, mrb_value obj)
{
switch (mrb_type(obj)) {
case MRB_TT_ICLASS:
copy_class(mrb, dest, obj);
return;
case MRB_TT_CLASS:
case MRB_TT_MODULE:
copy_class(mrb, dest, obj);
mrb_iv_copy(mrb, dest, obj);
mrb_iv_remove(mrb, dest, mrb_intern_lit(mrb, "__classname__"));
break;
case MRB_TT_OBJECT:
case MRB_TT_SCLASS:
case MRB_TT_HASH:
case MRB_TT_DATA:
case MRB_TT_EXCEPTION:
mrb_iv_copy(mrb, dest, obj);
break;
case MRB_TT_ISTRUCT:
mrb_istruct_copy(dest, obj);
break;
default:
break;
}
mrb_funcall(mrb, dest, "initialize_copy", 1, obj);
}
| 169,206
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: virtual void Predict(MB_PREDICTION_MODE mode) {
mbptr_->mode_info_context->mbmi.mode = mode;
REGISTER_STATE_CHECK(pred_fn_(mbptr_,
data_ptr_[0] - kStride,
data_ptr_[0] - 1, kStride,
data_ptr_[0], kStride));
}
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
|
virtual void Predict(MB_PREDICTION_MODE mode) {
mbptr_->mode_info_context->mbmi.mode = mode;
ASM_REGISTER_STATE_CHECK(pred_fn_(mbptr_,
data_ptr_[0] - kStride,
data_ptr_[0] - 1, kStride,
data_ptr_[0], kStride));
}
| 174,566
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->locationWithException());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHrefThrows(cppValue);
}
Commit Message: document.location bindings fix
BUG=352374
R=jochen@chromium.org
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
|
static void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithException());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHrefThrows(cppValue);
}
| 171,688
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kSegCountOffset = 6;
const size_t kEndCountOffset = 14;
const size_t kHeaderSize = 16;
const size_t kSegmentSize = 8; // total size of array elements for one segment
if (kEndCountOffset > size) {
return false;
}
size_t segCount = readU16(data, kSegCountOffset) >> 1;
if (kHeaderSize + segCount * kSegmentSize > size) {
return false;
}
for (size_t i = 0; i < segCount; i++) {
int end = readU16(data, kEndCountOffset + 2 * i);
int start = readU16(data, kHeaderSize + 2 * (segCount + i));
int rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i));
if (rangeOffset == 0) {
int delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i));
if (((end + delta) & 0xffff) > end - start) {
addRange(coverage, start, end + 1);
} else {
for (int j = start; j < end + 1; j++) {
if (((j + delta) & 0xffff) != 0) {
addRange(coverage, j, j + 1);
}
}
}
} else {
for (int j = start; j < end + 1; j++) {
uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset +
(i + j - start) * 2;
if (actualRangeOffset + 2 > size) {
return false;
}
int glyphId = readU16(data, actualRangeOffset);
if (glyphId != 0) {
addRange(coverage, j, j + 1);
}
}
}
}
return true;
}
Commit Message: Reject fonts with invalid ranges in cmap
A corrupt or malicious font may have a negative size in its cmap
range, which in turn could lead to memory corruption. This patch
detects the case and rejects the font, and also includes an assertion
in the sparse bit set implementation if we missed any such case.
External issue:
https://code.google.com/p/android/issues/detail?id=192618
Bug: 26413177
Change-Id: Icc0c80e4ef389abba0964495b89aa0fae3e9f4b2
CWE ID: CWE-20
|
static bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kSegCountOffset = 6;
const size_t kEndCountOffset = 14;
const size_t kHeaderSize = 16;
const size_t kSegmentSize = 8; // total size of array elements for one segment
if (kEndCountOffset > size) {
return false;
}
size_t segCount = readU16(data, kSegCountOffset) >> 1;
if (kHeaderSize + segCount * kSegmentSize > size) {
return false;
}
for (size_t i = 0; i < segCount; i++) {
uint32_t end = readU16(data, kEndCountOffset + 2 * i);
uint32_t start = readU16(data, kHeaderSize + 2 * (segCount + i));
if (end < start) {
// invalid segment range: size must be positive
return false;
}
uint32_t rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i));
if (rangeOffset == 0) {
uint32_t delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i));
if (((end + delta) & 0xffff) > end - start) {
addRange(coverage, start, end + 1);
} else {
for (uint32_t j = start; j < end + 1; j++) {
if (((j + delta) & 0xffff) != 0) {
addRange(coverage, j, j + 1);
}
}
}
} else {
for (uint32_t j = start; j < end + 1; j++) {
uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset +
(i + j - start) * 2;
if (actualRangeOffset + 2 > size) {
return false;
}
uint32_t glyphId = readU16(data, actualRangeOffset);
if (glyphId != 0) {
addRange(coverage, j, j + 1);
}
}
}
}
return true;
}
| 174,235
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 Chapters::Display* Chapters::Atom::GetDisplay(int index) const
{
if (index < 0)
return NULL;
if (index >= m_displays_count)
return NULL;
return m_displays + index;
}
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 Chapters::Display* Chapters::Atom::GetDisplay(int index) const
| 174,304
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: image_transform_png_set_@_add(image_transform *this,
PNG_CONST image_transform **that, char *name, size_t sizeof_name,
size_t *pos, png_byte colour_type, png_byte bit_depth)
{
this->next = *that;
*that = this;
*pos = safecat(name, sizeof_name, *pos, " +@");
return 1;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_png_set_@_add(image_transform *this,
| 173,600
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: seamless_process(STREAM s)
{
unsigned int pkglen;
char *buf;
pkglen = s->end - s->p;
/* str_handle_lines requires null terminated strings */
buf = xmalloc(pkglen + 1);
STRNCPY(buf, (char *) s->p, pkglen + 1);
str_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL);
xfree(buf);
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119
|
seamless_process(STREAM s)
{
unsigned int pkglen;
char *buf;
struct stream packet = *s;
if (!s_check(s))
{
rdp_protocol_error("seamless_process(), stream is in unstable state", &packet);
}
pkglen = s->end - s->p;
/* str_handle_lines requires null terminated strings */
buf = xmalloc(pkglen + 1);
STRNCPY(buf, (char *) s->p, pkglen + 1);
str_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL);
xfree(buf);
}
| 169,808
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: OMX_ERRORTYPE SimpleSoftOMXComponent::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamPortDefinition:
{
OMX_PARAM_PORTDEFINITIONTYPE *defParams =
(OMX_PARAM_PORTDEFINITIONTYPE *)params;
if (defParams->nPortIndex >= mPorts.size()) {
return OMX_ErrorBadPortIndex;
}
if (defParams->nSize != sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) {
return OMX_ErrorUnsupportedSetting;
}
PortInfo *port =
&mPorts.editItemAt(defParams->nPortIndex);
if (defParams->nBufferSize > port->mDef.nBufferSize) {
port->mDef.nBufferSize = defParams->nBufferSize;
}
if (defParams->nBufferCountActual < port->mDef.nBufferCountMin) {
ALOGW("component requires at least %u buffers (%u requested)",
port->mDef.nBufferCountMin, defParams->nBufferCountActual);
return OMX_ErrorUnsupportedSetting;
}
port->mDef.nBufferCountActual = defParams->nBufferCountActual;
return OMX_ErrorNone;
}
default:
return OMX_ErrorUnsupportedIndex;
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SimpleSoftOMXComponent::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamPortDefinition:
{
OMX_PARAM_PORTDEFINITIONTYPE *defParams =
(OMX_PARAM_PORTDEFINITIONTYPE *)params;
if (!isValidOMXParam(defParams)) {
return OMX_ErrorBadParameter;
}
if (defParams->nPortIndex >= mPorts.size()) {
return OMX_ErrorBadPortIndex;
}
if (defParams->nSize != sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) {
return OMX_ErrorUnsupportedSetting;
}
PortInfo *port =
&mPorts.editItemAt(defParams->nPortIndex);
if (defParams->nBufferSize > port->mDef.nBufferSize) {
port->mDef.nBufferSize = defParams->nBufferSize;
}
if (defParams->nBufferCountActual < port->mDef.nBufferCountMin) {
ALOGW("component requires at least %u buffers (%u requested)",
port->mDef.nBufferCountMin, defParams->nBufferCountActual);
return OMX_ErrorUnsupportedSetting;
}
port->mDef.nBufferCountActual = defParams->nBufferCountActual;
return OMX_ErrorNone;
}
default:
return OMX_ErrorUnsupportedIndex;
}
}
| 174,223
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
Handle<JSObject> object,
Handle<Object> value,
uint32_t start_from, uint32_t length) {
DCHECK(JSObject::PrototypeHasNoElements(isolate, *object));
Handle<Map> original_map = handle(object->map(), isolate);
Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()),
isolate);
for (uint32_t k = start_from; k < length; ++k) {
uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k,
ALL_PROPERTIES);
if (entry == kMaxUInt32) {
continue;
}
Handle<Object> element_k =
Subclass::GetImpl(isolate, *parameter_map, entry);
if (element_k->IsAccessorPair()) {
LookupIterator it(isolate, object, k, LookupIterator::OWN);
DCHECK(it.IsFound());
DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k,
Object::GetPropertyWithAccessor(&it),
Nothing<int64_t>());
if (value->StrictEquals(*element_k)) {
return Just<int64_t>(k);
}
if (object->map() != *original_map) {
return IndexOfValueSlowPath(isolate, object, value, k + 1, length);
}
} else if (value->StrictEquals(*element_k)) {
return Just<int64_t>(k);
}
}
return Just<int64_t>(-1);
}
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704
|
static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
Handle<JSObject> object,
Handle<Object> value,
uint32_t start_from, uint32_t length) {
DCHECK(JSObject::PrototypeHasNoElements(isolate, *object));
Handle<Map> original_map(object->map(), isolate);
Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()),
isolate);
for (uint32_t k = start_from; k < length; ++k) {
DCHECK_EQ(object->map(), *original_map);
uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k,
ALL_PROPERTIES);
if (entry == kMaxUInt32) {
continue;
}
Handle<Object> element_k =
Subclass::GetImpl(isolate, *parameter_map, entry);
if (element_k->IsAccessorPair()) {
LookupIterator it(isolate, object, k, LookupIterator::OWN);
DCHECK(it.IsFound());
DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k,
Object::GetPropertyWithAccessor(&it),
Nothing<int64_t>());
if (value->StrictEquals(*element_k)) {
return Just<int64_t>(k);
}
if (object->map() != *original_map) {
return IndexOfValueSlowPath(isolate, object, value, k + 1, length);
}
} else if (value->StrictEquals(*element_k)) {
return Just<int64_t>(k);
}
}
return Just<int64_t>(-1);
}
| 174,099
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 Document::open()
{
ASSERT(!importLoader());
if (m_frame) {
if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
if (parser->isParsing()) {
if (parser->isExecutingScript())
return;
if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
return;
}
}
if (m_frame->loader().provisionalDocumentLoader())
m_frame->loader().stopAllLoaders();
}
removeAllEventListenersRecursively();
implicitOpen(ForceSynchronousParsing);
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->setWasCreatedByScript(true);
if (m_frame)
m_frame->loader().didExplicitOpen();
if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
m_loadEventProgress = LoadEventNotRun;
}
Commit Message: Don't change Document load progress in any page dismissal events.
This can confuse the logic for blocking modal dialogs.
BUG=536652
Review URL: https://codereview.chromium.org/1373113002
Cr-Commit-Position: refs/heads/master@{#351419}
CWE ID: CWE-20
|
void Document::open()
{
ASSERT(!importLoader());
if (m_frame) {
if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
if (parser->isParsing()) {
if (parser->isExecutingScript())
return;
if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
return;
}
}
if (m_frame->loader().provisionalDocumentLoader())
m_frame->loader().stopAllLoaders();
}
removeAllEventListenersRecursively();
implicitOpen(ForceSynchronousParsing);
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->setWasCreatedByScript(true);
if (m_frame)
m_frame->loader().didExplicitOpen();
if (m_loadEventProgress != LoadEventInProgress && pageDismissalEventBeingDispatched() == NoDismissal)
m_loadEventProgress = LoadEventNotRun;
}
| 171,783
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 BlockEntry* Segment::GetBlock(
const CuePoint& cp,
const CuePoint::TrackPosition& tp)
{
Cluster** const ii = m_clusters;
Cluster** i = ii;
const long count = m_clusterCount + m_clusterPreloadCount;
Cluster** const jj = ii + count;
Cluster** j = jj;
while (i < j)
{
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pCluster = *k;
assert(pCluster);
const long long pos = pCluster->GetPosition();
assert(pos >= 0);
if (pos < tp.m_pos)
i = k + 1;
else if (pos > tp.m_pos)
j = k;
else
return pCluster->GetEntry(cp, tp);
}
assert(i == j);
Cluster* const pCluster = Cluster::Create(this, -1, tp.m_pos); //, -1);
assert(pCluster);
const ptrdiff_t idx = i - m_clusters;
PreloadCluster(pCluster, idx);
assert(m_clusters);
assert(m_clusterPreloadCount > 0);
assert(m_clusters[idx] == pCluster);
return pCluster->GetEntry(cp, tp);
}
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 BlockEntry* Segment::GetBlock(
const long count = m_clusterCount + m_clusterPreloadCount;
Cluster** const jj = ii + count;
Cluster** j = jj;
while (i < j) {
// INVARIANT:
//[ii, i) < pTP->m_pos
//[i, j) ?
//[j, jj) > pTP->m_pos
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pCluster = *k;
assert(pCluster);
// const long long pos_ = pCluster->m_pos;
// assert(pos_);
// const long long pos = pos_ * ((pos_ < 0) ? -1 : 1);
const long long pos = pCluster->GetPosition();
assert(pos >= 0);
if (pos < tp.m_pos)
i = k + 1;
else if (pos > tp.m_pos)
j = k;
else
return pCluster->GetEntry(cp, tp);
}
assert(i == j);
// assert(Cluster::HasBlockEntries(this, tp.m_pos));
Cluster* const pCluster = Cluster::Create(this, -1, tp.m_pos); //, -1);
assert(pCluster);
const ptrdiff_t idx = i - m_clusters;
PreloadCluster(pCluster, idx);
assert(m_clusters);
assert(m_clusterPreloadCount > 0);
assert(m_clusters[idx] == pCluster);
return pCluster->GetEntry(cp, tp);
}
| 174,288
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 ResetState() {
nav_handle1_.reset();
nav_handle2_.reset();
nav_handle3_.reset();
throttle1_.reset();
throttle2_.reset();
throttle3_.reset();
contents1_.reset();
contents2_.reset();
contents3_.reset();
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org>
Reviewed-by: François Doray <fdoray@chromium.org>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID:
|
void ResetState() {
nav_handle1_.reset();
nav_handle2_.reset();
nav_handle3_.reset();
throttle1_.reset();
throttle2_.reset();
throttle3_.reset();
// ChromeTestHarnessWithLocalDB::TearDown() deletes the
contents1_.reset();
contents2_.reset();
contents3_.reset();
}
| 172,231
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof TSRMLS_DC)
{
char *ksep, *vsep, *val;
size_t klen, vlen;
/* FIXME: string-size_t */
unsigned int new_vlen;
if (var->ptr >= var->end) {
return 0;
}
vsep = memchr(var->ptr, '&', var->end - var->ptr);
if (!vsep) {
if (!eof) {
return 0;
} else {
vsep = var->end;
}
}
ksep = memchr(var->ptr, '=', vsep - var->ptr);
if (ksep) {
*ksep = '\0';
/* "foo=bar&" or "foo=&" */
klen = ksep - var->ptr;
vlen = vsep - ++ksep;
} else {
ksep = "";
/* "foo&" */
klen = vsep - var->ptr;
vlen = 0;
}
php_url_decode(var->ptr, klen);
val = estrndup(ksep, vlen);
if (vlen) {
vlen = php_url_decode(val, vlen);
}
if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen TSRMLS_CC)) {
php_register_variable_safe(var->ptr, val, new_vlen, arr TSRMLS_CC);
}
efree(val);
var->ptr = vsep + (vsep != var->end);
return 1;
}
Commit Message: Fix bug #73807
CWE ID: CWE-400
|
static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof TSRMLS_DC)
{
char *start, *ksep, *vsep, *val;
size_t klen, vlen;
/* FIXME: string-size_t */
unsigned int new_vlen;
if (var->ptr >= var->end) {
return 0;
}
start = var->ptr + var->already_scanned;
vsep = memchr(start, '&', var->end - start);
if (!vsep) {
if (!eof) {
var->already_scanned = var->end - var->ptr;
return 0;
} else {
vsep = var->end;
}
}
ksep = memchr(var->ptr, '=', vsep - var->ptr);
if (ksep) {
*ksep = '\0';
/* "foo=bar&" or "foo=&" */
klen = ksep - var->ptr;
vlen = vsep - ++ksep;
} else {
ksep = "";
/* "foo&" */
klen = vsep - var->ptr;
vlen = 0;
}
php_url_decode(var->ptr, klen);
val = estrndup(ksep, vlen);
if (vlen) {
vlen = php_url_decode(val, vlen);
}
if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen TSRMLS_CC)) {
php_register_variable_safe(var->ptr, val, new_vlen, arr TSRMLS_CC);
}
efree(val);
var->ptr = vsep + (vsep != var->end);
var->already_scanned = 0;
return 1;
}
| 168,054
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 ExtensionTtsController::Stop() {
if (current_utterance_ && !current_utterance_->extension_id().empty()) {
current_utterance_->profile()->GetExtensionEventRouter()->
DispatchEventToExtension(
current_utterance_->extension_id(),
events::kOnStop,
"[]",
current_utterance_->profile(),
GURL());
} else {
GetPlatformImpl()->clear_error();
GetPlatformImpl()->StopSpeaking();
}
if (current_utterance_)
current_utterance_->set_error(kSpeechInterruptedError);
FinishCurrentUtterance();
ClearUtteranceQueue();
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void ExtensionTtsController::Stop() {
double volume = 1.0;
if (options->HasKey(constants::kVolumeKey)) {
EXTENSION_FUNCTION_VALIDATE(
options->GetDouble(constants::kVolumeKey, &volume));
if (volume < 0.0 || volume > 1.0) {
error_ = constants::kErrorInvalidVolume;
return false;
}
}
| 170,391
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void WebRuntimeFeatures::enableSpeechSynthesis(bool enable)
{
RuntimeEnabledFeatures::setSpeechSynthesisEnabled(enable);
}
Commit Message: Remove SpeechSynthesis runtime flag (status=stable)
BUG=402536
Review URL: https://codereview.chromium.org/482273005
git-svn-id: svn://svn.chromium.org/blink/trunk@180763 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-94
|
void WebRuntimeFeatures::enableSpeechSynthesis(bool enable)
| 171,458
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static size_t StringSize(const uint8_t *start, uint8_t encoding) {
//// return includes terminator; if unterminated, returns > limit
if (encoding == 0x00 || encoding == 0x03) {
return strlen((const char *)start) + 1;
}
size_t n = 0;
while (start[n] != '\0' || start[n + 1] != '\0') {
n += 2;
}
return n + 2;
}
Commit Message: DO NOT MERGE: defensive parsing of mp3 album art information
several points in stagefrights mp3 album art code
used strlen() to parse user-supplied strings that may be
unterminated, resulting in reading beyond the end of a buffer.
This changes the code to use strnlen() for 8-bit encodings and
strengthens the parsing of 16-bit encodings similarly. It also
reworks how we watch for the end-of-buffer to avoid all over-reads.
Bug: 32377688
Test: crafted mp3's w/ good/bad cover art. See what showed in play music
Change-Id: Ia9f526d71b21ef6a61acacf616b573753cd21df6
(cherry picked from commit fa0806b594e98f1aed3ebcfc6a801b4c0056f9eb)
CWE ID: CWE-200
|
static size_t StringSize(const uint8_t *start, uint8_t encoding) {
//// return includes terminator; if unterminated, returns > limit
static size_t StringSize(const uint8_t *start, size_t limit, uint8_t encoding) {
if (encoding == 0x00 || encoding == 0x03) {
return strnlen((const char *)start, limit) + 1;
}
size_t n = 0;
while ((n+1 < limit) && (start[n] != '\0' || start[n + 1] != '\0')) {
n += 2;
}
n += 2;
return n;
}
| 174,061
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 AddInputMethodNames(const GList* engines, InputMethodDescriptors* out) {
DCHECK(out);
for (; engines; engines = g_list_next(engines)) {
IBusEngineDesc* engine_desc = IBUS_ENGINE_DESC(engines->data);
const gchar* name = ibus_engine_desc_get_name(engine_desc);
const gchar* longname = ibus_engine_desc_get_longname(engine_desc);
const gchar* layout = ibus_engine_desc_get_layout(engine_desc);
const gchar* language = ibus_engine_desc_get_language(engine_desc);
if (InputMethodIdIsWhitelisted(name)) {
out->push_back(CreateInputMethodDescriptor(name,
longname,
layout,
language));
DLOG(INFO) << name << " (preloaded)";
}
}
}
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 AddInputMethodNames(const GList* engines, InputMethodDescriptors* out) {
DCHECK(out);
for (; engines; engines = g_list_next(engines)) {
IBusEngineDesc* engine_desc = IBUS_ENGINE_DESC(engines->data);
const gchar* name = ibus_engine_desc_get_name(engine_desc);
const gchar* longname = ibus_engine_desc_get_longname(engine_desc);
const gchar* layout = ibus_engine_desc_get_layout(engine_desc);
const gchar* language = ibus_engine_desc_get_language(engine_desc);
if (InputMethodIdIsWhitelisted(name)) {
out->push_back(CreateInputMethodDescriptor(name,
longname,
layout,
language));
VLOG(1) << name << " (preloaded)";
}
}
}
| 170,517
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RunCoeffCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 5000;
DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < kNumCoeffs; ++j)
input_block[j] = rnd.Rand8() - rnd.Rand8();
fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_);
REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j)
EXPECT_EQ(output_block[j], output_ref_block[j]);
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
void RunCoeffCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 5000;
DECLARE_ALIGNED(16, int16_t, input_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]);
for (int i = 0; i < count_test_block; ++i) {
// Initialize a test block with input range [-mask_, mask_].
for (int j = 0; j < kNumCoeffs; ++j)
input_block[j] = (rnd.Rand16() & mask_) - (rnd.Rand16() & mask_);
fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_);
ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j)
EXPECT_EQ(output_block[j], output_ref_block[j]);
}
}
| 174,548
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: MagickExport int LocaleUppercase(const int c)
{
if (c < 0)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
}
Commit Message: ...
CWE ID: CWE-125
|
MagickExport int LocaleUppercase(const int c)
{
if (c == EOF)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
}
| 170,236
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PageCaptureCustomBindings::PageCaptureCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("CreateBlob",
base::Bind(&PageCaptureCustomBindings::CreateBlob,
base::Unretained(this)));
RouteFunction("SendResponseAck",
base::Bind(&PageCaptureCustomBindings::SendResponseAck,
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:
|
PageCaptureCustomBindings::PageCaptureCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("CreateBlob", "pageCapture",
base::Bind(&PageCaptureCustomBindings::CreateBlob,
base::Unretained(this)));
RouteFunction("SendResponseAck", "pageCapture",
base::Bind(&PageCaptureCustomBindings::SendResponseAck,
base::Unretained(this)));
}
| 173,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: SProcXFixesChangeSaveSet(ClientPtr client)
{
REQUEST(xXFixesChangeSaveSetReq);
swaps(&stuff->length);
swapl(&stuff->window);
}
Commit Message:
CWE ID: CWE-20
|
SProcXFixesChangeSaveSet(ClientPtr client)
{
REQUEST(xXFixesChangeSaveSetReq);
REQUEST_SIZE_MATCH(xXFixesChangeSaveSetReq);
swaps(&stuff->length);
swapl(&stuff->window);
}
| 165,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: std::wstring GetSwitchValueFromCommandLine(const std::wstring& command_line,
const std::wstring& switch_name) {
assert(!command_line.empty());
assert(!switch_name.empty());
std::vector<std::wstring> as_array = TokenizeCommandLineToArray(command_line);
std::wstring switch_with_equal = L"--" + switch_name + L"=";
for (size_t i = 1; i < as_array.size(); ++i) {
const std::wstring& arg = as_array[i];
if (arg.compare(0, switch_with_equal.size(), switch_with_equal) == 0)
return arg.substr(switch_with_equal.size());
}
return std::wstring();
}
Commit Message: Ignore switches following "--" when parsing a command line.
BUG=933004
R=wfh@chromium.org
Change-Id: I911be4cbfc38a4d41dec85d85f7fe0f50ddca392
Reviewed-on: https://chromium-review.googlesource.com/c/1481210
Auto-Submit: Greg Thompson <grt@chromium.org>
Commit-Queue: Julian Pastarmov <pastarmovj@chromium.org>
Reviewed-by: Julian Pastarmov <pastarmovj@chromium.org>
Cr-Commit-Position: refs/heads/master@{#634604}
CWE ID: CWE-77
|
std::wstring GetSwitchValueFromCommandLine(const std::wstring& command_line,
const std::wstring& switch_name) {
static constexpr wchar_t kSwitchTerminator[] = L"--";
assert(!command_line.empty());
assert(!switch_name.empty());
std::vector<std::wstring> as_array = TokenizeCommandLineToArray(command_line);
std::wstring switch_with_equal = L"--" + switch_name + L"=";
auto end = std::find(as_array.cbegin(), as_array.cend(), kSwitchTerminator);
for (auto scan = as_array.cbegin(); scan != end; ++scan) {
const std::wstring& arg = *scan;
if (arg.compare(0, switch_with_equal.size(), switch_with_equal) == 0)
return arg.substr(switch_with_equal.size());
}
return std::wstring();
}
| 173,062
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static char* cJSON_strdup( const char* str )
{
size_t len;
char* copy;
len = strlen( str ) + 1;
if ( ! ( copy = (char*) cJSON_malloc( len ) ) )
return 0;
memcpy( copy, str, len );
return copy;
}
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 char* cJSON_strdup( const char* str )
void cJSON_InitHooks(cJSON_Hooks* hooks)
{
if (!hooks) { /* Reset hooks */
cJSON_malloc = malloc;
cJSON_free = free;
return;
}
cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc;
cJSON_free = (hooks->free_fn)?hooks->free_fn:free;
}
| 167,298
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: UWORD32 ihevcd_cabac_decode_bypass_bins_egk(cab_ctxt_t *ps_cabac,
bitstrm_t *ps_bitstrm,
WORD32 k)
{
UWORD32 u4_sym;
WORD32 numones;
WORD32 bin;
/* Sanity checks */
ASSERT((k >= 0));
numones = k;
bin = 1;
u4_sym = 0;
while(bin)
{
IHEVCD_CABAC_DECODE_BYPASS_BIN(bin, ps_cabac, ps_bitstrm);
u4_sym += bin << numones++;
}
numones -= 1;
numones = CLIP3(numones, 0, 16);
if(numones)
{
UWORD32 u4_suffix;
IHEVCD_CABAC_DECODE_BYPASS_BINS(u4_suffix, ps_cabac, ps_bitstrm, numones);
u4_sym += u4_suffix;
}
return (u4_sym);
}
Commit Message: Fix in handling wrong cu_qp_delta
cu_qp_delta is now checked for the range as specified in the spec
Bug: 33966031
Change-Id: I00420bf68081af92e9f2be9af7ce58d0683094ca
CWE ID: CWE-119
|
UWORD32 ihevcd_cabac_decode_bypass_bins_egk(cab_ctxt_t *ps_cabac,
bitstrm_t *ps_bitstrm,
WORD32 k)
{
UWORD32 u4_sym;
WORD32 numones;
WORD32 bin;
/* Sanity checks */
ASSERT((k >= 0));
numones = k;
bin = 1;
u4_sym = 0;
while(bin && (numones <= 16))
{
IHEVCD_CABAC_DECODE_BYPASS_BIN(bin, ps_cabac, ps_bitstrm);
u4_sym += bin << numones++;
}
numones -= 1;
if(numones)
{
UWORD32 u4_suffix;
IHEVCD_CABAC_DECODE_BYPASS_BINS(u4_suffix, ps_cabac, ps_bitstrm, numones);
u4_sym += u4_suffix;
}
return (u4_sym);
}
| 174,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: atol8(const char *p, size_t char_cnt)
{
int64_t l;
int digit;
l = 0;
while (char_cnt-- > 0) {
if (*p >= '0' && *p <= '7')
digit = *p - '0';
else
break;
p++;
l <<= 3;
l |= digit;
}
return (l);
}
Commit Message: Do something sensible for empty strings to make fuzzers happy.
CWE ID: CWE-125
|
atol8(const char *p, size_t char_cnt)
{
int64_t l;
int digit;
if (char_cnt == 0)
return (0);
l = 0;
while (char_cnt-- > 0) {
if (*p >= '0' && *p <= '7')
digit = *p - '0';
else
break;
p++;
l <<= 3;
l |= digit;
}
return (l);
}
| 167,768
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 DoCheckFakeData(uint8* audio_data, size_t length) {
Type* output = reinterpret_cast<Type*>(audio_data);
for (size_t i = 0; i < length; i++) {
EXPECT_TRUE(algorithm_.is_muted() || output[i] != 0);
}
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void DoCheckFakeData(uint8* audio_data, size_t length) {
if (algorithm_.is_muted())
ASSERT_EQ(sum, 0);
else
ASSERT_NE(sum, 0);
}
| 171,531
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void CrosLibrary::TestApi::SetSpeechSynthesisLibrary(
SpeechSynthesisLibrary* library, bool own) {
library_->speech_synthesis_lib_.SetImpl(library, own);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
void CrosLibrary::TestApi::SetSpeechSynthesisLibrary(
| 170,645
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 ext3_fsblk_t get_sb_block(void **data, struct super_block *sb)
{
ext3_fsblk_t sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
/*todo: use simple_strtoll with >32bit ext3 */
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
ext3_msg(sb, "error: invalid sb specification: %s",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
}
Commit Message: ext3: Fix format string issues
ext3_msg() takes the printk prefix as the second parameter and the
format string as the third parameter. Two callers of ext3_msg omit the
prefix and pass the format string as the second parameter and the first
parameter to the format string as the third parameter. In both cases
this string comes from an arbitrary source. Which means the string may
contain format string characters, which will
lead to undefined and potentially harmful behavior.
The issue was introduced in commit 4cf46b67eb("ext3: Unify log messages
in ext3") and is fixed by this patch.
CC: stable@vger.kernel.org
Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Signed-off-by: Jan Kara <jack@suse.cz>
CWE ID: CWE-20
|
static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb)
{
ext3_fsblk_t sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
/*todo: use simple_strtoll with >32bit ext3 */
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
ext3_msg(sb, KERN_ERR, "error: invalid sb specification: %s",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
}
| 166,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: DataReductionProxyIOData::DataReductionProxyIOData(
Client client,
PrefService* prefs,
network::NetworkConnectionTracker* network_connection_tracker,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
bool enabled,
const std::string& user_agent,
const std::string& channel)
: client_(client),
network_connection_tracker_(network_connection_tracker),
io_task_runner_(io_task_runner),
ui_task_runner_(ui_task_runner),
enabled_(enabled),
channel_(channel),
effective_connection_type_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) {
DCHECK(io_task_runner_);
DCHECK(ui_task_runner_);
configurator_.reset(new DataReductionProxyConfigurator());
configurator_->SetConfigUpdatedCallback(base::BindRepeating(
&DataReductionProxyIOData::OnProxyConfigUpdated, base::Unretained(this)));
DataReductionProxyMutableConfigValues* raw_mutable_config = nullptr;
std::unique_ptr<DataReductionProxyMutableConfigValues> mutable_config =
std::make_unique<DataReductionProxyMutableConfigValues>();
raw_mutable_config = mutable_config.get();
config_.reset(new DataReductionProxyConfig(
io_task_runner, ui_task_runner, network_connection_tracker_,
std::move(mutable_config), configurator_.get()));
request_options_.reset(
new DataReductionProxyRequestOptions(client_, config_.get()));
request_options_->Init();
request_options_->SetUpdateHeaderCallback(base::BindRepeating(
&DataReductionProxyIOData::UpdateProxyRequestHeaders,
base::Unretained(this)));
config_client_.reset(new DataReductionProxyConfigServiceClient(
GetBackoffPolicy(), request_options_.get(), raw_mutable_config,
config_.get(), this, network_connection_tracker_,
base::BindRepeating(&DataReductionProxyIOData::StoreSerializedConfig,
base::Unretained(this))));
network_properties_manager_.reset(new NetworkPropertiesManager(
base::DefaultClock::GetInstance(), prefs, ui_task_runner_));
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <tbansal@chromium.org>
Reviewed-by: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416
|
DataReductionProxyIOData::DataReductionProxyIOData(
Client client,
PrefService* prefs,
network::NetworkConnectionTracker* network_connection_tracker,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
bool enabled,
const std::string& user_agent,
const std::string& channel)
: client_(client),
network_connection_tracker_(network_connection_tracker),
io_task_runner_(io_task_runner),
ui_task_runner_(ui_task_runner),
enabled_(enabled),
channel_(channel),
effective_connection_type_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) {
DCHECK(io_task_runner_);
DCHECK(ui_task_runner_);
configurator_.reset(new DataReductionProxyConfigurator());
configurator_->SetConfigUpdatedCallback(base::BindRepeating(
&DataReductionProxyIOData::OnProxyConfigUpdated, base::Unretained(this)));
DataReductionProxyMutableConfigValues* raw_mutable_config = nullptr;
std::unique_ptr<DataReductionProxyMutableConfigValues> mutable_config =
std::make_unique<DataReductionProxyMutableConfigValues>();
raw_mutable_config = mutable_config.get();
config_.reset(new DataReductionProxyConfig(
io_task_runner, ui_task_runner, network_connection_tracker_,
std::move(mutable_config), configurator_.get()));
request_options_.reset(
new DataReductionProxyRequestOptions(client_, config_.get()));
request_options_->Init();
request_options_->SetUpdateHeaderCallback(base::BindRepeating(
&DataReductionProxyIOData::UpdateProxyRequestHeaders,
base::Unretained(this)));
if (!params::IsIncludedInHoldbackFieldTrial()) {
config_client_.reset(new DataReductionProxyConfigServiceClient(
GetBackoffPolicy(), request_options_.get(), raw_mutable_config,
config_.get(), this, network_connection_tracker_,
base::BindRepeating(&DataReductionProxyIOData::StoreSerializedConfig,
base::Unretained(this))));
}
network_properties_manager_.reset(new NetworkPropertiesManager(
base::DefaultClock::GetInstance(), prefs, ui_task_runner_));
}
| 172,421
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int rtnl_fill_link_ifmap(struct sk_buff *skb, struct net_device *dev)
{
struct rtnl_link_ifmap map = {
.mem_start = dev->mem_start,
.mem_end = dev->mem_end,
.base_addr = dev->base_addr,
.irq = dev->irq,
.dma = dev->dma,
.port = dev->if_port,
};
if (nla_put(skb, IFLA_MAP, sizeof(map), &map))
return -EMSGSIZE;
return 0;
}
Commit Message: net: fix infoleak in rtnetlink
The stack object “map” has a total size of 32 bytes. Its last 4
bytes are padding generated by compiler. These padding bytes are
not initialized and sent out via “nla_put”.
Signed-off-by: Kangjie Lu <kjlu@gatech.edu>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
|
static int rtnl_fill_link_ifmap(struct sk_buff *skb, struct net_device *dev)
{
struct rtnl_link_ifmap map;
memset(&map, 0, sizeof(map));
map.mem_start = dev->mem_start;
map.mem_end = dev->mem_end;
map.base_addr = dev->base_addr;
map.irq = dev->irq;
map.dma = dev->dma;
map.port = dev->if_port;
if (nla_put(skb, IFLA_MAP, sizeof(map), &map))
return -EMSGSIZE;
return 0;
}
| 167,257
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: long long CuePoint::GetTime(const Segment* pSegment) const
{
assert(pSegment);
assert(m_timecode >= 0);
const SegmentInfo* const pInfo = pSegment->GetInfo();
assert(pInfo);
const long long scale = pInfo->GetTimeCodeScale();
assert(scale >= 1);
const long long time = scale * m_timecode;
return time;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long CuePoint::GetTime(const Segment* pSegment) const
| 174,364
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 CastConfigDelegateChromeos::StopCasting(const std::string& activity_id) {
ExecuteJavaScript("backgroundSetup.stopCastMirroring('user-stop');");
}
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 CastConfigDelegateChromeos::StopCasting(const std::string& activity_id) {
void CastConfigDelegateChromeos::StopCasting() {
ExecuteJavaScript("backgroundSetup.stopCastMirroring('user-stop');");
// TODO(jdufault): Remove this after stopCastMirroring is properly exported.
// The current beta/release versions of the cast extension do not export
// stopCastMirroring, so we will also try to call the minified version.
// See crbug.com/489929.
ExecuteJavaScript("backgroundSetup.Qu('user-stop');");
}
| 171,627
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static struct dst_entry *ip6_sk_dst_check(struct sock *sk,
struct dst_entry *dst,
const struct flowi6 *fl6)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct rt6_info *rt = (struct rt6_info *)dst;
if (!dst)
goto out;
/* Yes, checking route validity in not connected
* case is not very simple. Take into account,
* that we do not support routing by source, TOS,
* and MSG_DONTROUTE --ANK (980726)
*
* 1. ip6_rt_check(): If route was host route,
* check that cached destination is current.
* If it is network route, we still may
* check its validity using saved pointer
* to the last used address: daddr_cache.
* We do not want to save whole address now,
* (because main consumer of this service
* is tcp, which has not this problem),
* so that the last trick works only on connected
* sockets.
* 2. oif also should be the same.
*/
if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) ||
#ifdef CONFIG_IPV6_SUBTREES
ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) ||
#endif
(fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) {
dst_release(dst);
dst = NULL;
}
out:
return dst;
}
Commit Message: ipv6: ip6_sk_dst_check() must not assume ipv6 dst
It's possible to use AF_INET6 sockets and to connect to an IPv4
destination. After this, socket dst cache is a pointer to a rtable,
not rt6_info.
ip6_sk_dst_check() should check the socket dst cache is IPv6, or else
various corruptions/crashes can happen.
Dave Jones can reproduce immediate crash with
trinity -q -l off -n -c sendmsg -c connect
With help from Hannes Frederic Sowa
Reported-by: Dave Jones <davej@redhat.com>
Reported-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
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-20
|
static struct dst_entry *ip6_sk_dst_check(struct sock *sk,
struct dst_entry *dst,
const struct flowi6 *fl6)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct rt6_info *rt;
if (!dst)
goto out;
if (dst->ops->family != AF_INET6) {
dst_release(dst);
return NULL;
}
rt = (struct rt6_info *)dst;
/* Yes, checking route validity in not connected
* case is not very simple. Take into account,
* that we do not support routing by source, TOS,
* and MSG_DONTROUTE --ANK (980726)
*
* 1. ip6_rt_check(): If route was host route,
* check that cached destination is current.
* If it is network route, we still may
* check its validity using saved pointer
* to the last used address: daddr_cache.
* We do not want to save whole address now,
* (because main consumer of this service
* is tcp, which has not this problem),
* so that the last trick works only on connected
* sockets.
* 2. oif also should be the same.
*/
if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) ||
#ifdef CONFIG_IPV6_SUBTREES
ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) ||
#endif
(fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) {
dst_release(dst);
dst = NULL;
}
out:
return dst;
}
| 166,076
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PHP_FUNCTION(mcrypt_list_algorithms)
{
char **modules;
char *lib_dir = MCG(algorithms_dir);
int lib_dir_len;
int i, count;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s",
&lib_dir, &lib_dir_len) == FAILURE) {
return;
}
array_init(return_value);
modules = mcrypt_list_algorithms(lib_dir, &count);
if (count == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "No algorithms found in module dir");
}
for (i = 0; i < count; i++) {
add_index_string(return_value, i, modules[i], 1);
}
mcrypt_free_p(modules, count);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
|
PHP_FUNCTION(mcrypt_list_algorithms)
{
char **modules;
char *lib_dir = MCG(algorithms_dir);
int lib_dir_len;
int i, count;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s",
&lib_dir, &lib_dir_len) == FAILURE) {
return;
}
array_init(return_value);
modules = mcrypt_list_algorithms(lib_dir, &count);
if (count == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "No algorithms found in module dir");
}
for (i = 0; i < count; i++) {
add_index_string(return_value, i, modules[i], 1);
}
mcrypt_free_p(modules, count);
}
| 167,102
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 DebuggerAttachFunction::RunAsync() {
scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitAgentHost())
return false;
if (!DevToolsHttpHandler::IsSupportedProtocolVersion(
params->required_version)) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kProtocolVersionNotSupportedError,
params->required_version);
return false;
}
if (agent_host_->IsAttached()) {
FormatErrorMessage(keys::kAlreadyAttachedError);
return false;
}
infobars::InfoBar* infobar = NULL;
if (!CommandLine::ForCurrentProcess()->
HasSwitch(switches::kSilentDebuggerExtensionAPI)) {
infobar = ExtensionDevToolsInfoBarDelegate::Create(
agent_host_->GetRenderViewHost(), GetExtension()->name());
if (!infobar) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kSilentDebuggingRequired,
switches::kSilentDebuggerExtensionAPI);
return false;
}
}
new ExtensionDevToolsClientHost(GetProfile(),
agent_host_.get(),
GetExtension()->id(),
GetExtension()->name(),
debuggee_,
infobar);
SendResponse(true);
return true;
}
Commit Message: Have the Debugger extension api check that it has access to the tab
Check PermissionsData::CanAccessTab() prior to attaching the debugger.
BUG=367567
Review URL: https://codereview.chromium.org/352523003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
bool DebuggerAttachFunction::RunAsync() {
scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitAgentHost())
return false;
if (!DevToolsHttpHandler::IsSupportedProtocolVersion(
params->required_version)) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kProtocolVersionNotSupportedError,
params->required_version);
return false;
}
if (agent_host_->IsAttached()) {
FormatErrorMessage(keys::kAlreadyAttachedError);
return false;
}
const Extension* extension = GetExtension();
infobars::InfoBar* infobar = NULL;
if (!CommandLine::ForCurrentProcess()->
HasSwitch(::switches::kSilentDebuggerExtensionAPI)) {
infobar = ExtensionDevToolsInfoBarDelegate::Create(
agent_host_->GetRenderViewHost(), extension->name());
if (!infobar) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kSilentDebuggingRequired,
::switches::kSilentDebuggerExtensionAPI);
return false;
}
}
new ExtensionDevToolsClientHost(GetProfile(),
agent_host_.get(),
extension->id(),
extension->name(),
debuggee_,
infobar);
SendResponse(true);
return true;
}
| 171,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: pango_glyph_string_set_size (PangoGlyphString *string, gint new_len)
{
g_return_if_fail (new_len >= 0);
while (new_len > string->space)
{
if (string->space == 0)
string->space = 1;
else
string->space *= 2;
if (string->space < 0)
{
g_warning ("glyph string length overflows maximum integer size, truncated");
new_len = string->space = G_MAXINT - 8;
}
}
string->glyphs = g_realloc (string->glyphs, string->space * sizeof (PangoGlyphInfo));
string->log_clusters = g_realloc (string->log_clusters, string->space * sizeof (gint));
string->num_glyphs = new_len;
}
Commit Message: [glyphstring] Handle overflow with very long glyphstrings
CWE ID: CWE-189
|
pango_glyph_string_set_size (PangoGlyphString *string, gint new_len)
{
g_return_if_fail (new_len >= 0);
while (new_len > string->space)
{
if (string->space == 0)
{
string->space = 4;
}
else
{
const guint max_space =
MIN (G_MAXINT, G_MAXSIZE / MAX (sizeof(PangoGlyphInfo), sizeof(gint)));
guint more_space = (guint)string->space * 2;
if (more_space > max_space)
{
more_space = max_space;
if ((guint)new_len > max_space)
{
g_error ("%s: failed to allocate glyph string of length %i\n",
G_STRLOC, new_len);
}
}
string->space = more_space;
}
}
string->glyphs = g_realloc (string->glyphs, string->space * sizeof (PangoGlyphInfo));
string->log_clusters = g_realloc (string->log_clusters, string->space * sizeof (gint));
string->num_glyphs = new_len;
}
| 165,514
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.