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: PHP_FUNCTION(locale_get_display_variant)
{
get_icu_disp_value_src_php( LOC_VARIANT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
|
PHP_FUNCTION(locale_get_display_variant)
PHP_FUNCTION(locale_get_display_variant)
{
get_icu_disp_value_src_php( LOC_VARIANT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,189
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PerformanceNavigationTiming::PerformanceNavigationTiming(
LocalFrame* frame,
ResourceTimingInfo* info,
TimeTicks time_origin,
const WebVector<WebServerTimingInfo>& server_timing)
: PerformanceResourceTiming(info ? info->InitialURL().GetString() : "",
"navigation",
time_origin,
server_timing),
ContextClient(frame),
resource_timing_info_(info) {
DCHECK(frame);
DCHECK(info);
}
Commit Message: Fix the |name| of PerformanceNavigationTiming
Previously, the |name| of a PerformanceNavigationTiming entry was the initial
URL (the request URL). After this CL, it is the response URL, so for example
a url of the form 'redirect?location=newLoc' will have 'newLoc' as the |name|.
Bug: 797465
Change-Id: Icab53ad8027d066422562c82bcf0354c264fea40
Reviewed-on: https://chromium-review.googlesource.com/996579
Reviewed-by: Yoav Weiss <yoav@yoav.ws>
Commit-Queue: Nicolás Peña Moreno <npm@chromium.org>
Cr-Commit-Position: refs/heads/master@{#548773}
CWE ID: CWE-200
|
PerformanceNavigationTiming::PerformanceNavigationTiming(
LocalFrame* frame,
ResourceTimingInfo* info,
TimeTicks time_origin,
const WebVector<WebServerTimingInfo>& server_timing)
: PerformanceResourceTiming(
info ? info->FinalResponse().Url().GetString() : "",
"navigation",
time_origin,
server_timing),
ContextClient(frame),
resource_timing_info_(info) {
DCHECK(frame);
DCHECK(info);
}
| 173,225
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: QString IRCView::openTags(TextHtmlData* data, int from)
{
QString ret, tag;
int i = from;
for ( ; i < data->openHtmlTags.count(); ++i)
{
tag = data->openHtmlTags.at(i);
if (data->reverse)
{
ret += fontColorOpenTag(Preferences::self()->color(Preferences::TextViewBackground).name());
}
else
{
ret += fontColorOpenTag(data->lastFgColor);
}
}
else if (tag == QLatin1String("span"))
{
if (data->reverse)
{
ret += spanColorOpenTag(data->defaultColor);
}
else
{
ret += spanColorOpenTag(data->lastBgColor);
}
}
else
{
ret += QLatin1Char('<') + tag + QLatin1Char('>');
}
}
Commit Message:
CWE ID:
|
QString IRCView::openTags(TextHtmlData* data, int from)
{
QString ret, tag;
int i = from > -1 ? from : 0;
for ( ; i < data->openHtmlTags.count(); ++i)
{
tag = data->openHtmlTags.at(i);
if (data->reverse)
{
ret += fontColorOpenTag(Preferences::self()->color(Preferences::TextViewBackground).name());
}
else
{
ret += fontColorOpenTag(data->lastFgColor);
}
}
else if (tag == QLatin1String("span"))
{
if (data->reverse)
{
ret += spanColorOpenTag(data->defaultColor);
}
else
{
ret += spanColorOpenTag(data->lastBgColor);
}
}
else
{
ret += QLatin1Char('<') + tag + QLatin1Char('>');
}
}
| 164,649
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: image_transform_default_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
UNUSED(bit_depth)
this->next = *that;
*that = this;
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_default_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
UNUSED(bit_depth)
this->next = *that;
*that = this;
return 1;
}
| 173,620
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void WebPluginDelegateProxy::SendUpdateGeometry(
bool bitmaps_changed) {
PluginMsg_UpdateGeometry_Param param;
param.window_rect = plugin_rect_;
param.clip_rect = clip_rect_;
param.windowless_buffer0 = TransportDIB::DefaultHandleValue();
param.windowless_buffer1 = TransportDIB::DefaultHandleValue();
param.windowless_buffer_index = back_buffer_index();
param.background_buffer = TransportDIB::DefaultHandleValue();
param.transparent = transparent_;
#if defined(OS_POSIX)
if (bitmaps_changed)
#endif
{
if (transport_stores_[0].dib.get())
CopyTransportDIBHandleForMessage(transport_stores_[0].dib->handle(),
¶m.windowless_buffer0);
if (transport_stores_[1].dib.get())
CopyTransportDIBHandleForMessage(transport_stores_[1].dib->handle(),
¶m.windowless_buffer1);
if (background_store_.dib.get())
CopyTransportDIBHandleForMessage(background_store_.dib->handle(),
¶m.background_buffer);
}
IPC::Message* msg;
#if defined(OS_WIN)
if (UseSynchronousGeometryUpdates()) {
msg = new PluginMsg_UpdateGeometrySync(instance_id_, param);
} else // NOLINT
#endif
{
msg = new PluginMsg_UpdateGeometry(instance_id_, param);
msg->set_unblock(true);
}
Send(msg);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void WebPluginDelegateProxy::SendUpdateGeometry(
bool bitmaps_changed) {
PluginMsg_UpdateGeometry_Param param;
param.window_rect = plugin_rect_;
param.clip_rect = clip_rect_;
param.windowless_buffer0 = TransportDIB::DefaultHandleValue();
param.windowless_buffer1 = TransportDIB::DefaultHandleValue();
param.windowless_buffer_index = back_buffer_index();
param.background_buffer = TransportDIB::DefaultHandleValue();
param.transparent = transparent_;
#if defined(OS_POSIX)
if (bitmaps_changed)
#endif
{
if (transport_stores_[0].dib.get())
CopyTransportDIBHandleForMessage(transport_stores_[0].dib->handle(),
¶m.windowless_buffer0,
channel_host_->peer_pid());
if (transport_stores_[1].dib.get())
CopyTransportDIBHandleForMessage(transport_stores_[1].dib->handle(),
¶m.windowless_buffer1,
channel_host_->peer_pid());
if (background_store_.dib.get())
CopyTransportDIBHandleForMessage(background_store_.dib->handle(),
¶m.background_buffer,
channel_host_->peer_pid());
}
IPC::Message* msg;
#if defined(OS_WIN)
if (UseSynchronousGeometryUpdates()) {
msg = new PluginMsg_UpdateGeometrySync(instance_id_, param);
} else // NOLINT
#endif
{
msg = new PluginMsg_UpdateGeometry(instance_id_, param);
msg->set_unblock(true);
}
Send(msg);
}
| 170,956
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 CuePoint* Cues::GetNext(const CuePoint* pCurr) const {
if (pCurr == NULL)
return NULL;
assert(pCurr->GetTimeCode() >= 0);
assert(m_cue_points);
assert(m_count >= 1);
#if 0
const size_t count = m_count + m_preload_count;
size_t index = pCurr->m_index;
assert(index < count);
CuePoint* const* const pp = m_cue_points;
assert(pp);
assert(pp[index] == pCurr);
++index;
if (index >= count)
return NULL;
CuePoint* const pNext = pp[index];
assert(pNext);
pNext->Load(m_pSegment->m_pReader);
#else
long index = pCurr->m_index;
assert(index < m_count);
CuePoint* const* const pp = m_cue_points;
assert(pp);
assert(pp[index] == pCurr);
++index;
if (index >= m_count)
return NULL;
CuePoint* const pNext = pp[index];
assert(pNext);
assert(pNext->GetTimeCode() >= 0);
#endif
return pNext;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
const CuePoint* Cues::GetNext(const CuePoint* pCurr) const {
if (pCurr == NULL || pCurr->GetTimeCode() < 0 ||
m_cue_points == NULL || m_count < 1) {
return NULL;
}
long index = pCurr->m_index;
if (index >= m_count)
return NULL;
CuePoint* const* const pp = m_cue_points;
if (pp == NULL || pp[index] != pCurr)
return NULL;
++index;
if (index >= m_count)
return NULL;
CuePoint* const pNext = pp[index];
if (pNext == NULL || pNext->GetTimeCode() < 0)
return NULL;
return pNext;
}
| 173,821
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize,
size_t pos, PNG_CONST char *msg)
{
if (pp != NULL && pp == ps->pread)
{
/* Reading a file */
pos = safecat(buffer, bufsize, pos, "read: ");
if (ps->current != NULL)
{
pos = safecat(buffer, bufsize, pos, ps->current->name);
pos = safecat(buffer, bufsize, pos, sep);
}
}
else if (pp != NULL && pp == ps->pwrite)
{
/* Writing a file */
pos = safecat(buffer, bufsize, pos, "write: ");
pos = safecat(buffer, bufsize, pos, ps->wname);
pos = safecat(buffer, bufsize, pos, sep);
}
else
{
/* Neither reading nor writing (or a memory error in struct delete) */
pos = safecat(buffer, bufsize, pos, "pngvalid: ");
}
if (ps->test[0] != 0)
{
pos = safecat(buffer, bufsize, pos, ps->test);
pos = safecat(buffer, bufsize, pos, sep);
}
pos = safecat(buffer, bufsize, pos, msg);
return pos;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize,
size_t pos, const char *msg)
{
if (pp != NULL && pp == ps->pread)
{
/* Reading a file */
pos = safecat(buffer, bufsize, pos, "read: ");
if (ps->current != NULL)
{
pos = safecat(buffer, bufsize, pos, ps->current->name);
pos = safecat(buffer, bufsize, pos, sep);
}
}
else if (pp != NULL && pp == ps->pwrite)
{
/* Writing a file */
pos = safecat(buffer, bufsize, pos, "write: ");
pos = safecat(buffer, bufsize, pos, ps->wname);
pos = safecat(buffer, bufsize, pos, sep);
}
else
{
/* Neither reading nor writing (or a memory error in struct delete) */
pos = safecat(buffer, bufsize, pos, "pngvalid: ");
}
if (ps->test[0] != 0)
{
pos = safecat(buffer, bufsize, pos, ps->test);
pos = safecat(buffer, bufsize, pos, sep);
}
pos = safecat(buffer, bufsize, pos, msg);
return pos;
}
| 173,706
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: get_caller_uid (GDBusMethodInvocation *context, gint *uid)
{
PolkitSubject *subject;
PolkitSubject *process;
subject = polkit_system_bus_name_new (g_dbus_method_invocation_get_sender (context));
process = polkit_system_bus_name_get_process_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, NULL);
if (!process) {
g_object_unref (subject);
return FALSE;
}
*uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (process));
g_object_unref (subject);
g_object_unref (process);
return TRUE;
}
Commit Message:
CWE ID: CWE-362
|
get_caller_uid (GDBusMethodInvocation *context, gint *uid)
get_caller_uid (GDBusMethodInvocation *context,
gint *uid)
{
GVariant *reply;
GError *error;
error = NULL;
reply = g_dbus_connection_call_sync (g_dbus_method_invocation_get_connection (context),
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"GetConnectionUnixUser",
g_variant_new ("(s)",
g_dbus_method_invocation_get_sender (context)),
G_VARIANT_TYPE ("(u)"),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (reply == NULL) {
g_warning ("Could not talk to message bus to find uid of sender %s: %s",
g_dbus_method_invocation_get_sender (context),
error->message);
g_error_free (error);
return FALSE;
}
g_variant_get (reply, "(u)", uid);
g_variant_unref (reply);
return TRUE;
}
| 165,011
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 snd_seq_ioctl_remove_events(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_remove_events info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
/*
* Input mostly not implemented XXX.
*/
if (info.remove_mode & SNDRV_SEQ_REMOVE_INPUT) {
/*
* No restrictions so for a user client we can clear
* the whole fifo
*/
if (client->type == USER_CLIENT)
snd_seq_fifo_clear(client->data.user.fifo);
}
if (info.remove_mode & SNDRV_SEQ_REMOVE_OUTPUT)
snd_seq_queue_remove_cells(client->number, &info);
return 0;
}
Commit Message: ALSA: seq: Fix missing NULL check at remove_events ioctl
snd_seq_ioctl_remove_events() calls snd_seq_fifo_clear()
unconditionally even if there is no FIFO assigned, and this leads to
an Oops due to NULL dereference. The fix is just to add a proper NULL
check.
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:
|
static int snd_seq_ioctl_remove_events(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_remove_events info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
/*
* Input mostly not implemented XXX.
*/
if (info.remove_mode & SNDRV_SEQ_REMOVE_INPUT) {
/*
* No restrictions so for a user client we can clear
* the whole fifo
*/
if (client->type == USER_CLIENT && client->data.user.fifo)
snd_seq_fifo_clear(client->data.user.fifo);
}
if (info.remove_mode & SNDRV_SEQ_REMOVE_OUTPUT)
snd_seq_queue_remove_cells(client->number, &info);
return 0;
}
| 167,410
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 t1_check_unusual_charstring(void)
{
char *p = strstr(t1_line_array, charstringname) + strlen(charstringname);
int i;
/* if no number follows "/CharStrings", let's read the next line */
if (sscanf(p, "%i", &i) != 1) {
/* pdftex_warn("no number found after `%s', I assume it's on the next line",
charstringname); */
strcpy(t1_buf_array, t1_line_array);
/* t1_getline always appends EOL to t1_line_array; let's change it to
* space before appending the next line
*/
*(strend(t1_buf_array) - 1) = ' ';
t1_getline();
strcat(t1_buf_array, t1_line_array);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
}
Commit Message: writet1 protection against buffer overflow
git-svn-id: svn://tug.org/texlive/trunk/Build/source@48697 c570f23f-e606-0410-a88d-b1316a301751
CWE ID: CWE-119
|
static void t1_check_unusual_charstring(void)
{
char *p = strstr(t1_line_array, charstringname) + strlen(charstringname);
int i;
/* if no number follows "/CharStrings", let's read the next line */
if (sscanf(p, "%i", &i) != 1) {
/* pdftex_warn("no number found after `%s', I assume it's on the next line",
charstringname); */
strcpy(t1_buf_array, t1_line_array);
/* t1_getline always appends EOL to t1_line_array; let's change it to
* space before appending the next line
*/
*(strend(t1_buf_array) - 1) = ' ';
t1_getline();
alloc_array(t1_buf, strlen(t1_line_array) + strlen(t1_buf_array) + 1, T1_BUF_SIZE);
strcat(t1_buf_array, t1_line_array);
alloc_array(t1_line, strlen(t1_buf_array) + 1, T1_BUF_SIZE);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
}
| 169,020
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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::set<std::string> GetDistinctHosts(const URLPatternSet& host_patterns,
bool include_rcd,
bool exclude_file_scheme) {
typedef base::StringPairs HostVector;
HostVector hosts_best_rcd;
for (const URLPattern& pattern : host_patterns) {
if (exclude_file_scheme && pattern.scheme() == url::kFileScheme)
continue;
std::string host = pattern.host();
if (pattern.match_subdomains())
host = "*." + host;
std::string rcd;
size_t reg_len =
net::registry_controlled_domains::PermissiveGetHostRegistryLength(
host, net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
if (reg_len && reg_len != std::string::npos) {
if (include_rcd) // else leave rcd empty
rcd = host.substr(host.size() - reg_len);
host = host.substr(0, host.size() - reg_len);
}
HostVector::iterator it = hosts_best_rcd.begin();
for (; it != hosts_best_rcd.end(); ++it) {
if (it->first == host)
break;
}
if (it != hosts_best_rcd.end()) {
if (include_rcd && RcdBetterThan(rcd, it->second))
it->second = rcd;
} else { // Previously unseen host, append it.
hosts_best_rcd.push_back(std::make_pair(host, rcd));
}
}
std::set<std::string> distinct_hosts;
for (const auto& host_rcd : hosts_best_rcd)
distinct_hosts.insert(host_rcd.first + host_rcd.second);
return distinct_hosts;
}
Commit Message: Ensure IDN domains are in punycode format in extension host permissions
Today in extension dialogs and bubbles, IDN domains in host permissions
are not displayed in punycode format. There is a low security risk that
granting such permission would allow extensions to interact with pages
using spoofy IDN domains. Note that this does not affect the omnibox,
which would represent the origin properly.
To address this issue, this CL converts IDN domains in host permissions
to punycode format.
Bug: 745580
Change-Id: Ifc04030fae645f8a78ac8fde170660f2d514acce
Reviewed-on: https://chromium-review.googlesource.com/644140
Commit-Queue: catmullings <catmullings@chromium.org>
Reviewed-by: Istiaque Ahmed <lazyboy@chromium.org>
Reviewed-by: Tommy Li <tommycli@chromium.org>
Cr-Commit-Position: refs/heads/master@{#499090}
CWE ID: CWE-20
|
std::set<std::string> GetDistinctHosts(const URLPatternSet& host_patterns,
bool include_rcd,
bool exclude_file_scheme) {
typedef base::StringPairs HostVector;
HostVector hosts_best_rcd;
for (const URLPattern& pattern : host_patterns) {
if (exclude_file_scheme && pattern.scheme() == url::kFileScheme)
continue;
std::string host = pattern.host();
if (!host.empty()) {
// Convert the host into a secure format. For example, an IDN domain is
// converted to punycode.
host = base::UTF16ToUTF8(url_formatter::FormatUrlForSecurityDisplay(
GURL(base::StringPrintf("%s%s%s", url::kHttpScheme,
url::kStandardSchemeSeparator, host.c_str())),
url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS));
}
if (pattern.match_subdomains())
host = "*." + host;
std::string rcd;
size_t reg_len =
net::registry_controlled_domains::PermissiveGetHostRegistryLength(
host, net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
if (reg_len && reg_len != std::string::npos) {
if (include_rcd) // else leave rcd empty
rcd = host.substr(host.size() - reg_len);
host = host.substr(0, host.size() - reg_len);
}
HostVector::iterator it = hosts_best_rcd.begin();
for (; it != hosts_best_rcd.end(); ++it) {
if (it->first == host)
break;
}
if (it != hosts_best_rcd.end()) {
if (include_rcd && RcdBetterThan(rcd, it->second))
it->second = rcd;
} else { // Previously unseen host, append it.
hosts_best_rcd.push_back(std::make_pair(host, rcd));
}
}
std::set<std::string> distinct_hosts;
for (const auto& host_rcd : hosts_best_rcd)
distinct_hosts.insert(host_rcd.first + host_rcd.second);
return distinct_hosts;
}
| 172,961
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int logi_dj_ll_raw_request(struct hid_device *hid,
unsigned char reportnum, __u8 *buf,
size_t count, unsigned char report_type,
int reqtype)
{
struct dj_device *djdev = hid->driver_data;
struct dj_receiver_dev *djrcv_dev = djdev->dj_receiver_dev;
u8 *out_buf;
int ret;
if (buf[0] != REPORT_TYPE_LEDS)
return -EINVAL;
out_buf = kzalloc(DJREPORT_SHORT_LENGTH, GFP_ATOMIC);
if (!out_buf)
return -ENOMEM;
if (count < DJREPORT_SHORT_LENGTH - 2)
count = DJREPORT_SHORT_LENGTH - 2;
out_buf[0] = REPORT_ID_DJ_SHORT;
out_buf[1] = djdev->device_index;
memcpy(out_buf + 2, buf, count);
ret = hid_hw_raw_request(djrcv_dev->hdev, out_buf[0], out_buf,
DJREPORT_SHORT_LENGTH, report_type, reqtype);
kfree(out_buf);
return ret;
}
Commit Message: HID: logitech: fix bounds checking on LED report size
The check on report size for REPORT_TYPE_LEDS in logi_dj_ll_raw_request()
is wrong; the current check doesn't make any sense -- the report allocated
by HID core in hid_hw_raw_request() can be much larger than
DJREPORT_SHORT_LENGTH, and currently logi_dj_ll_raw_request() doesn't
handle this properly at all.
Fix the check by actually trimming down the report size properly if it is
too large.
Cc: stable@vger.kernel.org
Reported-by: Ben Hawkes <hawkes@google.com>
Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com>
Signed-off-by: Jiri Kosina <jkosina@suse.cz>
CWE ID: CWE-119
|
static int logi_dj_ll_raw_request(struct hid_device *hid,
unsigned char reportnum, __u8 *buf,
size_t count, unsigned char report_type,
int reqtype)
{
struct dj_device *djdev = hid->driver_data;
struct dj_receiver_dev *djrcv_dev = djdev->dj_receiver_dev;
u8 *out_buf;
int ret;
if (buf[0] != REPORT_TYPE_LEDS)
return -EINVAL;
out_buf = kzalloc(DJREPORT_SHORT_LENGTH, GFP_ATOMIC);
if (!out_buf)
return -ENOMEM;
if (count > DJREPORT_SHORT_LENGTH - 2)
count = DJREPORT_SHORT_LENGTH - 2;
out_buf[0] = REPORT_ID_DJ_SHORT;
out_buf[1] = djdev->device_index;
memcpy(out_buf + 2, buf, count);
ret = hid_hw_raw_request(djrcv_dev->hdev, out_buf[0], out_buf,
DJREPORT_SHORT_LENGTH, report_type, reqtype);
kfree(out_buf);
return ret;
}
| 166,376
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: Cluster* Cluster::Create(
Segment* pSegment,
long idx,
long long off)
{
assert(pSegment);
assert(off >= 0);
const long long element_start = pSegment->m_start + off;
Cluster* const pCluster = new Cluster(pSegment,
idx,
element_start);
assert(pCluster);
return pCluster;
}
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
|
Cluster* Cluster::Create(
| 174,256
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: deinterlace_row(png_bytep buffer, png_const_bytep row,
unsigned int pixel_size, png_uint_32 w, int pass)
{
/* The inverse of the above, 'row' is part of row 'y' of the output image,
* in 'buffer'. The image is 'w' wide and this is pass 'pass', distribute
* the pixels of row into buffer and return the number written (to allow
* this to be checked).
*/
png_uint_32 xin, xout, xstep;
xout = PNG_PASS_START_COL(pass);
xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
for (xin=0; xout<w; xout+=xstep)
{
pixel_copy(buffer, xout, row, xin, pixel_size);
++xin;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
deinterlace_row(png_bytep buffer, png_const_bytep row,
| 173,607
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 AppCacheGroup::RemoveCache(AppCache* cache) {
DCHECK(cache->associated_hosts().empty());
if (cache == newest_complete_cache_) {
CancelUpdate();
AppCache* tmp_cache = newest_complete_cache_;
newest_complete_cache_ = nullptr;
tmp_cache->set_owning_group(nullptr); // may cause this group to be deleted
} else {
scoped_refptr<AppCacheGroup> protect(this);
Caches::iterator it =
std::find(old_caches_.begin(), old_caches_.end(), cache);
if (it != old_caches_.end()) {
AppCache* tmp_cache = *it;
old_caches_.erase(it);
tmp_cache->set_owning_group(nullptr); // may cause group to be released
}
if (!is_obsolete() && old_caches_.empty() &&
!newly_deletable_response_ids_.empty()) {
storage_->DeleteResponses(manifest_url_, newly_deletable_response_ids_);
newly_deletable_response_ids_.clear();
}
}
}
Commit Message: Refcount AppCacheGroup correctly.
Bug: 888926
Change-Id: Iab0d82d272e2f24a5e91180d64bc8e2aa8a8238d
Reviewed-on: https://chromium-review.googlesource.com/1246827
Reviewed-by: Marijn Kruisselbrink <mek@chromium.org>
Reviewed-by: Joshua Bell <jsbell@chromium.org>
Commit-Queue: Chris Palmer <palmer@chromium.org>
Cr-Commit-Position: refs/heads/master@{#594475}
CWE ID: CWE-20
|
void AppCacheGroup::RemoveCache(AppCache* cache) {
DCHECK(cache->associated_hosts().empty());
if (cache == newest_complete_cache_) {
AppCache* tmp_cache = newest_complete_cache_;
newest_complete_cache_ = nullptr;
CancelUpdate();
tmp_cache->set_owning_group(nullptr); // may cause this group to be deleted
} else {
scoped_refptr<AppCacheGroup> protect(this);
Caches::iterator it =
std::find(old_caches_.begin(), old_caches_.end(), cache);
if (it != old_caches_.end()) {
AppCache* tmp_cache = *it;
old_caches_.erase(it);
tmp_cache->set_owning_group(nullptr); // may cause group to be released
}
if (!is_obsolete() && old_caches_.empty() &&
!newly_deletable_response_ids_.empty()) {
storage_->DeleteResponses(manifest_url_, newly_deletable_response_ids_);
newly_deletable_response_ids_.clear();
}
}
}
| 172,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: void CreateAuthenticatorFactory() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
std::string local_certificate = key_pair_.GenerateCertificate();
if (local_certificate.empty()) {
LOG(ERROR) << "Failed to generate host certificate.";
Shutdown(kHostInitializationFailed);
return;
}
scoped_ptr<protocol::AuthenticatorFactory> factory(
new protocol::Me2MeHostAuthenticatorFactory(
local_certificate, *key_pair_.private_key(), host_secret_hash_));
host_->SetAuthenticatorFactory(factory.Pass());
}
Commit Message: Fix crash in CreateAuthenticatorFactory().
CreateAuthenticatorFactory() is called asynchronously, but it didn't handle
the case when it's called after host object is destroyed.
BUG=150644
Review URL: https://codereview.chromium.org/11090036
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161077 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void CreateAuthenticatorFactory() {
DCHECK(context_->network_task_runner()->BelongsToCurrentThread());
if (!host_ || shutting_down_)
return;
std::string local_certificate = key_pair_.GenerateCertificate();
if (local_certificate.empty()) {
LOG(ERROR) << "Failed to generate host certificate.";
Shutdown(kHostInitializationFailed);
return;
}
scoped_ptr<protocol::AuthenticatorFactory> factory(
new protocol::Me2MeHostAuthenticatorFactory(
local_certificate, *key_pair_.private_key(), host_secret_hash_));
host_->SetAuthenticatorFactory(factory.Pass());
}
| 171,338
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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_module_open)
{
char *cipher, *cipher_dir;
char *mode, *mode_dir;
int cipher_len, cipher_dir_len;
int mode_len, mode_dir_len;
MCRYPT td;
php_mcrypt *pm;
if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, "ssss",
&cipher, &cipher_len, &cipher_dir, &cipher_dir_len,
&mode, &mode_len, &mode_dir, &mode_dir_len)) {
return;
}
td = mcrypt_module_open (
cipher,
cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir),
mode,
mode_dir_len > 0 ? mode_dir : MCG(modes_dir)
);
if (td == MCRYPT_FAILED) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open encryption module");
RETURN_FALSE;
} else {
pm = emalloc(sizeof(php_mcrypt));
pm->td = td;
pm->init = 0;
ZEND_REGISTER_RESOURCE(return_value, pm, le_mcrypt);
}
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
|
PHP_FUNCTION(mcrypt_module_open)
{
char *cipher, *cipher_dir;
char *mode, *mode_dir;
int cipher_len, cipher_dir_len;
int mode_len, mode_dir_len;
MCRYPT td;
php_mcrypt *pm;
if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, "ssss",
&cipher, &cipher_len, &cipher_dir, &cipher_dir_len,
&mode, &mode_len, &mode_dir, &mode_dir_len)) {
return;
}
td = mcrypt_module_open (
cipher,
cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir),
mode,
mode_dir_len > 0 ? mode_dir : MCG(modes_dir)
);
if (td == MCRYPT_FAILED) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open encryption module");
RETURN_FALSE;
} else {
pm = emalloc(sizeof(php_mcrypt));
pm->td = td;
pm->init = 0;
ZEND_REGISTER_RESOURCE(return_value, pm, le_mcrypt);
}
}
| 167,089
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: Resource::Resource(PluginInstance* instance)
: resource_id_(0), instance_(instance) {
}
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
|
Resource::Resource(PluginInstance* instance)
: resource_id_(0), instance_(instance) {
ResourceTracker::Get()->ResourceCreated(this, instance_);
}
| 170,414
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ChromeGeolocationPermissionContext::ChromeGeolocationPermissionContext(
Profile* profile)
: profile_(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(geolocation_infobar_queue_controller_(
new GeolocationInfoBarQueueController(
base::Bind(
&ChromeGeolocationPermissionContext::NotifyPermissionSet,
this),
profile))) {
}
Commit Message: Don't retain reference to ChromeGeolocationPermissionContext
ChromeGeolocationPermissionContext owns
GeolocationInfoBarQueueController, so make sure that the callback
passed to GeolocationInfoBarQueueController doesn't increase the
reference count on ChromeGeolocationPermissionContext (which
https://chromiumcodereview.appspot.com/11072012 accidentally does).
TBR=bulach
BUG=152921
TEST=unittest:chrome_geolocation_permission_context on memory.fyi bot
Review URL: https://chromiumcodereview.appspot.com/11087030
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@160881 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
ChromeGeolocationPermissionContext::ChromeGeolocationPermissionContext(
Profile* profile)
: profile_(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(geolocation_infobar_queue_controller_(
new GeolocationInfoBarQueueController(
base::Bind(
&ChromeGeolocationPermissionContext::NotifyPermissionSet,
base::Unretained(this)),
profile))) {
}
| 171,589
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) {
fwd_txfm_(in, out, stride);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) {
void RunFwdTxfm(const int16_t *in, tran_low_t *out, int stride) {
fwd_txfm_(in, out, stride);
}
| 174,549
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const char *table) /* {{{ */
{
char *table_copy, *escaped, *token, *tmp;
size_t len;
/* schame.table should be "schame"."table" */
table_copy = estrdup(table);
token = php_strtok_r(table_copy, ".", &tmp);
len = strlen(token);
if (_php_pgsql_detect_identifier_escape(token, len) == SUCCESS) {
smart_str_appendl(querystr, token, len);
PGSQLfree(escaped);
}
if (tmp && *tmp) {
len = strlen(tmp);
/* "schema"."table" format */
if (_php_pgsql_detect_identifier_escape(tmp, len) == SUCCESS) {
smart_str_appendc(querystr, '.');
smart_str_appendl(querystr, tmp, len);
} else {
escaped = PGSQLescapeIdentifier(pg_link, tmp, len);
smart_str_appendc(querystr, '.');
smart_str_appends(querystr, escaped);
PGSQLfree(escaped);
}
}
efree(table_copy);
}
/* }}} */
Commit Message:
CWE ID:
|
static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const char *table) /* {{{ */
{
char *table_copy, *escaped, *token, *tmp;
size_t len;
/* schame.table should be "schame"."table" */
table_copy = estrdup(table);
token = php_strtok_r(table_copy, ".", &tmp);
if (token == NULL) {
token = table;
}
len = strlen(token);
if (_php_pgsql_detect_identifier_escape(token, len) == SUCCESS) {
smart_str_appendl(querystr, token, len);
PGSQLfree(escaped);
}
if (tmp && *tmp) {
len = strlen(tmp);
/* "schema"."table" format */
if (_php_pgsql_detect_identifier_escape(tmp, len) == SUCCESS) {
smart_str_appendc(querystr, '.');
smart_str_appendl(querystr, tmp, len);
} else {
escaped = PGSQLescapeIdentifier(pg_link, tmp, len);
smart_str_appendc(querystr, '.');
smart_str_appends(querystr, escaped);
PGSQLfree(escaped);
}
}
efree(table_copy);
}
/* }}} */
| 164,769
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: WebstoreBindings::WebstoreBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("Install",
base::Bind(&WebstoreBindings::Install, base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284
|
WebstoreBindings::WebstoreBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("Install", "webstore",
base::Bind(&WebstoreBindings::Install, base::Unretained(this)));
}
| 172,245
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static ssize_t aio_setup_vectored_rw(int type, struct kiocb *kiocb, bool compat)
{
ssize_t ret;
#ifdef CONFIG_COMPAT
if (compat)
ret = compat_rw_copy_check_uvector(type,
(struct compat_iovec __user *)kiocb->ki_buf,
kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec,
&kiocb->ki_iovec, 1);
else
#endif
ret = rw_copy_check_uvector(type,
(struct iovec __user *)kiocb->ki_buf,
kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec,
&kiocb->ki_iovec, 1);
if (ret < 0)
goto out;
kiocb->ki_nr_segs = kiocb->ki_nbytes;
kiocb->ki_cur_seg = 0;
/* ki_nbytes/left now reflect bytes instead of segs */
kiocb->ki_nbytes = ret;
kiocb->ki_left = ret;
ret = 0;
out:
return ret;
}
Commit Message: vfs: make AIO use the proper rw_verify_area() area helpers
We had for some reason overlooked the AIO interface, and it didn't use
the proper rw_verify_area() helper function that checks (for example)
mandatory locking on the file, and that the size of the access doesn't
cause us to overflow the provided offset limits etc.
Instead, AIO did just the security_file_permission() thing (that
rw_verify_area() also does) directly.
This fixes it to do all the proper helper functions, which not only
means that now mandatory file locking works with AIO too, we can
actually remove lines of code.
Reported-by: Manish Honap <manish_honap_vit@yahoo.co.in>
Cc: stable@vger.kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID:
|
static ssize_t aio_setup_vectored_rw(int type, struct kiocb *kiocb, bool compat)
{
ssize_t ret;
#ifdef CONFIG_COMPAT
if (compat)
ret = compat_rw_copy_check_uvector(type,
(struct compat_iovec __user *)kiocb->ki_buf,
kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec,
&kiocb->ki_iovec, 1);
else
#endif
ret = rw_copy_check_uvector(type,
(struct iovec __user *)kiocb->ki_buf,
kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec,
&kiocb->ki_iovec, 1);
if (ret < 0)
goto out;
ret = rw_verify_area(type, kiocb->ki_filp, &kiocb->ki_pos, ret);
if (ret < 0)
goto out;
kiocb->ki_nr_segs = kiocb->ki_nbytes;
kiocb->ki_cur_seg = 0;
/* ki_nbytes/left now reflect bytes instead of segs */
kiocb->ki_nbytes = ret;
kiocb->ki_left = ret;
ret = 0;
out:
return ret;
}
| 167,613
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 set_registers(rtl8150_t * dev, u16 indx, u16 size, void *data)
{
return usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
RTL8150_REQ_SET_REGS, RTL8150_REQT_WRITE,
indx, 0, data, size, 500);
}
Commit Message: rtl8150: Use heap buffers for all register access
Allocating USB buffers on the stack is not portable, and no longer
works on x86_64 (with VMAP_STACK enabled as per default).
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-119
|
static int set_registers(rtl8150_t * dev, u16 indx, u16 size, void *data)
static int set_registers(rtl8150_t * dev, u16 indx, u16 size, const void *data)
{
void *buf;
int ret;
buf = kmemdup(data, size, GFP_NOIO);
if (!buf)
return -ENOMEM;
ret = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
RTL8150_REQ_SET_REGS, RTL8150_REQT_WRITE,
indx, 0, buf, size, 500);
kfree(buf);
return ret;
}
| 168,215
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 rtecp_select_file(sc_card_t *card,
const sc_path_t *in_path, sc_file_t **file_out)
{
sc_file_t **file_out_copy, *file;
int r;
assert(card && card->ctx && in_path);
switch (in_path->type)
{
case SC_PATH_TYPE_DF_NAME:
case SC_PATH_TYPE_FROM_CURRENT:
case SC_PATH_TYPE_PARENT:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED);
}
assert(iso_ops && iso_ops->select_file);
file_out_copy = file_out;
r = iso_ops->select_file(card, in_path, file_out_copy);
if (r || file_out_copy == NULL)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
assert(file_out_copy);
file = *file_out_copy;
assert(file);
if (file->sec_attr && file->sec_attr_len == SC_RTECP_SEC_ATTR_SIZE)
set_acl_from_sec_attr(card, file);
else
r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
if (r)
sc_file_free(file);
else
{
assert(file_out);
*file_out = file;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
|
static int rtecp_select_file(sc_card_t *card,
const sc_path_t *in_path, sc_file_t **file_out)
{
sc_file_t **file_out_copy, *file;
int r;
assert(card && card->ctx && in_path);
switch (in_path->type)
{
case SC_PATH_TYPE_DF_NAME:
case SC_PATH_TYPE_FROM_CURRENT:
case SC_PATH_TYPE_PARENT:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED);
}
assert(iso_ops && iso_ops->select_file);
file_out_copy = file_out;
r = iso_ops->select_file(card, in_path, file_out_copy);
if (r || file_out_copy == NULL)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
assert(file_out_copy);
file = *file_out_copy;
assert(file);
if (file->sec_attr && file->sec_attr_len == SC_RTECP_SEC_ATTR_SIZE)
set_acl_from_sec_attr(card, file);
else
r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
if (r && !file_out)
sc_file_free(file);
else
{
assert(file_out);
*file_out = file;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
| 169,063
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: stringprep_utf8_nfkc_normalize (const char *str, ssize_t len)
{
return g_utf8_normalize (str, len, G_NORMALIZE_NFKC);
}
Commit Message:
CWE ID: CWE-125
|
stringprep_utf8_nfkc_normalize (const char *str, ssize_t len)
{
size_t n;
if (len < 0)
n = strlen (str);
else
n = len;
if (u8_check ((const uint8_t *) str, n))
return NULL;
return g_utf8_normalize (str, len, G_NORMALIZE_NFKC);
}
| 164,984
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: IndexedDBCursor::~IndexedDBCursor() {
Close();
}
Commit Message: [IndexedDB] Fix Cursor UAF
If the connection is closed before we return a cursor, it dies in
IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on
the correct thread, but we also need to makes sure to remove it from its
transaction.
To make things simpler, we have the cursor remove itself from its
transaction on destruction.
R: pwnall@chromium.org
Bug: 728887
Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2
Reviewed-on: https://chromium-review.googlesource.com/526284
Commit-Queue: Daniel Murphy <dmurph@chromium.org>
Reviewed-by: Victor Costan <pwnall@chromium.org>
Cr-Commit-Position: refs/heads/master@{#477504}
CWE ID: CWE-416
|
IndexedDBCursor::~IndexedDBCursor() {
if (transaction_)
transaction_->UnregisterOpenCursor(this);
Close();
}
| 172,308
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_auth a;
const char *v2_auth[]={ "invalid", "rsasig",
"shared-secret", "dsssig" };
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
ND_PRINT((ndo," len=%d method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (1 < ndo->ndo_vflag && 4 < len) {
ND_PRINT((ndo," authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo,") "));
} else if(ndo->ndo_vflag && 4 < len) {
if(!ike_show_somedata(ndo, authdata, ep)) goto trunc;
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
Commit Message: CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data.
The closest thing to a specification for the contents of the payload
data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it
is ever a complete ISAKMP message, so don't dissect types we don't have
specific code for as a complete ISAKMP message.
While we're at it, fix a comment, and clean up printing of V1 Nonce,
V2 Authentication payloads, and v2 Notice payloads.
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-835
|
ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_auth a;
const char *v2_auth[]={ "invalid", "rsasig",
"shared-secret", "dsssig" };
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," len=%u method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (len > 4) {
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo, ") "));
} else if (ndo->ndo_vflag) {
if (!ike_show_somedata(ndo, authdata, ep))
goto trunc;
}
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
| 167,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: ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_auth a;
const char *v2_auth[]={ "invalid", "rsasig",
"shared-secret", "dsssig" };
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," len=%u method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (len > 4) {
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo, ") "));
} else if (ndo->ndo_vflag) {
if (!ike_show_somedata(ndo, authdata, ep))
goto trunc;
}
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_auth a;
const char *v2_auth[]={ "invalid", "rsasig",
"shared-secret", "dsssig" };
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
ND_TCHECK2(*ext, sizeof(a));
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," len=%u method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (len > 4) {
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo, ") "));
} else if (ndo->ndo_vflag) {
if (!ike_show_somedata(ndo, authdata, ep))
goto trunc;
}
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
| 167,797
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: GURL DevToolsWindow::GetDevToolsURL(Profile* profile,
const GURL& base_url,
bool shared_worker_frontend,
bool v8_only_frontend,
const std::string& remote_frontend,
bool can_dock) {
if (base_url.SchemeIs("data"))
return base_url;
std::string frontend_url(
!remote_frontend.empty() ?
remote_frontend :
base_url.is_empty() ? chrome::kChromeUIDevToolsURL : base_url.spec());
std::string url_string(
frontend_url +
((frontend_url.find("?") == std::string::npos) ? "?" : "&"));
if (shared_worker_frontend)
url_string += "&isSharedWorker=true";
if (v8_only_frontend)
url_string += "&v8only=true";
if (remote_frontend.size()) {
url_string += "&remoteFrontend=true";
} else {
url_string += "&remoteBase=" + DevToolsUI::GetRemoteBaseURL().spec();
}
if (can_dock)
url_string += "&can_dock=true";
return GURL(url_string);
}
Commit Message: [DevTools] Move sanitize url to devtools_ui.cc.
Compatibility script is not reliable enough.
BUG=653134
Review-Url: https://codereview.chromium.org/2403633002
Cr-Commit-Position: refs/heads/master@{#425814}
CWE ID: CWE-200
|
GURL DevToolsWindow::GetDevToolsURL(Profile* profile,
const GURL& base_url,
bool shared_worker_frontend,
bool v8_only_frontend,
const std::string& remote_frontend,
bool can_dock) {
if (base_url.SchemeIs("data"))
return base_url;
std::string frontend_url(
!remote_frontend.empty() ?
remote_frontend :
base_url.is_empty() ? chrome::kChromeUIDevToolsURL : base_url.spec());
std::string url_string(
frontend_url +
((frontend_url.find("?") == std::string::npos) ? "?" : "&"));
if (shared_worker_frontend)
url_string += "&isSharedWorker=true";
if (v8_only_frontend)
url_string += "&v8only=true";
if (remote_frontend.size()) {
url_string += "&remoteFrontend=true";
} else {
url_string += "&remoteBase=" + DevToolsUI::GetRemoteBaseURL().spec();
}
if (can_dock)
url_string += "&can_dock=true";
return DevToolsUI::SanitizeFrontendURL(GURL(url_string));
}
| 172,509
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 ShouldUseNativeViews() {
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
return base::FeatureList::IsEnabled(kAutofillExpandedPopupViews) ||
base::FeatureList::IsEnabled(::features::kExperimentalUi);
#else
return false;
#endif
}
Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature.
Bug: 906135,831603
Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499
Reviewed-on: https://chromium-review.googlesource.com/c/1387124
Reviewed-by: Robert Kaplow <rkaplow@chromium.org>
Reviewed-by: Vasilii Sukhanov <vasilii@chromium.org>
Reviewed-by: Fabio Tirelo <ftirelo@chromium.org>
Reviewed-by: Tommy Martino <tmartino@chromium.org>
Commit-Queue: Mathieu Perreault <mathp@chromium.org>
Cr-Commit-Position: refs/heads/master@{#621360}
CWE ID: CWE-416
|
bool ShouldUseNativeViews() {
| 172,098
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: xmalloc (size_t size)
{
void *ptr = malloc (size);
if (!ptr
&& (size != 0)) /* some libc don't like size == 0 */
{
perror ("xmalloc: Memory allocation failure");
abort();
}
return ptr;
}
Commit Message: Fix integer overflows and harden memory allocator.
CWE ID: CWE-190
|
xmalloc (size_t size)
xmalloc (size_t num, size_t size)
{
size_t res;
if (check_mul_overflow(num, size, &res))
abort();
void *ptr = malloc (res);
if (!ptr
&& (size != 0)) /* some libc don't like size == 0 */
{
perror ("xmalloc: Memory allocation failure");
abort();
}
return ptr;
}
| 168,359
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 DidDownloadImage(const WebContents::ImageDownloadCallback& callback,
int id,
const GURL& image_url,
image_downloader::DownloadResultPtr result) {
DCHECK(result);
const std::vector<SkBitmap> images =
result->images.To<std::vector<SkBitmap>>();
const std::vector<gfx::Size> original_image_sizes =
result->original_image_sizes.To<std::vector<gfx::Size>>();
callback.Run(id, result->http_status_code, image_url, images,
original_image_sizes);
}
Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted
BUG=583718
Review URL: https://codereview.chromium.org/1685343004
Cr-Commit-Position: refs/heads/master@{#375700}
CWE ID:
|
static void DidDownloadImage(const WebContents::ImageDownloadCallback& callback,
| 172,209
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: rpl_daoack_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN);
if (length < ND_RPL_DAOACK_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAOACK_MIN_LEN;
length -= ND_RPL_DAOACK_MIN_LEN;
if(RPL_DAOACK_D(daoack->rpl_flags)) {
ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, daoack->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]",
dagid_str,
daoack->rpl_daoseq,
daoack->rpl_instanceid,
daoack->rpl_status));
/* no officially defined options for DAOACK, but print any we find */
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|dao-truncated]"));
return;
tooshort:
ND_PRINT((ndo," [|dao-length too short]"));
return;
}
Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.
CWE ID: CWE-125
|
rpl_daoack_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN);
if (length < ND_RPL_DAOACK_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAOACK_MIN_LEN;
length -= ND_RPL_DAOACK_MIN_LEN;
if(RPL_DAOACK_D(daoack->rpl_flags)) {
ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, daoack->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]",
dagid_str,
daoack->rpl_daoseq,
daoack->rpl_instanceid,
daoack->rpl_status));
/* no officially defined options for DAOACK, but print any we find */
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo, "%s", rpl_tstr));
return;
tooshort:
ND_PRINT((ndo," [|dao-length too short]"));
return;
}
| 169,829
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: DirectoryEntrySync* DirectoryEntrySync::getDirectory(const String& path, const Dictionary& options, ExceptionState& exceptionState)
{
FileSystemFlags flags(options);
RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create();
m_fileSystem->getDirectory(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return static_cast<DirectoryEntrySync*>(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
|
DirectoryEntrySync* DirectoryEntrySync::getDirectory(const String& path, const Dictionary& options, ExceptionState& exceptionState)
{
FileSystemFlags flags(options);
EntrySyncCallbackHelper* helper = EntrySyncCallbackHelper::create();
m_fileSystem->getDirectory(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return static_cast<DirectoryEntrySync*>(helper->getResult(exceptionState));
}
| 171,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: static bool blit_is_unsafe(struct CirrusVGAState *s)
{
/* should be the case, see cirrus_bitblt_start */
assert(s->cirrus_blt_width > 0);
assert(s->cirrus_blt_height > 0);
if (blit_region_is_unsafe(s, s->cirrus_blt_dstpitch,
s->cirrus_blt_dstaddr & s->cirrus_addr_mask)) {
return true;
}
return false;
}
Commit Message:
CWE ID: CWE-119
|
static bool blit_is_unsafe(struct CirrusVGAState *s)
{
/* should be the case, see cirrus_bitblt_start */
assert(s->cirrus_blt_width > 0);
assert(s->cirrus_blt_height > 0);
if (s->cirrus_blt_width > CIRRUS_BLTBUFSIZE) {
return true;
}
if (blit_region_is_unsafe(s, s->cirrus_blt_dstpitch,
s->cirrus_blt_dstaddr & s->cirrus_addr_mask)) {
return true;
}
return false;
}
| 164,894
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 TabLifecycleUnitSource::TabLifecycleUnit::CanFreeze(
DecisionDetails* decision_details) const {
DCHECK(decision_details->reasons().empty());
if (!IsValidStateChange(GetState(), LifecycleUnitState::PENDING_FREEZE,
StateChangeReason::BROWSER_INITIATED)) {
return false;
}
if (TabLoadTracker::Get()->GetLoadingState(GetWebContents()) !=
TabLoadTracker::LoadingState::LOADED) {
return false;
}
if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE)
decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE);
IsMediaTabImpl(decision_details);
if (decision_details->reasons().empty()) {
decision_details->AddReason(
DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE);
DCHECK(decision_details->IsPositive());
}
return decision_details->IsPositive();
}
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:
|
bool TabLifecycleUnitSource::TabLifecycleUnit::CanFreeze(
DecisionDetails* decision_details) const {
DCHECK(decision_details->reasons().empty());
if (!IsValidStateChange(GetState(), LifecycleUnitState::PENDING_FREEZE,
StateChangeReason::BROWSER_INITIATED)) {
return false;
}
if (TabLoadTracker::Get()->GetLoadingState(GetWebContents()) !=
TabLoadTracker::LoadingState::LOADED) {
return false;
}
if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE)
decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE);
IsMediaTabImpl(decision_details);
// Consult the local database to see if this tab could try to communicate with
// the user while in background (don't check for the visibility here as
// there's already a check for that above).
CheckIfTabCanCommunicateWithUserWhileInBackground(GetWebContents(),
decision_details);
if (decision_details->reasons().empty()) {
decision_details->AddReason(
DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE);
}
return decision_details->IsPositive();
}
| 172,219
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool ChromeContentRendererClient::WillSendRequest(WebKit::WebFrame* frame,
const GURL& url,
GURL* new_url) {
if (url.SchemeIs(chrome::kExtensionScheme) &&
!ExtensionResourceRequestPolicy::CanRequestResource(
url,
GURL(frame->document().url()),
extension_dispatcher_->extensions())) {
*new_url = GURL("chrome-extension://invalid/");
return true;
}
return false;
}
Commit Message: Do not require DevTools extension resources to be white-listed in manifest.
Currently, resources used by DevTools extensions need to be white-listed as web_accessible_resources in manifest. This is quite inconvenitent and appears to be an overkill, given the fact that DevTools front-end is
(a) trusted and
(b) picky on the frames it loads.
This change adds resources that belong to DevTools extensions and are being loaded into a DevTools front-end page to the list of exceptions from web_accessible_resources check.
BUG=none
TEST=DevToolsExtensionTest.*
Review URL: https://chromiumcodereview.appspot.com/9663076
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126378 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
bool ChromeContentRendererClient::WillSendRequest(WebKit::WebFrame* frame,
const GURL& url,
GURL* new_url) {
if (url.SchemeIs(chrome::kExtensionScheme) &&
!ExtensionResourceRequestPolicy::CanRequestResource(
url,
frame,
extension_dispatcher_->extensions())) {
*new_url = GURL("chrome-extension://invalid/");
return true;
}
return false;
}
| 171,000
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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, setMaxLineLen)
{
long max_len;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) {
return;
}
if (max_len < 0) {
zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero");
return;
}
intern->u.file.max_line_len = max_len;
} /* }}} */
/* {{{ proto int SplFileObject::getMaxLineLen()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileObject, setMaxLineLen)
{
long max_len;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) {
return;
}
if (max_len < 0) {
zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero");
return;
}
intern->u.file.max_line_len = max_len;
} /* }}} */
/* {{{ proto int SplFileObject::getMaxLineLen()
| 167,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: static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
AVFilterContext *ctx = inlink->dst;
BoxBlurContext *s = ctx->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFrame *out;
int plane;
int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub);
int w[4] = { inlink->w, cw, cw, inlink->w };
int h[4] = { in->height, ch, ch, in->height };
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
for (plane = 0; in->data[plane] && plane < 4; plane++)
hblur(out->data[plane], out->linesize[plane],
in ->data[plane], in ->linesize[plane],
w[plane], h[plane], s->radius[plane], s->power[plane],
s->temp);
for (plane = 0; in->data[plane] && plane < 4; plane++)
vblur(out->data[plane], out->linesize[plane],
out->data[plane], out->linesize[plane],
w[plane], h[plane], s->radius[plane], s->power[plane],
s->temp);
av_frame_free(&in);
return ff_filter_frame(outlink, out);
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>
CWE ID: CWE-119
|
static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
AVFilterContext *ctx = inlink->dst;
BoxBlurContext *s = ctx->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFrame *out;
int plane;
int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub);
int w[4] = { inlink->w, cw, cw, inlink->w };
int h[4] = { in->height, ch, ch, in->height };
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++)
hblur(out->data[plane], out->linesize[plane],
in ->data[plane], in ->linesize[plane],
w[plane], h[plane], s->radius[plane], s->power[plane],
s->temp);
for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++)
vblur(out->data[plane], out->linesize[plane],
out->data[plane], out->linesize[plane],
w[plane], h[plane], s->radius[plane], s->power[plane],
s->temp);
av_frame_free(&in);
return ff_filter_frame(outlink, out);
}
| 165,997
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 ChromeOSSetImeConfig(InputMethodStatusConnection* connection,
const char* section,
const char* config_name,
const ImeConfigValue& value) {
DCHECK(section);
DCHECK(config_name);
g_return_val_if_fail(connection, FALSE);
return connection->SetImeConfig(section, config_name, value);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool ChromeOSSetImeConfig(InputMethodStatusConnection* connection,
| 170,526
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
Commit Message: http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=26861
CWE ID: CWE-399
|
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
if (SeekBlob(image,offset,SEEK_CUR) < 0)
break;
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
| 170,122
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int main(int argc, char *argv[]) {
struct mschm_decompressor *chmd;
struct mschmd_header *chm;
struct mschmd_file *file, **f;
unsigned int numf, i;
setbuf(stdout, NULL);
setbuf(stderr, NULL);
user_umask = umask(0); umask(user_umask);
MSPACK_SYS_SELFTEST(i);
if (i) return 0;
if ((chmd = mspack_create_chm_decompressor(NULL))) {
for (argv++; *argv; argv++) {
printf("%s\n", *argv);
if ((chm = chmd->open(chmd, *argv))) {
/* build an ordered list of files for maximum extraction speed */
for (numf=0, file=chm->files; file; file = file->next) numf++;
if ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) {
for (i=0, file=chm->files; file; file = file->next) f[i++] = file;
qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc);
for (i = 0; i < numf; i++) {
char *outname = create_output_name((unsigned char *)f[i]->filename,NULL,0,1,0);
printf("Extracting %s\n", outname);
ensure_filepath(outname);
if (chmd->extract(chmd, f[i], outname)) {
printf("%s: extract error on \"%s\": %s\n",
*argv, f[i]->filename, ERROR(chmd));
}
free(outname);
}
free(f);
}
chmd->close(chmd, chm);
}
else {
printf("%s: can't open -- %s\n", *argv, ERROR(chmd));
}
}
mspack_destroy_chm_decompressor(chmd);
}
return 0;
}
Commit Message: add anti "../" and leading slash protection to chmextract
CWE ID: CWE-22
|
int main(int argc, char *argv[]) {
struct mschm_decompressor *chmd;
struct mschmd_header *chm;
struct mschmd_file *file, **f;
unsigned int numf, i;
setbuf(stdout, NULL);
setbuf(stderr, NULL);
user_umask = umask(0); umask(user_umask);
MSPACK_SYS_SELFTEST(i);
if (i) return 0;
if ((chmd = mspack_create_chm_decompressor(NULL))) {
for (argv++; *argv; argv++) {
printf("%s\n", *argv);
if ((chm = chmd->open(chmd, *argv))) {
/* build an ordered list of files for maximum extraction speed */
for (numf=0, file=chm->files; file; file = file->next) numf++;
if ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) {
for (i=0, file=chm->files; file; file = file->next) f[i++] = file;
qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc);
for (i = 0; i < numf; i++) {
char *outname = create_output_name(f[i]->filename);
printf("Extracting %s\n", outname);
ensure_filepath(outname);
if (chmd->extract(chmd, f[i], outname)) {
printf("%s: extract error on \"%s\": %s\n",
*argv, f[i]->filename, ERROR(chmd));
}
free(outname);
}
free(f);
}
chmd->close(chmd, chm);
}
else {
printf("%s: can't open -- %s\n", *argv, ERROR(chmd));
}
}
mspack_destroy_chm_decompressor(chmd);
}
return 0;
}
| 169,002
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 WorkerProcessLauncher::Core::OnChannelConnected(int32 peer_pid) {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
if (ipc_enabled_)
worker_delegate_->OnChannelConnected();
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void WorkerProcessLauncher::Core::OnChannelConnected(int32 peer_pid) {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
if (!ipc_enabled_)
return;
// Verify |peer_pid| because it is controlled by the client and cannot be
// trusted.
DWORD actual_pid = launcher_delegate_->GetProcessId();
if (peer_pid != static_cast<int32>(actual_pid)) {
LOG(ERROR) << "The actual client PID " << actual_pid
<< " does not match the one reported by the client: "
<< peer_pid;
StopWorker();
return;
}
worker_delegate_->OnChannelConnected(peer_pid);
}
| 171,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: virtual status_t configureVideoTunnelMode(
node_id node, OMX_U32 portIndex, OMX_BOOL tunneled,
OMX_U32 audioHwSync, native_handle_t **sidebandHandle ) {
Parcel data, reply;
data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
data.writeInt32((int32_t)node);
data.writeInt32(portIndex);
data.writeInt32((int32_t)tunneled);
data.writeInt32(audioHwSync);
remote()->transact(CONFIGURE_VIDEO_TUNNEL_MODE, data, &reply);
status_t err = reply.readInt32();
if (sidebandHandle) {
*sidebandHandle = (native_handle_t *)reply.readNativeHandle();
}
return err;
}
Commit Message: IOMX.cpp uninitialized pointer in BnOMX::onTransact
This can lead to local code execution in media server.
Fix initializes the pointer and checks the error conditions before
returning
Bug: 26403627
Change-Id: I7fa90682060148448dba01d6acbe3471d1ddb500
CWE ID: CWE-264
|
virtual status_t configureVideoTunnelMode(
node_id node, OMX_U32 portIndex, OMX_BOOL tunneled,
OMX_U32 audioHwSync, native_handle_t **sidebandHandle ) {
Parcel data, reply;
data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
data.writeInt32((int32_t)node);
data.writeInt32(portIndex);
data.writeInt32((int32_t)tunneled);
data.writeInt32(audioHwSync);
remote()->transact(CONFIGURE_VIDEO_TUNNEL_MODE, data, &reply);
status_t err = reply.readInt32();
if (err == OK && sidebandHandle) {
*sidebandHandle = (native_handle_t *)reply.readNativeHandle();
}
return err;
}
| 173,897
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: perform_gamma_composition_tests(png_modifier *pm, int do_background,
int expand_16)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
/* Skip the non-alpha cases - there is no setting of a transparency colour at
* present.
*/
while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/))
if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0)
{
unsigned int i, j;
/* Don't skip the i==j case here - it's relevant. */
for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
{
gamma_composition_test(pm, colour_type, bit_depth, palette_number,
pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
pm->use_input_precision, do_background, expand_16);
if (fail(pm))
return;
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
perform_gamma_composition_tests(png_modifier *pm, int do_background,
int expand_16)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
/* Skip the non-alpha cases - there is no setting of a transparency colour at
* present.
*
* TODO: incorrect; the palette case sets tRNS and, now RGB and gray do,
* however the palette case fails miserably so is commented out below.
*/
while (next_format(&colour_type, &bit_depth, &palette_number,
pm->test_lbg_gamma_composition, pm->test_tRNS))
if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0
#if 0 /* TODO: FIXME */
/*TODO: FIXME: this should work */
|| colour_type == 3
#endif
|| (colour_type != 3 && palette_number != 0))
{
unsigned int i, j;
/* Don't skip the i==j case here - it's relevant. */
for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
{
gamma_composition_test(pm, colour_type, bit_depth, palette_number,
pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
pm->use_input_precision, do_background, expand_16);
if (fail(pm))
return;
}
}
}
| 173,679
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int __jfs_set_acl(tid_t tid, struct inode *inode, int type,
struct posix_acl *acl)
{
char *ea_name;
int rc;
int size = 0;
char *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
ea_name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
rc = posix_acl_equiv_mode(acl, &inode->i_mode);
if (rc < 0)
return rc;
inode->i_ctime = CURRENT_TIME;
mark_inode_dirty(inode);
if (rc == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
ea_name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value)
return -ENOMEM;
rc = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (rc < 0)
goto out;
}
rc = __jfs_setxattr(tid, inode, ea_name, value, size, 0);
out:
kfree(value);
if (!rc)
set_cached_acl(inode, type, acl);
return rc;
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <hch@lst.de>
Reviewed-by: Jeff Layton <jlayton@redhat.com>
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com>
CWE ID: CWE-285
|
static int __jfs_set_acl(tid_t tid, struct inode *inode, int type,
struct posix_acl *acl)
{
char *ea_name;
int rc;
int size = 0;
char *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
ea_name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
rc = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (rc)
return rc;
inode->i_ctime = CURRENT_TIME;
mark_inode_dirty(inode);
}
break;
case ACL_TYPE_DEFAULT:
ea_name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value)
return -ENOMEM;
rc = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (rc < 0)
goto out;
}
rc = __jfs_setxattr(tid, inode, ea_name, value, size, 0);
out:
kfree(value);
if (!rc)
set_cached_acl(inode, type, acl);
return rc;
}
| 166,975
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 Layer::SetScrollOffset(gfx::Vector2d scroll_offset) {
DCHECK(IsPropertyChangeAllowed());
if (layer_tree_host()) {
scroll_offset = layer_tree_host()->DistributeScrollOffsetToViewports(
scroll_offset, this);
}
if (scroll_offset_ == scroll_offset)
return;
scroll_offset_ = scroll_offset;
SetNeedsCommit();
}
Commit Message: Removed pinch viewport scroll offset distribution
The associated change in Blink makes the pinch viewport a proper
ScrollableArea meaning the normal path for synchronizing layer scroll
offsets is used.
This is a 2 sided patch, the other CL:
https://codereview.chromium.org/199253002/
BUG=349941
Review URL: https://codereview.chromium.org/210543002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260105 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void Layer::SetScrollOffset(gfx::Vector2d scroll_offset) {
DCHECK(IsPropertyChangeAllowed());
if (scroll_offset_ == scroll_offset)
return;
scroll_offset_ = scroll_offset;
SetNeedsCommit();
}
| 171,198
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 readpng2_warning_handler(png_structp png_ptr, png_const_charp msg)
{
fprintf(stderr, "readpng2 libpng warning: %s\n", msg);
fflush(stderr);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
static void readpng2_warning_handler(png_structp png_ptr, png_const_charp msg)
{
fprintf(stderr, "readpng2 libpng warning: %s\n", msg);
fflush(stderr);
(void)png_ptr; /* Unused */
}
| 173,571
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 opl3_panning(int dev, int voice, int value)
{
devc->voc[voice].panning = value;
}
Commit Message: sound/oss/opl3: validate voice and channel indexes
User-controllable indexes for voice and channel values may cause reading
and writing beyond the bounds of their respective arrays, leading to
potentially exploitable memory corruption. Validate these indexes.
Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com>
Cc: stable@kernel.org
Signed-off-by: Takashi Iwai <tiwai@suse.de>
CWE ID: CWE-119
|
static void opl3_panning(int dev, int voice, int value)
{
if (voice < 0 || voice >= devc->nr_voice)
return;
devc->voc[voice].panning = value;
}
| 165,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: ssize_t socket_write(const socket_t *socket, const void *buf, size_t count) {
assert(socket != NULL);
assert(buf != NULL);
return send(socket->fd, buf, count, MSG_DONTWAIT);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
ssize_t socket_write(const socket_t *socket, const void *buf, size_t count) {
assert(socket != NULL);
assert(buf != NULL);
return TEMP_FAILURE_RETRY(send(socket->fd, buf, count, MSG_DONTWAIT));
}
| 173,487
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: set_store_for_write(png_store *ps, png_infopp ppi,
PNG_CONST char * volatile name)
{
anon_context(ps);
Try
{
if (ps->pwrite != NULL)
png_error(ps->pwrite, "write store already in use");
store_write_reset(ps);
safecat(ps->wname, sizeof ps->wname, 0, name);
/* Don't do the slow memory checks if doing a speed test, also if user
* memory is not supported we can't do it anyway.
*/
# ifdef PNG_USER_MEM_SUPPORTED
if (!ps->speed)
ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
ps, store_error, store_warning, &ps->write_memory_pool,
store_malloc, store_free);
else
# endif
ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING,
ps, store_error, store_warning);
png_set_write_fn(ps->pwrite, ps, store_write, store_flush);
# ifdef PNG_SET_OPTION_SUPPORTED
{
int opt;
for (opt=0; opt<ps->noptions; ++opt)
if (png_set_option(ps->pwrite, ps->options[opt].option,
ps->options[opt].setting) == PNG_OPTION_INVALID)
png_error(ps->pwrite, "png option invalid");
}
# endif
if (ppi != NULL)
*ppi = ps->piwrite = png_create_info_struct(ps->pwrite);
}
Catch_anonymous
return NULL;
return ps->pwrite;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
set_store_for_write(png_store *ps, png_infopp ppi,
set_store_for_write(png_store *ps, png_infopp ppi, const char *name)
{
anon_context(ps);
Try
{
if (ps->pwrite != NULL)
png_error(ps->pwrite, "write store already in use");
store_write_reset(ps);
safecat(ps->wname, sizeof ps->wname, 0, name);
/* Don't do the slow memory checks if doing a speed test, also if user
* memory is not supported we can't do it anyway.
*/
# ifdef PNG_USER_MEM_SUPPORTED
if (!ps->speed)
ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
ps, store_error, store_warning, &ps->write_memory_pool,
store_malloc, store_free);
else
# endif
ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING,
ps, store_error, store_warning);
png_set_write_fn(ps->pwrite, ps, store_write, store_flush);
# ifdef PNG_SET_OPTION_SUPPORTED
{
int opt;
for (opt=0; opt<ps->noptions; ++opt)
if (png_set_option(ps->pwrite, ps->options[opt].option,
ps->options[opt].setting) == PNG_OPTION_INVALID)
png_error(ps->pwrite, "png option invalid");
}
# endif
if (ppi != NULL)
*ppi = ps->piwrite = png_create_info_struct(ps->pwrite);
}
Catch_anonymous
return NULL;
return ps->pwrite;
}
| 173,696
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SSLErrorHandler::SSLErrorHandler(base::WeakPtr<Delegate> delegate,
const content::GlobalRequestID& id,
ResourceType::Type resource_type,
const GURL& url,
int render_process_id,
int render_view_id)
: manager_(NULL),
request_id_(id),
delegate_(delegate),
render_process_id_(render_process_id),
render_view_id_(render_view_id),
request_url_(url),
resource_type_(resource_type),
request_has_been_notified_(false) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(delegate);
AddRef();
}
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
|
SSLErrorHandler::SSLErrorHandler(base::WeakPtr<Delegate> delegate,
SSLErrorHandler::SSLErrorHandler(const base::WeakPtr<Delegate>& delegate,
const content::GlobalRequestID& id,
ResourceType::Type resource_type,
const GURL& url,
int render_process_id,
int render_view_id)
: manager_(NULL),
request_id_(id),
delegate_(delegate),
render_process_id_(render_process_id),
render_view_id_(render_view_id),
request_url_(url),
resource_type_(resource_type),
request_has_been_notified_(false) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(delegate);
AddRef();
}
| 170,995
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: server_request_direct_streamlocal(void)
{
Channel *c = NULL;
char *target, *originator;
u_short originator_port;
target = packet_get_string(NULL);
originator = packet_get_string(NULL);
originator_port = packet_get_int();
packet_check_eom();
debug("server_request_direct_streamlocal: originator %s port %d, target %s",
originator, originator_port, target);
/* XXX fine grained permissions */
if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
!no_port_forwarding_flag && !options.disable_forwarding) {
c = channel_connect_to_path(target,
"direct-streamlocal@openssh.com", "direct-streamlocal");
} else {
logit("refused streamlocal port forward: "
"originator %s port %d, target %s",
originator, originator_port, target);
}
free(originator);
free(target);
return c;
}
Commit Message: disable Unix-domain socket forwarding when privsep is disabled
CWE ID: CWE-264
|
server_request_direct_streamlocal(void)
{
Channel *c = NULL;
char *target, *originator;
u_short originator_port;
target = packet_get_string(NULL);
originator = packet_get_string(NULL);
originator_port = packet_get_int();
packet_check_eom();
debug("server_request_direct_streamlocal: originator %s port %d, target %s",
originator, originator_port, target);
/* XXX fine grained permissions */
if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
!no_port_forwarding_flag && !options.disable_forwarding &&
use_privsep) {
c = channel_connect_to_path(target,
"direct-streamlocal@openssh.com", "direct-streamlocal");
} else {
logit("refused streamlocal port forward: "
"originator %s port %d, target %s",
originator, originator_port, target);
}
free(originator);
free(target);
return c;
}
| 168,662
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 setup_test_dir(char *tmp_dir, const char *files, ...) {
va_list ap;
assert_se(mkdtemp(tmp_dir) != NULL);
va_start(ap, files);
while (files != NULL) {
_cleanup_free_ char *path = strappend(tmp_dir, files);
assert_se(touch_file(path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0) == 0);
files = va_arg(ap, const char *);
}
va_end(ap);
}
Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere
CWE ID: CWE-264
|
static void setup_test_dir(char *tmp_dir, const char *files, ...) {
va_list ap;
assert_se(mkdtemp(tmp_dir) != NULL);
va_start(ap, files);
while (files != NULL) {
_cleanup_free_ char *path = strappend(tmp_dir, files);
assert_se(touch_file(path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID) == 0);
files = va_arg(ap, const char *);
}
va_end(ap);
}
| 170,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: kdc_process_s4u_x509_user(krb5_context context,
krb5_kdc_req *request,
krb5_pa_data *pa_data,
krb5_keyblock *tgs_subkey,
krb5_keyblock *tgs_session,
krb5_pa_s4u_x509_user **s4u_x509_user,
const char **status)
{
krb5_error_code code;
krb5_data req_data;
req_data.length = pa_data->length;
req_data.data = (char *)pa_data->contents;
code = decode_krb5_pa_s4u_x509_user(&req_data, s4u_x509_user);
if (code)
return code;
code = verify_s4u_x509_user_checksum(context,
tgs_subkey ? tgs_subkey :
tgs_session,
&req_data,
request->nonce, *s4u_x509_user);
if (code) {
*status = "INVALID_S4U2SELF_CHECKSUM";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return code;
}
if (krb5_princ_size(context, (*s4u_x509_user)->user_id.user) == 0 ||
(*s4u_x509_user)->user_id.subject_cert.length != 0) {
*status = "INVALID_S4U2SELF_REQUEST";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
}
return 0;
}
Commit Message: Prevent KDC unset status assertion failures
Assign status values if S4U2Self padata fails to decode, if an
S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request
uses an evidence ticket which does not match the canonicalized request
server principal name. Reported by Samuel Cabrero.
If a status value is not assigned during KDC processing, default to
"UNKNOWN_REASON" rather than failing an assertion. This change will
prevent future denial of service bugs due to similar mistakes, and
will allow us to omit assigning status values for unlikely errors such
as small memory allocation failures.
CVE-2017-11368:
In MIT krb5 1.7 and later, an authenticated attacker can cause an
assertion failure in krb5kdc by sending an invalid S4U2Self or
S4U2Proxy request.
CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C
ticket: 8599 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-617
|
kdc_process_s4u_x509_user(krb5_context context,
krb5_kdc_req *request,
krb5_pa_data *pa_data,
krb5_keyblock *tgs_subkey,
krb5_keyblock *tgs_session,
krb5_pa_s4u_x509_user **s4u_x509_user,
const char **status)
{
krb5_error_code code;
krb5_data req_data;
req_data.length = pa_data->length;
req_data.data = (char *)pa_data->contents;
code = decode_krb5_pa_s4u_x509_user(&req_data, s4u_x509_user);
if (code) {
*status = "DECODE_PA_S4U_X509_USER";
return code;
}
code = verify_s4u_x509_user_checksum(context,
tgs_subkey ? tgs_subkey :
tgs_session,
&req_data,
request->nonce, *s4u_x509_user);
if (code) {
*status = "INVALID_S4U2SELF_CHECKSUM";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return code;
}
if (krb5_princ_size(context, (*s4u_x509_user)->user_id.user) == 0 ||
(*s4u_x509_user)->user_id.subject_cert.length != 0) {
*status = "INVALID_S4U2SELF_REQUEST";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
}
return 0;
}
| 168,043
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: CmdBufferImageTransportFactory::CreateSharedSurfaceHandle() {
if (!context_->makeContextCurrent()) {
NOTREACHED() << "Failed to make shared graphics context current";
return gfx::GLSurfaceHandle();
}
gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
gfx::kNullPluginWindow, true);
handle.parent_gpu_process_id = context_->GetGPUProcessID();
handle.parent_client_id = context_->GetChannelID();
handle.parent_context_id = context_->GetContextID();
handle.parent_texture_id[0] = context_->createTexture();
handle.parent_texture_id[1] = context_->createTexture();
handle.sync_point = context_->insertSyncPoint();
context_->flush();
return handle;
}
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:
|
CmdBufferImageTransportFactory::CreateSharedSurfaceHandle() {
if (!context_->makeContextCurrent()) {
NOTREACHED() << "Failed to make shared graphics context current";
return gfx::GLSurfaceHandle();
}
gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
gfx::kNullPluginWindow, true);
handle.parent_gpu_process_id = context_->GetGPUProcessID();
context_->flush();
return handle;
}
| 171,363
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 SoftGSM::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 8000;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftGSM::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 8000;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,207
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int skt_write(int fd, const void *p, size_t len)
{
int sent;
struct pollfd pfd;
FNLOG();
pfd.fd = fd;
pfd.events = POLLOUT;
/* poll for 500 ms */
/* send time out */
if (poll(&pfd, 1, 500) == 0)
return 0;
ts_log("skt_write", len, NULL);
if ((sent = send(fd, p, len, MSG_NOSIGNAL)) == -1)
{
ERROR("write failed with errno=%d\n", errno);
return -1;
}
return sent;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static int skt_write(int fd, const void *p, size_t len)
{
int sent;
struct pollfd pfd;
FNLOG();
pfd.fd = fd;
pfd.events = POLLOUT;
/* poll for 500 ms */
/* send time out */
if (TEMP_FAILURE_RETRY(poll(&pfd, 1, 500)) == 0)
return 0;
ts_log("skt_write", len, NULL);
if ((sent = TEMP_FAILURE_RETRY(send(fd, p, len, MSG_NOSIGNAL))) == -1)
{
ERROR("write failed with errno=%d\n", errno);
return -1;
}
return sent;
}
| 173,429
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 Cluster* BlockEntry::GetCluster() const
{
return m_pCluster;
}
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 Cluster* BlockEntry::GetCluster() const
| 174,291
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 Editor::insertTextWithoutSendingTextEvent(const String& text,
bool selectInsertedText,
TextEvent* triggeringEvent) {
if (text.isEmpty())
return false;
const VisibleSelection& selection = selectionForCommand(triggeringEvent);
if (!selection.isContentEditable())
return false;
spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
TypingCommand::insertText(
*selection.start().document(), text, selection,
selectInsertedText ? TypingCommand::SelectInsertedText : 0,
triggeringEvent && triggeringEvent->isComposition()
? TypingCommand::TextCompositionConfirm
: TypingCommand::TextCompositionNone);
if (LocalFrame* editedFrame = selection.start().document()->frame()) {
if (Page* page = editedFrame->page()) {
LocalFrame* focusedOrMainFrame =
toLocalFrame(page->focusController().focusedOrMainFrame());
focusedOrMainFrame->selection().revealSelection(
ScrollAlignment::alignCenterIfNeeded);
}
}
return true;
}
Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection
This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree|
instead of |VisibleSelection| to reduce usage of |VisibleSelection| for
improving code health.
BUG=657237
TEST=n/a
Review-Url: https://codereview.chromium.org/2733183002
Cr-Commit-Position: refs/heads/master@{#455368}
CWE ID:
|
bool Editor::insertTextWithoutSendingTextEvent(const String& text,
bool selectInsertedText,
TextEvent* triggeringEvent) {
if (text.isEmpty())
return false;
const VisibleSelection& selection = selectionForCommand(triggeringEvent);
if (!selection.isContentEditable())
return false;
spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
TypingCommand::insertText(
*selection.start().document(), text, selection.asSelection(),
selectInsertedText ? TypingCommand::SelectInsertedText : 0,
triggeringEvent && triggeringEvent->isComposition()
? TypingCommand::TextCompositionConfirm
: TypingCommand::TextCompositionNone);
if (LocalFrame* editedFrame = selection.start().document()->frame()) {
if (Page* page = editedFrame->page()) {
LocalFrame* focusedOrMainFrame =
toLocalFrame(page->focusController().focusedOrMainFrame());
focusedOrMainFrame->selection().revealSelection(
ScrollAlignment::alignCenterIfNeeded);
}
}
return true;
}
| 172,030
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 ExtensionTtsSpeakFunction::SpeechFinished() {
error_ = utterance_->error();
bool success = error_.empty();
SendResponse(success);
Release(); // Balanced in RunImpl().
}
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 ExtensionTtsSpeakFunction::SpeechFinished() {
| 170,390
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) {
size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0);
icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length);
if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) ==
ustr_host.length())
transliterator_.get()->transliterate(ustr_host);
UErrorCode status = U_ZERO_ERROR;
icu::UnicodeString ustr_skeleton;
uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton,
&status);
if (U_FAILURE(status))
return false;
std::string skeleton;
ustr_skeleton.toUTF8String(skeleton);
return LookupMatchInTopDomains(skeleton);
}
Commit Message: Add a few more confusable map entries
1. Map Malaylam U+0D1F to 's'.
2. Map 'small-cap-like' Cyrillic letters to "look-alike" Latin lowercase
letters.
The characters in new confusable map entries are replaced by their Latin
"look-alike" characters before the skeleton is calculated to compare with
top domain names.
Bug: 784761,773930
Test: components_unittests --gtest_filter=*IDNToUni*
Change-Id: Ib26664e21ac5eb290e4a2993b01cbf0edaade0ee
Reviewed-on: https://chromium-review.googlesource.com/805214
Reviewed-by: Peter Kasting <pkasting@chromium.org>
Commit-Queue: Jungshik Shin <jshin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#521648}
CWE ID: CWE-20
|
bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) {
size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0);
icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length);
if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) ==
ustr_host.length())
diacritic_remover_.get()->transliterate(ustr_host);
extra_confusable_mapper_.get()->transliterate(ustr_host);
UErrorCode status = U_ZERO_ERROR;
icu::UnicodeString ustr_skeleton;
uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton,
&status);
if (U_FAILURE(status))
return false;
std::string skeleton;
return LookupMatchInTopDomains(ustr_skeleton.toUTF8String(skeleton));
}
| 172,686
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: jbig2_page_add_result(Jbig2Ctx *ctx, Jbig2Page *page, Jbig2Image *image, int x, int y, Jbig2ComposeOp op)
{
/* ensure image exists first */
if (page->image == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "page info possibly missing, no image defined");
return 0;
}
/* grow the page to accomodate a new stripe if necessary */
if (page->striped) {
int new_height = y + image->height + page->end_row;
if (page->image->height < new_height) {
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "growing page buffer to %d rows " "to accomodate new stripe", new_height);
jbig2_image_resize(ctx, page->image, page->image->width, new_height);
}
}
jbig2_image_compose(ctx, page->image, image, x, y + page->end_row, op);
return 0;
}
Commit Message:
CWE ID: CWE-119
|
jbig2_page_add_result(Jbig2Ctx *ctx, Jbig2Page *page, Jbig2Image *image, int x, int y, Jbig2ComposeOp op)
{
/* ensure image exists first */
if (page->image == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "page info possibly missing, no image defined");
return 0;
}
/* grow the page to accomodate a new stripe if necessary */
if (page->striped) {
uint32_t new_height = y + image->height + page->end_row;
if (page->image->height < new_height) {
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "growing page buffer to %d rows " "to accomodate new stripe", new_height);
jbig2_image_resize(ctx, page->image, page->image->width, new_height);
}
}
jbig2_image_compose(ctx, page->image, image, x, y + page->end_row, op);
return 0;
}
| 165,496
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void FrameLoader::StopAllLoaders() {
if (frame_->GetDocument()->PageDismissalEventBeingDispatched() !=
Document::kNoDismissal)
return;
if (in_stop_all_loaders_)
return;
in_stop_all_loaders_ = true;
for (Frame* child = frame_->Tree().FirstChild(); child;
child = child->Tree().NextSibling()) {
if (child->IsLocalFrame())
ToLocalFrame(child)->Loader().StopAllLoaders();
}
frame_->GetDocument()->CancelParsing();
if (document_loader_)
document_loader_->Fetcher()->StopFetching();
if (!protect_provisional_loader_)
DetachDocumentLoader(provisional_document_loader_);
frame_->GetNavigationScheduler().Cancel();
if (document_loader_ && !document_loader_->SentDidFinishLoad()) {
document_loader_->LoadFailed(
ResourceError::CancelledError(document_loader_->Url()));
}
in_stop_all_loaders_ = false;
TakeObjectSnapshot();
}
Commit Message: Fix detach with open()ed document leaving parent loading indefinitely
Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6
Bug: 803416
Test: fast/loader/document-open-iframe-then-detach.html
Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6
Reviewed-on: https://chromium-review.googlesource.com/887298
Reviewed-by: Mike West <mkwst@chromium.org>
Commit-Queue: Nate Chapin <japhet@chromium.org>
Cr-Commit-Position: refs/heads/master@{#532967}
CWE ID: CWE-362
|
void FrameLoader::StopAllLoaders() {
if (frame_->GetDocument()->PageDismissalEventBeingDispatched() !=
Document::kNoDismissal)
return;
if (in_stop_all_loaders_)
return;
AutoReset<bool> in_stop_all_loaders(&in_stop_all_loaders_, true);
for (Frame* child = frame_->Tree().FirstChild(); child;
child = child->Tree().NextSibling()) {
if (child->IsLocalFrame())
ToLocalFrame(child)->Loader().StopAllLoaders();
}
frame_->GetDocument()->CancelParsing();
if (document_loader_)
document_loader_->StopLoading();
if (!protect_provisional_loader_)
DetachDocumentLoader(provisional_document_loader_);
frame_->GetNavigationScheduler().Cancel();
DidFinishNavigation();
TakeObjectSnapshot();
}
| 171,852
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PepperMediaDeviceManager* PepperMediaDeviceManager::GetForRenderFrame(
RenderFrame* render_frame) {
PepperMediaDeviceManager* handler =
PepperMediaDeviceManager::Get(render_frame);
if (!handler)
handler = new PepperMediaDeviceManager(render_frame);
return handler;
}
Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr
Its lifetime is scoped to the RenderFrame, and it might go away before the
hosts that refer to it.
BUG=423030
Review URL: https://codereview.chromium.org/653243003
Cr-Commit-Position: refs/heads/master@{#299897}
CWE ID: CWE-399
|
PepperMediaDeviceManager* PepperMediaDeviceManager::GetForRenderFrame(
base::WeakPtr<PepperMediaDeviceManager>
PepperMediaDeviceManager::GetForRenderFrame(
RenderFrame* render_frame) {
PepperMediaDeviceManager* handler =
PepperMediaDeviceManager::Get(render_frame);
if (!handler)
handler = new PepperMediaDeviceManager(render_frame);
return handler->AsWeakPtr();
}
| 171,608
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void php_mcrypt_module_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */
{
php_mcrypt *pm = (php_mcrypt *) rsrc->ptr;
if (pm) {
mcrypt_generic_deinit(pm->td);
mcrypt_module_close(pm->td);
efree(pm);
pm = NULL;
}
}
/* }}} */
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
|
static void php_mcrypt_module_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */
{
php_mcrypt *pm = (php_mcrypt *) rsrc->ptr;
if (pm) {
mcrypt_generic_deinit(pm->td);
mcrypt_module_close(pm->td);
efree(pm);
pm = NULL;
}
}
/* }}} */
| 167,114
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ContentEncoding::ContentCompression::~ContentCompression() {
delete [] settings;
}
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
|
ContentEncoding::ContentCompression::~ContentCompression() {
delete[] settings;
}
| 174,459
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: get_html_data (MAPI_Attr *a)
{
VarLenData **body = XCALLOC(VarLenData*, a->num_values + 1);
int j;
for (j = 0; j < a->num_values; j++)
{
body[j] = XMALLOC(VarLenData, 1);
body[j]->len = a->values[j].len;
body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);
memmove (body[j]->data, a->values[j].data.buf, body[j]->len);
}
return body;
}
Commit Message: Check types to avoid invalid reads/writes.
CWE ID: CWE-125
|
get_html_data (MAPI_Attr *a)
{
VarLenData **body = XCALLOC(VarLenData*, a->num_values + 1);
int j;
for (j = 0; j < a->num_values; j++)
{
if (a->type == szMAPI_BINARY) {
body[j] = XMALLOC(VarLenData, 1);
body[j]->len = a->values[j].len;
body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);
memmove (body[j]->data, a->values[j].data.buf, body[j]->len);
}
}
return body;
}
| 168,352
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: InputMethodLibrary* CrosLibrary::GetInputMethodLibrary() {
return input_method_lib_.GetDefaultImpl(use_stub_impl_);
}
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
|
InputMethodLibrary* CrosLibrary::GetInputMethodLibrary() {
| 170,623
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 char* Chapters::Display::GetLanguage() const
{
return m_language;
}
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 char* Chapters::Display::GetLanguage() const
| 174,336
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData)
{
Mutex::Autolock _l(mLock);
ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
if (mState == DESTROYED || mEffectInterface == NULL) {
return NO_INIT;
}
if (mStatus != NO_ERROR) {
return mStatus;
}
if (cmdCode == EFFECT_CMD_GET_PARAM &&
(*replySize < sizeof(effect_param_t) ||
((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) {
android_errorWriteLog(0x534e4554, "29251553");
return -EINVAL;
}
status_t status = (*mEffectInterface)->command(mEffectInterface,
cmdCode,
cmdSize,
pCmdData,
replySize,
pReplyData);
if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
uint32_t size = (replySize == NULL) ? 0 : *replySize;
for (size_t i = 1; i < mHandles.size(); i++) {
EffectHandle *h = mHandles[i];
if (h != NULL && !h->destroyed_l()) {
h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
}
}
}
return status;
}
Commit Message: Add EFFECT_CMD_SET_PARAM parameter checking
Bug: 30204301
Change-Id: Ib9c3ee1c2f23c96f8f7092dd9e146bc453d7a290
(cherry picked from commit e4a1d91501d47931dbae19c47815952378787ab6)
CWE ID: CWE-200
|
status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData)
{
Mutex::Autolock _l(mLock);
ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
if (mState == DESTROYED || mEffectInterface == NULL) {
return NO_INIT;
}
if (mStatus != NO_ERROR) {
return mStatus;
}
if (cmdCode == EFFECT_CMD_GET_PARAM &&
(*replySize < sizeof(effect_param_t) ||
((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) {
android_errorWriteLog(0x534e4554, "29251553");
return -EINVAL;
}
if ((cmdCode == EFFECT_CMD_SET_PARAM
|| cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) && // DEFERRED not generally used
(sizeof(effect_param_t) > cmdSize
|| ((effect_param_t *)pCmdData)->psize > cmdSize
- sizeof(effect_param_t)
|| ((effect_param_t *)pCmdData)->vsize > cmdSize
- sizeof(effect_param_t)
- ((effect_param_t *)pCmdData)->psize
|| roundUpDelta(((effect_param_t *)pCmdData)->psize, (uint32_t)sizeof(int)) >
cmdSize
- sizeof(effect_param_t)
- ((effect_param_t *)pCmdData)->psize
- ((effect_param_t *)pCmdData)->vsize)) {
android_errorWriteLog(0x534e4554, "30204301");
return -EINVAL;
}
status_t status = (*mEffectInterface)->command(mEffectInterface,
cmdCode,
cmdSize,
pCmdData,
replySize,
pReplyData);
if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
uint32_t size = (replySize == NULL) ? 0 : *replySize;
for (size_t i = 1; i < mHandles.size(); i++) {
EffectHandle *h = mHandles[i];
if (h != NULL && !h->destroyed_l()) {
h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
}
}
}
return status;
}
| 173,387
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 * gdImageGifPtr (gdImagePtr im, int *size)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
gdImageGifCtx (im, out);
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 * gdImageGifPtr (gdImagePtr im, int *size)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
if (!_gdImageGifCtx(im, out)) {
rv = gdDPExtractData(out, size);
} else {
rv = NULL;
}
out->gd_free (out);
return rv;
}
| 169,734
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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::SpeakOrEnqueue(Utterance* utterance) {
if (IsSpeaking() && utterance->can_enqueue()) {
utterance_queue_.push(utterance);
} else {
Stop();
SpeakNow(utterance);
}
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void ExtensionTtsController::SpeakOrEnqueue(Utterance* utterance) {
std::string gender;
if (options->HasKey(constants::kGenderKey))
EXTENSION_FUNCTION_VALIDATE(
options->GetString(constants::kGenderKey, &gender));
if (!gender.empty() &&
gender != constants::kGenderFemale &&
gender != constants::kGenderMale) {
error_ = constants::kErrorInvalidGender;
return false;
}
| 170,389
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: std::string SanitizeRevision(const std::string& revision) {
for (size_t i = 0; i < revision.length(); i++) {
if (!(revision[i] == '@' && i == 0)
&& !(revision[i] >= '0' && revision[i] <= '9')
&& !(revision[i] >= 'a' && revision[i] <= 'z')
&& !(revision[i] >= 'A' && revision[i] <= 'Z')) {
return std::string();
}
}
return revision;
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200
|
std::string SanitizeRevision(const std::string& revision) {
| 172,464
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 compare_img(const vpx_image_t *img1,
const vpx_image_t *img2) {
bool match = (img1->fmt == img2->fmt) &&
(img1->d_w == img2->d_w) &&
(img1->d_h == img2->d_h);
const unsigned int width_y = img1->d_w;
const unsigned int height_y = img1->d_h;
unsigned int i;
for (i = 0; i < height_y; ++i)
match = (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
width_y) == 0) && match;
const unsigned int width_uv = (img1->d_w + 1) >> 1;
const unsigned int height_uv = (img1->d_h + 1) >> 1;
for (i = 0; i < height_uv; ++i)
match = (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
width_uv) == 0) && match;
for (i = 0; i < height_uv; ++i)
match = (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_V],
img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_V],
width_uv) == 0) && match;
return match;
}
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
|
static bool compare_img(const vpx_image_t *img1,
const vpx_image_t *img2) {
bool match = (img1->fmt == img2->fmt) &&
(img1->cs == img2->cs) &&
(img1->d_w == img2->d_w) &&
(img1->d_h == img2->d_h);
const unsigned int width_y = img1->d_w;
const unsigned int height_y = img1->d_h;
unsigned int i;
for (i = 0; i < height_y; ++i)
match = (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
width_y) == 0) && match;
const unsigned int width_uv = (img1->d_w + 1) >> 1;
const unsigned int height_uv = (img1->d_h + 1) >> 1;
for (i = 0; i < height_uv; ++i)
match = (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
width_uv) == 0) && match;
for (i = 0; i < height_uv; ++i)
match = (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_V],
img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_V],
width_uv) == 0) && match;
return match;
}
| 174,541
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 ReceiverWasAdded(const RtpTransceiverState& transceiver_state) {
uintptr_t receiver_id = RTCRtpReceiver::getId(
transceiver_state.receiver_state()->webrtc_receiver().get());
for (const auto& receiver : handler_->rtp_receivers_) {
if (receiver->Id() == receiver_id)
return false;
}
return true;
}
Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl
Bug: 912074
Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8
Reviewed-on: https://chromium-review.googlesource.com/c/1411916
Commit-Queue: Guido Urdaneta <guidou@chromium.org>
Reviewed-by: Henrik Boström <hbos@chromium.org>
Cr-Commit-Position: refs/heads/master@{#622945}
CWE ID: CWE-416
|
bool ReceiverWasAdded(const RtpTransceiverState& transceiver_state) {
DCHECK(handler_);
uintptr_t receiver_id = RTCRtpReceiver::getId(
transceiver_state.receiver_state()->webrtc_receiver().get());
for (const auto& receiver : handler_->rtp_receivers_) {
if (receiver->Id() == receiver_id)
return false;
}
return true;
}
| 173,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: static int ccid3_hc_tx_getsockopt(struct sock *sk, const int optname, int len,
u32 __user *optval, int __user *optlen)
{
const struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
struct tfrc_tx_info tfrc;
const void *val;
switch (optname) {
case DCCP_SOCKOPT_CCID_TX_INFO:
if (len < sizeof(tfrc))
return -EINVAL;
tfrc.tfrctx_x = hc->tx_x;
tfrc.tfrctx_x_recv = hc->tx_x_recv;
tfrc.tfrctx_x_calc = hc->tx_x_calc;
tfrc.tfrctx_rtt = hc->tx_rtt;
tfrc.tfrctx_p = hc->tx_p;
tfrc.tfrctx_rto = hc->tx_t_rto;
tfrc.tfrctx_ipi = hc->tx_t_ipi;
len = sizeof(tfrc);
val = &tfrc;
break;
default:
return -ENOPROTOOPT;
}
if (put_user(len, optlen) || copy_to_user(optval, val, len))
return -EFAULT;
return 0;
}
Commit Message: dccp: fix info leak via getsockopt(DCCP_SOCKOPT_CCID_TX_INFO)
The CCID3 code fails to initialize the trailing padding bytes of struct
tfrc_tx_info added for alignment on 64 bit architectures. It that for
potentially leaks four bytes kernel stack via the getsockopt() syscall.
Add an explicit memset(0) before filling the structure to avoid the
info leak.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Cc: Gerrit Renker <gerrit@erg.abdn.ac.uk>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
|
static int ccid3_hc_tx_getsockopt(struct sock *sk, const int optname, int len,
u32 __user *optval, int __user *optlen)
{
const struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
struct tfrc_tx_info tfrc;
const void *val;
switch (optname) {
case DCCP_SOCKOPT_CCID_TX_INFO:
if (len < sizeof(tfrc))
return -EINVAL;
memset(&tfrc, 0, sizeof(tfrc));
tfrc.tfrctx_x = hc->tx_x;
tfrc.tfrctx_x_recv = hc->tx_x_recv;
tfrc.tfrctx_x_calc = hc->tx_x_calc;
tfrc.tfrctx_rtt = hc->tx_rtt;
tfrc.tfrctx_p = hc->tx_p;
tfrc.tfrctx_rto = hc->tx_t_rto;
tfrc.tfrctx_ipi = hc->tx_t_ipi;
len = sizeof(tfrc);
val = &tfrc;
break;
default:
return -ENOPROTOOPT;
}
if (put_user(len, optlen) || copy_to_user(optval, val, len))
return -EFAULT;
return 0;
}
| 166,185
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ExpectCanDiscardFalseTrivial(const LifecycleUnit* lifecycle_unit,
DiscardReason discard_reason) {
DecisionDetails decision_details;
EXPECT_FALSE(lifecycle_unit->CanDiscard(discard_reason, &decision_details));
EXPECT_FALSE(decision_details.IsPositive());
EXPECT_TRUE(decision_details.reasons().empty());
}
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 ExpectCanDiscardFalseTrivial(const LifecycleUnit* lifecycle_unit,
DiscardReason discard_reason) {
DecisionDetails decision_details;
EXPECT_FALSE(lifecycle_unit->CanDiscard(discard_reason, &decision_details));
EXPECT_FALSE(decision_details.IsPositive());
// |reasons()| will either contain the status for the 4 local site features
// heuristics or be empty if the database doesn't track this lifecycle unit.
EXPECT_TRUE(decision_details.reasons().empty() ||
(decision_details.reasons().size() == 4));
}
| 172,232
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: unsigned long long Chapters::Atom::GetUID() const
{
return m_uid;
}
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
|
unsigned long long Chapters::Atom::GetUID() const
const char* SegmentInfo::GetWritingAppAsUTF8() const {
return m_pWritingAppAsUTF8;
}
| 174,376
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 CloudPrintInfoCallback(bool enabled,
const std::string& email,
const std::string& proxy_id) {
QuitMessageLoop();
}
Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated().
Bug: 844016
Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0
Reviewed-on: https://chromium-review.googlesource.com/1126576
Commit-Queue: Wez <wez@chromium.org>
Reviewed-by: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#573131}
CWE ID: CWE-94
|
static void CloudPrintInfoCallback(bool enabled,
void LaunchServiceProcessControlAndWait() {
base::RunLoop run_loop;
LaunchServiceProcessControl(run_loop.QuitClosure());
run_loop.Run();
}
| 172,048
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 FileBrowserHandlerCustomBindings::GetEntryURL(
const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK(args.Length() == 1);
CHECK(args[0]->IsObject());
const blink::WebURL& url =
blink::WebDOMFileSystem::createFileSystemURL(args[0]);
args.GetReturnValue().Set(v8_helpers::ToV8StringUnsafe(
args.GetIsolate(), url.string().utf8().c_str()));
}
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:
|
void FileBrowserHandlerCustomBindings::GetEntryURL(
void FileBrowserHandlerCustomBindings::GetExternalFileEntryCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
GetExternalFileEntry(args, context());
}
| 173,272
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: IW_IMPL(unsigned int) iw_get_ui32le(const iw_byte *b)
{
return b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24);
}
Commit Message: Trying to fix some invalid left shift operations
Fixes issue #16
CWE ID: CWE-682
|
IW_IMPL(unsigned int) iw_get_ui32le(const iw_byte *b)
{
return (unsigned int)b[0] | ((unsigned int)b[1]<<8) |
((unsigned int)b[2]<<16) | ((unsigned int)b[3]<<24);
}
| 168,200
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 MagickBooleanType ConcatenateImages(int argc,char **argv,
ExceptionInfo *exception )
{
FILE
*input,
*output;
int
c;
register ssize_t
i;
if (ExpandFilenames(&argc,&argv) == MagickFalse)
ThrowFileException(exception,ResourceLimitError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
output=fopen_utf8(argv[argc-1],"wb");
if (output == (FILE *) NULL) {
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[argc-1]);
return(MagickFalse);
}
for (i=2; i < (ssize_t) (argc-1); i++) {
#if 0
fprintf(stderr, "DEBUG: Concatenate Image: \"%s\"\n", argv[i]);
#endif
input=fopen_utf8(argv[i],"rb");
if (input == (FILE *) NULL) {
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[i]);
continue;
}
for (c=fgetc(input); c != EOF; c=fgetc(input))
(void) fputc((char) c,output);
(void) fclose(input);
(void) remove_utf8(argv[i]);
}
(void) fclose(output);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/196
CWE ID: CWE-20
|
static MagickBooleanType ConcatenateImages(int argc,char **argv,
ExceptionInfo *exception )
{
FILE
*input,
*output;
MagickBooleanType
status;
int
c;
register ssize_t
i;
if (ExpandFilenames(&argc,&argv) == MagickFalse)
ThrowFileException(exception,ResourceLimitError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
output=fopen_utf8(argv[argc-1],"wb");
if (output == (FILE *) NULL)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
argv[argc-1]);
return(MagickFalse);
}
status=MagickTrue;
for (i=2; i < (ssize_t) (argc-1); i++)
{
input=fopen_utf8(argv[i],"rb");
if (input == (FILE *) NULL)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[i]);
continue;
}
for (c=fgetc(input); c != EOF; c=fgetc(input))
if (fputc((char) c,output) != c)
status=MagickFalse;
(void) fclose(input);
(void) remove_utf8(argv[i]);
}
(void) fclose(output);
return(status);
}
| 168,628
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 SoftVPXEncoder::setConfig(
OMX_INDEXTYPE index, const OMX_PTR _params) {
switch (index) {
case OMX_IndexConfigVideoIntraVOPRefresh:
{
OMX_CONFIG_INTRAREFRESHVOPTYPE *params =
(OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params;
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
mKeyFrameRequested = params->IntraRefreshVOP;
return OMX_ErrorNone;
}
case OMX_IndexConfigVideoBitrate:
{
OMX_VIDEO_CONFIG_BITRATETYPE *params =
(OMX_VIDEO_CONFIG_BITRATETYPE *)_params;
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
if (mBitrate != params->nEncodeBitrate) {
mBitrate = params->nEncodeBitrate;
mBitrateUpdated = true;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::setConfig(index, _params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftVPXEncoder::setConfig(
OMX_INDEXTYPE index, const OMX_PTR _params) {
switch (index) {
case OMX_IndexConfigVideoIntraVOPRefresh:
{
OMX_CONFIG_INTRAREFRESHVOPTYPE *params =
(OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params;
if (!isValidOMXParam(params)) {
return OMX_ErrorBadParameter;
}
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
mKeyFrameRequested = params->IntraRefreshVOP;
return OMX_ErrorNone;
}
case OMX_IndexConfigVideoBitrate:
{
OMX_VIDEO_CONFIG_BITRATETYPE *params =
(OMX_VIDEO_CONFIG_BITRATETYPE *)_params;
if (!isValidOMXParam(params)) {
return OMX_ErrorBadParameter;
}
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
if (mBitrate != params->nEncodeBitrate) {
mBitrate = params->nEncodeBitrate;
mBitrateUpdated = true;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::setConfig(index, _params);
}
}
| 174,215
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 ctrycatchfinally(JF, js_Ast *trystm, js_Ast *catchvar, js_Ast *catchstm, js_Ast *finallystm)
{
int L1, L2, L3;
L1 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the try block */
L2 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the catch block */
cstm(J, F, finallystm); /* inline finally block */
emit(J, F, OP_THROW); /* rethrow exception */
}
label(J, F, L2);
if (F->strict) {
checkfutureword(J, F, catchvar);
if (!strcmp(catchvar->string, "arguments"))
jsC_error(J, catchvar, "redefining 'arguments' is not allowed in strict mode");
if (!strcmp(catchvar->string, "eval"))
jsC_error(J, catchvar, "redefining 'eval' is not allowed in strict mode");
}
emitline(J, F, catchvar);
emitstring(J, F, OP_CATCH, catchvar->string);
cstm(J, F, catchstm);
emit(J, F, OP_ENDCATCH);
L3 = emitjump(J, F, OP_JUMP); /* skip past the try block to the finally block */
}
label(J, F, L1);
cstm(J, F, trystm);
emit(J, F, OP_ENDTRY);
label(J, F, L3);
cstm(J, F, finallystm);
}
Commit Message: Bug 700947: Add missing ENDTRY opcode in try/catch/finally byte code.
In one of the code branches in handling exceptions in the catch block
we forgot to call the ENDTRY opcode to pop the inner hidden try.
This leads to an unbalanced exception stack which can cause a crash
due to us jumping to a stack frame that has already been exited.
CWE ID: CWE-119
|
static void ctrycatchfinally(JF, js_Ast *trystm, js_Ast *catchvar, js_Ast *catchstm, js_Ast *finallystm)
{
int L1, L2, L3;
L1 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the try block */
L2 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the catch block */
cstm(J, F, finallystm); /* inline finally block */
emit(J, F, OP_THROW); /* rethrow exception */
}
label(J, F, L2);
if (F->strict) {
checkfutureword(J, F, catchvar);
if (!strcmp(catchvar->string, "arguments"))
jsC_error(J, catchvar, "redefining 'arguments' is not allowed in strict mode");
if (!strcmp(catchvar->string, "eval"))
jsC_error(J, catchvar, "redefining 'eval' is not allowed in strict mode");
}
emitline(J, F, catchvar);
emitstring(J, F, OP_CATCH, catchvar->string);
cstm(J, F, catchstm);
emit(J, F, OP_ENDCATCH);
emit(J, F, OP_ENDTRY);
L3 = emitjump(J, F, OP_JUMP); /* skip past the try block to the finally block */
}
label(J, F, L1);
cstm(J, F, trystm);
emit(J, F, OP_ENDTRY);
label(J, F, L3);
cstm(J, F, finallystm);
}
| 169,702
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 Smb4KMountJob::fillArgs(Smb4KShare *share, QMap<QString, QVariant>& map)
{
QString mount;
QStringList paths;
paths << "/bin";
paths << "/sbin";
paths << "/usr/bin";
paths << "/usr/sbin";
paths << "/usr/local/bin";
paths << "/usr/local/sbin";
for (int i = 0; i < paths.size(); ++i)
{
mount = KGlobal::dirs()->findExe("mount.cifs", paths.at(i));
if (!mount.isEmpty())
{
map.insert("mh_command", mount);
break;
}
else
{
continue;
}
}
if (mount.isEmpty())
{
paths << "/sbin";
paths << "/usr/bin";
paths << "/usr/sbin";
paths << "/usr/local/bin";
paths << "/usr/local/sbin";
}
QMap<QString, QString> global_options = globalSambaOptions();
Smb4KCustomOptions *options = Smb4KCustomOptionsManager::self()->findOptions(share);
break;
}
Commit Message:
CWE ID: CWE-20
|
bool Smb4KMountJob::fillArgs(Smb4KShare *share, QMap<QString, QVariant>& map)
{
const QString mount = findMountExecutable();
if (mount.isEmpty())
{
paths << "/sbin";
paths << "/usr/bin";
paths << "/usr/sbin";
paths << "/usr/local/bin";
paths << "/usr/local/sbin";
}
map.insert("mh_command", mount);
QMap<QString, QString> global_options = globalSambaOptions();
Smb4KCustomOptions *options = Smb4KCustomOptionsManager::self()->findOptions(share);
break;
}
| 164,825
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BrowserViewRenderer::SetTotalRootLayerScrollOffset(
gfx::Vector2dF scroll_offset_dip) {
if (scroll_offset_dip_ == scroll_offset_dip)
return;
scroll_offset_dip_ = scroll_offset_dip;
gfx::Vector2d max_offset = max_scroll_offset();
gfx::Vector2d scroll_offset;
if (max_scroll_offset_dip_.x()) {
scroll_offset.set_x((scroll_offset_dip.x() * max_offset.x()) /
max_scroll_offset_dip_.x());
}
if (max_scroll_offset_dip_.y()) {
scroll_offset.set_y((scroll_offset_dip.y() * max_offset.y()) /
max_scroll_offset_dip_.y());
}
DCHECK_LE(0, scroll_offset.x());
DCHECK_LE(0, scroll_offset.y());
DCHECK_LE(scroll_offset.x(), max_offset.x());
DCHECK_LE(scroll_offset.y(), max_offset.y());
client_->ScrollContainerViewTo(scroll_offset);
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
|
void BrowserViewRenderer::SetTotalRootLayerScrollOffset(
const gfx::Vector2dF& scroll_offset_dip) {
if (scroll_offset_dip_ == scroll_offset_dip)
return;
scroll_offset_dip_ = scroll_offset_dip;
gfx::Vector2d max_offset = max_scroll_offset();
gfx::Vector2d scroll_offset;
if (max_scroll_offset_dip_.x()) {
scroll_offset.set_x((scroll_offset_dip.x() * max_offset.x()) /
max_scroll_offset_dip_.x());
}
if (max_scroll_offset_dip_.y()) {
scroll_offset.set_y((scroll_offset_dip.y() * max_offset.y()) /
max_scroll_offset_dip_.y());
}
DCHECK_LE(0, scroll_offset.x());
DCHECK_LE(0, scroll_offset.y());
DCHECK_LE(scroll_offset.x(), max_offset.x());
DCHECK_LE(scroll_offset.y(), max_offset.y());
client_->ScrollContainerViewTo(scroll_offset);
}
| 171,615
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: cJSON *cJSON_CreateFloatArray( double *numbers, int count )
{
int i;
cJSON *n = 0, *p = 0, *a = cJSON_CreateArray();
for ( i = 0; a && i < count; ++i ) {
n = cJSON_CreateFloat( numbers[i] );
if ( ! i )
a->child = n;
else
suffix_object( p, n );
p = n;
}
return a;
}
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
|
cJSON *cJSON_CreateFloatArray( double *numbers, int count )
| 167,273
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PrintWebViewHelper::OnPrintingDone(bool success) {
notify_browser_of_print_failure_ = false;
if (!success)
LOG(ERROR) << "Failure in OnPrintingDone";
DidFinishPrinting(success ? OK : FAIL_PRINT);
}
Commit Message: Crash on nested IPC handlers in PrintWebViewHelper
Class is not designed to handle nested IPC. Regular flows also does not
expect them. Still during printing of plugging them may show message
boxes and start nested message loops.
For now we are going just crash. If stats show us that this case is
frequent we will have to do something more complicated.
BUG=502562
Review URL: https://codereview.chromium.org/1228693002
Cr-Commit-Position: refs/heads/master@{#338100}
CWE ID:
|
void PrintWebViewHelper::OnPrintingDone(bool success) {
CHECK_LE(ipc_nesting_level_, 1);
notify_browser_of_print_failure_ = false;
if (!success)
LOG(ERROR) << "Failure in OnPrintingDone";
DidFinishPrinting(success ? OK : FAIL_PRINT);
}
| 171,877
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 PrintWebViewHelper::InitPrintSettings(WebKit::WebFrame* frame,
WebKit::WebNode* node,
bool is_preview) {
DCHECK(frame);
PrintMsg_PrintPages_Params settings;
Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
&settings.params));
bool result = true;
if (PrintMsg_Print_Params_IsEmpty(settings.params)) {
if (!is_preview) {
render_view()->runModalAlertDialog(
frame,
l10n_util::GetStringUTF16(
IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS));
}
result = false;
}
if (result &&
(settings.params.dpi < kMinDpi || settings.params.document_cookie == 0)) {
NOTREACHED();
result = false;
}
settings.pages.clear();
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
return result;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool PrintWebViewHelper::InitPrintSettings(WebKit::WebFrame* frame,
bool PrintWebViewHelper::InitPrintSettings(WebKit::WebFrame* frame) {
DCHECK(frame);
PrintMsg_PrintPages_Params settings;
Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
&settings.params));
bool result = true;
if (PrintMsg_Print_Params_IsEmpty(settings.params)) {
render_view()->runModalAlertDialog(
frame,
l10n_util::GetStringUTF16(
IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS));
result = false;
}
if (result &&
(settings.params.dpi < kMinDpi || settings.params.document_cookie == 0)) {
NOTREACHED();
result = false;
}
settings.pages.clear();
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
return result;
}
| 170,259
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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::requestFileSystem(ExecutionContext* context, FileSystemType type, long long size, PassOwnPtr<AsyncFileSystemCallbacks> callbacks)
{
RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context);
RefPtr<CallbackWrapper> wrapper = adoptRef(new CallbackWrapper(callbacks));
requestFileSystemAccessInternal(context,
bind(&LocalFileSystem::fileSystemAllowedInternal, this, contextPtr, type, wrapper),
bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper));
}
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::requestFileSystem(ExecutionContext* context, FileSystemType type, long long size, PassOwnPtr<AsyncFileSystemCallbacks> callbacks)
{
RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context);
CallbackWrapper* wrapper = new CallbackWrapper(callbacks);
requestFileSystemAccessInternal(context,
bind(&LocalFileSystem::fileSystemAllowedInternal, this, contextPtr, type, wrapper),
bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper));
}
| 171,429
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 UkmPageLoadMetricsObserver::RecordPageLoadExtraInfoMetrics(
const page_load_metrics::PageLoadExtraInfo& info,
base::TimeTicks app_background_time) {
ukm::builders::PageLoad builder(info.source_id);
base::Optional<base::TimeDelta> foreground_duration =
page_load_metrics::GetInitialForegroundDuration(info,
app_background_time);
if (foreground_duration) {
builder.SetPageTiming_ForegroundDuration(
foreground_duration.value().InMilliseconds());
}
metrics::SystemProfileProto::Network::EffectiveConnectionType
proto_effective_connection_type =
metrics::ConvertEffectiveConnectionType(effective_connection_type_);
if (proto_effective_connection_type !=
metrics::SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) {
builder.SetNet_EffectiveConnectionType2_OnNavigationStart(
static_cast<int64_t>(proto_effective_connection_type));
}
if (http_response_code_) {
builder.SetNet_HttpResponseCode(
static_cast<int64_t>(http_response_code_.value()));
}
if (http_rtt_estimate_) {
builder.SetNet_HttpRttEstimate_OnNavigationStart(
static_cast<int64_t>(http_rtt_estimate_.value().InMilliseconds()));
}
if (transport_rtt_estimate_) {
builder.SetNet_TransportRttEstimate_OnNavigationStart(
static_cast<int64_t>(transport_rtt_estimate_.value().InMilliseconds()));
}
if (downstream_kbps_estimate_) {
builder.SetNet_DownstreamKbpsEstimate_OnNavigationStart(
static_cast<int64_t>(downstream_kbps_estimate_.value()));
}
builder.SetNavigation_PageTransition(static_cast<int64_t>(page_transition_));
builder.SetNavigation_PageEndReason(
static_cast<int64_t>(info.page_end_reason));
if (info.did_commit && was_cached_) {
builder.SetWasCached(1);
}
builder.Record(ukm::UkmRecorder::Get());
}
Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation.
Also refactor UkmPageLoadMetricsObserver to use this new boolean to
report the user initiated metric in RecordPageLoadExtraInfoMetrics, so
that it works correctly in the case when the page load failed.
Bug: 925104
Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff
Reviewed-on: https://chromium-review.googlesource.com/c/1450460
Commit-Queue: Annie Sullivan <sullivan@chromium.org>
Reviewed-by: Bryan McQuade <bmcquade@chromium.org>
Cr-Commit-Position: refs/heads/master@{#630870}
CWE ID: CWE-79
|
void UkmPageLoadMetricsObserver::RecordPageLoadExtraInfoMetrics(
const page_load_metrics::PageLoadExtraInfo& info,
base::TimeTicks app_background_time) {
ukm::builders::PageLoad builder(info.source_id);
base::Optional<base::TimeDelta> foreground_duration =
page_load_metrics::GetInitialForegroundDuration(info,
app_background_time);
if (foreground_duration) {
builder.SetPageTiming_ForegroundDuration(
foreground_duration.value().InMilliseconds());
}
bool is_user_initiated_navigation =
// All browser initiated page loads are user-initiated.
info.user_initiated_info.browser_initiated ||
// Renderer-initiated navigations are user-initiated if there is an
// associated input event.
info.user_initiated_info.user_input_event;
builder.SetExperimental_Navigation_UserInitiated(
is_user_initiated_navigation);
metrics::SystemProfileProto::Network::EffectiveConnectionType
proto_effective_connection_type =
metrics::ConvertEffectiveConnectionType(effective_connection_type_);
if (proto_effective_connection_type !=
metrics::SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) {
builder.SetNet_EffectiveConnectionType2_OnNavigationStart(
static_cast<int64_t>(proto_effective_connection_type));
}
if (http_response_code_) {
builder.SetNet_HttpResponseCode(
static_cast<int64_t>(http_response_code_.value()));
}
if (http_rtt_estimate_) {
builder.SetNet_HttpRttEstimate_OnNavigationStart(
static_cast<int64_t>(http_rtt_estimate_.value().InMilliseconds()));
}
if (transport_rtt_estimate_) {
builder.SetNet_TransportRttEstimate_OnNavigationStart(
static_cast<int64_t>(transport_rtt_estimate_.value().InMilliseconds()));
}
if (downstream_kbps_estimate_) {
builder.SetNet_DownstreamKbpsEstimate_OnNavigationStart(
static_cast<int64_t>(downstream_kbps_estimate_.value()));
}
builder.SetNavigation_PageTransition(static_cast<int64_t>(page_transition_));
builder.SetNavigation_PageEndReason(
static_cast<int64_t>(info.page_end_reason));
if (info.did_commit && was_cached_) {
builder.SetWasCached(1);
}
builder.Record(ukm::UkmRecorder::Get());
}
| 172,496
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void build_ntlmssp_negotiate_blob(unsigned char *pbuffer,
struct cifs_ses *ses)
{
NEGOTIATE_MESSAGE *sec_blob = (NEGOTIATE_MESSAGE *)pbuffer;
__u32 flags;
memset(pbuffer, 0, sizeof(NEGOTIATE_MESSAGE));
memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
sec_blob->MessageType = NtLmNegotiate;
/* BB is NTLMV2 session security format easier to use here? */
flags = NTLMSSP_NEGOTIATE_56 | NTLMSSP_REQUEST_TARGET |
NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC;
if (ses->server->sign) {
flags |= NTLMSSP_NEGOTIATE_SIGN;
if (!ses->server->session_estab ||
ses->ntlmssp->sesskey_per_smbsess)
flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
}
sec_blob->NegotiateFlags = cpu_to_le32(flags);
sec_blob->WorkstationName.BufferOffset = 0;
sec_blob->WorkstationName.Length = 0;
sec_blob->WorkstationName.MaximumLength = 0;
/* Domain name is sent on the Challenge not Negotiate NTLMSSP request */
sec_blob->DomainName.BufferOffset = 0;
sec_blob->DomainName.Length = 0;
sec_blob->DomainName.MaximumLength = 0;
}
Commit Message: CIFS: Enable encryption during session setup phase
In order to allow encryption on SMB connection we need to exchange
a session key and generate encryption and decryption keys.
Signed-off-by: Pavel Shilovsky <pshilov@microsoft.com>
CWE ID: CWE-476
|
void build_ntlmssp_negotiate_blob(unsigned char *pbuffer,
struct cifs_ses *ses)
{
NEGOTIATE_MESSAGE *sec_blob = (NEGOTIATE_MESSAGE *)pbuffer;
__u32 flags;
memset(pbuffer, 0, sizeof(NEGOTIATE_MESSAGE));
memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
sec_blob->MessageType = NtLmNegotiate;
/* BB is NTLMV2 session security format easier to use here? */
flags = NTLMSSP_NEGOTIATE_56 | NTLMSSP_REQUEST_TARGET |
NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC |
NTLMSSP_NEGOTIATE_SEAL;
if (ses->server->sign)
flags |= NTLMSSP_NEGOTIATE_SIGN;
if (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess)
flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
sec_blob->NegotiateFlags = cpu_to_le32(flags);
sec_blob->WorkstationName.BufferOffset = 0;
sec_blob->WorkstationName.Length = 0;
sec_blob->WorkstationName.MaximumLength = 0;
/* Domain name is sent on the Challenge not Negotiate NTLMSSP request */
sec_blob->DomainName.BufferOffset = 0;
sec_blob->DomainName.Length = 0;
sec_blob->DomainName.MaximumLength = 0;
}
| 169,360
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 enum_dir(sc_path_t path, int depth)
{
sc_file_t *file;
int r, file_type;
u8 files[SC_MAX_APDU_BUFFER_SIZE];
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_select_file(card, &path, &file);
sc_unlock(card);
if (r) {
fprintf(stderr, "SELECT FILE failed: %s\n", sc_strerror(r));
return 1;
}
print_file(card, file, &path, depth);
file_type = file->type;
sc_file_free(file);
if (file_type == SC_FILE_TYPE_DF) {
int i;
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_list_files(card, files, sizeof(files));
sc_unlock(card);
if (r < 0) {
fprintf(stderr, "sc_list_files() failed: %s\n", sc_strerror(r));
return 1;
}
if (r == 0) {
printf("Empty directory\n");
} else
for (i = 0; i < r/2; i++) {
sc_path_t tmppath;
memset(&tmppath, 0, sizeof(tmppath));
memcpy(&tmppath, &path, sizeof(path));
memcpy(tmppath.value + tmppath.len, files + 2*i, 2);
tmppath.len += 2;
enum_dir(tmppath, depth + 1);
}
}
return 0;
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
|
static int enum_dir(sc_path_t path, int depth)
{
sc_file_t *file;
int r, file_type;
u8 files[SC_MAX_EXT_APDU_BUFFER_SIZE];
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_select_file(card, &path, &file);
sc_unlock(card);
if (r) {
fprintf(stderr, "SELECT FILE failed: %s\n", sc_strerror(r));
return 1;
}
print_file(card, file, &path, depth);
file_type = file->type;
sc_file_free(file);
if (file_type == SC_FILE_TYPE_DF) {
int i;
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_list_files(card, files, sizeof(files));
sc_unlock(card);
if (r < 0) {
fprintf(stderr, "sc_list_files() failed: %s\n", sc_strerror(r));
return 1;
}
if (r == 0) {
printf("Empty directory\n");
} else {
for (i = 0; i < r/2; i++) {
sc_path_t tmppath;
memset(&tmppath, 0, sizeof(tmppath));
memcpy(&tmppath, &path, sizeof(path));
memcpy(tmppath.value + tmppath.len, files + 2*i, 2);
tmppath.len += 2;
enum_dir(tmppath, depth + 1);
}
}
}
return 0;
}
| 169,069
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ContentEncoding::~ContentEncoding() {
ContentCompression** comp_i = compression_entries_;
ContentCompression** const comp_j = compression_entries_end_;
while (comp_i != comp_j) {
ContentCompression* const comp = *comp_i++;
delete comp;
}
delete [] compression_entries_;
ContentEncryption** enc_i = encryption_entries_;
ContentEncryption** const enc_j = encryption_entries_end_;
while (enc_i != enc_j) {
ContentEncryption* const enc = *enc_i++;
delete enc;
}
delete [] encryption_entries_;
}
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
|
ContentEncoding::~ContentEncoding() {
ContentCompression** comp_i = compression_entries_;
ContentCompression** const comp_j = compression_entries_end_;
while (comp_i != comp_j) {
ContentCompression* const comp = *comp_i++;
delete comp;
}
delete[] compression_entries_;
ContentEncryption** enc_i = encryption_entries_;
ContentEncryption** const enc_j = encryption_entries_end_;
while (enc_i != enc_j) {
ContentEncryption* const enc = *enc_i++;
delete enc;
}
delete[] encryption_entries_;
}
| 174,460
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 parse_input(h2o_http2_conn_t *conn)
{
size_t http2_max_concurrent_requests_per_connection = conn->super.ctx->globalconf->http2.max_concurrent_requests_per_connection;
int perform_early_exit = 0;
if (conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed != http2_max_concurrent_requests_per_connection)
perform_early_exit = 1;
/* handle the input */
while (conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING && conn->sock->input->size != 0) {
if (perform_early_exit == 1 &&
conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed == http2_max_concurrent_requests_per_connection)
goto EarlyExit;
/* process a frame */
const char *err_desc = NULL;
ssize_t ret = conn->_read_expect(conn, (uint8_t *)conn->sock->input->bytes, conn->sock->input->size, &err_desc);
if (ret == H2O_HTTP2_ERROR_INCOMPLETE) {
break;
} else if (ret < 0) {
if (ret != H2O_HTTP2_ERROR_PROTOCOL_CLOSE_IMMEDIATELY) {
enqueue_goaway(conn, (int)ret,
err_desc != NULL ? (h2o_iovec_t){(char *)err_desc, strlen(err_desc)} : (h2o_iovec_t){});
}
close_connection(conn);
return;
}
/* advance to the next frame */
h2o_buffer_consume(&conn->sock->input, ret);
}
if (!h2o_socket_is_reading(conn->sock))
h2o_socket_read_start(conn->sock, on_read);
return;
EarlyExit:
if (h2o_socket_is_reading(conn->sock))
h2o_socket_read_stop(conn->sock);
}
Commit Message: h2: use after free on premature connection close #920
lib/http2/connection.c:on_read() calls parse_input(), which might free
`conn`. It does so in particular if the connection preface isn't
the expected one in expect_preface(). `conn` is then used after the free
in `if (h2o_timeout_is_linked(&conn->_write.timeout_entry)`.
We fix this by adding a return value to close_connection that returns a
negative value if `conn` has been free'd and can't be used anymore.
Credits for finding the bug to Tim Newsham.
CWE ID:
|
static void parse_input(h2o_http2_conn_t *conn)
static int parse_input(h2o_http2_conn_t *conn)
{
size_t http2_max_concurrent_requests_per_connection = conn->super.ctx->globalconf->http2.max_concurrent_requests_per_connection;
int perform_early_exit = 0;
if (conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed != http2_max_concurrent_requests_per_connection)
perform_early_exit = 1;
/* handle the input */
while (conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING && conn->sock->input->size != 0) {
if (perform_early_exit == 1 &&
conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed == http2_max_concurrent_requests_per_connection)
goto EarlyExit;
/* process a frame */
const char *err_desc = NULL;
ssize_t ret = conn->_read_expect(conn, (uint8_t *)conn->sock->input->bytes, conn->sock->input->size, &err_desc);
if (ret == H2O_HTTP2_ERROR_INCOMPLETE) {
break;
} else if (ret < 0) {
if (ret != H2O_HTTP2_ERROR_PROTOCOL_CLOSE_IMMEDIATELY) {
enqueue_goaway(conn, (int)ret,
err_desc != NULL ? (h2o_iovec_t){(char *)err_desc, strlen(err_desc)} : (h2o_iovec_t){});
}
return close_connection(conn);
}
/* advance to the next frame */
h2o_buffer_consume(&conn->sock->input, ret);
}
if (!h2o_socket_is_reading(conn->sock))
h2o_socket_read_start(conn->sock, on_read);
return 0;
EarlyExit:
if (h2o_socket_is_reading(conn->sock))
h2o_socket_read_stop(conn->sock);
return 0;
}
| 167,227
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 AddObserver(Observer* observer) {
if (!observers_.size()) {
observer->FirstObserverIsAdded(this);
}
observers_.AddObserver(observer);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
virtual void AddObserver(Observer* observer) {
virtual void AddObserver(InputMethodLibrary::Observer* observer) {
if (!observers_.size()) {
observer->FirstObserverIsAdded(this);
}
observers_.AddObserver(observer);
}
| 170,476
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void timer_enter_running(Timer *t) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
int r;
assert(t);
/* Don't start job if we are supposed to go down */
if (unit_stop_pending(UNIT(t)))
return;
r = manager_add_job(UNIT(t)->manager, JOB_START, UNIT_TRIGGER(UNIT(t)),
JOB_REPLACE, true, &error, NULL);
if (r < 0)
goto fail;
dual_timestamp_get(&t->last_trigger);
if (t->stamp_path)
touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, 0);
timer_set_state(t, TIMER_RUNNING);
return;
fail:
log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
}
Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere
CWE ID: CWE-264
|
static void timer_enter_running(Timer *t) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
int r;
assert(t);
/* Don't start job if we are supposed to go down */
if (unit_stop_pending(UNIT(t)))
return;
r = manager_add_job(UNIT(t)->manager, JOB_START, UNIT_TRIGGER(UNIT(t)),
JOB_REPLACE, true, &error, NULL);
if (r < 0)
goto fail;
dual_timestamp_get(&t->last_trigger);
if (t->stamp_path)
touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID);
timer_set_state(t, TIMER_RUNNING);
return;
fail:
log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
}
| 170,106
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *a)
{
return (tsfb->numlvls > 0) ? jpc_tsfb_synthesize2(tsfb,
jas_seq2d_getref(a, jas_seq2d_xstart(a), jas_seq2d_ystart(a)),
jas_seq2d_xstart(a), jas_seq2d_ystart(a), jas_seq2d_width(a),
jas_seq2d_height(a), jas_seq2d_rowstep(a), tsfb->numlvls - 1) : 0;
}
Commit Message: Fixed an integral type promotion problem by adding a JAS_CAST.
Modified the jpc_tsfb_synthesize function so that it will be a noop for
an empty sequence (in order to avoid dereferencing a null pointer).
CWE ID: CWE-476
|
int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *a)
{
return (tsfb->numlvls > 0 && jas_seq2d_size(a)) ?
jpc_tsfb_synthesize2(tsfb,
jas_seq2d_getref(a, jas_seq2d_xstart(a), jas_seq2d_ystart(a)),
jas_seq2d_xstart(a), jas_seq2d_ystart(a), jas_seq2d_width(a),
jas_seq2d_height(a), jas_seq2d_rowstep(a), tsfb->numlvls - 1) : 0;
}
| 168,478
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.