instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: enum nss_status _nss_mymachines_getpwnam_r(
const char *name,
struct passwd *pwd,
char *buffer, size_t buflen,
int *errnop) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
const char *p, *e, *machine;
uint32_t mapped;
uid_t uid;
size_t l;
int r;
assert(name);
assert(pwd);
p = startswith(name, "vu-");
if (!p)
goto not_found;
e = strrchr(p, '-');
if (!e || e == p)
goto not_found;
r = parse_uid(e + 1, &uid);
if (r < 0)
goto not_found;
machine = strndupa(p, e - p);
if (!machine_name_is_valid(machine))
goto not_found;
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"MapFromMachineUser",
&error,
&reply,
"su",
machine, (uint32_t) uid);
if (r < 0) {
if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_USER_MAPPING))
goto not_found;
goto fail;
}
r = sd_bus_message_read(reply, "u", &mapped);
if (r < 0)
goto fail;
l = strlen(name);
if (buflen < l+1) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
memcpy(buffer, name, l+1);
pwd->pw_name = buffer;
pwd->pw_uid = mapped;
pwd->pw_gid = 65534; /* nobody */
pwd->pw_gecos = buffer;
pwd->pw_passwd = (char*) "*"; /* locked */
pwd->pw_dir = (char*) "/";
pwd->pw_shell = (char*) "/sbin/nologin";
*errnop = 0;
return NSS_STATUS_SUCCESS;
not_found:
*errnop = 0;
return NSS_STATUS_NOTFOUND;
fail:
*errnop = -r;
return NSS_STATUS_UNAVAIL;
}
Commit Message: nss-mymachines: do not allow overlong machine names
https://github.com/systemd/systemd/issues/2002
CWE ID: CWE-119
|
enum nss_status _nss_mymachines_getpwnam_r(
const char *name,
struct passwd *pwd,
char *buffer, size_t buflen,
int *errnop) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
const char *p, *e, *machine;
uint32_t mapped;
uid_t uid;
size_t l;
int r;
assert(name);
assert(pwd);
p = startswith(name, "vu-");
if (!p)
goto not_found;
e = strrchr(p, '-');
if (!e || e == p)
goto not_found;
if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */
goto not_found;
r = parse_uid(e + 1, &uid);
if (r < 0)
goto not_found;
machine = strndupa(p, e - p);
if (!machine_name_is_valid(machine))
goto not_found;
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"MapFromMachineUser",
&error,
&reply,
"su",
machine, (uint32_t) uid);
if (r < 0) {
if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_USER_MAPPING))
goto not_found;
goto fail;
}
r = sd_bus_message_read(reply, "u", &mapped);
if (r < 0)
goto fail;
l = strlen(name);
if (buflen < l+1) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
memcpy(buffer, name, l+1);
pwd->pw_name = buffer;
pwd->pw_uid = mapped;
pwd->pw_gid = 65534; /* nobody */
pwd->pw_gecos = buffer;
pwd->pw_passwd = (char*) "*"; /* locked */
pwd->pw_dir = (char*) "/";
pwd->pw_shell = (char*) "/sbin/nologin";
*errnop = 0;
return NSS_STATUS_SUCCESS;
not_found:
*errnop = 0;
return NSS_STATUS_NOTFOUND;
fail:
*errnop = -r;
return NSS_STATUS_UNAVAIL;
}
| 168,870
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: update_info_partition_on_linux_dmmp (Device *device)
{
const gchar *dm_name;
const gchar* const *targets_type;
const gchar* const *targets_params;
gchar *params;
gint linear_slave_major;
gint linear_slave_minor;
guint64 offset_sectors;
Device *linear_slave;
gchar *s;
params = NULL;
dm_name = g_udev_device_get_property (device->priv->d, "DM_NAME");
if (dm_name == NULL)
goto out;
targets_type = g_udev_device_get_property_as_strv (device->priv->d, "UDISKS_DM_TARGETS_TYPE");
if (targets_type == NULL || g_strcmp0 (targets_type[0], "linear") != 0)
goto out;
goto out;
params = decode_udev_encoded_string (targets_params[0]);
if (sscanf (params,
"%d:%d %" G_GUINT64_FORMAT,
&linear_slave_major,
&linear_slave_minor,
&offset_sectors) != 3)
goto out;
linear_slave = daemon_local_find_by_dev (device->priv->daemon,
makedev (linear_slave_major, linear_slave_minor));
if (linear_slave == NULL)
goto out;
if (!linear_slave->priv->device_is_linux_dmmp)
goto out;
/* The Partition* properties has been set as part of
* update_info_partition() by reading UDISKS_PARTITION_*
* properties.. so here we bascially just update the presentation
* device file name and and whether the device is a drive.
*/
s = g_strdup_printf ("/dev/mapper/%s", dm_name);
device_set_device_file_presentation (device, s);
g_free (s);
device_set_device_is_drive (device, FALSE);
out:
g_free (params);
return TRUE;
}
Commit Message:
CWE ID: CWE-200
|
update_info_partition_on_linux_dmmp (Device *device)
{
const gchar *dm_name;
const gchar* const *targets_type;
const gchar* const *targets_params;
gchar *params;
gint linear_slave_major;
gint linear_slave_minor;
guint64 offset_sectors;
Device *linear_slave;
gchar *s;
params = NULL;
dm_name = g_udev_device_get_property (device->priv->d, "DM_NAME");
if (dm_name == NULL)
goto out;
targets_type = g_udev_device_get_property_as_strv (device->priv->d, "UDISKS_DM_TARGETS_TYPE");
/* If we ever need this for other types than "linear", remember to update
udisks-dm-export.c as well. */
if (targets_type == NULL || g_strcmp0 (targets_type[0], "linear") != 0)
goto out;
goto out;
params = decode_udev_encoded_string (targets_params[0]);
if (sscanf (params,
"%d:%d %" G_GUINT64_FORMAT,
&linear_slave_major,
&linear_slave_minor,
&offset_sectors) != 3)
goto out;
linear_slave = daemon_local_find_by_dev (device->priv->daemon,
makedev (linear_slave_major, linear_slave_minor));
if (linear_slave == NULL)
goto out;
if (!linear_slave->priv->device_is_linux_dmmp)
goto out;
/* The Partition* properties has been set as part of
* update_info_partition() by reading UDISKS_PARTITION_*
* properties.. so here we bascially just update the presentation
* device file name and and whether the device is a drive.
*/
s = g_strdup_printf ("/dev/mapper/%s", dm_name);
device_set_device_file_presentation (device, s);
g_free (s);
device_set_device_is_drive (device, FALSE);
out:
g_free (params);
return TRUE;
}
| 165,132
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: jbig2_parse_segment_header(Jbig2Ctx *ctx, uint8_t *buf, size_t buf_size, size_t *p_header_size)
{
Jbig2Segment *result;
uint8_t rtscarf;
uint32_t rtscarf_long;
uint32_t *referred_to_segments;
int referred_to_segment_count;
int referred_to_segment_size;
int pa_size;
int offset;
/* minimum possible size of a jbig2 segment header */
if (buf_size < 11)
return NULL;
result = jbig2_new(ctx, Jbig2Segment, 1);
if (result == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate segment in jbig2_parse_segment_header");
return result;
}
/* 7.2.2 */
result->number = jbig2_get_uint32(buf);
/* 7.2.3 */
result->flags = buf[4];
/* 7.2.4 referred-to segments */
rtscarf = buf[5];
if ((rtscarf & 0xe0) == 0xe0) {
rtscarf_long = jbig2_get_uint32(buf + 5);
referred_to_segment_count = rtscarf_long & 0x1fffffff;
offset = 5 + 4 + (referred_to_segment_count + 1) / 8;
} else {
referred_to_segment_count = (rtscarf >> 5);
offset = 5 + 1;
}
result->referred_to_segment_count = referred_to_segment_count;
/* we now have enough information to compute the full header length */
referred_to_segment_size = result->number <= 256 ? 1 : result->number <= 65536 ? 2 : 4; /* 7.2.5 */
pa_size = result->flags & 0x40 ? 4 : 1; /* 7.2.6 */
if (offset + referred_to_segment_count * referred_to_segment_size + pa_size + 4 > buf_size) {
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "jbig2_parse_segment_header() called with insufficient data", -1);
jbig2_free(ctx->allocator, result);
return NULL;
}
/* 7.2.5 */
if (referred_to_segment_count) {
int i;
referred_to_segments = jbig2_new(ctx, uint32_t, referred_to_segment_count * referred_to_segment_size);
if (referred_to_segments == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate referred_to_segments " "in jbig2_parse_segment_header");
return NULL;
}
for (i = 0; i < referred_to_segment_count; i++) {
referred_to_segments[i] =
(referred_to_segment_size == 1) ? buf[offset] :
(referred_to_segment_size == 2) ? jbig2_get_uint16(buf + offset) : jbig2_get_uint32(buf + offset);
offset += referred_to_segment_size;
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "segment %d refers to segment %d", result->number, referred_to_segments[i]);
}
result->referred_to_segments = referred_to_segments;
} else { /* no referred-to segments */
result->referred_to_segments = NULL;
}
/* 7.2.6 */
if (result->flags & 0x40) {
result->page_association = jbig2_get_uint32(buf + offset);
offset += 4;
} else {
result->page_association = buf[offset++];
}
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "segment %d is associated with page %d", result->number, result->page_association);
/* 7.2.7 */
result->data_length = jbig2_get_uint32(buf + offset);
*p_header_size = offset + 4;
/* no body parsing results yet */
result->result = NULL;
return result;
}
Commit Message:
CWE ID: CWE-119
|
jbig2_parse_segment_header(Jbig2Ctx *ctx, uint8_t *buf, size_t buf_size, size_t *p_header_size)
{
Jbig2Segment *result;
uint8_t rtscarf;
uint32_t rtscarf_long;
uint32_t *referred_to_segments;
uint32_t referred_to_segment_count;
uint32_t referred_to_segment_size;
uint32_t pa_size;
uint32_t offset;
/* minimum possible size of a jbig2 segment header */
if (buf_size < 11)
return NULL;
result = jbig2_new(ctx, Jbig2Segment, 1);
if (result == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate segment in jbig2_parse_segment_header");
return result;
}
/* 7.2.2 */
result->number = jbig2_get_uint32(buf);
/* 7.2.3 */
result->flags = buf[4];
/* 7.2.4 referred-to segments */
rtscarf = buf[5];
if ((rtscarf & 0xe0) == 0xe0) {
rtscarf_long = jbig2_get_uint32(buf + 5);
referred_to_segment_count = rtscarf_long & 0x1fffffff;
offset = 5 + 4 + (referred_to_segment_count + 1) / 8;
} else {
referred_to_segment_count = (rtscarf >> 5);
offset = 5 + 1;
}
result->referred_to_segment_count = referred_to_segment_count;
/* we now have enough information to compute the full header length */
referred_to_segment_size = result->number <= 256 ? 1 : result->number <= 65536 ? 2 : 4; /* 7.2.5 */
pa_size = result->flags & 0x40 ? 4 : 1; /* 7.2.6 */
if (offset + referred_to_segment_count * referred_to_segment_size + pa_size + 4 > buf_size) {
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "jbig2_parse_segment_header() called with insufficient data", -1);
jbig2_free(ctx->allocator, result);
return NULL;
}
/* 7.2.5 */
if (referred_to_segment_count) {
uint32_t i;
referred_to_segments = jbig2_new(ctx, uint32_t, referred_to_segment_count * referred_to_segment_size);
if (referred_to_segments == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate referred_to_segments " "in jbig2_parse_segment_header");
return NULL;
}
for (i = 0; i < referred_to_segment_count; i++) {
referred_to_segments[i] =
(referred_to_segment_size == 1) ? buf[offset] :
(referred_to_segment_size == 2) ? jbig2_get_uint16(buf + offset) : jbig2_get_uint32(buf + offset);
offset += referred_to_segment_size;
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "segment %d refers to segment %d", result->number, referred_to_segments[i]);
}
result->referred_to_segments = referred_to_segments;
} else { /* no referred-to segments */
result->referred_to_segments = NULL;
}
/* 7.2.6 */
if (result->flags & 0x40) {
result->page_association = jbig2_get_uint32(buf + offset);
offset += 4;
} else {
result->page_association = buf[offset++];
}
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "segment %d is associated with page %d", result->number, result->page_association);
/* 7.2.7 */
result->data_length = jbig2_get_uint32(buf + offset);
*p_header_size = offset + 4;
/* no body parsing results yet */
result->result = NULL;
return result;
}
| 165,497
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
{
ssize_t ret;
uint8_t *buffer = g_malloc(MIN(65536, size));
while (size > 0) {
size_t count = MIN(65536, size);
ret = nbd_negotiate_read(ioc, buffer, count);
if (ret < 0) {
g_free(buffer);
return ret;
}
size -= count;
}
g_free(buffer);
return 0;
}
Commit Message:
CWE ID: CWE-20
|
static int nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
| 165,453
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: status_t OMXNodeInstance::storeMetaDataInBuffers_l(
OMX_U32 portIndex, OMX_BOOL enable, MetadataBufferType *type) {
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
android_errorWriteLog(0x534e4554, "26324358");
if (type != NULL) {
*type = kMetadataBufferTypeInvalid;
}
return BAD_VALUE;
}
OMX_INDEXTYPE index;
OMX_STRING name = const_cast<OMX_STRING>(
"OMX.google.android.index.storeMetaDataInBuffers");
OMX_STRING nativeBufferName = const_cast<OMX_STRING>(
"OMX.google.android.index.storeANWBufferInMetadata");
MetadataBufferType negotiatedType;
MetadataBufferType requestedType = type != NULL ? *type : kMetadataBufferTypeANWBuffer;
StoreMetaDataInBuffersParams params;
InitOMXParams(¶ms);
params.nPortIndex = portIndex;
params.bStoreMetaData = enable;
OMX_ERRORTYPE err =
requestedType == kMetadataBufferTypeANWBuffer
? OMX_GetExtensionIndex(mHandle, nativeBufferName, &index)
: OMX_ErrorUnsupportedIndex;
OMX_ERRORTYPE xerr = err;
if (err == OMX_ErrorNone) {
err = OMX_SetParameter(mHandle, index, ¶ms);
if (err == OMX_ErrorNone) {
name = nativeBufferName; // set name for debugging
negotiatedType = requestedType;
}
}
if (err != OMX_ErrorNone) {
err = OMX_GetExtensionIndex(mHandle, name, &index);
xerr = err;
if (err == OMX_ErrorNone) {
negotiatedType =
requestedType == kMetadataBufferTypeANWBuffer
? kMetadataBufferTypeGrallocSource : requestedType;
err = OMX_SetParameter(mHandle, index, ¶ms);
}
}
if (err != OMX_ErrorNone) {
if (err == OMX_ErrorUnsupportedIndex && portIndex == kPortIndexOutput) {
CLOGW("component does not support metadata mode; using fallback");
} else if (xerr != OMX_ErrorNone) {
CLOG_ERROR(getExtensionIndex, xerr, "%s", name);
} else {
CLOG_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d type=%d", name, index,
portString(portIndex), portIndex, enable, negotiatedType);
}
negotiatedType = mMetadataType[portIndex];
} else {
if (!enable) {
negotiatedType = kMetadataBufferTypeInvalid;
}
mMetadataType[portIndex] = negotiatedType;
}
CLOG_CONFIG(storeMetaDataInBuffers, "%s:%u %srequested %s:%d negotiated %s:%d",
portString(portIndex), portIndex, enable ? "" : "UN",
asString(requestedType), requestedType, asString(negotiatedType), negotiatedType);
if (type != NULL) {
*type = negotiatedType;
}
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200
|
status_t OMXNodeInstance::storeMetaDataInBuffers_l(
OMX_U32 portIndex, OMX_BOOL enable, MetadataBufferType *type) {
if (mSailed) {
android_errorWriteLog(0x534e4554, "29422020");
return INVALID_OPERATION;
}
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
android_errorWriteLog(0x534e4554, "26324358");
if (type != NULL) {
*type = kMetadataBufferTypeInvalid;
}
return BAD_VALUE;
}
OMX_INDEXTYPE index;
OMX_STRING name = const_cast<OMX_STRING>(
"OMX.google.android.index.storeMetaDataInBuffers");
OMX_STRING nativeBufferName = const_cast<OMX_STRING>(
"OMX.google.android.index.storeANWBufferInMetadata");
MetadataBufferType negotiatedType;
MetadataBufferType requestedType = type != NULL ? *type : kMetadataBufferTypeANWBuffer;
StoreMetaDataInBuffersParams params;
InitOMXParams(¶ms);
params.nPortIndex = portIndex;
params.bStoreMetaData = enable;
OMX_ERRORTYPE err =
requestedType == kMetadataBufferTypeANWBuffer
? OMX_GetExtensionIndex(mHandle, nativeBufferName, &index)
: OMX_ErrorUnsupportedIndex;
OMX_ERRORTYPE xerr = err;
if (err == OMX_ErrorNone) {
err = OMX_SetParameter(mHandle, index, ¶ms);
if (err == OMX_ErrorNone) {
name = nativeBufferName; // set name for debugging
negotiatedType = requestedType;
}
}
if (err != OMX_ErrorNone) {
err = OMX_GetExtensionIndex(mHandle, name, &index);
xerr = err;
if (err == OMX_ErrorNone) {
negotiatedType =
requestedType == kMetadataBufferTypeANWBuffer
? kMetadataBufferTypeGrallocSource : requestedType;
err = OMX_SetParameter(mHandle, index, ¶ms);
}
}
if (err != OMX_ErrorNone) {
if (err == OMX_ErrorUnsupportedIndex && portIndex == kPortIndexOutput) {
CLOGW("component does not support metadata mode; using fallback");
} else if (xerr != OMX_ErrorNone) {
CLOG_ERROR(getExtensionIndex, xerr, "%s", name);
} else {
CLOG_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d type=%d", name, index,
portString(portIndex), portIndex, enable, negotiatedType);
}
negotiatedType = mMetadataType[portIndex];
} else {
if (!enable) {
negotiatedType = kMetadataBufferTypeInvalid;
}
mMetadataType[portIndex] = negotiatedType;
}
CLOG_CONFIG(storeMetaDataInBuffers, "%s:%u %srequested %s:%d negotiated %s:%d",
portString(portIndex), portIndex, enable ? "" : "UN",
asString(requestedType), requestedType, asString(negotiatedType), negotiatedType);
if (type != NULL) {
*type = negotiatedType;
}
return StatusFromOMXError(err);
}
| 174,140
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: mainloop_destroy_trigger(crm_trigger_t * source)
{
source->trigger = FALSE;
if (source->id > 0) {
g_source_remove(source->id);
}
return TRUE;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
|
mainloop_destroy_trigger(crm_trigger_t * source)
{
source->trigger = FALSE;
if (source->id > 0) {
g_source_remove(source->id);
source->id = 0;
}
return TRUE;
}
| 166,157
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: rename_principal_2_svc(rprinc_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg1,
*prime_arg2;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
restriction_t *rp;
const char *errmsg = NULL;
size_t tlen1, tlen2, clen, slen;
char *tdots1, *tdots2, *cdots, *sdots;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->src, &prime_arg1) ||
krb5_unparse_name(handle->context, arg->dest, &prime_arg2)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
tlen1 = strlen(prime_arg1);
trunc_name(&tlen1, &tdots1);
tlen2 = strlen(prime_arg2);
trunc_name(&tlen2, &tdots2);
clen = client_name.length;
trunc_name(&clen, &cdots);
slen = service_name.length;
trunc_name(&slen, &sdots);
ret.code = KADM5_OK;
if (! CHANGEPW_SERVICE(rqstp)) {
if (!kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_DELETE, arg->src, NULL))
ret.code = KADM5_AUTH_DELETE;
/* any restrictions at all on the ADD kills the RENAME */
if (!kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_ADD, arg->dest, &rp) || rp) {
if (ret.code == KADM5_AUTH_DELETE)
ret.code = KADM5_AUTH_INSUFFICIENT;
else
ret.code = KADM5_AUTH_ADD;
}
} else
ret.code = KADM5_AUTH_INSUFFICIENT;
if (ret.code != KADM5_OK) {
/* okay to cast lengths to int because trunc_name limits max value */
krb5_klog_syslog(LOG_NOTICE,
_("Unauthorized request: kadm5_rename_principal, "
"%.*s%s to %.*s%s, "
"client=%.*s%s, service=%.*s%s, addr=%s"),
(int)tlen1, prime_arg1, tdots1,
(int)tlen2, prime_arg2, tdots2,
(int)clen, (char *)client_name.value, cdots,
(int)slen, (char *)service_name.value, sdots,
client_addr(rqstp->rq_xprt));
} else {
ret.code = kadm5_rename_principal((void *)handle, arg->src,
arg->dest);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
/* okay to cast lengths to int because trunc_name limits max value */
krb5_klog_syslog(LOG_NOTICE,
_("Request: kadm5_rename_principal, "
"%.*s%s to %.*s%s, %s, "
"client=%.*s%s, service=%.*s%s, addr=%s"),
(int)tlen1, prime_arg1, tdots1,
(int)tlen2, prime_arg2, tdots2,
errmsg ? errmsg : _("success"),
(int)clen, (char *)client_name.value, cdots,
(int)slen, (char *)service_name.value, sdots,
client_addr(rqstp->rq_xprt));
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg1);
free(prime_arg2);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119
|
rename_principal_2_svc(rprinc_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg1 = NULL, *prime_arg2 = NULL;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
restriction_t *rp;
const char *errmsg = NULL;
size_t tlen1, tlen2, clen, slen;
char *tdots1, *tdots2, *cdots, *sdots;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->src, &prime_arg1) ||
krb5_unparse_name(handle->context, arg->dest, &prime_arg2)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
tlen1 = strlen(prime_arg1);
trunc_name(&tlen1, &tdots1);
tlen2 = strlen(prime_arg2);
trunc_name(&tlen2, &tdots2);
clen = client_name.length;
trunc_name(&clen, &cdots);
slen = service_name.length;
trunc_name(&slen, &sdots);
ret.code = KADM5_OK;
if (! CHANGEPW_SERVICE(rqstp)) {
if (!kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_DELETE, arg->src, NULL))
ret.code = KADM5_AUTH_DELETE;
/* any restrictions at all on the ADD kills the RENAME */
if (!kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_ADD, arg->dest, &rp) || rp) {
if (ret.code == KADM5_AUTH_DELETE)
ret.code = KADM5_AUTH_INSUFFICIENT;
else
ret.code = KADM5_AUTH_ADD;
}
} else
ret.code = KADM5_AUTH_INSUFFICIENT;
if (ret.code != KADM5_OK) {
/* okay to cast lengths to int because trunc_name limits max value */
krb5_klog_syslog(LOG_NOTICE,
_("Unauthorized request: kadm5_rename_principal, "
"%.*s%s to %.*s%s, "
"client=%.*s%s, service=%.*s%s, addr=%s"),
(int)tlen1, prime_arg1, tdots1,
(int)tlen2, prime_arg2, tdots2,
(int)clen, (char *)client_name.value, cdots,
(int)slen, (char *)service_name.value, sdots,
client_addr(rqstp->rq_xprt));
} else {
ret.code = kadm5_rename_principal((void *)handle, arg->src,
arg->dest);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
/* okay to cast lengths to int because trunc_name limits max value */
krb5_klog_syslog(LOG_NOTICE,
_("Request: kadm5_rename_principal, "
"%.*s%s to %.*s%s, %s, "
"client=%.*s%s, service=%.*s%s, addr=%s"),
(int)tlen1, prime_arg1, tdots1,
(int)tlen2, prime_arg2, tdots2,
errmsg ? errmsg : _("success"),
(int)clen, (char *)client_name.value, cdots,
(int)slen, (char *)service_name.value, sdots,
client_addr(rqstp->rq_xprt));
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
exit_func:
free(prime_arg1);
free(prime_arg2);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,523
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long Chapters::Edition::ParseAtom(
IMkvReader* pReader,
long long pos,
long long size)
{
if (!ExpandAtomsArray())
return -1;
Atom& a = m_atoms[m_atoms_count++];
a.Init();
return a.Parse(pReader, pos, size);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long Chapters::Edition::ParseAtom(
SegmentInfo::~SegmentInfo() {
delete[] m_pMuxingAppAsUTF8;
m_pMuxingAppAsUTF8 = NULL;
delete[] m_pWritingAppAsUTF8;
m_pWritingAppAsUTF8 = NULL;
delete[] m_pTitleAsUTF8;
m_pTitleAsUTF8 = NULL;
}
| 174,415
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: Horizontal_Sweep_Span( RAS_ARGS Short y,
FT_F26Dot6 x1,
FT_F26Dot6 x2,
PProfile left,
PProfile right )
{
FT_UNUSED( left );
FT_UNUSED( right );
if ( x2 - x1 < ras.precision )
{
Long e1, e2;
e1 = CEILING( x1 );
e2 = FLOOR ( x2 );
if ( e1 == e2 )
{
Byte f1;
PByte bits;
bits = ras.bTarget + ( y >> 3 );
f1 = (Byte)( 0x80 >> ( y & 7 ) );
e1 = TRUNC( e1 );
if ( e1 >= 0 && e1 < ras.target.rows )
{
PByte p;
p = bits - e1 * ras.target.pitch;
if ( ras.target.pitch > 0 )
p += ( ras.target.rows - 1 ) * ras.target.pitch;
p[0] |= f1;
}
}
}
}
Commit Message:
CWE ID: CWE-119
|
Horizontal_Sweep_Span( RAS_ARGS Short y,
FT_F26Dot6 x1,
FT_F26Dot6 x2,
PProfile left,
PProfile right )
{
FT_UNUSED( left );
FT_UNUSED( right );
if ( x2 - x1 < ras.precision )
{
Long e1, e2;
e1 = CEILING( x1 );
e2 = FLOOR ( x2 );
if ( e1 == e2 )
{
Byte f1;
PByte bits;
bits = ras.bTarget + ( y >> 3 );
f1 = (Byte)( 0x80 >> ( y & 7 ) );
e1 = TRUNC( e1 );
if ( e1 >= 0 && (ULong)e1 < ras.target.rows )
{
PByte p;
p = bits - e1 * ras.target.pitch;
if ( ras.target.pitch > 0 )
p += ( ras.target.rows - 1 ) * ras.target.pitch;
p[0] |= f1;
}
}
}
}
| 164,853
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert,
BIO *dcont, BIO *out, unsigned int flags)
{
int r;
BIO *cont;
if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_enveloped) {
CMSerr(CMS_F_CMS_DECRYPT, CMS_R_TYPE_NOT_ENVELOPED_DATA);
return 0;
}
if (!dcont && !check_content(cms))
return 0;
if (flags & CMS_DEBUG_DECRYPT)
cms->d.envelopedData->encryptedContentInfo->debug = 1;
else
cms->d.envelopedData->encryptedContentInfo->debug = 0;
if (!pk && !cert && !dcont && !out)
return 1;
if (pk && !CMS_decrypt_set1_pkey(cms, pk, cert))
r = cms_copy_content(out, cont, flags);
do_free_upto(cont, dcont);
return r;
}
Commit Message:
CWE ID: CWE-311
|
int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert,
BIO *dcont, BIO *out, unsigned int flags)
{
int r;
BIO *cont;
if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_enveloped) {
CMSerr(CMS_F_CMS_DECRYPT, CMS_R_TYPE_NOT_ENVELOPED_DATA);
return 0;
}
if (!dcont && !check_content(cms))
return 0;
if (flags & CMS_DEBUG_DECRYPT)
cms->d.envelopedData->encryptedContentInfo->debug = 1;
else
cms->d.envelopedData->encryptedContentInfo->debug = 0;
if (!cert)
cms->d.envelopedData->encryptedContentInfo->havenocert = 1;
else
cms->d.envelopedData->encryptedContentInfo->havenocert = 0;
if (!pk && !cert && !dcont && !out)
return 1;
if (pk && !CMS_decrypt_set1_pkey(cms, pk, cert))
r = cms_copy_content(out, cont, flags);
do_free_upto(cont, dcont);
return r;
}
| 165,138
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static Image *ReadNULLImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickPixelPacket
background;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if (image->columns == 0)
image->columns=1;
if (image->rows == 0)
image->rows=1;
image->matte=MagickTrue;
GetMagickPixelPacket(image,&background);
background.opacity=(MagickRealType) TransparentOpacity;
if (image->colorspace == CMYKColorspace)
ConvertRGBToCMYK(&background);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelPacket(image,&background,q,indexes);
q++;
indexes++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
|
static Image *ReadNULLImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickPixelPacket
background;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if (image->columns == 0)
image->columns=1;
if (image->rows == 0)
image->rows=1;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->matte=MagickTrue;
GetMagickPixelPacket(image,&background);
background.opacity=(MagickRealType) TransparentOpacity;
if (image->colorspace == CMYKColorspace)
ConvertRGBToCMYK(&background);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelPacket(image,&background,q,indexes);
q++;
indexes++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(GetFirstImageInList(image));
}
| 168,586
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void _php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax TSRMLS_DC)
{
if (prev_options != NULL) {
*prev_options = MBREX(regex_default_options);
}
if (prev_syntax != NULL) {
*prev_syntax = MBREX(regex_default_syntax);
}
MBREX(regex_default_options) = options;
MBREX(regex_default_syntax) = syntax;
}
Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free
CWE ID: CWE-415
|
static void _php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax TSRMLS_DC)
static void _php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax TSRMLS_DC)
{
if (prev_options != NULL) {
*prev_options = MBREX(regex_default_options);
}
if (prev_syntax != NULL) {
*prev_syntax = MBREX(regex_default_syntax);
}
MBREX(regex_default_options) = options;
MBREX(regex_default_syntax) = syntax;
}
| 167,121
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: freeimage(Image *image)
{
freebuffer(image);
png_image_free(&image->image);
if (image->input_file != NULL)
{
fclose(image->input_file);
image->input_file = NULL;
}
if (image->input_memory != NULL)
{
free(image->input_memory);
image->input_memory = NULL;
image->input_memory_size = 0;
}
if (image->tmpfile_name[0] != 0 && (image->opts & KEEP_TMPFILES) == 0)
{
remove(image->tmpfile_name);
image->tmpfile_name[0] = 0;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
freeimage(Image *image)
{
freebuffer(image);
png_image_free(&image->image);
if (image->input_file != NULL)
{
fclose(image->input_file);
image->input_file = NULL;
}
if (image->input_memory != NULL)
{
free(image->input_memory);
image->input_memory = NULL;
image->input_memory_size = 0;
}
if (image->tmpfile_name[0] != 0 && (image->opts & KEEP_TMPFILES) == 0)
{
(void)remove(image->tmpfile_name);
image->tmpfile_name[0] = 0;
}
}
| 173,594
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: TestWCDelegateForDialogsAndFullscreen()
: is_fullscreen_(false), message_loop_runner_(new MessageLoopRunner) {}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <nasko@chromium.org>
Reviewed-by: Philip Jägenstedt <foolip@chromium.org>
Commit-Queue: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
|
TestWCDelegateForDialogsAndFullscreen()
| 172,718
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
int in_depth, int out_depth)
{
PNG_CONST unsigned int outmax = (1U<<out_depth)-1;
vi->pp = pp;
vi->dp = dp;
if (dp->sbit > 0 && dp->sbit < in_depth)
{
vi->sbit = dp->sbit;
vi->isbit_shift = in_depth - dp->sbit;
}
else
{
vi->sbit = (png_byte)in_depth;
vi->isbit_shift = 0;
}
vi->sbit_max = (1U << vi->sbit)-1;
/* This mimics the libpng threshold test, '0' is used to prevent gamma
* correction in the validation test.
*/
vi->screen_gamma = dp->screen_gamma;
if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
vi->screen_gamma = vi->screen_inverse = 0;
else
vi->screen_inverse = 1/vi->screen_gamma;
vi->use_input_precision = dp->use_input_precision;
vi->outmax = outmax;
vi->maxabs = abserr(dp->pm, in_depth, out_depth);
vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
vi->maxout = outerr(dp->pm, in_depth, out_depth);
vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
vi->maxout_total = vi->maxout + vi->outquant * .5;
vi->outlog = outlog(dp->pm, in_depth, out_depth);
if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
(dp->this.colour_type == 3 && dp->this.is_transparent))
{
vi->do_background = dp->do_background;
if (vi->do_background != 0)
{
PNG_CONST double bg_inverse = 1/dp->background_gamma;
double r, g, b;
/* Caller must at least put the gray value into the red channel */
r = dp->background_color.red; r /= outmax;
g = dp->background_color.green; g /= outmax;
b = dp->background_color.blue; b /= outmax;
# if 0
/* libpng doesn't do this optimization, if we do pngvalid will fail.
*/
if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
# endif
{
r = pow(r, bg_inverse);
g = pow(g, bg_inverse);
b = pow(b, bg_inverse);
}
vi->background_red = r;
vi->background_green = g;
vi->background_blue = b;
}
}
else
vi->do_background = 0;
if (vi->do_background == 0)
vi->background_red = vi->background_green = vi->background_blue = 0;
vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
vi->gamma_correction = 0;
vi->file_inverse = 1/dp->file_gamma;
if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
vi->file_inverse = 0;
vi->scale16 = dp->scale16;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
int in_depth, int out_depth)
{
const unsigned int outmax = (1U<<out_depth)-1;
vi->pp = pp;
vi->dp = dp;
if (dp->sbit > 0 && dp->sbit < in_depth)
{
vi->sbit = dp->sbit;
vi->isbit_shift = in_depth - dp->sbit;
}
else
{
vi->sbit = (png_byte)in_depth;
vi->isbit_shift = 0;
}
vi->sbit_max = (1U << vi->sbit)-1;
/* This mimics the libpng threshold test, '0' is used to prevent gamma
* correction in the validation test.
*/
vi->screen_gamma = dp->screen_gamma;
if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
vi->screen_gamma = vi->screen_inverse = 0;
else
vi->screen_inverse = 1/vi->screen_gamma;
vi->use_input_precision = dp->use_input_precision;
vi->outmax = outmax;
vi->maxabs = abserr(dp->pm, in_depth, out_depth);
vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
vi->maxout = outerr(dp->pm, in_depth, out_depth);
vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
vi->maxout_total = vi->maxout + vi->outquant * .5;
vi->outlog = outlog(dp->pm, in_depth, out_depth);
if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
(dp->this.colour_type == 3 && dp->this.is_transparent) ||
((dp->this.colour_type == 0 || dp->this.colour_type == 2) &&
dp->this.has_tRNS))
{
vi->do_background = dp->do_background;
if (vi->do_background != 0)
{
const double bg_inverse = 1/dp->background_gamma;
double r, g, b;
/* Caller must at least put the gray value into the red channel */
r = dp->background_color.red; r /= outmax;
g = dp->background_color.green; g /= outmax;
b = dp->background_color.blue; b /= outmax;
# if 0
/* libpng doesn't do this optimization, if we do pngvalid will fail.
*/
if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
# endif
{
r = pow(r, bg_inverse);
g = pow(g, bg_inverse);
b = pow(b, bg_inverse);
}
vi->background_red = r;
vi->background_green = g;
vi->background_blue = b;
}
}
else /* Do not expect any background processing */
vi->do_background = 0;
if (vi->do_background == 0)
vi->background_red = vi->background_green = vi->background_blue = 0;
vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
vi->gamma_correction = 0;
vi->file_inverse = 1/dp->file_gamma;
if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
vi->file_inverse = 0;
vi->scale16 = dp->scale16;
}
| 173,658
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (0 == plen) {
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[1], (plen + 7) / 8);
memcpy(&route_target, &pptr[1], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)),
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
}
Commit Message: CVE-2017-13053/BGP: fix VPN route target bounds checks
decode_rt_routing_info() didn't check bounds before fetching 4 octets of
the origin AS field and could over-read the input buffer, put it right.
It also fetched the varying number of octets of the route target field
from 4 octets lower than the correct offset, put it right.
It also used the same temporary buffer explicitly through as_printf()
and implicitly through bgp_vpn_rd_print() so the end result of snprintf()
was not what was originally intended.
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
|
decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
char asbuf[sizeof(astostr)]; /* bgp_vpn_rd_print() overwrites astostr */
/* NLRI "prefix length" from RFC 2858 Section 4. */
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
/* NLRI "prefix" (ibid), valid lengths are { 0, 32, 33, ..., 96 } bits.
* RFC 4684 Section 4 defines the layout of "origin AS" and "route
* target" fields inside the "prefix" depending on its length.
*/
if (0 == plen) {
/* Without "origin AS", without "route target". */
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
/* With at least "origin AS", possibly with "route target". */
ND_TCHECK_32BITS(pptr + 1);
as_printf(ndo, asbuf, sizeof(asbuf), EXTRACT_32BITS(pptr + 1));
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
/* From now on (plen + 7) / 8 evaluates to { 0, 1, 2, ..., 8 }
* and gives the number of octets in the variable-length "route
* target" field inside this NLRI "prefix". Look for it.
*/
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[5], (plen + 7) / 8);
memcpy(&route_target, &pptr[5], (plen + 7) / 8);
/* Which specification says to do this? */
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
asbuf,
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
}
| 167,820
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void SubpelVarianceTest<vp9_subp_avg_variance_fn_t>::RefTest() {
for (int x = 0; x < 16; ++x) {
for (int y = 0; y < 16; ++y) {
for (int j = 0; j < block_size_; j++) {
src_[j] = rnd.Rand8();
sec_[j] = rnd.Rand8();
}
for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) {
ref_[j] = rnd.Rand8();
}
unsigned int sse1, sse2;
unsigned int var1;
REGISTER_STATE_CHECK(var1 = subpel_variance_(ref_, width_ + 1, x, y,
src_, width_, &sse1, sec_));
const unsigned int var2 = subpel_avg_variance_ref(ref_, src_, sec_,
log2width_, log2height_,
x, y, &sse2);
EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y;
EXPECT_EQ(var1, var2) << "at position " << x << ", " << y;
}
}
}
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 SubpelVarianceTest<vp9_subp_avg_variance_fn_t>::RefTest() {
void SubpelVarianceTest<SubpixAvgVarMxNFunc>::RefTest() {
for (int x = 0; x < 8; ++x) {
for (int y = 0; y < 8; ++y) {
if (!use_high_bit_depth_) {
for (int j = 0; j < block_size_; j++) {
src_[j] = rnd_.Rand8();
sec_[j] = rnd_.Rand8();
}
for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) {
ref_[j] = rnd_.Rand8();
}
#if CONFIG_VP9_HIGHBITDEPTH
} else {
for (int j = 0; j < block_size_; j++) {
CONVERT_TO_SHORTPTR(src_)[j] = rnd_.Rand16() & mask_;
CONVERT_TO_SHORTPTR(sec_)[j] = rnd_.Rand16() & mask_;
}
for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) {
CONVERT_TO_SHORTPTR(ref_)[j] = rnd_.Rand16() & mask_;
}
#endif // CONFIG_VP9_HIGHBITDEPTH
}
unsigned int sse1, sse2;
unsigned int var1;
ASM_REGISTER_STATE_CHECK(
var1 = subpel_variance_(ref_, width_ + 1, x, y,
src_, width_, &sse1, sec_));
const unsigned int var2 = subpel_avg_variance_ref(ref_, src_, sec_,
log2width_, log2height_,
x, y, &sse2,
use_high_bit_depth_,
bit_depth_);
EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y;
EXPECT_EQ(var1, var2) << "at position " << x << ", " << y;
}
}
}
| 174,588
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ChromeRenderMessageFilter::OnWriteTcmallocHeapProfile(
const FilePath::StringType& filepath,
const std::string& output) {
VLOG(0) << "Writing renderer heap profile dump to: " << filepath;
file_util::WriteFile(FilePath(filepath), output.c_str(), output.size());
}
Commit Message: Disable tcmalloc profile files.
BUG=154983
TBR=darin@chromium.org
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/11087041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void ChromeRenderMessageFilter::OnWriteTcmallocHeapProfile(
| 170,664
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool SVGElement::HasSVGParent() const {
return ParentOrShadowHostElement() &&
ParentOrShadowHostElement()->IsSVGElement();
}
Commit Message: Fix SVG crash for v0 distribution into foreignObject.
We require a parent element to be an SVG element for non-svg-root
elements in order to create a LayoutObject for them. However, we checked
the light tree parent element, not the flat tree one which is the parent
for the layout tree construction. Note that this is just an issue in
Shadow DOM v0 since v1 does not allow shadow roots on SVG elements.
Bug: 915469
Change-Id: Id81843abad08814fae747b5bc81c09666583f130
Reviewed-on: https://chromium-review.googlesource.com/c/1382494
Reviewed-by: Fredrik Söderquist <fs@opera.com>
Commit-Queue: Rune Lillesveen <futhark@chromium.org>
Cr-Commit-Position: refs/heads/master@{#617487}
CWE ID: CWE-704
|
bool SVGElement::HasSVGParent() const {
Element* parent = FlatTreeTraversal::ParentElement(*this);
return parent && parent->IsSVGElement();
}
| 173,065
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
int pkt_len, pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9d", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, TOSHIBA_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
Commit Message: Fix packet length handling.
Treat the packet length as unsigned - it shouldn't be negative in the
file. If it is, that'll probably cause the sscanf to fail, so we'll
report the file as bad.
Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to
allocate a huge amount of memory, just as we do in other file readers.
Use the now-validated packet size as the length in
ws_buffer_assure_space(), so we are certain to have enough space, and
don't allocate too much space.
Bug: 12394
Change-Id: Ifa023ce70f7a2697bf151009b035a6e6cf8d5d90
Reviewed-on: https://code.wireshark.org/review/15169
Reviewed-by: Guy Harris <guy@alum.mit.edu>
CWE ID: CWE-20
|
parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
guint pkt_len;
int pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9u", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("toshiba: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
| 169,967
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void test_burl_normalize (void) {
buffer *psrc = buffer_init();
buffer *ptmp = buffer_init();
int flags;
flags = HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("no-slash"), CONST_STR_LEN("no-slash"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/"), CONST_STR_LEN("/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc"), CONST_STR_LEN("/abc"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/"), CONST_STR_LEN("/abc/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/def"), CONST_STR_LEN("/abc/def"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?"), CONST_STR_LEN("/abc?"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d"), CONST_STR_LEN("/abc?d"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d="), CONST_STR_LEN("/abc?d="));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e"), CONST_STR_LEN("/abc?d=e"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&"), CONST_STR_LEN("/abc?d=e&"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f"), CONST_STR_LEN("/abc?d=e&f"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#any"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2F"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%20"), CONST_STR_LEN("/%20"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2b"), CONST_STR_LEN("/%2B"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2B"), CONST_STR_LEN("/%2B"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3a"), CONST_STR_LEN("/%3A"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3A"), CONST_STR_LEN("/%3A"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/~test%20ä_"), CONST_STR_LEN("/~test%20%C3%A4_"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\375"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\376"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\377"), "", (size_t)-2);
flags = HTTP_PARSEOPT_URL_NORMALIZE_REQUIRED;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/"), CONST_STR_LEN("/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc"), CONST_STR_LEN("/abc"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/"), CONST_STR_LEN("/abc/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/def"), CONST_STR_LEN("/abc/def"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?"), CONST_STR_LEN("/abc?"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d"), CONST_STR_LEN("/abc?d"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d="), CONST_STR_LEN("/abc?d="));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e"), CONST_STR_LEN("/abc?d=e"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&"), CONST_STR_LEN("/abc?d=e&"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f"), CONST_STR_LEN("/abc?d=e&f"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#any"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2F"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%20"), CONST_STR_LEN("/%20"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2b"), CONST_STR_LEN("/+"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2B"), CONST_STR_LEN("/+"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3a"), CONST_STR_LEN("/:"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3A"), CONST_STR_LEN("/:"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/~test%20ä_"), CONST_STR_LEN("/~test%20%C3%A4_"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\375"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\376"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\377"), "", (size_t)-2);
flags |= HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\a"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\t"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\r"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\177"), "", (size_t)-2);
#if defined(__WIN32) || defined(__CYGWIN__)
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_BACKSLASH_TRANS;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a\\b"), CONST_STR_LEN("/a/b"));
#endif
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=/"), CONST_STR_LEN("/a/b?c=/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=%2f"), CONST_STR_LEN("/a/b?c=/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2Fb"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb?c=/"), CONST_STR_LEN("/a/b?c=/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb?c=%2f"), CONST_STR_LEN("/a/b?c=/"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2Fb"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=%2f"), CONST_STR_LEN("/a/b?c=/"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("./a/b"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("../a/b"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/./b"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b"), CONST_STR_LEN("/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/."), CONST_STR_LEN("/a/b/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/.."), CONST_STR_LEN("/a/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b/.."), CONST_STR_LEN("/"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("./a/b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("../a/b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/./b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/."), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/.."), "", (size_t)-2);
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=d+e"), CONST_STR_LEN("/a/b?c=d+e"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=d%20e"), CONST_STR_LEN("/a/b?c=d+e"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS;
buffer_free(psrc);
buffer_free(ptmp);
}
Commit Message: [core] fix abort in http-parseopts (fixes #2945)
fix abort in server.http-parseopts with url-path-2f-decode enabled
(thx stze)
x-ref:
"Security - SIGABRT during GET request handling with url-path-2f-decode enabled"
https://redmine.lighttpd.net/issues/2945
CWE ID: CWE-190
|
static void test_burl_normalize (void) {
buffer *psrc = buffer_init();
buffer *ptmp = buffer_init();
int flags;
flags = HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("no-slash"), CONST_STR_LEN("no-slash"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/"), CONST_STR_LEN("/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc"), CONST_STR_LEN("/abc"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/"), CONST_STR_LEN("/abc/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/def"), CONST_STR_LEN("/abc/def"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?"), CONST_STR_LEN("/abc?"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d"), CONST_STR_LEN("/abc?d"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d="), CONST_STR_LEN("/abc?d="));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e"), CONST_STR_LEN("/abc?d=e"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&"), CONST_STR_LEN("/abc?d=e&"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f"), CONST_STR_LEN("/abc?d=e&f"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#any"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2F"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%20"), CONST_STR_LEN("/%20"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2b"), CONST_STR_LEN("/%2B"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2B"), CONST_STR_LEN("/%2B"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3a"), CONST_STR_LEN("/%3A"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3A"), CONST_STR_LEN("/%3A"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/~test%20ä_"), CONST_STR_LEN("/~test%20%C3%A4_"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\375"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\376"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\377"), "", (size_t)-2);
flags = HTTP_PARSEOPT_URL_NORMALIZE_REQUIRED;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/"), CONST_STR_LEN("/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc"), CONST_STR_LEN("/abc"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/"), CONST_STR_LEN("/abc/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/def"), CONST_STR_LEN("/abc/def"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?"), CONST_STR_LEN("/abc?"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d"), CONST_STR_LEN("/abc?d"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d="), CONST_STR_LEN("/abc?d="));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e"), CONST_STR_LEN("/abc?d=e"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&"), CONST_STR_LEN("/abc?d=e&"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f"), CONST_STR_LEN("/abc?d=e&f"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#any"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2F"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%20"), CONST_STR_LEN("/%20"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2b"), CONST_STR_LEN("/+"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2B"), CONST_STR_LEN("/+"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3a"), CONST_STR_LEN("/:"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3A"), CONST_STR_LEN("/:"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/~test%20ä_"), CONST_STR_LEN("/~test%20%C3%A4_"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\375"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\376"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\377"), "", (size_t)-2);
flags |= HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\a"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\t"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\r"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\177"), "", (size_t)-2);
#if defined(__WIN32) || defined(__CYGWIN__)
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_BACKSLASH_TRANS;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a\\b"), CONST_STR_LEN("/a/b"));
#endif
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=/"), CONST_STR_LEN("/a/b?c=/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=%2f"), CONST_STR_LEN("/a/b?c=/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("%2f?"), CONST_STR_LEN("/?"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f?"), CONST_STR_LEN("//?"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2Fb"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb?c=/"), CONST_STR_LEN("/a/b?c=/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb?c=%2f"), CONST_STR_LEN("/a/b?c=/"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2Fb"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=%2f"), CONST_STR_LEN("/a/b?c=/"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("./a/b"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("../a/b"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/./b"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b"), CONST_STR_LEN("/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/."), CONST_STR_LEN("/a/b/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/.."), CONST_STR_LEN("/a/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b/.."), CONST_STR_LEN("/"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("./a/b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("../a/b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/./b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/."), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/.."), "", (size_t)-2);
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=d+e"), CONST_STR_LEN("/a/b?c=d+e"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=d%20e"), CONST_STR_LEN("/a/b?c=d+e"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS;
buffer_free(psrc);
buffer_free(ptmp);
}
| 169,710
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void Resource::LastPluginRefWasDeleted(bool instance_destroyed) {
DCHECK(resource_id_ != 0);
instance()->module()->GetCallbackTracker()->PostAbortForResource(
resource_id_);
resource_id_ = 0;
if (instance_destroyed)
instance_ = NULL;
}
Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed,
BUG=85808
Review URL: http://codereview.chromium.org/7196001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void Resource::LastPluginRefWasDeleted(bool instance_destroyed) {
void Resource::LastPluginRefWasDeleted() {
DCHECK(resource_id_ != 0);
instance()->module()->GetCallbackTracker()->PostAbortForResource(
resource_id_);
resource_id_ = 0;
}
| 170,413
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: cliprdr_process(STREAM s)
{
uint16 type, status;
uint32 length, format;
uint8 *data;
in_uint16_le(s, type);
in_uint16_le(s, status);
in_uint32_le(s, length);
data = s->p;
logger(Clipboard, Debug, "cliprdr_process(), type=%d, status=%d, length=%d", type, status,
length);
if (status == CLIPRDR_ERROR)
{
switch (type)
{
case CLIPRDR_FORMAT_ACK:
/* FIXME: We seem to get this when we send an announce while the server is
still processing a paste. Try sending another announce. */
cliprdr_send_native_format_announce(last_formats,
last_formats_length);
break;
case CLIPRDR_DATA_RESPONSE:
ui_clip_request_failed();
break;
default:
logger(Clipboard, Warning,
"cliprdr_process(), unhandled error (type=%d)", type);
}
return;
}
switch (type)
{
case CLIPRDR_CONNECT:
ui_clip_sync();
break;
case CLIPRDR_FORMAT_ANNOUNCE:
ui_clip_format_announce(data, length);
cliprdr_send_packet(CLIPRDR_FORMAT_ACK, CLIPRDR_RESPONSE, NULL, 0);
return;
case CLIPRDR_FORMAT_ACK:
break;
case CLIPRDR_DATA_REQUEST:
in_uint32_le(s, format);
ui_clip_request_data(format);
break;
case CLIPRDR_DATA_RESPONSE:
ui_clip_handle_data(data, length);
break;
case 7: /* TODO: W2K3 SP1 sends this on connect with a value of 1 */
break;
default:
logger(Clipboard, Warning, "cliprdr_process(), unhandled packet type %d",
type);
}
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119
|
cliprdr_process(STREAM s)
{
uint16 type, status;
uint32 length, format;
uint8 *data;
struct stream packet = *s;
in_uint16_le(s, type);
in_uint16_le(s, status);
in_uint32_le(s, length);
data = s->p;
logger(Clipboard, Debug, "cliprdr_process(), type=%d, status=%d, length=%d", type, status,
length);
if (!s_check_rem(s, length))
{
rdp_protocol_error("cliprdr_process(), consume of packet from stream would overrun", &packet);
}
if (status == CLIPRDR_ERROR)
{
switch (type)
{
case CLIPRDR_FORMAT_ACK:
/* FIXME: We seem to get this when we send an announce while the server is
still processing a paste. Try sending another announce. */
cliprdr_send_native_format_announce(last_formats,
last_formats_length);
break;
case CLIPRDR_DATA_RESPONSE:
ui_clip_request_failed();
break;
default:
logger(Clipboard, Warning,
"cliprdr_process(), unhandled error (type=%d)", type);
}
return;
}
switch (type)
{
case CLIPRDR_CONNECT:
ui_clip_sync();
break;
case CLIPRDR_FORMAT_ANNOUNCE:
ui_clip_format_announce(data, length);
cliprdr_send_packet(CLIPRDR_FORMAT_ACK, CLIPRDR_RESPONSE, NULL, 0);
return;
case CLIPRDR_FORMAT_ACK:
break;
case CLIPRDR_DATA_REQUEST:
in_uint32_le(s, format);
ui_clip_request_data(format);
break;
case CLIPRDR_DATA_RESPONSE:
ui_clip_handle_data(data, length);
break;
case 7: /* TODO: W2K3 SP1 sends this on connect with a value of 1 */
break;
default:
logger(Clipboard, Warning, "cliprdr_process(), unhandled packet type %d",
type);
}
}
| 169,796
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool SessionManager::Remove(const std::string& id) {
std::map<std::string, Session*>::iterator it;
Session* session;
base::AutoLock lock(map_lock_);
it = map_.find(id);
if (it == map_.end()) {
VLOG(1) << "No such session with ID " << id;
return false;
}
session = it->second;
map_.erase(it);
return true;
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool SessionManager::Remove(const std::string& id) {
std::map<std::string, Session*>::iterator it;
Session* session;
base::AutoLock lock(map_lock_);
it = map_.find(id);
if (it == map_.end())
return false;
session = it->second;
map_.erase(it);
return true;
}
| 170,464
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: INST_HANDLER (sts) { // STS k, Rr
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
ESIL_A ("r%d,", r);
__generic_ld_st (op, "ram", 0, 1, 0, k, 1);
op->cycles = 2;
}
Commit Message: Fix #10091 - crash in AVR analysis
CWE ID: CWE-125
|
INST_HANDLER (sts) { // STS k, Rr
if (len < 4) {
return;
}
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
ESIL_A ("r%d,", r);
__generic_ld_st (op, "ram", 0, 1, 0, k, 1);
op->cycles = 2;
}
| 169,223
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: header_put_le_8byte (SF_PRIVATE *psf, sf_count_t x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8)
{ psf->header [psf->headindex++] = x ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 24) ;
psf->header [psf->headindex++] = (x >> 32) ;
psf->header [psf->headindex++] = (x >> 40) ;
psf->header [psf->headindex++] = (x >> 48) ;
psf->header [psf->headindex++] = (x >> 56) ;
} ;
} /* header_put_le_8byte */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119
|
header_put_le_8byte (SF_PRIVATE *psf, sf_count_t x)
{ psf->header.ptr [psf->header.indx++] = x ;
psf->header.ptr [psf->header.indx++] = (x >> 8) ;
psf->header.ptr [psf->header.indx++] = (x >> 16) ;
psf->header.ptr [psf->header.indx++] = (x >> 24) ;
psf->header.ptr [psf->header.indx++] = (x >> 32) ;
psf->header.ptr [psf->header.indx++] = (x >> 40) ;
psf->header.ptr [psf->header.indx++] = (x >> 48) ;
psf->header.ptr [psf->header.indx++] = (x >> 56) ;
} /* header_put_le_8byte */
| 170,056
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int php_stream_memory_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */
{
time_t timestamp = 0;
php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract;
assert(ms != NULL);
memset(ssb, 0, sizeof(php_stream_statbuf));
/* read-only across the board */
ssb->sb.st_mode = ms->mode & TEMP_STREAM_READONLY ? 0444 : 0666;
ssb->sb.st_size = ms->fsize;
ssb->sb.st_mode |= S_IFREG; /* regular file */
#ifdef NETWARE
ssb->sb.st_mtime.tv_sec = timestamp;
ssb->sb.st_atime.tv_sec = timestamp;
ssb->sb.st_ctime.tv_sec = timestamp;
#else
ssb->sb.st_mtime = timestamp;
ssb->sb.st_atime = timestamp;
ssb->sb.st_ctime = timestamp;
#endif
ssb->sb.st_nlink = 1;
ssb->sb.st_rdev = -1;
/* this is only for APC, so use /dev/null device - no chance of conflict there! */
ssb->sb.st_dev = 0xC;
/* generate unique inode number for alias/filename, so no phars will conflict */
ssb->sb.st_ino = 0;
#ifndef PHP_WIN32
ssb->sb.st_blksize = -1;
#endif
#if !defined(PHP_WIN32) && !defined(__BEOS__)
ssb->sb.st_blocks = -1;
#endif
return 0;
}
/* }}} */
Commit Message:
CWE ID: CWE-20
|
static int php_stream_memory_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */
{
time_t timestamp = 0;
php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract;
assert(ms != NULL);
memset(ssb, 0, sizeof(php_stream_statbuf));
/* read-only across the board */
ssb->sb.st_mode = ms->mode & TEMP_STREAM_READONLY ? 0444 : 0666;
ssb->sb.st_size = ms->fsize;
ssb->sb.st_mode |= S_IFREG; /* regular file */
#ifdef NETWARE
ssb->sb.st_mtime.tv_sec = timestamp;
ssb->sb.st_atime.tv_sec = timestamp;
ssb->sb.st_ctime.tv_sec = timestamp;
#else
ssb->sb.st_mtime = timestamp;
ssb->sb.st_atime = timestamp;
ssb->sb.st_ctime = timestamp;
#endif
ssb->sb.st_nlink = 1;
ssb->sb.st_rdev = -1;
/* this is only for APC, so use /dev/null device - no chance of conflict there! */
ssb->sb.st_dev = 0xC;
/* generate unique inode number for alias/filename, so no phars will conflict */
ssb->sb.st_ino = 0;
#ifndef PHP_WIN32
ssb->sb.st_blksize = -1;
#endif
#if !defined(PHP_WIN32) && !defined(__BEOS__)
ssb->sb.st_blocks = -1;
#endif
return 0;
}
/* }}} */
| 165,477
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
length,
row_size;
ssize_t
count,
y;
unsigned char
*compact_pixels,
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RLE compressed");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
if ((MagickOffsetType) length < sizes[y])
length=(size_t) sizes[y];
if (length > row_size + 256) // arbitrary number
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"InvalidLength",
image->filename);
}
compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (compact_pixels == (unsigned char *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,(size_t) sizes[y],compact_pixels);
if (count != (ssize_t) sizes[y])
break;
count=DecodePSDPixels((size_t) sizes[y],compact_pixels,
(ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,
exception);
if (status == MagickFalse)
break;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/350
CWE ID: CWE-787
|
static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
length,
row_size;
ssize_t
count,
y;
unsigned char
*compact_pixels,
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RLE compressed");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
if ((MagickOffsetType) length < sizes[y])
length=(size_t) sizes[y];
if (length > row_size + 256) // arbitrary number
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"InvalidLength",image->filename);
}
compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (compact_pixels == (unsigned char *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,(size_t) sizes[y],compact_pixels);
if (count != (ssize_t) sizes[y])
break;
count=DecodePSDPixels((size_t) sizes[y],compact_pixels,
(ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,
exception);
if (status == MagickFalse)
break;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
| 168,404
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int svc_can_register(const uint16_t *name, size_t name_len, pid_t spid, uid_t uid)
{
const char *perm = "add";
return check_mac_perms_from_lookup(spid, uid, perm, str8(name, name_len)) ? 1 : 0;
}
Commit Message: ServiceManager: Restore basic uid check
Prevent apps from registering services without relying on selinux checks.
Bug: 29431260
Change-Id: I38c6e8bc7f7cba1cbd3568e8fed1ae7ac2054a9b
(cherry picked from commit 2b74d2c1d2a2c1bb6e9c420f7e9b339ba2a95179)
CWE ID: CWE-264
|
static int svc_can_register(const uint16_t *name, size_t name_len, pid_t spid, uid_t uid)
{
const char *perm = "add";
if (uid >= AID_APP) {
return 0; /* Don't allow apps to register services */
}
return check_mac_perms_from_lookup(spid, uid, perm, str8(name, name_len)) ? 1 : 0;
}
| 174,149
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: LosslessTestLarge()
: EncoderTest(GET_PARAM(0)),
psnr_(kMaxPsnr),
nframes_(0),
encoding_mode_(GET_PARAM(1)) {
}
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
|
LosslessTestLarge()
LosslessTest()
: EncoderTest(GET_PARAM(0)),
psnr_(kMaxPsnr),
nframes_(0),
encoding_mode_(GET_PARAM(1)) {
}
| 174,597
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void CheckSad(unsigned int max_sad) {
unsigned int reference_sad, exp_sad;
reference_sad = ReferenceSAD(max_sad);
exp_sad = SAD(max_sad);
if (reference_sad <= max_sad) {
ASSERT_EQ(exp_sad, reference_sad);
} else {
ASSERT_GE(exp_sad, reference_sad);
}
}
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 CheckSad(unsigned int max_sad) {
| 174,570
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void DestroySkImageOnOriginalThread(
sk_sp<SkImage> image,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
std::unique_ptr<gpu::SyncToken> sync_token) {
if (context_provider_wrapper &&
image->isValid(
context_provider_wrapper->ContextProvider()->GetGrContext())) {
if (sync_token->HasData()) {
context_provider_wrapper->ContextProvider()
->ContextGL()
->WaitSyncTokenCHROMIUM(sync_token->GetData());
}
image->getTexture()->textureParamsModified();
}
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <gab@chromium.org>
Reviewed-by: Jeremy Roman <jbroman@chromium.org>
Commit-Queue: Fernando Serboncini <fserb@chromium.org>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119
|
void DestroySkImageOnOriginalThread(
sk_sp<SkImage> image,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
std::unique_ptr<gpu::SyncToken> sync_token) {
if (context_provider_wrapper &&
image->isValid(
context_provider_wrapper->ContextProvider()->GetGrContext())) {
if (sync_token->HasData()) {
context_provider_wrapper->ContextProvider()
->ContextGL()
->WaitSyncTokenCHROMIUM(sync_token->GetData());
}
image->getTexture()->textureParamsModified();
}
image.reset();
}
| 172,593
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int raw_cmd_copyout(int cmd, void __user *param,
struct floppy_raw_cmd *ptr)
{
int ret;
while (ptr) {
ret = copy_to_user(param, ptr, sizeof(*ptr));
if (ret)
return -EFAULT;
param += sizeof(struct floppy_raw_cmd);
if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {
if (ptr->length >= 0 &&
ptr->length <= ptr->buffer_length) {
long length = ptr->buffer_length - ptr->length;
ret = fd_copyout(ptr->data, ptr->kernel_data,
length);
if (ret)
return ret;
}
}
ptr = ptr->next;
}
return 0;
}
Commit Message: floppy: don't write kernel-only members to FDRAWCMD ioctl output
Do not leak kernel-only floppy_raw_cmd structure members to userspace.
This includes the linked-list pointer and the pointer to the allocated
DMA space.
Signed-off-by: Matthew Daley <mattd@bugfuzz.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-264
|
static int raw_cmd_copyout(int cmd, void __user *param,
struct floppy_raw_cmd *ptr)
{
int ret;
while (ptr) {
struct floppy_raw_cmd cmd = *ptr;
cmd.next = NULL;
cmd.kernel_data = NULL;
ret = copy_to_user(param, &cmd, sizeof(cmd));
if (ret)
return -EFAULT;
param += sizeof(struct floppy_raw_cmd);
if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {
if (ptr->length >= 0 &&
ptr->length <= ptr->buffer_length) {
long length = ptr->buffer_length - ptr->length;
ret = fd_copyout(ptr->data, ptr->kernel_data,
length);
if (ret)
return ret;
}
}
ptr = ptr->next;
}
return 0;
}
| 166,434
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: explicit ElementsAccessorBase(const char* name)
: ElementsAccessor(name) { }
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704
|
explicit ElementsAccessorBase(const char* name)
| 174,095
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void WriteDDSInfo(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps)
{
char
software[MaxTextExtent];
register ssize_t
i;
unsigned int
format,
caps,
flags;
flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT |
DDSD_PIXELFORMAT | DDSD_LINEARSIZE);
caps=(unsigned int) DDSCAPS_TEXTURE;
format=(unsigned int) pixelFormat;
if (mipmaps > 0)
{
flags=flags | (unsigned int) DDSD_MIPMAPCOUNT;
caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX);
}
if (format != DDPF_FOURCC && image->matte)
format=format | DDPF_ALPHAPIXELS;
(void) WriteBlob(image,4,(unsigned char *) "DDS ");
(void) WriteBlobLSBLong(image,124);
(void) WriteBlobLSBLong(image,flags);
(void) WriteBlobLSBLong(image,(unsigned int) image->rows);
(void) WriteBlobLSBLong(image,(unsigned int) image->columns);
if (compression == FOURCC_DXT1)
(void) WriteBlobLSBLong(image,
(unsigned int) (Max(1,(image->columns+3)/4) * 8));
else
(void) WriteBlobLSBLong(image,
(unsigned int) (Max(1,(image->columns+3)/4) * 16));
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);
(void) ResetMagickMemory(software,0,sizeof(software));
(void) strcpy(software,"IMAGEMAGICK");
(void) WriteBlob(image,44,(unsigned char *) software);
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,format);
if (pixelFormat == DDPF_FOURCC)
{
(void) WriteBlobLSBLong(image,(unsigned int) compression);
for(i=0;i < 5;i++) // bitcount / masks
(void) WriteBlobLSBLong(image,0x00);
}
else
{
(void) WriteBlobLSBLong(image,0x00);
if (image->matte)
{
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0xff000000);
}
else
{
(void) WriteBlobLSBLong(image,24);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
}
}
(void) WriteBlobLSBLong(image,caps);
for(i=0;i < 4;i++) // ddscaps2 + reserved region
(void) WriteBlobLSBLong(image,0x00);
}
Commit Message: Added extra EOF check and some minor refactoring.
CWE ID: CWE-20
|
static void WriteDDSInfo(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps)
{
char
software[MaxTextExtent];
register ssize_t
i;
unsigned int
format,
caps,
flags;
flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT |
DDSD_PIXELFORMAT | DDSD_LINEARSIZE);
caps=(unsigned int) DDSCAPS_TEXTURE;
format=(unsigned int) pixelFormat;
if (mipmaps > 0)
{
flags=flags | (unsigned int) DDSD_MIPMAPCOUNT;
caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX);
}
if (format != DDPF_FOURCC && image->matte)
format=format | DDPF_ALPHAPIXELS;
(void) WriteBlob(image,4,(unsigned char *) "DDS ");
(void) WriteBlobLSBLong(image,124);
(void) WriteBlobLSBLong(image,flags);
(void) WriteBlobLSBLong(image,(unsigned int) image->rows);
(void) WriteBlobLSBLong(image,(unsigned int) image->columns);
if (compression == FOURCC_DXT1)
(void) WriteBlobLSBLong(image,
(unsigned int) (MagickMax(1,(image->columns+3)/4) * 8));
else
(void) WriteBlobLSBLong(image,
(unsigned int) (MagickMax(1,(image->columns+3)/4) * 16));
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);
(void) ResetMagickMemory(software,0,sizeof(software));
(void) strcpy(software,"IMAGEMAGICK");
(void) WriteBlob(image,44,(unsigned char *) software);
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,format);
if (pixelFormat == DDPF_FOURCC)
{
(void) WriteBlobLSBLong(image,(unsigned int) compression);
for(i=0;i < 5;i++) // bitcount / masks
(void) WriteBlobLSBLong(image,0x00);
}
else
{
(void) WriteBlobLSBLong(image,0x00);
if (image->matte)
{
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0xff000000);
}
else
{
(void) WriteBlobLSBLong(image,24);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,0x00);
}
}
(void) WriteBlobLSBLong(image,caps);
for(i=0;i < 4;i++) // ddscaps2 + reserved region
(void) WriteBlobLSBLong(image,0x00);
}
| 168,908
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: BlockEntry::~BlockEntry()
{
}
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
|
BlockEntry::~BlockEntry()
| 174,456
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int asepcos_parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf,
size_t len)
{
const u8 *p = buf;
while (len != 0) {
unsigned int amode, tlen = 3;
if (len < 5 && p[0] != 0x80 && p[1] != 0x01) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid access mode encoding");
return SC_ERROR_INTERNAL;
}
amode = p[2];
if (p[3] == 0x90 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NONE);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0x97 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NEVER);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0xA0 && len >= 4U + p[4]) {
/* TODO: support OR expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else if (p[3] == 0xAF && len >= 4U + p[4]) {
/* TODO: support AND expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid security condition");
return SC_ERROR_INTERNAL;
}
p += tlen;
len -= tlen;
}
return SC_SUCCESS;
}
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 asepcos_parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf,
size_t len)
{
const u8 *p = buf;
while (len != 0) {
unsigned int amode, tlen = 3;
if (len < 5 || p[0] != 0x80 || p[1] != 0x01) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid access mode encoding");
return SC_ERROR_INTERNAL;
}
amode = p[2];
if (p[3] == 0x90 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NONE);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0x97 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NEVER);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0xA0 && len >= 4U + p[4]) {
/* TODO: support OR expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else if (p[3] == 0xAF && len >= 4U + p[4]) {
/* TODO: support AND expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid security condition");
return SC_ERROR_INTERNAL;
}
p += tlen;
len -= tlen;
}
return SC_SUCCESS;
}
| 169,047
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: update_display(struct display *dp)
/* called once after the first read to update all the info, original_pp and
* original_ip must have been filled in.
*/
{
png_structp pp;
png_infop ip;
/* Now perform the initial read with a 0 tranform. */
read_png(dp, &dp->original_file, "original read", 0/*no transform*/);
/* Move the result to the 'original' fields */
dp->original_pp = pp = dp->read_pp, dp->read_pp = NULL;
dp->original_ip = ip = dp->read_ip, dp->read_ip = NULL;
dp->original_rowbytes = png_get_rowbytes(pp, ip);
if (dp->original_rowbytes == 0)
display_log(dp, LIBPNG_BUG, "png_get_rowbytes returned 0");
dp->chunks = png_get_valid(pp, ip, 0xffffffff);
if ((dp->chunks & PNG_INFO_IDAT) == 0) /* set by png_read_png */
display_log(dp, LIBPNG_BUG, "png_read_png did not set IDAT flag");
dp->original_rows = png_get_rows(pp, ip);
if (dp->original_rows == NULL)
display_log(dp, LIBPNG_BUG, "png_read_png did not create row buffers");
if (!png_get_IHDR(pp, ip,
&dp->width, &dp->height, &dp->bit_depth, &dp->color_type,
&dp->interlace_method, &dp->compression_method, &dp->filter_method))
display_log(dp, LIBPNG_BUG, "png_get_IHDR failed");
/* 'active' transforms are discovered based on the original image format;
* running one active transform can activate others. At present the code
* does not attempt to determine the closure.
*/
{
png_uint_32 chunks = dp->chunks;
int active = 0, inactive = 0;
int ct = dp->color_type;
int bd = dp->bit_depth;
unsigned int i;
for (i=0; i<TTABLE_SIZE; ++i)
{
int transform = transform_info[i].transform;
if ((transform_info[i].valid_chunks == 0 ||
(transform_info[i].valid_chunks & chunks) != 0) &&
(transform_info[i].color_mask_required & ct) ==
transform_info[i].color_mask_required &&
(transform_info[i].color_mask_absent & ct) == 0 &&
(transform_info[i].bit_depths & bd) != 0 &&
(transform_info[i].when & TRANSFORM_R) != 0)
active |= transform;
else if ((transform_info[i].when & TRANSFORM_R) != 0)
inactive |= transform;
}
/* Some transforms appear multiple times in the table; the 'active' status
* is the logical OR of these and the inactive status must be adjusted to
* take this into account.
*/
inactive &= ~active;
dp->active_transforms = active;
dp->ignored_transforms = inactive; /* excluding write-only transforms */
if (active == 0)
display_log(dp, INTERNAL_ERROR, "bad transform table");
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
update_display(struct display *dp)
/* called once after the first read to update all the info, original_pp and
* original_ip must have been filled in.
*/
{
png_structp pp;
png_infop ip;
/* Now perform the initial read with a 0 tranform. */
read_png(dp, &dp->original_file, "original read", 0/*no transform*/);
/* Move the result to the 'original' fields */
dp->original_pp = pp = dp->read_pp, dp->read_pp = NULL;
dp->original_ip = ip = dp->read_ip, dp->read_ip = NULL;
dp->original_rowbytes = png_get_rowbytes(pp, ip);
if (dp->original_rowbytes == 0)
display_log(dp, LIBPNG_BUG, "png_get_rowbytes returned 0");
dp->chunks = png_get_valid(pp, ip, 0xffffffff);
if ((dp->chunks & PNG_INFO_IDAT) == 0) /* set by png_read_png */
display_log(dp, LIBPNG_BUG, "png_read_png did not set IDAT flag");
dp->original_rows = png_get_rows(pp, ip);
if (dp->original_rows == NULL)
display_log(dp, LIBPNG_BUG, "png_read_png did not create row buffers");
if (!png_get_IHDR(pp, ip,
&dp->width, &dp->height, &dp->bit_depth, &dp->color_type,
&dp->interlace_method, &dp->compression_method, &dp->filter_method))
display_log(dp, LIBPNG_BUG, "png_get_IHDR failed");
/* 'active' transforms are discovered based on the original image format;
* running one active transform can activate others. At present the code
* does not attempt to determine the closure.
*/
{
png_uint_32 chunks = dp->chunks;
int active = 0, inactive = 0;
int ct = dp->color_type;
int bd = dp->bit_depth;
unsigned int i;
for (i=0; i<TTABLE_SIZE; ++i) if (transform_info[i].name != NULL)
{
int transform = transform_info[i].transform;
if ((transform_info[i].valid_chunks == 0 ||
(transform_info[i].valid_chunks & chunks) != 0) &&
(transform_info[i].color_mask_required & ct) ==
transform_info[i].color_mask_required &&
(transform_info[i].color_mask_absent & ct) == 0 &&
(transform_info[i].bit_depths & bd) != 0 &&
(transform_info[i].when & TRANSFORM_R) != 0)
active |= transform;
else if ((transform_info[i].when & TRANSFORM_R) != 0)
inactive |= transform;
}
/* Some transforms appear multiple times in the table; the 'active' status
* is the logical OR of these and the inactive status must be adjusted to
* take this into account.
*/
inactive &= ~active;
dp->active_transforms = active;
dp->ignored_transforms = inactive; /* excluding write-only transforms */
}
}
| 173,591
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: main(void)
{
fwrite(signature, sizeof signature, 1, stdout);
put_chunk(IHDR, sizeof IHDR);
for(;;)
put_chunk(unknown, sizeof unknown);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
main(void)
{
fwrite(signature, sizeof signature, 1, stdout);
put_chunk(IHDR, sizeof IHDR);
for (;;)
put_chunk(unknown, sizeof unknown);
}
| 173,577
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: const Block* Track::EOSBlock::GetBlock() const
{
return NULL;
}
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 Block* Track::EOSBlock::GetBlock() const
| 174,284
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftAACEncoder::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_encoder.aac",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPortFormat:
{
const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
if ((formatParams->nPortIndex == 0
&& formatParams->eEncoding != OMX_AUDIO_CodingPCM)
|| (formatParams->nPortIndex == 1
&& formatParams->eEncoding != OMX_AUDIO_CodingAAC)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (aacParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mBitRate = aacParams->nBitRate;
mNumChannels = aacParams->nChannels;
mSampleRate = aacParams->nSampleRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mNumChannels = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftAACEncoder::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_encoder.aac",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPortFormat:
{
const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (!isValidOMXParam(formatParams)) {
return OMX_ErrorBadParameter;
}
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
if ((formatParams->nPortIndex == 0
&& formatParams->eEncoding != OMX_AUDIO_CodingPCM)
|| (formatParams->nPortIndex == 1
&& formatParams->eEncoding != OMX_AUDIO_CodingAAC)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (!isValidOMXParam(aacParams)) {
return OMX_ErrorBadParameter;
}
if (aacParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mBitRate = aacParams->nBitRate;
mNumChannels = aacParams->nChannels;
mSampleRate = aacParams->nSampleRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mNumChannels = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,189
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static inline void uipc_wakeup_locked(void)
{
char sig_on = 1;
BTIF_TRACE_EVENT("UIPC SEND WAKE UP");
send(uipc_main.signal_fds[1], &sig_on, sizeof(sig_on), 0);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static inline void uipc_wakeup_locked(void)
{
char sig_on = 1;
BTIF_TRACE_EVENT("UIPC SEND WAKE UP");
TEMP_FAILURE_RETRY(send(uipc_main.signal_fds[1], &sig_on, sizeof(sig_on), 0));
}
| 173,499
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void v9fs_device_unrealize_common(V9fsState *s, Error **errp)
{
g_free(s->ctx.fs_root);
g_free(s->tag);
}
Commit Message:
CWE ID: CWE-400
|
void v9fs_device_unrealize_common(V9fsState *s, Error **errp)
{
g_free(s->tag);
g_free(s->ctx.fs_root);
}
| 164,896
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: InputImeEventRouter* GetInputImeEventRouter(Profile* profile) {
if (!profile)
return nullptr;
return extensions::InputImeEventRouterFactory::GetInstance()->GetRouter(
profile->GetOriginalProfile());
}
Commit Message: Fix the regression caused by http://crrev.com/c/1288350.
Bug: 900124,856135
Change-Id: Ie11ad406bd1ea383dc2a83cc8661076309154865
Reviewed-on: https://chromium-review.googlesource.com/c/1317010
Reviewed-by: Lan Wei <azurewei@chromium.org>
Commit-Queue: Shu Chen <shuchen@chromium.org>
Cr-Commit-Position: refs/heads/master@{#605282}
CWE ID: CWE-416
|
InputImeEventRouter* GetInputImeEventRouter(Profile* profile) {
if (!profile)
return nullptr;
return extensions::InputImeEventRouterFactory::GetInstance()->GetRouter(
profile);
}
| 172,646
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int cdxl_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *pkt)
{
CDXLVideoContext *c = avctx->priv_data;
AVFrame * const p = data;
int ret, w, h, encoding, aligned_width, buf_size = pkt->size;
const uint8_t *buf = pkt->data;
if (buf_size < 32)
return AVERROR_INVALIDDATA;
encoding = buf[1] & 7;
c->format = buf[1] & 0xE0;
w = AV_RB16(&buf[14]);
h = AV_RB16(&buf[16]);
c->bpp = buf[19];
c->palette_size = AV_RB16(&buf[20]);
c->palette = buf + 32;
c->video = c->palette + c->palette_size;
c->video_size = buf_size - c->palette_size - 32;
if (c->palette_size > 512)
return AVERROR_INVALIDDATA;
if (buf_size < c->palette_size + 32)
return AVERROR_INVALIDDATA;
if (c->bpp < 1)
return AVERROR_INVALIDDATA;
if (c->format != BIT_PLANAR && c->format != BIT_LINE && c->format != CHUNKY) {
avpriv_request_sample(avctx, "Pixel format 0x%0x", c->format);
return AVERROR_PATCHWELCOME;
}
if ((ret = ff_set_dimensions(avctx, w, h)) < 0)
return ret;
if (c->format == CHUNKY)
aligned_width = avctx->width;
else
aligned_width = FFALIGN(c->avctx->width, 16);
c->padded_bits = aligned_width - c->avctx->width;
if (c->video_size < aligned_width * avctx->height * (int64_t)c->bpp / 8)
return AVERROR_INVALIDDATA;
if (!encoding && c->palette_size && c->bpp <= 8 && c->format != CHUNKY) {
avctx->pix_fmt = AV_PIX_FMT_PAL8;
} else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8)) {
if (c->palette_size != (1 << (c->bpp - 1)))
return AVERROR_INVALIDDATA;
avctx->pix_fmt = AV_PIX_FMT_BGR24;
} else if (!encoding && c->bpp == 24 && c->format == CHUNKY &&
!c->palette_size) {
avctx->pix_fmt = AV_PIX_FMT_RGB24;
} else {
avpriv_request_sample(avctx, "Encoding %d, bpp %d and format 0x%x",
encoding, c->bpp, c->format);
return AVERROR_PATCHWELCOME;
}
if ((ret = ff_get_buffer(avctx, p, 0)) < 0)
return ret;
p->pict_type = AV_PICTURE_TYPE_I;
if (encoding) {
av_fast_padded_malloc(&c->new_video, &c->new_video_size,
h * w + AV_INPUT_BUFFER_PADDING_SIZE);
if (!c->new_video)
return AVERROR(ENOMEM);
if (c->bpp == 8)
cdxl_decode_ham8(c, p);
else
cdxl_decode_ham6(c, p);
} else if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
cdxl_decode_rgb(c, p);
} else {
cdxl_decode_raw(c, p);
}
*got_frame = 1;
return buf_size;
}
Commit Message: avcodec/cdxl: Check format for BGR24
Fixes: out of array access
Fixes: 1427/clusterfuzz-testcase-minimized-5020737339392000
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-119
|
static int cdxl_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *pkt)
{
CDXLVideoContext *c = avctx->priv_data;
AVFrame * const p = data;
int ret, w, h, encoding, aligned_width, buf_size = pkt->size;
const uint8_t *buf = pkt->data;
if (buf_size < 32)
return AVERROR_INVALIDDATA;
encoding = buf[1] & 7;
c->format = buf[1] & 0xE0;
w = AV_RB16(&buf[14]);
h = AV_RB16(&buf[16]);
c->bpp = buf[19];
c->palette_size = AV_RB16(&buf[20]);
c->palette = buf + 32;
c->video = c->palette + c->palette_size;
c->video_size = buf_size - c->palette_size - 32;
if (c->palette_size > 512)
return AVERROR_INVALIDDATA;
if (buf_size < c->palette_size + 32)
return AVERROR_INVALIDDATA;
if (c->bpp < 1)
return AVERROR_INVALIDDATA;
if (c->format != BIT_PLANAR && c->format != BIT_LINE && c->format != CHUNKY) {
avpriv_request_sample(avctx, "Pixel format 0x%0x", c->format);
return AVERROR_PATCHWELCOME;
}
if ((ret = ff_set_dimensions(avctx, w, h)) < 0)
return ret;
if (c->format == CHUNKY)
aligned_width = avctx->width;
else
aligned_width = FFALIGN(c->avctx->width, 16);
c->padded_bits = aligned_width - c->avctx->width;
if (c->video_size < aligned_width * avctx->height * (int64_t)c->bpp / 8)
return AVERROR_INVALIDDATA;
if (!encoding && c->palette_size && c->bpp <= 8 && c->format != CHUNKY) {
avctx->pix_fmt = AV_PIX_FMT_PAL8;
} else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8) && c->format != CHUNKY) {
if (c->palette_size != (1 << (c->bpp - 1)))
return AVERROR_INVALIDDATA;
avctx->pix_fmt = AV_PIX_FMT_BGR24;
} else if (!encoding && c->bpp == 24 && c->format == CHUNKY &&
!c->palette_size) {
avctx->pix_fmt = AV_PIX_FMT_RGB24;
} else {
avpriv_request_sample(avctx, "Encoding %d, bpp %d and format 0x%x",
encoding, c->bpp, c->format);
return AVERROR_PATCHWELCOME;
}
if ((ret = ff_get_buffer(avctx, p, 0)) < 0)
return ret;
p->pict_type = AV_PICTURE_TYPE_I;
if (encoding) {
av_fast_padded_malloc(&c->new_video, &c->new_video_size,
h * w + AV_INPUT_BUFFER_PADDING_SIZE);
if (!c->new_video)
return AVERROR(ENOMEM);
if (c->bpp == 8)
cdxl_decode_ham8(c, p);
else
cdxl_decode_ham6(c, p);
} else if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
cdxl_decode_rgb(c, p);
} else {
cdxl_decode_raw(c, p);
}
*got_frame = 1;
return buf_size;
}
| 168,069
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: flatpak_proxy_client_init (FlatpakProxyClient *client)
{
init_side (client, &client->client_side);
init_side (client, &client->bus_side);
client->auth_end_offset = AUTH_END_INIT_OFFSET;
client->rewrite_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref);
client->get_owner_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free);
client->unique_id_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
}
Commit Message: Fix vulnerability in dbus proxy
During the authentication all client data is directly forwarded
to the dbus daemon as is, until we detect the BEGIN command after
which we start filtering the binary dbus protocol.
Unfortunately the detection of the BEGIN command in the proxy
did not exactly match the detection in the dbus daemon. A BEGIN
followed by a space or tab was considered ok in the daemon but
not by the proxy. This could be exploited to send arbitrary
dbus messages to the host, which can be used to break out of
the sandbox.
This was noticed by Gabriel Campana of The Google Security Team.
This fix makes the detection of the authentication phase end
match the dbus code. In addition we duplicate the authentication
line validation from dbus, which includes ensuring all data is
ASCII, and limiting the size of a line to 16k. In fact, we add
some extra stringent checks, disallowing ASCII control chars and
requiring that auth lines start with a capital letter.
CWE ID: CWE-436
|
flatpak_proxy_client_init (FlatpakProxyClient *client)
{
init_side (client, &client->client_side);
init_side (client, &client->bus_side);
client->auth_buffer = g_byte_array_new ();
client->rewrite_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref);
client->get_owner_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free);
client->unique_id_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
}
| 169,342
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void PageRequestSummary::UpdateOrAddToOrigins(
const content::mojom::ResourceLoadInfo& resource_load_info) {
for (const auto& redirect_info : resource_load_info.redirect_info_chain)
UpdateOrAddToOrigins(redirect_info->url, redirect_info->network_info);
UpdateOrAddToOrigins(resource_load_info.url, resource_load_info.network_info);
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org>
Reviewed-by: Alex Ilin <alexilin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125
|
void PageRequestSummary::UpdateOrAddToOrigins(
const content::mojom::ResourceLoadInfo& resource_load_info) {
for (const auto& redirect_info : resource_load_info.redirect_info_chain) {
UpdateOrAddToOrigins(url::Origin::Create(redirect_info->url),
redirect_info->network_info);
}
UpdateOrAddToOrigins(url::Origin::Create(resource_load_info.url),
resource_load_info.network_info);
}
| 172,367
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long BlockEntry::GetIndex() const
{
return m_index;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long BlockEntry::GetIndex() const
| 174,329
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void WebPluginProxy::CreateCanvasFromHandle(
const TransportDIB::Handle& dib_handle,
const gfx::Rect& window_rect,
scoped_ptr<skia::PlatformCanvas>* canvas_out) {
HANDLE section;
DuplicateHandle(channel_->renderer_handle(), dib_handle, GetCurrentProcess(),
§ion,
STANDARD_RIGHTS_REQUIRED | FILE_MAP_READ | FILE_MAP_WRITE,
FALSE, 0);
scoped_ptr<skia::PlatformCanvas> canvas(new skia::PlatformCanvas);
if (!canvas->initialize(
window_rect.width(),
window_rect.height(),
true,
section)) {
canvas_out->reset();
}
canvas_out->reset(canvas.release());
CloseHandle(section);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void WebPluginProxy::CreateCanvasFromHandle(
const TransportDIB::Handle& dib_handle,
const gfx::Rect& window_rect,
scoped_ptr<skia::PlatformCanvas>* canvas_out) {
scoped_ptr<skia::PlatformCanvas> canvas(new skia::PlatformCanvas);
if (!canvas->initialize(
window_rect.width(),
window_rect.height(),
true,
dib_handle)) {
canvas_out->reset();
}
canvas_out->reset(canvas.release());
CloseHandle(dib_handle);
}
| 170,952
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool Track::VetEntry(const BlockEntry* pBlockEntry) const
{
assert(pBlockEntry);
const Block* const pBlock = pBlockEntry->GetBlock();
assert(pBlock);
assert(pBlock->GetTrackNumber() == m_info.number);
if (!pBlock || pBlock->GetTrackNumber() != m_info.number)
return false;
return true;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
bool Track::VetEntry(const BlockEntry* pBlockEntry) const
bool Track::VetEntry(const BlockEntry* pBlockEntry) const {
assert(pBlockEntry);
const Block* const pBlock = pBlockEntry->GetBlock();
assert(pBlock);
assert(pBlock->GetTrackNumber() == m_info.number);
if (!pBlock || pBlock->GetTrackNumber() != m_info.number)
return false;
// This function is used during a seek to determine whether the
// frame is a valid seek target. This default function simply
// returns true, which means all frames are valid seek targets.
// It gets overridden by the VideoTrack class, because only video
// keyframes can be used as seek target.
return true;
}
| 174,451
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: Cluster::Cluster(
Segment* pSegment,
long idx,
long long element_start
/* long long element_size */ ) :
m_pSegment(pSegment),
m_element_start(element_start),
m_index(idx),
m_pos(element_start),
m_element_size(-1 /* element_size */ ),
m_timecode(-1),
m_entries(NULL),
m_entries_size(0),
m_entries_count(-1) //means "has not been parsed yet"
{
}
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(
| 174,249
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx)
{
struct Vmxnet3_TxDesc txd;
uint32_t txd_idx;
uint32_t data_len;
hwaddr data_pa;
for (;;) {
if (!vmxnet3_pop_next_tx_descr(s, qidx, &txd, &txd_idx)) {
break;
}
vmxnet3_dump_tx_descr(&txd);
if (!s->skip_current_tx_pkt) {
data_len = (txd.len > 0) ? txd.len : VMXNET3_MAX_TX_BUF_SIZE;
data_pa = le64_to_cpu(txd.addr);
if (!vmxnet_tx_pkt_add_raw_fragment(s->tx_pkt,
data_pa,
data_len)) {
s->skip_current_tx_pkt = true;
}
}
if (s->tx_sop) {
vmxnet3_tx_retrieve_metadata(s, &txd);
s->tx_sop = false;
}
if (txd.eop) {
if (!s->skip_current_tx_pkt) {
vmxnet_tx_pkt_parse(s->tx_pkt);
if (s->needs_vlan) {
vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci);
}
vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci);
}
vmxnet3_send_packet(s, qidx);
} else {
vmxnet3_on_tx_done_update_stats(s, qidx,
VMXNET3_PKT_STATUS_ERROR);
}
vmxnet3_complete_packet(s, qidx, txd_idx);
s->tx_sop = true;
s->skip_current_tx_pkt = false;
vmxnet_tx_pkt_reset(s->tx_pkt);
}
}
Commit Message:
CWE ID: CWE-20
|
static void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx)
{
struct Vmxnet3_TxDesc txd;
uint32_t txd_idx;
uint32_t data_len;
hwaddr data_pa;
for (;;) {
if (!vmxnet3_pop_next_tx_descr(s, qidx, &txd, &txd_idx)) {
break;
}
vmxnet3_dump_tx_descr(&txd);
if (!s->skip_current_tx_pkt) {
data_len = (txd.len > 0) ? txd.len : VMXNET3_MAX_TX_BUF_SIZE;
data_pa = le64_to_cpu(txd.addr);
if (!vmxnet_tx_pkt_add_raw_fragment(s->tx_pkt,
data_pa,
data_len)) {
s->skip_current_tx_pkt = true;
}
}
if (s->tx_sop) {
vmxnet3_tx_retrieve_metadata(s, &txd);
s->tx_sop = false;
}
if (txd.eop) {
if (!s->skip_current_tx_pkt && vmxnet_tx_pkt_parse(s->tx_pkt)) {
if (s->needs_vlan) {
vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci);
}
vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci);
}
vmxnet3_send_packet(s, qidx);
} else {
vmxnet3_on_tx_done_update_stats(s, qidx,
VMXNET3_PKT_STATUS_ERROR);
}
vmxnet3_complete_packet(s, qidx, txd_idx);
s->tx_sop = true;
s->skip_current_tx_pkt = false;
vmxnet_tx_pkt_reset(s->tx_pkt);
}
}
| 165,276
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int Track::Info::Copy(Info& dst) const
{
if (&dst == this)
return 0;
dst.type = type;
dst.number = number;
dst.defaultDuration = defaultDuration;
dst.codecDelay = codecDelay;
dst.seekPreRoll = seekPreRoll;
dst.uid = uid;
dst.lacing = lacing;
dst.settings = settings;
if (int status = CopyStr(&Info::nameAsUTF8, dst))
return status;
if (int status = CopyStr(&Info::language, dst))
return status;
if (int status = CopyStr(&Info::codecId, dst))
return status;
if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
return status;
if (codecPrivateSize > 0)
{
if (codecPrivate == NULL)
return -1;
if (dst.codecPrivate)
return -1;
if (dst.codecPrivateSize != 0)
return -1;
dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize];
if (dst.codecPrivate == NULL)
return -1;
memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
dst.codecPrivateSize = codecPrivateSize;
}
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
int Track::Info::Copy(Info& dst) const
dst.type = type;
dst.number = number;
dst.defaultDuration = defaultDuration;
dst.codecDelay = codecDelay;
dst.seekPreRoll = seekPreRoll;
dst.uid = uid;
dst.lacing = lacing;
dst.settings = settings;
// We now copy the string member variables from src to dst.
// This involves memory allocation so in principle the operation
// can fail (indeed, that's why we have Info::Copy), so we must
// report this to the caller. An error return from this function
// therefore implies that the copy was only partially successful.
if (int status = CopyStr(&Info::nameAsUTF8, dst))
return status;
if (int status = CopyStr(&Info::language, dst))
return status;
if (int status = CopyStr(&Info::codecId, dst))
return status;
if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
return status;
if (codecPrivateSize > 0) {
if (codecPrivate == NULL)
return -1;
if (dst.codecPrivate)
return -1;
if (dst.codecPrivateSize != 0)
return -1;
dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize];
if (dst.codecPrivate == NULL)
return -1;
memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
dst.codecPrivateSize = codecPrivateSize;
}
return 0;
}
const BlockEntry* Track::GetEOS() const { return &m_eos; }
long Track::GetType() const { return m_info.type; }
long Track::GetNumber() const { return m_info.number; }
unsigned long long Track::GetUid() const { return m_info.uid; }
const char* Track::GetNameAsUTF8() const { return m_info.nameAsUTF8; }
const char* Track::GetLanguage() const { return m_info.language; }
const char* Track::GetCodecNameAsUTF8() const { return m_info.codecNameAsUTF8; }
const char* Track::GetCodecId() const { return m_info.codecId; }
const unsigned char* Track::GetCodecPrivate(size_t& size) const {
size = m_info.codecPrivateSize;
return m_info.codecPrivate;
}
bool Track::GetLacing() const { return m_info.lacing; }
unsigned long long Track::GetDefaultDuration() const {
return m_info.defaultDuration;
}
unsigned long long Track::GetCodecDelay() const { return m_info.codecDelay; }
unsigned long long Track::GetSeekPreRoll() const { return m_info.seekPreRoll; }
long Track::GetFirst(const BlockEntry*& pBlockEntry) const {
const Cluster* pCluster = m_pSegment->GetFirst();
for (int i = 0;;) {
if (pCluster == NULL) {
pBlockEntry = GetEOS();
return 1;
}
| 174,253
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int SeekHead::GetCount() const
{
return m_entry_count;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
int SeekHead::GetCount() const
const SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const {
if (idx < 0)
return 0;
if (idx >= m_void_element_count)
return 0;
return m_void_elements + idx;
}
| 174,297
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
EAS_PCM *pInputBuffer;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I32 numSamples;
#if (NUM_OUTPUT_CHANNELS == 2)
EAS_I32 gainLeft, gainRight;
#endif
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
pMixBuffer = pWTIntFrame->pMixBuffer;
pInputBuffer = pWTIntFrame->pAudioBuffer;
/*lint -e{703} <avoid multiply for performance>*/
gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
/*lint -e{703} <avoid multiply for performance>*/
gain = pWTIntFrame->prevGain << 16;
#if (NUM_OUTPUT_CHANNELS == 2)
gainLeft = pWTVoice->gainLeft;
gainRight = pWTVoice->gainRight;
#endif
while (numSamples--) {
/* incremental gain step to prevent zipper noise */
tmp0 = *pInputBuffer++;
gain += gainIncrement;
/*lint -e{704} <avoid divide>*/
tmp2 = gain >> 16;
/* scale sample by gain */
tmp2 *= tmp0;
/* stereo output */
#if (NUM_OUTPUT_CHANNELS == 2)
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> 14;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* left channel */
tmp0 = tmp2 * gainLeft;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* right channel */
tmp0 = tmp2 * gainRight;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* mono output */
#else
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1);
tmp1 += tmp2;
*pMixBuffer++ = tmp1;
#endif
}
}
Commit Message: Sonivox: sanity check numSamples.
Bug: 26366256
Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc
CWE ID: CWE-119
|
void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
EAS_PCM *pInputBuffer;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I32 numSamples;
#if (NUM_OUTPUT_CHANNELS == 2)
EAS_I32 gainLeft, gainRight;
#endif
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pMixBuffer = pWTIntFrame->pMixBuffer;
pInputBuffer = pWTIntFrame->pAudioBuffer;
/*lint -e{703} <avoid multiply for performance>*/
gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
/*lint -e{703} <avoid multiply for performance>*/
gain = pWTIntFrame->prevGain << 16;
#if (NUM_OUTPUT_CHANNELS == 2)
gainLeft = pWTVoice->gainLeft;
gainRight = pWTVoice->gainRight;
#endif
while (numSamples--) {
/* incremental gain step to prevent zipper noise */
tmp0 = *pInputBuffer++;
gain += gainIncrement;
/*lint -e{704} <avoid divide>*/
tmp2 = gain >> 16;
/* scale sample by gain */
tmp2 *= tmp0;
/* stereo output */
#if (NUM_OUTPUT_CHANNELS == 2)
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> 14;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* left channel */
tmp0 = tmp2 * gainLeft;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* right channel */
tmp0 = tmp2 * gainRight;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* mono output */
#else
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1);
tmp1 += tmp2;
*pMixBuffer++ = tmp1;
#endif
}
}
| 173,922
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: parse_field(netdissect_options *ndo, const char **pptr, int *len)
{
const char *s;
if (*len <= 0 || !pptr || !*pptr)
return NULL;
if (*pptr > (const char *) ndo->ndo_snapend)
return NULL;
s = *pptr;
while (*pptr <= (const char *) ndo->ndo_snapend && *len >= 0 && **pptr) {
(*pptr)++;
(*len)--;
}
(*pptr)++;
(*len)--;
if (*len < 0 || *pptr > (const char *) ndo->ndo_snapend)
return NULL;
return s;
}
Commit Message: CVE-2017-12902/Zephyr: Fix bounds checking.
Use ND_TTEST() rather than comparing against ndo->ndo_snapend ourselves;
it's easy to get the tests wrong.
Check for running out of packet data before checking for running out of
captured data, and distinguish between running out of packet data (which
might just mean "no more strings") and running out of captured data
(which means "truncated").
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
parse_field(netdissect_options *ndo, const char **pptr, int *len)
parse_field(netdissect_options *ndo, const char **pptr, int *len, int *truncated)
{
const char *s;
/* Start of string */
s = *pptr;
/* Scan for the NUL terminator */
for (;;) {
if (*len == 0) {
/* Ran out of packet data without finding it */
return NULL;
}
if (!ND_TTEST(**pptr)) {
/* Ran out of captured data without finding it */
*truncated = 1;
return NULL;
}
if (**pptr == '\0') {
/* Found it */
break;
}
/* Keep scanning */
(*pptr)++;
(*len)--;
}
/* Skip the NUL terminator */
(*pptr)++;
(*len)--;
return s;
}
| 167,935
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: AcceleratedStaticBitmapImage::AcceleratedStaticBitmapImage(
const gpu::Mailbox& mailbox,
const gpu::SyncToken& sync_token,
unsigned texture_id,
base::WeakPtr<WebGraphicsContext3DProviderWrapper>&&
context_provider_wrapper,
IntSize mailbox_size)
: paint_image_content_id_(cc::PaintImage::GetNextContentId()) {
texture_holder_ = std::make_unique<MailboxTextureHolder>(
mailbox, sync_token, texture_id, std::move(context_provider_wrapper),
mailbox_size);
thread_checker_.DetachFromThread();
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <gab@chromium.org>
Reviewed-by: Jeremy Roman <jbroman@chromium.org>
Commit-Queue: Fernando Serboncini <fserb@chromium.org>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119
|
AcceleratedStaticBitmapImage::AcceleratedStaticBitmapImage(
const gpu::Mailbox& mailbox,
const gpu::SyncToken& sync_token,
unsigned texture_id,
base::WeakPtr<WebGraphicsContext3DProviderWrapper>&&
context_provider_wrapper,
IntSize mailbox_size)
: paint_image_content_id_(cc::PaintImage::GetNextContentId()) {
texture_holder_ = std::make_unique<MailboxTextureHolder>(
mailbox, sync_token, texture_id, std::move(context_provider_wrapper),
mailbox_size);
}
| 172,589
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: FLAC__StreamDecoderWriteStatus FLACParser::writeCallback(
const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
{
if (mWriteRequested) {
mWriteRequested = false;
mWriteHeader = frame->header;
mWriteBuffer = buffer;
mWriteCompleted = true;
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
} else {
ALOGE("FLACParser::writeCallback unexpected");
return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119
|
FLAC__StreamDecoderWriteStatus FLACParser::writeCallback(
const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
{
if (mWriteRequested) {
mWriteRequested = false;
mWriteHeader = frame->header;
memmove(mWriteBuffer, buffer, sizeof(const FLAC__int32 * const) * getChannels());
mWriteCompleted = true;
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
} else {
ALOGE("FLACParser::writeCallback unexpected");
return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}
}
| 174,026
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void DocumentLoader::DidInstallNewDocument(
Document* document,
const ContentSecurityPolicy* previous_csp) {
document->SetReadyState(Document::kLoading);
if (content_security_policy_) {
document->InitContentSecurityPolicy(content_security_policy_.Release(),
nullptr, previous_csp);
}
if (history_item_ && IsBackForwardLoadType(load_type_))
document->SetStateForNewFormElements(history_item_->GetDocumentState());
DCHECK(document->GetFrame());
document->GetFrame()->GetClientHintsPreferences().UpdateFrom(
client_hints_preferences_);
Settings* settings = document->GetSettings();
fetcher_->SetImagesEnabled(settings->GetImagesEnabled());
fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically());
const AtomicString& dns_prefetch_control =
response_.HttpHeaderField(http_names::kXDNSPrefetchControl);
if (!dns_prefetch_control.IsEmpty())
document->ParseDNSPrefetchControlHeader(dns_prefetch_control);
String header_content_language =
response_.HttpHeaderField(http_names::kContentLanguage);
if (!header_content_language.IsEmpty()) {
wtf_size_t comma_index = header_content_language.find(',');
header_content_language.Truncate(comma_index);
header_content_language =
header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>);
if (!header_content_language.IsEmpty())
document->SetContentLanguage(AtomicString(header_content_language));
}
String referrer_policy_header =
response_.HttpHeaderField(http_names::kReferrerPolicy);
if (!referrer_policy_header.IsNull()) {
UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader);
document->ParseAndSetReferrerPolicy(referrer_policy_header);
}
if (response_.IsSignedExchangeInnerResponse())
UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse);
GetLocalFrameClient().DidCreateNewDocument();
}
Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener
Spec PR: https://github.com/w3c/webappsec-csp/pull/358
Bug: 905301, 894228, 836148
Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a
Reviewed-on: https://chromium-review.googlesource.com/c/1314633
Commit-Queue: Andy Paicu <andypaicu@chromium.org>
Reviewed-by: Mike West <mkwst@chromium.org>
Cr-Commit-Position: refs/heads/master@{#610850}
CWE ID: CWE-20
|
void DocumentLoader::DidInstallNewDocument(
void DocumentLoader::DidInstallNewDocument(Document* document) {
document->SetReadyState(Document::kLoading);
if (content_security_policy_) {
document->InitContentSecurityPolicy(
content_security_policy_.Release(),
GetFrameLoader().GetLastOriginDocument());
}
if (history_item_ && IsBackForwardLoadType(load_type_))
document->SetStateForNewFormElements(history_item_->GetDocumentState());
DCHECK(document->GetFrame());
document->GetFrame()->GetClientHintsPreferences().UpdateFrom(
client_hints_preferences_);
Settings* settings = document->GetSettings();
fetcher_->SetImagesEnabled(settings->GetImagesEnabled());
fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically());
const AtomicString& dns_prefetch_control =
response_.HttpHeaderField(http_names::kXDNSPrefetchControl);
if (!dns_prefetch_control.IsEmpty())
document->ParseDNSPrefetchControlHeader(dns_prefetch_control);
String header_content_language =
response_.HttpHeaderField(http_names::kContentLanguage);
if (!header_content_language.IsEmpty()) {
wtf_size_t comma_index = header_content_language.find(',');
header_content_language.Truncate(comma_index);
header_content_language =
header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>);
if (!header_content_language.IsEmpty())
document->SetContentLanguage(AtomicString(header_content_language));
}
String referrer_policy_header =
response_.HttpHeaderField(http_names::kReferrerPolicy);
if (!referrer_policy_header.IsNull()) {
UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader);
document->ParseAndSetReferrerPolicy(referrer_policy_header);
}
if (response_.IsSignedExchangeInnerResponse())
UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse);
GetLocalFrameClient().DidCreateNewDocument();
}
| 173,056
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void BrowserViewRenderer::ScrollTo(gfx::Vector2d scroll_offset) {
gfx::Vector2d max_offset = max_scroll_offset();
gfx::Vector2dF scroll_offset_dip;
if (max_offset.x()) {
scroll_offset_dip.set_x((scroll_offset.x() * max_scroll_offset_dip_.x()) /
max_offset.x());
}
if (max_offset.y()) {
scroll_offset_dip.set_y((scroll_offset.y() * max_scroll_offset_dip_.y()) /
max_offset.y());
}
DCHECK_LE(0.f, scroll_offset_dip.x());
DCHECK_LE(0.f, scroll_offset_dip.y());
DCHECK(scroll_offset_dip.x() < max_scroll_offset_dip_.x() ||
scroll_offset_dip.x() - max_scroll_offset_dip_.x() < kEpsilon)
<< scroll_offset_dip.x() << " " << max_scroll_offset_dip_.x();
DCHECK(scroll_offset_dip.y() < max_scroll_offset_dip_.y() ||
scroll_offset_dip.y() - max_scroll_offset_dip_.y() < kEpsilon)
<< scroll_offset_dip.y() << " " << max_scroll_offset_dip_.y();
if (scroll_offset_dip_ == scroll_offset_dip)
return;
scroll_offset_dip_ = scroll_offset_dip;
TRACE_EVENT_INSTANT2("android_webview",
"BrowserViewRenderer::ScrollTo",
TRACE_EVENT_SCOPE_THREAD,
"x",
scroll_offset_dip.x(),
"y",
scroll_offset_dip.y());
if (compositor_) {
compositor_->DidChangeRootLayerScrollOffset(
gfx::ScrollOffset(scroll_offset_dip_));
}
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
|
void BrowserViewRenderer::ScrollTo(gfx::Vector2d scroll_offset) {
void BrowserViewRenderer::ScrollTo(const gfx::Vector2d& scroll_offset) {
gfx::Vector2d max_offset = max_scroll_offset();
gfx::Vector2dF scroll_offset_dip;
if (max_offset.x()) {
scroll_offset_dip.set_x((scroll_offset.x() * max_scroll_offset_dip_.x()) /
max_offset.x());
}
if (max_offset.y()) {
scroll_offset_dip.set_y((scroll_offset.y() * max_scroll_offset_dip_.y()) /
max_offset.y());
}
DCHECK_LE(0.f, scroll_offset_dip.x());
DCHECK_LE(0.f, scroll_offset_dip.y());
DCHECK(scroll_offset_dip.x() < max_scroll_offset_dip_.x() ||
scroll_offset_dip.x() - max_scroll_offset_dip_.x() < kEpsilon)
<< scroll_offset_dip.x() << " " << max_scroll_offset_dip_.x();
DCHECK(scroll_offset_dip.y() < max_scroll_offset_dip_.y() ||
scroll_offset_dip.y() - max_scroll_offset_dip_.y() < kEpsilon)
<< scroll_offset_dip.y() << " " << max_scroll_offset_dip_.y();
if (scroll_offset_dip_ == scroll_offset_dip)
return;
scroll_offset_dip_ = scroll_offset_dip;
TRACE_EVENT_INSTANT2("android_webview",
"BrowserViewRenderer::ScrollTo",
TRACE_EVENT_SCOPE_THREAD,
"x",
scroll_offset_dip.x(),
"y",
scroll_offset_dip.y());
if (compositor_) {
compositor_->DidChangeRootLayerScrollOffset(
gfx::ScrollOffset(scroll_offset_dip_));
}
}
| 171,614
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_METHOD(Phar, count)
{
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest));
}
Commit Message:
CWE ID: CWE-20
|
PHP_METHOD(Phar, count)
{
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest));
}
| 165,295
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: gfx::Size ShellWindowFrameView::GetMinimumSize() {
gfx::Size min_size = frame_->client_view()->GetMinimumSize();
gfx::Rect client_bounds = GetBoundsForClientView();
min_size.Enlarge(0, client_bounds.y());
int closeButtonOffsetX =
(kCaptionHeight - close_button_->height()) / 2;
int header_width = close_button_->width() + closeButtonOffsetX * 2;
if (header_width > min_size.width())
min_size.set_width(header_width);
return min_size;
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
R=ben@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79
|
gfx::Size ShellWindowFrameView::GetMinimumSize() {
gfx::Size min_size = frame_->client_view()->GetMinimumSize();
if (is_frameless_)
return min_size;
gfx::Rect client_bounds = GetBoundsForClientView();
min_size.Enlarge(0, client_bounds.y());
int closeButtonOffsetX =
(kCaptionHeight - close_button_->height()) / 2;
int header_width = close_button_->width() + closeButtonOffsetX * 2;
if (header_width > min_size.width())
min_size.set_width(header_width);
return min_size;
}
| 170,713
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: sc_parse_ef_gdo_content(const unsigned char *gdo, size_t gdo_len,
unsigned char *iccsn, size_t *iccsn_len,
unsigned char *chn, size_t *chn_len)
{
int r = SC_SUCCESS, iccsn_found = 0, chn_found = 0;
const unsigned char *p = gdo;
size_t left = gdo_len;
while (left >= 2) {
unsigned int cla, tag;
size_t tag_len;
r = sc_asn1_read_tag(&p, left, &cla, &tag, &tag_len);
if (r != SC_SUCCESS) {
if (r == SC_ERROR_ASN1_END_OF_CONTENTS) {
/* not enough data */
r = SC_SUCCESS;
}
break;
}
if (p == NULL) {
/* done parsing */
break;
}
if (cla == SC_ASN1_TAG_APPLICATION) {
switch (tag) {
case 0x1A:
iccsn_found = 1;
if (iccsn && iccsn_len) {
memcpy(iccsn, p, MIN(tag_len, *iccsn_len));
*iccsn_len = MIN(tag_len, *iccsn_len);
}
break;
case 0x1F20:
chn_found = 1;
if (chn && chn_len) {
memcpy(chn, p, MIN(tag_len, *chn_len));
*chn_len = MIN(tag_len, *chn_len);
}
break;
}
}
p += tag_len;
left -= (p - gdo);
}
if (!iccsn_found && iccsn_len)
*iccsn_len = 0;
if (!chn_found && chn_len)
*chn_len = 0;
return 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
|
sc_parse_ef_gdo_content(const unsigned char *gdo, size_t gdo_len,
unsigned char *iccsn, size_t *iccsn_len,
unsigned char *chn, size_t *chn_len)
{
int r = SC_SUCCESS, iccsn_found = 0, chn_found = 0;
const unsigned char *p = gdo;
size_t left = gdo_len;
while (left >= 2) {
unsigned int cla, tag;
size_t tag_len;
r = sc_asn1_read_tag(&p, left, &cla, &tag, &tag_len);
if (r != SC_SUCCESS) {
if (r == SC_ERROR_ASN1_END_OF_CONTENTS) {
/* not enough data */
r = SC_SUCCESS;
}
break;
}
if (p == NULL) {
/* done parsing */
break;
}
if (cla == SC_ASN1_TAG_APPLICATION) {
switch (tag) {
case 0x1A:
iccsn_found = 1;
if (iccsn && iccsn_len) {
memcpy(iccsn, p, MIN(tag_len, *iccsn_len));
*iccsn_len = MIN(tag_len, *iccsn_len);
}
break;
case 0x1F20:
chn_found = 1;
if (chn && chn_len) {
memcpy(chn, p, MIN(tag_len, *chn_len));
*chn_len = MIN(tag_len, *chn_len);
}
break;
}
}
p += tag_len;
left = gdo_len - (p - gdo);
}
if (!iccsn_found && iccsn_len)
*iccsn_len = 0;
if (!chn_found && chn_len)
*chn_len = 0;
return r;
}
| 169,065
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: decode_bundle(bool load, const struct nx_action_bundle *nab,
const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap,
struct ofpbuf *ofpacts)
{
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
struct ofpact_bundle *bundle;
uint32_t slave_type;
size_t slaves_size, i;
enum ofperr error;
bundle = ofpact_put_BUNDLE(ofpacts);
bundle->n_slaves = ntohs(nab->n_slaves);
bundle->basis = ntohs(nab->basis);
bundle->fields = ntohs(nab->fields);
bundle->algorithm = ntohs(nab->algorithm);
slave_type = ntohl(nab->slave_type);
slaves_size = ntohs(nab->len) - sizeof *nab;
error = OFPERR_OFPBAC_BAD_ARGUMENT;
if (!flow_hash_fields_valid(bundle->fields)) {
VLOG_WARN_RL(&rl, "unsupported fields %d", (int) bundle->fields);
} else if (bundle->n_slaves > BUNDLE_MAX_SLAVES) {
VLOG_WARN_RL(&rl, "too many slaves");
} else if (bundle->algorithm != NX_BD_ALG_HRW
&& bundle->algorithm != NX_BD_ALG_ACTIVE_BACKUP) {
VLOG_WARN_RL(&rl, "unsupported algorithm %d", (int) bundle->algorithm);
} else if (slave_type != mf_nxm_header(MFF_IN_PORT)) {
VLOG_WARN_RL(&rl, "unsupported slave type %"PRIu16, slave_type);
} else {
error = 0;
}
if (!is_all_zeros(nab->zero, sizeof nab->zero)) {
VLOG_WARN_RL(&rl, "reserved field is nonzero");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
if (load) {
bundle->dst.ofs = nxm_decode_ofs(nab->ofs_nbits);
bundle->dst.n_bits = nxm_decode_n_bits(nab->ofs_nbits);
error = mf_vl_mff_mf_from_nxm_header(ntohl(nab->dst), vl_mff_map,
&bundle->dst.field, tlv_bitmap);
if (error) {
return error;
}
if (bundle->dst.n_bits < 16) {
VLOG_WARN_RL(&rl, "bundle_load action requires at least 16 bit "
"destination.");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
} else {
if (nab->ofs_nbits || nab->dst) {
VLOG_WARN_RL(&rl, "bundle action has nonzero reserved fields");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
}
if (slaves_size < bundle->n_slaves * sizeof(ovs_be16)) {
VLOG_WARN_RL(&rl, "Nicira action %s only has %"PRIuSIZE" bytes "
"allocated for slaves. %"PRIuSIZE" bytes are required "
"for %"PRIu16" slaves.",
load ? "bundle_load" : "bundle", slaves_size,
bundle->n_slaves * sizeof(ovs_be16), bundle->n_slaves);
error = OFPERR_OFPBAC_BAD_LEN;
}
for (i = 0; i < bundle->n_slaves; i++) {
ofp_port_t ofp_port = u16_to_ofp(ntohs(((ovs_be16 *)(nab + 1))[i]));
ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port);
bundle = ofpacts->header;
}
ofpact_finish_BUNDLE(ofpacts, &bundle);
if (!error) {
error = bundle_check(bundle, OFPP_MAX, NULL);
}
return error;
}
Commit Message: ofp-actions: Avoid buffer overread in BUNDLE action decoding.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9052
Signed-off-by: Ben Pfaff <blp@ovn.org>
Acked-by: Justin Pettit <jpettit@ovn.org>
CWE ID:
|
decode_bundle(bool load, const struct nx_action_bundle *nab,
const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap,
struct ofpbuf *ofpacts)
{
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
struct ofpact_bundle *bundle;
uint32_t slave_type;
size_t slaves_size, i;
enum ofperr error;
bundle = ofpact_put_BUNDLE(ofpacts);
bundle->n_slaves = ntohs(nab->n_slaves);
bundle->basis = ntohs(nab->basis);
bundle->fields = ntohs(nab->fields);
bundle->algorithm = ntohs(nab->algorithm);
slave_type = ntohl(nab->slave_type);
slaves_size = ntohs(nab->len) - sizeof *nab;
error = OFPERR_OFPBAC_BAD_ARGUMENT;
if (!flow_hash_fields_valid(bundle->fields)) {
VLOG_WARN_RL(&rl, "unsupported fields %d", (int) bundle->fields);
} else if (bundle->n_slaves > BUNDLE_MAX_SLAVES) {
VLOG_WARN_RL(&rl, "too many slaves");
} else if (bundle->algorithm != NX_BD_ALG_HRW
&& bundle->algorithm != NX_BD_ALG_ACTIVE_BACKUP) {
VLOG_WARN_RL(&rl, "unsupported algorithm %d", (int) bundle->algorithm);
} else if (slave_type != mf_nxm_header(MFF_IN_PORT)) {
VLOG_WARN_RL(&rl, "unsupported slave type %"PRIu16, slave_type);
} else {
error = 0;
}
if (!is_all_zeros(nab->zero, sizeof nab->zero)) {
VLOG_WARN_RL(&rl, "reserved field is nonzero");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
if (load) {
bundle->dst.ofs = nxm_decode_ofs(nab->ofs_nbits);
bundle->dst.n_bits = nxm_decode_n_bits(nab->ofs_nbits);
error = mf_vl_mff_mf_from_nxm_header(ntohl(nab->dst), vl_mff_map,
&bundle->dst.field, tlv_bitmap);
if (error) {
return error;
}
if (bundle->dst.n_bits < 16) {
VLOG_WARN_RL(&rl, "bundle_load action requires at least 16 bit "
"destination.");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
} else {
if (nab->ofs_nbits || nab->dst) {
VLOG_WARN_RL(&rl, "bundle action has nonzero reserved fields");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
}
if (slaves_size < bundle->n_slaves * sizeof(ovs_be16)) {
VLOG_WARN_RL(&rl, "Nicira action %s only has %"PRIuSIZE" bytes "
"allocated for slaves. %"PRIuSIZE" bytes are required "
"for %"PRIu16" slaves.",
load ? "bundle_load" : "bundle", slaves_size,
bundle->n_slaves * sizeof(ovs_be16), bundle->n_slaves);
error = OFPERR_OFPBAC_BAD_LEN;
} else {
for (i = 0; i < bundle->n_slaves; i++) {
ofp_port_t ofp_port
= u16_to_ofp(ntohs(((ovs_be16 *)(nab + 1))[i]));
ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port);
bundle = ofpacts->header;
}
}
ofpact_finish_BUNDLE(ofpacts, &bundle);
if (!error) {
error = bundle_check(bundle, OFPP_MAX, NULL);
}
return error;
}
| 169,023
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void DocumentModuleScriptFetcher::NotifyFinished(Resource* resource) {
ClearResource();
ScriptResource* script_resource = ToScriptResource(resource);
HeapVector<Member<ConsoleMessage>> error_messages;
if (!WasModuleLoadSuccessful(script_resource, &error_messages)) {
Finalize(WTF::nullopt, error_messages);
return;
}
ModuleScriptCreationParams params(
script_resource->GetResponse().Url(), script_resource->SourceText(),
script_resource->GetResourceRequest().GetFetchCredentialsMode(),
script_resource->CalculateAccessControlStatus());
Finalize(params, error_messages);
}
Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin
Partial revert of https://chromium-review.googlesource.com/535694.
Bug: 799477
Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3
Reviewed-on: https://chromium-review.googlesource.com/898427
Commit-Queue: Hiroshige Hayashizaki <hiroshige@chromium.org>
Reviewed-by: Kouhei Ueno <kouhei@chromium.org>
Reviewed-by: Yutaka Hirano <yhirano@chromium.org>
Reviewed-by: Takeshi Yoshino <tyoshino@chromium.org>
Cr-Commit-Position: refs/heads/master@{#535176}
CWE ID: CWE-200
|
void DocumentModuleScriptFetcher::NotifyFinished(Resource* resource) {
ClearResource();
ScriptResource* script_resource = ToScriptResource(resource);
HeapVector<Member<ConsoleMessage>> error_messages;
if (!WasModuleLoadSuccessful(script_resource, &error_messages)) {
Finalize(WTF::nullopt, error_messages);
return;
}
ModuleScriptCreationParams params(
script_resource->GetResponse().Url(), script_resource->SourceText(),
script_resource->GetResourceRequest().GetFetchCredentialsMode(),
script_resource->CalculateAccessControlStatus(
fetcher_->Context().GetSecurityOrigin()));
Finalize(params, error_messages);
}
| 172,887
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 5000;
DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, input_extreme_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < kNumCoeffs; ++j) {
input_block[j] = rnd.Rand8() - rnd.Rand8();
input_extreme_block[j] = rnd.Rand8() % 2 ? 255 : -255;
}
if (i == 0)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = 255;
if (i == 1)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -255;
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE, abs(output_block[j]))
<< "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
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 RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 5000;
DECLARE_ALIGNED(16, int16_t, input_extreme_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]);
for (int i = 0; i < count_test_block; ++i) {
// Initialize a test block with input range [-mask_, mask_].
for (int j = 0; j < kNumCoeffs; ++j) {
input_extreme_block[j] = rnd.Rand8() % 2 ? mask_ : -mask_;
}
if (i == 0) {
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = mask_;
} else if (i == 1) {
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -mask_;
}
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE << (bit_depth_ - 8), abs(output_block[j]))
<< "Error: 4x4 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
| 174,554
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,
const iw_byte *d, size_t d_len)
{
struct iw_exif_state e;
iw_uint32 ifd;
if(d_len<8) return;
iw_zeromem(&e,sizeof(struct iw_exif_state));
e.d = d;
e.d_len = d_len;
e.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;
ifd = iw_get_ui32_e(&d[4],e.endian);
iwjpeg_scan_exif_ifd(rctx,&e,ifd);
}
Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data
Fixes issues #22, #23, #24, #25
CWE ID: CWE-125
|
static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,
const iw_byte *d, size_t d_len)
{
struct iw_exif_state e;
iw_uint32 ifd;
if(d_len<8) return;
iw_zeromem(&e,sizeof(struct iw_exif_state));
e.d = d;
e.d_len = d_len;
e.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;
ifd = get_exif_ui32(&e, 4);
iwjpeg_scan_exif_ifd(rctx,&e,ifd);
}
| 168,115
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool FakePluginServiceFilter::IsPluginEnabled(int render_process_id,
int render_view_id,
const void* context,
const GURL& url,
const GURL& policy_url,
webkit::WebPluginInfo* plugin) {
std::map<FilePath, bool>::iterator it = plugin_state_.find(plugin->path);
if (it == plugin_state_.end()) {
ADD_FAILURE() << "No plug-in state for '" << plugin->path.value() << "'";
return false;
}
return it->second;
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287
|
bool FakePluginServiceFilter::IsPluginEnabled(int render_process_id,
bool FakePluginServiceFilter::IsPluginAvailable(int render_process_id,
int render_view_id,
const void* context,
const GURL& url,
const GURL& policy_url,
webkit::WebPluginInfo* plugin) {
std::map<FilePath, bool>::iterator it = plugin_state_.find(plugin->path);
if (it == plugin_state_.end()) {
ADD_FAILURE() << "No plug-in state for '" << plugin->path.value() << "'";
return false;
}
return it->second;
}
| 171,474
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void copy_asoundrc(void) {
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
drop_privs(0);
int rv = copy_file(src, dest);
if (rv)
fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
waitpid(child, NULL, 0);
if (chown(dest, getuid(), getgid()) < 0)
errExit("chown");
if (chmod(dest, S_IRUSR | S_IWUSR) < 0)
errExit("chmod");
unlink(src);
}
Commit Message: security fix
CWE ID: CWE-269
|
static void copy_asoundrc(void) {
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); // regular user
fs_logger2("clone", dest);
unlink(src);
}
| 170,096
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::AllocateHistogram(
HistogramType histogram_type,
const std::string& name,
int minimum,
int maximum,
const BucketRanges* bucket_ranges,
int32_t flags,
Reference* ref_ptr) {
if (memory_allocator_->IsCorrupt()) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_CORRUPT);
return nullptr;
}
PersistentHistogramData* histogram_data =
memory_allocator_->New<PersistentHistogramData>(
offsetof(PersistentHistogramData, name) + name.length() + 1);
if (histogram_data) {
memcpy(histogram_data->name, name.c_str(), name.size() + 1);
histogram_data->histogram_type = histogram_type;
histogram_data->flags = flags | HistogramBase::kIsPersistent;
}
if (histogram_type != SPARSE_HISTOGRAM) {
size_t bucket_count = bucket_ranges->bucket_count();
size_t counts_bytes = CalculateRequiredCountsBytes(bucket_count);
if (counts_bytes == 0) {
NOTREACHED();
return nullptr;
}
DCHECK_EQ(this, GlobalHistogramAllocator::Get());
PersistentMemoryAllocator::Reference ranges_ref =
bucket_ranges->persistent_reference();
if (!ranges_ref) {
size_t ranges_count = bucket_count + 1;
size_t ranges_bytes = ranges_count * sizeof(HistogramBase::Sample);
ranges_ref =
memory_allocator_->Allocate(ranges_bytes, kTypeIdRangesArray);
if (ranges_ref) {
HistogramBase::Sample* ranges_data =
memory_allocator_->GetAsArray<HistogramBase::Sample>(
ranges_ref, kTypeIdRangesArray, ranges_count);
if (ranges_data) {
for (size_t i = 0; i < bucket_ranges->size(); ++i)
ranges_data[i] = bucket_ranges->range(i);
bucket_ranges->set_persistent_reference(ranges_ref);
} else {
NOTREACHED();
ranges_ref = PersistentMemoryAllocator::kReferenceNull;
}
}
} else {
DCHECK_EQ(kTypeIdRangesArray, memory_allocator_->GetType(ranges_ref));
}
if (ranges_ref && histogram_data) {
histogram_data->minimum = minimum;
histogram_data->maximum = maximum;
histogram_data->bucket_count = static_cast<uint32_t>(bucket_count);
histogram_data->ranges_ref = ranges_ref;
histogram_data->ranges_checksum = bucket_ranges->checksum();
} else {
histogram_data = nullptr; // Clear this for proper handling below.
}
}
if (histogram_data) {
std::unique_ptr<HistogramBase> histogram = CreateHistogram(histogram_data);
DCHECK(histogram);
DCHECK_NE(0U, histogram_data->samples_metadata.id);
DCHECK_NE(0U, histogram_data->logged_metadata.id);
PersistentMemoryAllocator::Reference histogram_ref =
memory_allocator_->GetAsReference(histogram_data);
if (ref_ptr != nullptr)
*ref_ptr = histogram_ref;
subtle::NoBarrier_Store(&last_created_, histogram_ref);
return histogram;
}
CreateHistogramResultType result;
if (memory_allocator_->IsCorrupt()) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_NEWLY_CORRUPT);
result = CREATE_HISTOGRAM_ALLOCATOR_CORRUPT;
} else if (memory_allocator_->IsFull()) {
result = CREATE_HISTOGRAM_ALLOCATOR_FULL;
} else {
result = CREATE_HISTOGRAM_ALLOCATOR_ERROR;
}
RecordCreateHistogramResult(result);
if (result != CREATE_HISTOGRAM_ALLOCATOR_FULL)
NOTREACHED() << memory_allocator_->Name() << ", error=" << result;
return nullptr;
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <bcwhite@chromium.org>
Reviewed-by: Alexei Svitkine <asvitkine@chromium.org>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264
|
std::unique_ptr<HistogramBase> PersistentHistogramAllocator::AllocateHistogram(
HistogramType histogram_type,
const std::string& name,
int minimum,
int maximum,
const BucketRanges* bucket_ranges,
int32_t flags,
Reference* ref_ptr) {
if (memory_allocator_->IsCorrupt())
return nullptr;
PersistentHistogramData* histogram_data =
memory_allocator_->New<PersistentHistogramData>(
offsetof(PersistentHistogramData, name) + name.length() + 1);
if (histogram_data) {
memcpy(histogram_data->name, name.c_str(), name.size() + 1);
histogram_data->histogram_type = histogram_type;
histogram_data->flags = flags | HistogramBase::kIsPersistent;
}
if (histogram_type != SPARSE_HISTOGRAM) {
size_t bucket_count = bucket_ranges->bucket_count();
size_t counts_bytes = CalculateRequiredCountsBytes(bucket_count);
if (counts_bytes == 0) {
NOTREACHED();
return nullptr;
}
DCHECK_EQ(this, GlobalHistogramAllocator::Get());
PersistentMemoryAllocator::Reference ranges_ref =
bucket_ranges->persistent_reference();
if (!ranges_ref) {
size_t ranges_count = bucket_count + 1;
size_t ranges_bytes = ranges_count * sizeof(HistogramBase::Sample);
ranges_ref =
memory_allocator_->Allocate(ranges_bytes, kTypeIdRangesArray);
if (ranges_ref) {
HistogramBase::Sample* ranges_data =
memory_allocator_->GetAsArray<HistogramBase::Sample>(
ranges_ref, kTypeIdRangesArray, ranges_count);
if (ranges_data) {
for (size_t i = 0; i < bucket_ranges->size(); ++i)
ranges_data[i] = bucket_ranges->range(i);
bucket_ranges->set_persistent_reference(ranges_ref);
} else {
NOTREACHED();
ranges_ref = PersistentMemoryAllocator::kReferenceNull;
}
}
} else {
DCHECK_EQ(kTypeIdRangesArray, memory_allocator_->GetType(ranges_ref));
}
if (ranges_ref && histogram_data) {
histogram_data->minimum = minimum;
histogram_data->maximum = maximum;
histogram_data->bucket_count = static_cast<uint32_t>(bucket_count);
histogram_data->ranges_ref = ranges_ref;
histogram_data->ranges_checksum = bucket_ranges->checksum();
} else {
histogram_data = nullptr; // Clear this for proper handling below.
}
}
if (histogram_data) {
std::unique_ptr<HistogramBase> histogram = CreateHistogram(histogram_data);
DCHECK(histogram);
DCHECK_NE(0U, histogram_data->samples_metadata.id);
DCHECK_NE(0U, histogram_data->logged_metadata.id);
PersistentMemoryAllocator::Reference histogram_ref =
memory_allocator_->GetAsReference(histogram_data);
if (ref_ptr != nullptr)
*ref_ptr = histogram_ref;
subtle::NoBarrier_Store(&last_created_, histogram_ref);
return histogram;
}
if (memory_allocator_->IsCorrupt())
NOTREACHED() << memory_allocator_->Name() << " is corrupt!";
return nullptr;
}
| 172,131
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: base::string16 TranslateInfoBarDelegate::GetLanguageDisplayableName(
const std::string& language_code) {
return l10n_util::GetDisplayNameForLocale(
language_code, g_browser_process->GetApplicationLocale(), true);
}
Commit Message: Remove dependency of TranslateInfobarDelegate on profile
This CL uses TranslateTabHelper instead of Profile and also cleans up
some unused code and irrelevant dependencies.
BUG=371845
Review URL: https://codereview.chromium.org/286973003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@270758 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
|
base::string16 TranslateInfoBarDelegate::GetLanguageDisplayableName(
| 171,173
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static char *get_header(FILE *fp)
{
long start;
/* First 1024 bytes of doc must be header (1.7 spec pg 1102) */
char *header;
header = calloc(1, 1024);
start = ftell(fp);
fseek(fp, 0, SEEK_SET);
SAFE_E(fread(header, 1, 1023, fp), 1023, "Failed to load PDF header.\n");
fseek(fp, start, SEEK_SET);
return header;
}
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
CWE ID: CWE-787
|
static char *get_header(FILE *fp)
{
/* First 1024 bytes of doc must be header (1.7 spec pg 1102) */
char *header = safe_calloc(1024);
long start = ftell(fp);
fseek(fp, 0, SEEK_SET);
SAFE_E(fread(header, 1, 1023, fp), 1023, "Failed to load PDF header.\n");
fseek(fp, start, SEEK_SET);
return header;
}
| 169,567
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: status_t BnSoundTriggerHwService::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code) {
case LIST_MODULES: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
unsigned int numModulesReq = data.readInt32();
unsigned int numModules = numModulesReq;
struct sound_trigger_module_descriptor *modules =
(struct sound_trigger_module_descriptor *)calloc(numModulesReq,
sizeof(struct sound_trigger_module_descriptor));
status_t status = listModules(modules, &numModules);
reply->writeInt32(status);
reply->writeInt32(numModules);
ALOGV("LIST_MODULES status %d got numModules %d", status, numModules);
if (status == NO_ERROR) {
if (numModulesReq > numModules) {
numModulesReq = numModules;
}
reply->write(modules,
numModulesReq * sizeof(struct sound_trigger_module_descriptor));
}
free(modules);
return NO_ERROR;
}
case ATTACH: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
sound_trigger_module_handle_t handle;
data.read(&handle, sizeof(sound_trigger_module_handle_t));
sp<ISoundTriggerClient> client =
interface_cast<ISoundTriggerClient>(data.readStrongBinder());
sp<ISoundTrigger> module;
status_t status = attach(handle, client, module);
reply->writeInt32(status);
if (module != 0) {
reply->writeInt32(1);
reply->writeStrongBinder(IInterface::asBinder(module));
} else {
reply->writeInt32(0);
}
return NO_ERROR;
} break;
case SET_CAPTURE_STATE: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
reply->writeInt32(setCaptureState((bool)data.readInt32()));
return NO_ERROR;
} break;
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
Commit Message: Check memory allocation in ISoundTriggerHwService
Add memory allocation check in ISoundTriggerHwService::listModules().
Bug: 19385640.
Change-Id: Iaf74b6f154c3437e1bfc9da78b773d64b16a7604
CWE ID: CWE-190
|
status_t BnSoundTriggerHwService::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code) {
case LIST_MODULES: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
unsigned int numModulesReq = data.readInt32();
if (numModulesReq > MAX_ITEMS_PER_LIST) {
numModulesReq = MAX_ITEMS_PER_LIST;
}
unsigned int numModules = numModulesReq;
struct sound_trigger_module_descriptor *modules =
(struct sound_trigger_module_descriptor *)calloc(numModulesReq,
sizeof(struct sound_trigger_module_descriptor));
if (modules == NULL) {
reply->writeInt32(NO_MEMORY);
reply->writeInt32(0);
return NO_ERROR;
}
status_t status = listModules(modules, &numModules);
reply->writeInt32(status);
reply->writeInt32(numModules);
ALOGV("LIST_MODULES status %d got numModules %d", status, numModules);
if (status == NO_ERROR) {
if (numModulesReq > numModules) {
numModulesReq = numModules;
}
reply->write(modules,
numModulesReq * sizeof(struct sound_trigger_module_descriptor));
}
free(modules);
return NO_ERROR;
}
case ATTACH: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
sound_trigger_module_handle_t handle;
data.read(&handle, sizeof(sound_trigger_module_handle_t));
sp<ISoundTriggerClient> client =
interface_cast<ISoundTriggerClient>(data.readStrongBinder());
sp<ISoundTrigger> module;
status_t status = attach(handle, client, module);
reply->writeInt32(status);
if (module != 0) {
reply->writeInt32(1);
reply->writeStrongBinder(IInterface::asBinder(module));
} else {
reply->writeInt32(0);
}
return NO_ERROR;
} break;
case SET_CAPTURE_STATE: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
reply->writeInt32(setCaptureState((bool)data.readInt32()));
return NO_ERROR;
} break;
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
| 174,072
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: AcceleratedStaticBitmapImage::~AcceleratedStaticBitmapImage() {
if (original_skia_image_) {
std::unique_ptr<gpu::SyncToken> sync_token =
base::WrapUnique(new gpu::SyncToken(texture_holder_->GetSyncToken()));
if (original_skia_image_thread_id_ !=
Platform::Current()->CurrentThread()->ThreadId()) {
PostCrossThreadTask(
*original_skia_image_task_runner_, FROM_HERE,
CrossThreadBind(
&DestroySkImageOnOriginalThread, std::move(original_skia_image_),
std::move(original_skia_image_context_provider_wrapper_),
WTF::Passed(std::move(sync_token))));
} else {
DestroySkImageOnOriginalThread(
std::move(original_skia_image_),
std::move(original_skia_image_context_provider_wrapper_),
std::move(sync_token));
}
}
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <gab@chromium.org>
Reviewed-by: Jeremy Roman <jbroman@chromium.org>
Commit-Queue: Fernando Serboncini <fserb@chromium.org>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119
|
AcceleratedStaticBitmapImage::~AcceleratedStaticBitmapImage() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (original_skia_image_) {
std::unique_ptr<gpu::SyncToken> sync_token =
base::WrapUnique(new gpu::SyncToken(texture_holder_->GetSyncToken()));
if (!original_skia_image_task_runner_->BelongsToCurrentThread()) {
PostCrossThreadTask(
*original_skia_image_task_runner_, FROM_HERE,
CrossThreadBind(
&DestroySkImageOnOriginalThread, std::move(original_skia_image_),
std::move(original_skia_image_context_provider_wrapper_),
WTF::Passed(std::move(sync_token))));
} else {
DestroySkImageOnOriginalThread(
std::move(original_skia_image_),
std::move(original_skia_image_context_provider_wrapper_),
std::move(sync_token));
}
}
}
| 172,599
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: pktap_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
uint32_t dlt, hdrlen, rectype;
u_int caplen = h->caplen;
u_int length = h->len;
if_printer printer;
const pktap_header_t *hdr;
if (caplen < sizeof(pktap_header_t) || length < sizeof(pktap_header_t)) {
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
hdr = (const pktap_header_t *)p;
dlt = EXTRACT_LE_32BITS(&hdr->pkt_dlt);
hdrlen = EXTRACT_LE_32BITS(&hdr->pkt_len);
if (hdrlen < sizeof(pktap_header_t)) {
/*
* Claimed header length < structure length.
* XXX - does this just mean some fields aren't
* being supplied, or is it truly an error (i.e.,
* is the length supplied so that the header can
* be expanded in the future)?
*/
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
if (caplen < hdrlen || length < hdrlen) {
ND_PRINT((ndo, "[|pktap]"));
return (hdrlen);
}
if (ndo->ndo_eflag)
pktap_header_print(ndo, p, length);
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
rectype = EXTRACT_LE_32BITS(&hdr->pkt_rectype);
switch (rectype) {
case PKT_REC_NONE:
ND_PRINT((ndo, "no data"));
break;
case PKT_REC_PACKET:
if ((printer = lookup_printer(dlt)) != NULL) {
hdrlen += printer(ndo, h, p);
} else {
if (!ndo->ndo_eflag)
pktap_header_print(ndo, (const u_char *)hdr,
length + hdrlen);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
}
break;
}
return (hdrlen);
}
Commit Message: CVE-2017-13007/PKTAP: Pass a properly updated struct pcap_pkthdr to the sub-dissector.
The sub-dissector expects that the length and captured length will
reflect the actual remaining data in the packet, not the raw amount
including the PKTAP header; pass an updated header, just as we do for
PPI.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
pktap_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
uint32_t dlt, hdrlen, rectype;
u_int caplen = h->caplen;
u_int length = h->len;
if_printer printer;
const pktap_header_t *hdr;
struct pcap_pkthdr nhdr;
if (caplen < sizeof(pktap_header_t) || length < sizeof(pktap_header_t)) {
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
hdr = (const pktap_header_t *)p;
dlt = EXTRACT_LE_32BITS(&hdr->pkt_dlt);
hdrlen = EXTRACT_LE_32BITS(&hdr->pkt_len);
if (hdrlen < sizeof(pktap_header_t)) {
/*
* Claimed header length < structure length.
* XXX - does this just mean some fields aren't
* being supplied, or is it truly an error (i.e.,
* is the length supplied so that the header can
* be expanded in the future)?
*/
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
if (caplen < hdrlen || length < hdrlen) {
ND_PRINT((ndo, "[|pktap]"));
return (hdrlen);
}
if (ndo->ndo_eflag)
pktap_header_print(ndo, p, length);
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
rectype = EXTRACT_LE_32BITS(&hdr->pkt_rectype);
switch (rectype) {
case PKT_REC_NONE:
ND_PRINT((ndo, "no data"));
break;
case PKT_REC_PACKET:
if ((printer = lookup_printer(dlt)) != NULL) {
nhdr = *h;
nhdr.caplen = caplen;
nhdr.len = length;
hdrlen += printer(ndo, &nhdr, p);
} else {
if (!ndo->ndo_eflag)
pktap_header_print(ndo, (const u_char *)hdr,
length + hdrlen);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
}
break;
}
return (hdrlen);
}
| 167,888
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ikev2_sa_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext1,
u_int osa_length, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth)
{
const struct isakmp_gen *ext;
struct isakmp_gen e;
u_int sa_length;
const u_char *cp;
int i;
int pcount;
u_char np;
u_int item_len;
ND_TCHECK(*ext1);
UNALIGNED_MEMCPY(&e, ext1, sizeof(e));
ikev2_pay_print(ndo, "sa", e.critical);
/*
* ikev2_sub0_print() guarantees that this is >= 4.
*/
osa_length= ntohs(e.len);
sa_length = osa_length - 4;
ND_PRINT((ndo," len=%d", sa_length));
/*
* Print the payloads.
*/
cp = (const u_char *)(ext1 + 1);
pcount = 0;
for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) {
pcount++;
ext = (const struct isakmp_gen *)cp;
if (sa_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (sa_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_P) {
cp = ikev2_p_print(ndo, np, pcount, ext, item_len,
ep, depth);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
sa_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the SA.
*/
cp += sa_length;
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return cp;
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_sa_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext1,
u_int osa_length, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth)
{
const struct isakmp_gen *ext;
struct isakmp_gen e;
u_int sa_length;
const u_char *cp;
int i;
int pcount;
u_char np;
u_int item_len;
ND_TCHECK(*ext1);
UNALIGNED_MEMCPY(&e, ext1, sizeof(e));
ikev2_pay_print(ndo, "sa", e.critical);
/*
* ikev2_sub0_print() guarantees that this is >= 4.
*/
osa_length= ntohs(e.len);
sa_length = osa_length - 4;
ND_PRINT((ndo," len=%d", sa_length));
/*
* Print the payloads.
*/
cp = (const u_char *)(ext1 + 1);
pcount = 0;
for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) {
pcount++;
ext = (const struct isakmp_gen *)cp;
if (sa_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (sa_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_P) {
cp = ikev2_p_print(ndo, np, pcount, ext, item_len,
ep, depth);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
sa_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the SA.
*/
cp += sa_length;
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
| 167,801
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: my_object_get_value (MyObject *obj, guint *ret, GError **error)
{
*ret = obj->val;
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_get_value (MyObject *obj, guint *ret, GError **error)
| 165,104
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: char *strstr(char *s1, char *s2)
{ /* from libiberty */
char *p;
int len = strlen(s2);
if (*s2 == '\0') /* everything matches empty string */
return s1;
for (p = s1; (p = strchr(p, *s2)) != NULL; p = strchr(p + 1, *s2)) {
if (strncmp(p, s2, len) == 0)
return (p);
}
return NULL;
}
Commit Message: misc oom and possible memory leak fix
CWE ID:
|
char *strstr(char *s1, char *s2)
{ /* from libiberty */
char *p;
int len = strlen(s2);
if (*s2 == '\0') /* everything matches empty string */
return s1;
for (p = s1; (p = strchr(p, *s2)) != NULL; p++) {
if (strncmp(p, s2, len) == 0)
return (p);
}
return NULL;
}
| 169,755
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ShellSurface::OnSurfaceCommit() {
surface_->CheckIfSurfaceHierarchyNeedsCommitToNewSurfaces();
surface_->CommitSurfaceHierarchy();
if (enabled() && !widget_)
CreateShellSurfaceWidget(ui::SHOW_STATE_NORMAL);
origin_ += pending_origin_offset_;
pending_origin_offset_ = gfx::Vector2d();
resize_component_ = pending_resize_component_;
if (widget_) {
geometry_ = pending_geometry_;
UpdateWidgetBounds();
gfx::Point surface_origin = GetSurfaceOrigin();
gfx::Rect hit_test_bounds =
surface_->GetHitTestBounds() + surface_origin.OffsetFromOrigin();
bool activatable = activatable_ && !hit_test_bounds.IsEmpty();
if (activatable != CanActivate()) {
set_can_activate(activatable);
aura::client::ActivationClient* activation_client =
ash::Shell::GetInstance()->activation_client();
if (activatable)
activation_client->ActivateWindow(widget_->GetNativeWindow());
else if (widget_->IsActive())
activation_client->DeactivateWindow(widget_->GetNativeWindow());
}
surface_->window()->SetBounds(
gfx::Rect(surface_origin, surface_->window()->layer()->size()));
if (pending_scale_ != scale_) {
gfx::Transform transform;
DCHECK_NE(pending_scale_, 0.0);
transform.Scale(1.0 / pending_scale_, 1.0 / pending_scale_);
surface_->window()->SetTransform(transform);
scale_ = pending_scale_;
}
if (pending_show_widget_) {
DCHECK(!widget_->IsClosed());
DCHECK(!widget_->IsVisible());
pending_show_widget_ = false;
widget_->Show();
}
}
}
Commit Message: exo: Reduce side-effects of dynamic activation code.
This code exists for clients that need to managed their own system
modal dialogs. Since the addition of the remote surface API we
can limit the impact of this to surfaces created for system modal
container.
BUG=29528396
Review-Url: https://codereview.chromium.org/2084023003
Cr-Commit-Position: refs/heads/master@{#401115}
CWE ID: CWE-416
|
void ShellSurface::OnSurfaceCommit() {
surface_->CheckIfSurfaceHierarchyNeedsCommitToNewSurfaces();
surface_->CommitSurfaceHierarchy();
if (enabled() && !widget_)
CreateShellSurfaceWidget(ui::SHOW_STATE_NORMAL);
origin_ += pending_origin_offset_;
pending_origin_offset_ = gfx::Vector2d();
resize_component_ = pending_resize_component_;
if (widget_) {
geometry_ = pending_geometry_;
UpdateWidgetBounds();
gfx::Point surface_origin = GetSurfaceOrigin();
// System modal container is used by clients to implement client side
// managed system modal dialogs using a single ShellSurface instance.
// Hit-test region will be non-empty when at least one dialog exists on
// the client side. Here we detect the transition between no client side
// dialog and at least one dialog so activatable state is properly
// updated.
if (container_ == ash::kShellWindowId_SystemModalContainer) {
gfx::Rect hit_test_bounds =
surface_->GetHitTestBounds() + surface_origin.OffsetFromOrigin();
// Prevent window from being activated when hit test bounds are empty.
bool activatable = activatable_ && !hit_test_bounds.IsEmpty();
if (activatable != CanActivate()) {
set_can_activate(activatable);
// Activate or deactivate window if activation state changed.
aura::client::ActivationClient* activation_client =
ash::Shell::GetInstance()->activation_client();
if (activatable)
activation_client->ActivateWindow(widget_->GetNativeWindow());
else if (widget_->IsActive())
activation_client->DeactivateWindow(widget_->GetNativeWindow());
}
}
surface_->window()->SetBounds(
gfx::Rect(surface_origin, surface_->window()->layer()->size()));
if (pending_scale_ != scale_) {
gfx::Transform transform;
DCHECK_NE(pending_scale_, 0.0);
transform.Scale(1.0 / pending_scale_, 1.0 / pending_scale_);
surface_->window()->SetTransform(transform);
scale_ = pending_scale_;
}
if (pending_show_widget_) {
DCHECK(!widget_->IsClosed());
DCHECK(!widget_->IsVisible());
pending_show_widget_ = false;
widget_->Show();
}
}
}
| 171,639
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: INLINE UWORD8 impeg2d_bit_stream_get_bit(stream_t *ps_stream)
{
UWORD32 u4_bit,u4_offset,u4_temp;
UWORD32 u4_curr_bit;
u4_offset = ps_stream->u4_offset;
u4_curr_bit = u4_offset & 0x1F;
u4_bit = ps_stream->u4_buf;
/* Move the current bit read from the current word to the
least significant bit positions of 'c'.*/
u4_bit >>= BITS_IN_INT - u4_curr_bit - 1;
u4_offset++;
/* If the last bit of the last word of the buffer has been read update
the currrent buf with next, and read next buf from bit stream buffer */
if (u4_curr_bit == 31)
{
ps_stream->u4_buf = ps_stream->u4_buf_nxt;
u4_temp = *(ps_stream->pu4_buf_aligned)++;
CONV_LE_TO_BE(ps_stream->u4_buf_nxt,u4_temp)
}
ps_stream->u4_offset = u4_offset;
return (u4_bit & 0x1);
}
Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size.
Bug: 25765591
Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
CWE ID: CWE-254
|
INLINE UWORD8 impeg2d_bit_stream_get_bit(stream_t *ps_stream)
{
UWORD32 u4_bit,u4_offset,u4_temp;
UWORD32 u4_curr_bit;
u4_offset = ps_stream->u4_offset;
u4_curr_bit = u4_offset & 0x1F;
u4_bit = ps_stream->u4_buf;
/* Move the current bit read from the current word to the
least significant bit positions of 'c'.*/
u4_bit >>= BITS_IN_INT - u4_curr_bit - 1;
u4_offset++;
/* If the last bit of the last word of the buffer has been read update
the currrent buf with next, and read next buf from bit stream buffer */
if (u4_curr_bit == 31)
{
ps_stream->u4_buf = ps_stream->u4_buf_nxt;
if (ps_stream->u4_offset < ps_stream->u4_max_offset)
{
u4_temp = *(ps_stream->pu4_buf_aligned)++;
CONV_LE_TO_BE(ps_stream->u4_buf_nxt,u4_temp)
}
}
ps_stream->u4_offset = u4_offset;
return (u4_bit & 0x1);
}
| 173,942
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
uint_fast32_t inmem)
{
jas_image_cmpt_t *cmpt;
size_t size;
cmpt = 0;
if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {
goto error;
}
if (!jas_safe_intfast32_add(tlx, width, 0) ||
!jas_safe_intfast32_add(tly, height, 0)) {
goto error;
}
if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
goto error;
}
cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
cmpt->tlx_ = tlx;
cmpt->tly_ = tly;
cmpt->hstep_ = hstep;
cmpt->vstep_ = vstep;
cmpt->width_ = width;
cmpt->height_ = height;
cmpt->prec_ = depth;
cmpt->sgnd_ = sgnd;
cmpt->stream_ = 0;
cmpt->cps_ = (depth + 7) / 8;
if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||
!jas_safe_size_mul(size, cmpt->cps_, &size)) {
goto error;
}
cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) :
jas_stream_tmpfile();
if (!cmpt->stream_) {
goto error;
}
/* Zero the component data. This isn't necessary, but it is
convenient for debugging purposes. */
/* Note: conversion of size - 1 to long can overflow */
if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
jas_stream_putc(cmpt->stream_, 0) == EOF ||
jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
goto error;
}
return cmpt;
error:
if (cmpt) {
jas_image_cmpt_destroy(cmpt);
}
return 0;
}
Commit Message: Made some changes to the I/O stream library for memory streams.
There were a number of potential problems due to the possibility
of integer overflow.
Changed some integral types to the larger types size_t or ssize_t.
For example, the function mem_resize now takes the buffer size parameter
as a size_t.
Added a new function jas_stream_memopen2, which takes a
buffer size specified as a size_t instead of an int.
This can be used in jas_image_cmpt_create to avoid potential
overflow problems.
Added a new function jas_deprecated to warn about reliance on
deprecated library behavior.
CWE ID: CWE-190
|
static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
uint_fast32_t inmem)
{
jas_image_cmpt_t *cmpt;
size_t size;
cmpt = 0;
if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {
goto error;
}
if (!jas_safe_intfast32_add(tlx, width, 0) ||
!jas_safe_intfast32_add(tly, height, 0)) {
goto error;
}
if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
goto error;
}
cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
cmpt->tlx_ = tlx;
cmpt->tly_ = tly;
cmpt->hstep_ = hstep;
cmpt->vstep_ = vstep;
cmpt->width_ = width;
cmpt->height_ = height;
cmpt->prec_ = depth;
cmpt->sgnd_ = sgnd;
cmpt->stream_ = 0;
cmpt->cps_ = (depth + 7) / 8;
if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||
!jas_safe_size_mul(size, cmpt->cps_, &size)) {
goto error;
}
cmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) :
jas_stream_tmpfile();
if (!cmpt->stream_) {
goto error;
}
/* Zero the component data. This isn't necessary, but it is
convenient for debugging purposes. */
/* Note: conversion of size - 1 to long can overflow */
if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
jas_stream_putc(cmpt->stream_, 0) == EOF ||
jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
goto error;
}
return cmpt;
error:
if (cmpt) {
jas_image_cmpt_destroy(cmpt);
}
return 0;
}
| 168,744
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) {
if (!initialized_successfully_)
return "";
return chromeos::GetKeyboardOverlayId(input_method_id);
}
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 std::string GetKeyboardOverlayId(const std::string& input_method_id) {
if (!initialized_successfully_)
return "";
return input_method::GetKeyboardOverlayId(input_method_id);
}
| 170,489
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
line += PKT_LEN_SIZE;
/*
* TODO: How do we deal with empty lines? Try again? with the next
* line?
*/
if (len == PKT_LEN_SIZE) {
*head = NULL;
*out = line;
return 0;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
Commit Message: smart_pkt: verify packet length exceeds PKT_LEN_SIZE
Each packet line in the Git protocol is prefixed by a four-byte
length of how much data will follow, which we parse in
`git_pkt_parse_line`. The transmitted length can either be equal
to zero in case of a flush packet or has to be at least of length
four, as it also includes the encoded length itself. Not
checking this may result in a buffer overflow as we directly pass
the length to functions which accept a `size_t` length as
parameter.
Fix the issue by verifying that non-flush packets have at least a
length of `PKT_LEN_SIZE`.
CWE ID: CWE-119
|
int git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
/*
* The length has to be exactly 0 in case of a flush
* packet or greater than PKT_LEN_SIZE, as the decoded
* length includes its own encoded length of four bytes.
*/
if (len != 0 && len < PKT_LEN_SIZE)
return GIT_ERROR;
line += PKT_LEN_SIZE;
/*
* TODO: How do we deal with empty lines? Try again? with the next
* line?
*/
if (len == PKT_LEN_SIZE) {
*head = NULL;
*out = line;
return 0;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
| 168,530
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: gboolean lxterminal_socket_initialize(LXTermWindow * lxtermwin, gint argc, gchar * * argv)
{
/* Normally, LXTerminal uses one process to control all of its windows.
* The first process to start will create a Unix domain socket in /tmp.
* It will then bind and listen on this socket.
* The subsequent processes will connect to the controller that owns the Unix domain socket.
* They will pass their command line over the socket and exit.
*
* If for any reason both the connect and bind fail, we will fall back to having that
* process be standalone; it will not be either the controller or a user of the controller.
* This behavior was introduced in response to a problem report (2973537).
*
* This function returns TRUE if this process should keep running and FALSE if it should exit. */
/* Formulate the path for the Unix domain socket. */
gchar * socket_path = g_strdup_printf("/tmp/.lxterminal-socket%s-%s", gdk_display_get_name(gdk_display_get_default()), g_get_user_name());
/* Create socket. */
int fd = socket(PF_UNIX, SOCK_STREAM, 0);
{
g_warning("Socket create failed: %s\n", g_strerror(errno));
g_free(socket_path);
return TRUE;
}
/* Initialize socket address for Unix domain socket. */
struct sockaddr_un sock_addr;
memset(&sock_addr, 0, sizeof(sock_addr));
sock_addr.sun_family = AF_UNIX;
snprintf(sock_addr.sun_path, sizeof(sock_addr.sun_path), "%s", socket_path);
/* Try to connect to an existing LXTerminal process. */
if (connect(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0)
{
/* Connect failed. We are the controller, unless something fails. */
unlink(socket_path);
g_free(socket_path);
/* Bind to socket. */
if (bind(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0)
{
g_warning("Bind on socket failed: %s\n", g_strerror(errno));
close(fd);
return TRUE;
}
/* Listen on socket. */
if (listen(fd, 5) < 0)
{
g_warning("Listen on socket failed: %s\n", g_strerror(errno));
close(fd);
return TRUE;
}
/* Create a glib I/O channel. */
GIOChannel * gio = g_io_channel_unix_new(fd);
if (gio == NULL)
{
g_warning("Cannot create GIOChannel\n");
close(fd);
return TRUE;
}
/* Set up GIOChannel. */
g_io_channel_set_encoding(gio, NULL, NULL);
g_io_channel_set_buffered(gio, FALSE);
g_io_channel_set_close_on_unref(gio, TRUE);
/* Add I/O channel to the main event loop. */
if ( ! g_io_add_watch(gio, G_IO_IN | G_IO_HUP, (GIOFunc) lxterminal_socket_accept_client, lxtermwin))
{
g_warning("Cannot add watch on GIOChannel\n");
close(fd);
g_io_channel_unref(gio);
return TRUE;
}
/* Channel will automatically shut down when the watch returns FALSE. */
g_io_channel_set_close_on_unref(gio, TRUE);
g_io_channel_unref(gio);
return TRUE;
}
else
{
g_free(socket_path);
/* Create a glib I/O channel. */
GIOChannel * gio = g_io_channel_unix_new(fd);
g_io_channel_set_encoding(gio, NULL, NULL);
/* Push current dir in case it is needed later */
gchar * cur_dir = g_get_current_dir();
g_io_channel_write_chars(gio, cur_dir, -1, NULL, NULL);
/* Use "" as a pointer to '\0' since g_io_channel_write_chars() won't accept NULL */
g_io_channel_write_chars(gio, "", 1, NULL, NULL);
g_free(cur_dir);
/* push all of argv. */
gint i;
for (i = 0; i < argc; i ++)
{
g_io_channel_write_chars(gio, argv[i], -1, NULL, NULL);
g_io_channel_write_chars(gio, "", 1, NULL, NULL);
}
g_io_channel_flush(gio, NULL);
g_io_channel_unref(gio);
return FALSE;
}
}
Commit Message:
CWE ID: CWE-284
|
gboolean lxterminal_socket_initialize(LXTermWindow * lxtermwin, gint argc, gchar * * argv)
{
/* Normally, LXTerminal uses one process to control all of its windows.
* The first process to start will create a Unix domain socket in /tmp.
* It will then bind and listen on this socket.
* The subsequent processes will connect to the controller that owns the Unix domain socket.
* They will pass their command line over the socket and exit.
*
* If for any reason both the connect and bind fail, we will fall back to having that
* process be standalone; it will not be either the controller or a user of the controller.
* This behavior was introduced in response to a problem report (2973537).
*
* This function returns TRUE if this process should keep running and FALSE if it should exit. */
/* Formulate the path for the Unix domain socket. */
gchar * socket_path = g_strdup_printf("%s/.lxterminal-socket-%s", g_get_user_runtime_dir(), gdk_display_get_name(gdk_display_get_default()));
printf("%s\n", socket_path);
/* Create socket. */
int fd = socket(PF_UNIX, SOCK_STREAM, 0);
{
g_warning("Socket create failed: %s\n", g_strerror(errno));
g_free(socket_path);
return TRUE;
}
/* Initialize socket address for Unix domain socket. */
struct sockaddr_un sock_addr;
memset(&sock_addr, 0, sizeof(sock_addr));
sock_addr.sun_family = AF_UNIX;
snprintf(sock_addr.sun_path, sizeof(sock_addr.sun_path), "%s", socket_path);
/* Try to connect to an existing LXTerminal process. */
if (connect(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0)
{
/* Connect failed. We are the controller, unless something fails. */
unlink(socket_path);
g_free(socket_path);
/* Bind to socket. */
if (bind(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0)
{
g_warning("Bind on socket failed: %s\n", g_strerror(errno));
close(fd);
return TRUE;
}
/* Listen on socket. */
if (listen(fd, 5) < 0)
{
g_warning("Listen on socket failed: %s\n", g_strerror(errno));
close(fd);
return TRUE;
}
/* Create a glib I/O channel. */
GIOChannel * gio = g_io_channel_unix_new(fd);
if (gio == NULL)
{
g_warning("Cannot create GIOChannel\n");
close(fd);
return TRUE;
}
/* Set up GIOChannel. */
g_io_channel_set_encoding(gio, NULL, NULL);
g_io_channel_set_buffered(gio, FALSE);
g_io_channel_set_close_on_unref(gio, TRUE);
/* Add I/O channel to the main event loop. */
if ( ! g_io_add_watch(gio, G_IO_IN | G_IO_HUP, (GIOFunc) lxterminal_socket_accept_client, lxtermwin))
{
g_warning("Cannot add watch on GIOChannel\n");
close(fd);
g_io_channel_unref(gio);
return TRUE;
}
/* Channel will automatically shut down when the watch returns FALSE. */
g_io_channel_set_close_on_unref(gio, TRUE);
g_io_channel_unref(gio);
return TRUE;
}
else
{
g_free(socket_path);
/* Create a glib I/O channel. */
GIOChannel * gio = g_io_channel_unix_new(fd);
g_io_channel_set_encoding(gio, NULL, NULL);
/* Push current dir in case it is needed later */
gchar * cur_dir = g_get_current_dir();
g_io_channel_write_chars(gio, cur_dir, -1, NULL, NULL);
/* Use "" as a pointer to '\0' since g_io_channel_write_chars() won't accept NULL */
g_io_channel_write_chars(gio, "", 1, NULL, NULL);
g_free(cur_dir);
/* push all of argv. */
gint i;
for (i = 0; i < argc; i ++)
{
g_io_channel_write_chars(gio, argv[i], -1, NULL, NULL);
g_io_channel_write_chars(gio, "", 1, NULL, NULL);
}
g_io_channel_flush(gio, NULL);
g_io_channel_unref(gio);
return FALSE;
}
}
| 165,232
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static BOOL region16_simplify_bands(REGION16* region)
{
/** Simplify consecutive bands that touch and have the same items
*
* ==================== ====================
* | 1 | | 2 | | | | |
* ==================== | | | |
* | 1 | | 2 | ====> | 1 | | 2 |
* ==================== | | | |
* | 1 | | 2 | | | | |
* ==================== ====================
*
*/
RECTANGLE_16* band1, *band2, *endPtr, *endBand, *tmp;
int nbRects, finalNbRects;
int bandItems, toMove;
finalNbRects = nbRects = region16_n_rects(region);
if (nbRects < 2)
return TRUE;
band1 = region16_rects_noconst(region);
endPtr = band1 + nbRects;
do
{
band2 = next_band(band1, endPtr, &bandItems);
if (band2 == endPtr)
break;
if ((band1->bottom == band2->top) && band_match(band1, band2, endPtr))
{
/* adjust the bottom of band1 items */
tmp = band1;
while (tmp < band2)
{
tmp->bottom = band2->bottom;
tmp++;
}
/* override band2, we don't move band1 pointer as the band after band2
* may be merged too */
endBand = band2 + bandItems;
toMove = (endPtr - endBand) * sizeof(RECTANGLE_16);
if (toMove)
MoveMemory(band2, endBand, toMove);
finalNbRects -= bandItems;
endPtr -= bandItems;
}
else
{
band1 = band2;
}
}
while (TRUE);
if (finalNbRects != nbRects)
{
int allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16));
region->data = realloc(region->data, allocSize);
if (!region->data)
{
region->data = &empty_region;
return FALSE;
}
region->data->nbRects = finalNbRects;
region->data->size = allocSize;
}
return TRUE;
}
Commit Message: Fixed #5645: realloc return handling
CWE ID: CWE-772
|
static BOOL region16_simplify_bands(REGION16* region)
{
/** Simplify consecutive bands that touch and have the same items
*
* ==================== ====================
* | 1 | | 2 | | | | |
* ==================== | | | |
* | 1 | | 2 | ====> | 1 | | 2 |
* ==================== | | | |
* | 1 | | 2 | | | | |
* ==================== ====================
*
*/
RECTANGLE_16* band1, *band2, *endPtr, *endBand, *tmp;
int nbRects, finalNbRects;
int bandItems, toMove;
finalNbRects = nbRects = region16_n_rects(region);
if (nbRects < 2)
return TRUE;
band1 = region16_rects_noconst(region);
endPtr = band1 + nbRects;
do
{
band2 = next_band(band1, endPtr, &bandItems);
if (band2 == endPtr)
break;
if ((band1->bottom == band2->top) && band_match(band1, band2, endPtr))
{
/* adjust the bottom of band1 items */
tmp = band1;
while (tmp < band2)
{
tmp->bottom = band2->bottom;
tmp++;
}
/* override band2, we don't move band1 pointer as the band after band2
* may be merged too */
endBand = band2 + bandItems;
toMove = (endPtr - endBand) * sizeof(RECTANGLE_16);
if (toMove)
MoveMemory(band2, endBand, toMove);
finalNbRects -= bandItems;
endPtr -= bandItems;
}
else
{
band1 = band2;
}
}
while (TRUE);
if (finalNbRects != nbRects)
{
REGION16_DATA* data;
size_t allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16));
data = realloc(region->data, allocSize);
if (!data)
free(region->data);
region->data = data;
if (!region->data)
{
region->data = &empty_region;
return FALSE;
}
region->data->nbRects = finalNbRects;
region->data->size = allocSize;
}
return TRUE;
}
| 169,497
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: create_surface_from_thumbnail_data (guchar *data,
gint width,
gint height,
gint rowstride)
{
guchar *cairo_pixels;
cairo_surface_t *surface;
static cairo_user_data_key_t key;
int j;
cairo_pixels = (guchar *)g_malloc (4 * width * height);
surface = cairo_image_surface_create_for_data ((unsigned char *)cairo_pixels,
CAIRO_FORMAT_RGB24,
width, height, 4 * width);
cairo_surface_set_user_data (surface, &key,
cairo_pixels, (cairo_destroy_func_t)g_free);
for (j = height; j; j--) {
guchar *p = data;
guchar *q = cairo_pixels;
guchar *end = p + 3 * width;
while (p < end) {
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
q[0] = p[2];
q[1] = p[1];
q[2] = p[0];
#else
q[1] = p[0];
q[2] = p[1];
q[3] = p[2];
#endif
p += 3;
q += 4;
}
data += rowstride;
cairo_pixels += 4 * width;
}
return surface;
}
Commit Message:
CWE ID: CWE-189
|
create_surface_from_thumbnail_data (guchar *data,
gint width,
gint height,
gint rowstride)
{
guchar *cairo_pixels;
gint cairo_stride;
cairo_surface_t *surface;
int j;
surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, height);
if (cairo_surface_status (surface))
return NULL;
cairo_pixels = cairo_image_surface_get_data (surface);
cairo_stride = cairo_image_surface_get_stride (surface);
for (j = height; j; j--) {
guchar *p = data;
guchar *q = cairo_pixels;
guchar *end = p + 3 * width;
while (p < end) {
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
q[0] = p[2];
q[1] = p[1];
q[2] = p[0];
#else
q[1] = p[0];
q[2] = p[1];
q[3] = p[2];
#endif
p += 3;
q += 4;
}
data += rowstride;
cairo_pixels += cairo_stride;
}
return surface;
}
| 164,601
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void nw_cache_free(nw_cache *cache, void *obj)
{
if (cache->free < cache->free_total) {
cache->free_arr[cache->free++] = obj;
} else {
uint32_t new_free_total = cache->free_total * 2;
void *new_arr = realloc(cache->free_arr, new_free_total * sizeof(void *));
if (new_arr) {
cache->free_total = new_free_total;
cache->free_arr = new_arr;
cache->free_arr[cache->free++] = obj;
} else {
free(obj);
}
}
}
Commit Message: Merge pull request #131 from benjaminchodroff/master
fix memory corruption and other 32bit overflows
CWE ID: CWE-190
|
void nw_cache_free(nw_cache *cache, void *obj)
{
if (cache->free < cache->free_total) {
cache->free_arr[cache->free++] = obj;
} else if (cache->free_total < NW_CACHE_MAX_SIZE) {
uint32_t new_free_total = cache->free_total * 2;
void *new_arr = realloc(cache->free_arr, new_free_total * sizeof(void *));
if (new_arr) {
cache->free_total = new_free_total;
cache->free_arr = new_arr;
cache->free_arr[cache->free++] = obj;
} else {
free(obj);
}
} else {
free(obj);
}
}
| 169,016
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SPL_METHOD(SplFileObject, getMaxLineLen)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG((long)intern->u.file.max_line_len);
} /* }}} */
/* {{{ proto bool SplFileObject::hasChildren()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileObject, getMaxLineLen)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG((long)intern->u.file.max_line_len);
} /* }}} */
/* {{{ proto bool SplFileObject::hasChildren()
| 167,059
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void UsbFindDevicesFunction::OnGetDevicesComplete(
const std::vector<scoped_refptr<UsbDevice>>& devices) {
result_.reset(new base::ListValue());
barrier_ = base::BarrierClosure(
devices.size(), base::Bind(&UsbFindDevicesFunction::OpenComplete, this));
for (const scoped_refptr<UsbDevice>& device : devices) {
if (device->vendor_id() != vendor_id_ ||
device->product_id() != product_id_) {
barrier_.Run();
} else {
device->OpenInterface(
interface_id_,
base::Bind(&UsbFindDevicesFunction::OnDeviceOpened, this));
}
}
}
Commit Message: Remove fallback when requesting a single USB interface.
This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The
permission broker now supports opening devices that are partially
claimed through the OpenPath method and RequestPathAccess will always
fail for these devices so the fallback path from RequestPathAccess to
OpenPath is always taken.
BUG=500057
Review URL: https://codereview.chromium.org/1227313003
Cr-Commit-Position: refs/heads/master@{#338354}
CWE ID: CWE-399
|
void UsbFindDevicesFunction::OnGetDevicesComplete(
const std::vector<scoped_refptr<UsbDevice>>& devices) {
result_.reset(new base::ListValue());
barrier_ = base::BarrierClosure(
devices.size(), base::Bind(&UsbFindDevicesFunction::OpenComplete, this));
for (const scoped_refptr<UsbDevice>& device : devices) {
if (device->vendor_id() != vendor_id_ ||
device->product_id() != product_id_) {
barrier_.Run();
} else {
device->Open(base::Bind(&UsbFindDevicesFunction::OnDeviceOpened, this));
}
}
}
| 171,703
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void AcceleratedSurfaceBuffersSwappedCompletedForGPU(int host_id,
int route_id,
bool alive,
bool did_swap) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU,
host_id,
route_id,
alive,
did_swap));
return;
}
GpuProcessHost* host = GpuProcessHost::FromID(host_id);
if (host) {
if (alive)
host->Send(new AcceleratedSurfaceMsg_BufferPresented(
route_id, did_swap, 0));
else
host->ForceShutdown();
}
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void AcceleratedSurfaceBuffersSwappedCompletedForGPU(int host_id,
int route_id,
bool alive,
uint64 surface_handle) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU,
host_id,
route_id,
alive,
surface_handle));
return;
}
GpuProcessHost* host = GpuProcessHost::FromID(host_id);
if (host) {
if (alive)
host->Send(new AcceleratedSurfaceMsg_BufferPresented(
route_id, surface_handle, 0));
else
host->ForceShutdown();
}
}
| 171,354
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡვဒ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add additional Lao character to IDN confusables
U+0E01 (ก) => n
Prior Lao/Thai entries were added in crrev.com/c/1058710.
Test: components_unittests --gtest_filter=*IDN*
Bug: 882078
Change-Id: I1e90b144a1d791341b515d026a6bc4be7cbed57d
Reviewed-on: https://chromium-review.googlesource.com/1220773
Reviewed-by: Peter Kasting <pkasting@chromium.org>
Commit-Queue: Christopher Thompson <cthomp@chromium.org>
Cr-Commit-Position: refs/heads/master@{#591227}
CWE ID: CWE-20
|
IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+014B (ŋ), U+043F (п), U+0525 (ԥ), U+0E01 (ก)} => n
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡვဒ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 172,662
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: unsigned long long Track::GetCodecDelay() const
{
return m_info.codecDelay;
}
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 Track::GetCodecDelay() const
| 174,292
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool AXNodeObject::isModal() const {
if (roleValue() != DialogRole && roleValue() != AlertDialogRole)
return false;
if (hasAttribute(aria_modalAttr)) {
const AtomicString& modal = getAttribute(aria_modalAttr);
if (equalIgnoringCase(modal, "true"))
return true;
if (equalIgnoringCase(modal, "false"))
return false;
}
if (getNode() && isHTMLDialogElement(*getNode()))
return toElement(getNode())->isInTopLayer();
return false;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
bool AXNodeObject::isModal() const {
if (roleValue() != DialogRole && roleValue() != AlertDialogRole)
return false;
if (hasAttribute(aria_modalAttr)) {
const AtomicString& modal = getAttribute(aria_modalAttr);
if (equalIgnoringASCIICase(modal, "true"))
return true;
if (equalIgnoringASCIICase(modal, "false"))
return false;
}
if (getNode() && isHTMLDialogElement(*getNode()))
return toElement(getNode())->isInTopLayer();
return false;
}
| 171,916
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
const unsigned char
*pixels;
Image
*image;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
MagickBooleanType
status;
size_t
length;
ssize_t
count,
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=1;
image->endian=MSBEndian;
(void) ReadBlobLSBShort(image);
image->columns=(size_t) ReadBlobLSBShort(image);
(void) ReadBlobLSBShort(image);
image->rows=(size_t) ReadBlobLSBShort(image);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Convert bi-level image to pixel packets.
*/
SetImageColorspace(image,GRAYColorspace);
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
pixels=(const unsigned char *) ReadBlobStream(image,length,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) ReadBlobStream(image,(size_t) (-(ssize_t) length) & 0x01,
GetQuantumPixels(quantum_info),&count);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: Fixed memory leak reported in #456.
CWE ID: CWE-772
|
static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
const unsigned char
*pixels;
Image
*image;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
MagickBooleanType
status;
size_t
length;
ssize_t
count,
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=1;
image->endian=MSBEndian;
(void) ReadBlobLSBShort(image);
image->columns=(size_t) ReadBlobLSBShort(image);
(void) ReadBlobLSBShort(image);
image->rows=(size_t) ReadBlobLSBShort(image);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Convert bi-level image to pixel packets.
*/
SetImageColorspace(image,GRAYColorspace);
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
pixels=(const unsigned char *) ReadBlobStream(image,length,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) length)
{
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) ReadBlobStream(image,(size_t) (-(ssize_t) length) & 0x01,
GetQuantumPixels(quantum_info),&count);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,123
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int tls_construct_cke_dhe(SSL *s, unsigned char **p, int *len, int *al)
{
#ifndef OPENSSL_NO_DH
DH *dh_clnt = NULL;
const BIGNUM *pub_key;
EVP_PKEY *ckey = NULL, *skey = NULL;
skey = s->s3->peer_tmp;
if (skey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
return 0;
}
ckey = ssl_generate_pkey(skey);
dh_clnt = EVP_PKEY_get0_DH(ckey);
if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
EVP_PKEY_free(ckey);
return 0;
}
/* send off the data */
DH_get0_key(dh_clnt, &pub_key, NULL);
*len = BN_num_bytes(pub_key);
s2n(*len, *p);
BN_bn2bin(pub_key, *p);
*len += 2;
EVP_PKEY_free(ckey);
return 1;
#else
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
#endif
}
Commit Message: Fix missing NULL checks in CKE processing
Reviewed-by: Rich Salz <rsalz@openssl.org>
CWE ID: CWE-476
|
static int tls_construct_cke_dhe(SSL *s, unsigned char **p, int *len, int *al)
{
#ifndef OPENSSL_NO_DH
DH *dh_clnt = NULL;
const BIGNUM *pub_key;
EVP_PKEY *ckey = NULL, *skey = NULL;
skey = s->s3->peer_tmp;
if (skey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
return 0;
}
ckey = ssl_generate_pkey(skey);
if (ckey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
return 0;
}
dh_clnt = EVP_PKEY_get0_DH(ckey);
if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
EVP_PKEY_free(ckey);
return 0;
}
/* send off the data */
DH_get0_key(dh_clnt, &pub_key, NULL);
*len = BN_num_bytes(pub_key);
s2n(*len, *p);
BN_bn2bin(pub_key, *p);
*len += 2;
EVP_PKEY_free(ckey);
return 1;
#else
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
#endif
}
| 168,433
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int fsmVerify(const char *path, rpmfi fi)
{
int rc;
int saveerrno = errno;
struct stat dsb;
mode_t mode = rpmfiFMode(fi);
rc = fsmStat(path, 1, &dsb);
if (rc)
return rc;
if (S_ISREG(mode)) {
/* HP-UX (and other os'es) don't permit unlink on busy files. */
char *rmpath = rstrscat(NULL, path, "-RPMDELETE", NULL);
rc = fsmRename(path, rmpath);
/* XXX shouldn't we take unlink return code here? */
if (!rc)
(void) fsmUnlink(rmpath);
else
rc = RPMERR_UNLINK_FAILED;
free(rmpath);
return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */
} else if (S_ISDIR(mode)) {
if (S_ISDIR(dsb.st_mode)) return 0;
if (S_ISLNK(dsb.st_mode)) {
rc = fsmStat(path, 0, &dsb);
if (rc == RPMERR_ENOENT) rc = 0;
if (rc) return rc;
errno = saveerrno;
if (S_ISDIR(dsb.st_mode)) return 0;
}
} else if (S_ISLNK(mode)) {
if (S_ISLNK(dsb.st_mode)) {
char buf[8 * BUFSIZ];
size_t len;
rc = fsmReadLink(path, buf, 8 * BUFSIZ, &len);
errno = saveerrno;
if (rc) return rc;
if (rstreq(rpmfiFLink(fi), buf)) return 0;
}
} else if (S_ISFIFO(mode)) {
if (S_ISFIFO(dsb.st_mode)) return 0;
} else if (S_ISCHR(mode) || S_ISBLK(mode)) {
if ((S_ISCHR(dsb.st_mode) || S_ISBLK(dsb.st_mode)) &&
(dsb.st_rdev == rpmfiFRdev(fi))) return 0;
} else if (S_ISSOCK(mode)) {
if (S_ISSOCK(dsb.st_mode)) return 0;
}
/* XXX shouldn't do this with commit/undo. */
rc = fsmUnlink(path);
if (rc == 0) rc = RPMERR_ENOENT;
return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */
}
Commit Message: Restrict following symlinks to directories by ownership (CVE-2017-7500)
Only follow directory symlinks owned by target directory owner or root.
This prevents privilege escalation from user-writable directories via
directory symlinks to privileged directories on package upgrade, while
still allowing admin to arrange disk usage with symlinks.
The rationale is that if you can create symlinks owned by user X you *are*
user X (or root), and if you also own directory Y you can do whatever with
it already, including change permissions. So when you create a symlink to
that directory, the link ownership acts as a simple stamp of authority that
you indeed want rpm to treat this symlink as it were the directory that
you own. Such a permission can only be given by you or root, which
is just the way we want it. Plus it's almost ridiculously simple as far
as rules go, compared to trying to calculate something from the
source vs destination directory permissions etc.
In the normal case, the user arranging diskspace with symlinks is indeed
root so nothing changes, the only real change here is to links created by
non-privileged users which should be few and far between in practise.
Unfortunately our test-suite runs as a regular user via fakechroot and
thus the testcase for this fails under the new rules. Adjust the testcase
to get the ownership straight and add a second case for the illegal
behavior, basically the same as the old one but with different expectations.
CWE ID: CWE-59
|
static int fsmVerify(const char *path, rpmfi fi)
static int fsmVerify(const char *path, rpmfi fi, const struct stat *fsb)
{
int rc;
int saveerrno = errno;
struct stat dsb;
mode_t mode = rpmfiFMode(fi);
rc = fsmStat(path, 1, &dsb);
if (rc)
return rc;
if (S_ISREG(mode)) {
/* HP-UX (and other os'es) don't permit unlink on busy files. */
char *rmpath = rstrscat(NULL, path, "-RPMDELETE", NULL);
rc = fsmRename(path, rmpath);
/* XXX shouldn't we take unlink return code here? */
if (!rc)
(void) fsmUnlink(rmpath);
else
rc = RPMERR_UNLINK_FAILED;
free(rmpath);
return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */
} else if (S_ISDIR(mode)) {
if (S_ISDIR(dsb.st_mode)) return 0;
if (S_ISLNK(dsb.st_mode)) {
uid_t luid = dsb.st_uid;
rc = fsmStat(path, 0, &dsb);
if (rc == RPMERR_ENOENT) rc = 0;
if (rc) return rc;
errno = saveerrno;
/* Only permit directory symlinks by target owner and root */
if (S_ISDIR(dsb.st_mode) && (luid == 0 || luid == fsb->st_uid))
return 0;
}
} else if (S_ISLNK(mode)) {
if (S_ISLNK(dsb.st_mode)) {
char buf[8 * BUFSIZ];
size_t len;
rc = fsmReadLink(path, buf, 8 * BUFSIZ, &len);
errno = saveerrno;
if (rc) return rc;
if (rstreq(rpmfiFLink(fi), buf)) return 0;
}
} else if (S_ISFIFO(mode)) {
if (S_ISFIFO(dsb.st_mode)) return 0;
} else if (S_ISCHR(mode) || S_ISBLK(mode)) {
if ((S_ISCHR(dsb.st_mode) || S_ISBLK(dsb.st_mode)) &&
(dsb.st_rdev == rpmfiFRdev(fi))) return 0;
} else if (S_ISSOCK(mode)) {
if (S_ISSOCK(dsb.st_mode)) return 0;
}
/* XXX shouldn't do this with commit/undo. */
rc = fsmUnlink(path);
if (rc == 0) rc = RPMERR_ENOENT;
return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */
}
| 170,176
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long Segment::Load() {
assert(m_clusters == NULL);
assert(m_clusterSize == 0);
assert(m_clusterCount == 0);
const long long header_status = ParseHeaders();
if (header_status < 0) // error
return static_cast<long>(header_status);
if (header_status > 0) // underflow
return E_BUFFER_NOT_FULL;
assert(m_pInfo);
assert(m_pTracks);
for (;;) {
const int status = LoadCluster();
if (status < 0) // error
return status;
if (status >= 1) // no more clusters
return 0;
}
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
long Segment::Load() {
assert(m_clusters == NULL);
assert(m_clusterSize == 0);
assert(m_clusterCount == 0);
const long long header_status = ParseHeaders();
if (header_status < 0) // error
return static_cast<long>(header_status);
if (header_status > 0) // underflow
return E_BUFFER_NOT_FULL;
if (m_pInfo == NULL || m_pTracks == NULL)
return E_FILE_FORMAT_INVALID;
for (;;) {
const int status = LoadCluster();
if (status < 0) // error
return status;
if (status >= 1) // no more clusters
return 0;
}
}
| 173,828
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: DataReductionProxySettings::DataReductionProxySettings()
: unreachable_(false),
deferred_initialization_(false),
prefs_(nullptr),
config_(nullptr),
clock_(base::DefaultClock::GetInstance()) {}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <waffles@chromium.org>
Reviewed-by: Tarun Bansal <tbansal@chromium.org>
Commit-Queue: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
|
DataReductionProxySettings::DataReductionProxySettings()
: unreachable_(false),
deferred_initialization_(false),
prefs_(nullptr),
config_(nullptr),
clock_(base::DefaultClock::GetInstance()) {}
| 172,550
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void v9fs_walk(void *opaque)
{
int name_idx;
V9fsFidState *newfidp = NULL;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
if (err < 0) {
pdu_complete(pdu, err);
return ;
}
V9fsFidState *newfidp = NULL;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
if (err < 0) {
for (i = 0; i < nwnames; i++) {
err = pdu_unmarshal(pdu, offset, "s", &wnames[i]);
if (err < 0) {
goto out_nofid;
}
if (name_is_illegal(wnames[i].data)) {
err = -ENOENT;
goto out_nofid;
}
offset += err;
}
} else if (nwnames > P9_MAXWELEM) {
err = -EINVAL;
goto out_nofid;
}
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
v9fs_path_init(&dpath);
v9fs_path_init(&path);
/*
* Both dpath and path initially poin to fidp.
* Needed to handle request with nwnames == 0
*/
v9fs_path_copy(&dpath, &fidp->path);
err = -ENOENT;
goto out_nofid;
}
Commit Message:
CWE ID: CWE-22
|
static void v9fs_walk(void *opaque)
{
int name_idx;
V9fsFidState *newfidp = NULL;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
if (err < 0) {
pdu_complete(pdu, err);
return ;
}
V9fsFidState *newfidp = NULL;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
V9fsQID qid;
err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
if (err < 0) {
for (i = 0; i < nwnames; i++) {
err = pdu_unmarshal(pdu, offset, "s", &wnames[i]);
if (err < 0) {
goto out_nofid;
}
if (name_is_illegal(wnames[i].data)) {
err = -ENOENT;
goto out_nofid;
}
offset += err;
}
} else if (nwnames > P9_MAXWELEM) {
err = -EINVAL;
goto out_nofid;
}
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
v9fs_path_init(&dpath);
v9fs_path_init(&path);
/*
* Both dpath and path initially poin to fidp.
* Needed to handle request with nwnames == 0
*/
v9fs_path_copy(&dpath, &fidp->path);
err = -ENOENT;
goto out_nofid;
}
| 164,939
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.