instruction
stringclasses 1
value | input
stringlengths 93
3.53k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: mm_sshpam_init_ctx(Authctxt *authctxt)
{
Buffer m;
int success;
debug3("%s", __func__);
buffer_init(&m);
buffer_put_cstring(&m, authctxt->user);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m);
debug3("%s: waiting for MONITOR_ANS_PAM_INIT_CTX", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m);
success = buffer_get_int(&m);
if (success == 0) {
debug3("%s: pam_init_ctx failed", __func__);
buffer_free(&m);
return (NULL);
}
buffer_free(&m);
return (authctxt);
}
Commit Message: Don't resend username to PAM; it already has it.
Pointed out by Moritz Jodeit; ok dtucker@
CWE ID: CWE-20 | mm_sshpam_init_ctx(Authctxt *authctxt)
{
Buffer m;
int success;
debug3("%s", __func__);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m);
debug3("%s: waiting for MONITOR_ANS_PAM_INIT_CTX", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m);
success = buffer_get_int(&m);
if (success == 0) {
debug3("%s: pam_init_ctx failed", __func__);
buffer_free(&m);
return (NULL);
}
buffer_free(&m);
return (authctxt);
}
| 166,586 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: DownloadUrlParameters::DownloadUrlParameters(
const GURL& url,
int render_process_host_id,
int render_view_host_routing_id,
int render_frame_host_routing_id,
const net::NetworkTrafficAnnotationTag& traffic_annotation)
: content_initiated_(false),
use_if_range_(true),
method_("GET"),
post_id_(-1),
prefer_cache_(false),
referrer_policy_(
net::URLRequest::
CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
render_process_host_id_(render_process_host_id),
render_view_host_routing_id_(render_view_host_routing_id),
render_frame_host_routing_id_(render_frame_host_routing_id),
url_(url),
do_not_prompt_for_login_(false),
follow_cross_origin_redirects_(true),
fetch_error_body_(false),
transient_(false),
traffic_annotation_(traffic_annotation),
download_source_(DownloadSource::UNKNOWN) {}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <[email protected]>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284 | DownloadUrlParameters::DownloadUrlParameters(
const GURL& url,
int render_process_host_id,
int render_view_host_routing_id,
int render_frame_host_routing_id,
const net::NetworkTrafficAnnotationTag& traffic_annotation)
: content_initiated_(false),
use_if_range_(true),
method_("GET"),
post_id_(-1),
prefer_cache_(false),
referrer_policy_(
net::URLRequest::
CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
render_process_host_id_(render_process_host_id),
render_view_host_routing_id_(render_view_host_routing_id),
render_frame_host_routing_id_(render_frame_host_routing_id),
frame_tree_node_id_(-1),
url_(url),
do_not_prompt_for_login_(false),
follow_cross_origin_redirects_(true),
fetch_error_body_(false),
transient_(false),
traffic_annotation_(traffic_annotation),
download_source_(DownloadSource::UNKNOWN) {}
| 173,020 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: status_t OMXNodeInstance::freeBuffer(
OMX_U32 portIndex, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
CLOG_BUFFER(freeBuffer, "%s:%u %#x", portString(portIndex), portIndex, buffer);
removeActiveBuffer(portIndex, buffer);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer);
BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate);
OMX_ERRORTYPE err = OMX_FreeBuffer(mHandle, portIndex, header);
CLOG_IF_ERROR(freeBuffer, err, "%s:%u %#x", portString(portIndex), portIndex, buffer);
delete buffer_meta;
buffer_meta = NULL;
invalidateBufferID(buffer);
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | status_t OMXNodeInstance::freeBuffer(
OMX_U32 portIndex, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
CLOG_BUFFER(freeBuffer, "%s:%u %#x", portString(portIndex), portIndex, buffer);
removeActiveBuffer(portIndex, buffer);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate);
OMX_ERRORTYPE err = OMX_FreeBuffer(mHandle, portIndex, header);
CLOG_IF_ERROR(freeBuffer, err, "%s:%u %#x", portString(portIndex), portIndex, buffer);
delete buffer_meta;
buffer_meta = NULL;
invalidateBufferID(buffer);
return StatusFromOMXError(err);
}
| 173,529 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static MagickPixelPacket **AcquirePixelThreadSet(const Image *images)
{
const Image
*next;
MagickPixelPacket
**pixels;
register ssize_t
i,
j;
size_t
columns,
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (MagickPixelPacket **) NULL)
return((MagickPixelPacket **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
columns=images->columns;
for (next=images; next != (Image *) NULL; next=next->next)
columns=MagickMax(next->columns,columns);
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns,
sizeof(**pixels));
if (pixels[i] == (MagickPixelPacket *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) columns; j++)
GetMagickPixelPacket(images,&pixels[i][j]);
}
return(pixels);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1615
CWE ID: CWE-119 | static MagickPixelPacket **AcquirePixelThreadSet(const Image *images)
{
const Image
*next;
MagickPixelPacket
**pixels;
register ssize_t
i,
j;
size_t
columns,
rows;
rows=MagickMax(GetImageListLength(images),
(size_t) GetMagickResourceLimit(ThreadResource));
pixels=(MagickPixelPacket **) AcquireQuantumMemory(rows,sizeof(*pixels));
if (pixels == (MagickPixelPacket **) NULL)
return((MagickPixelPacket **) NULL);
columns=images->columns;
for (next=images; next != (Image *) NULL; next=next->next)
columns=MagickMax(next->columns,columns);
for (i=0; i < (ssize_t) rows; i++)
{
pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns,
sizeof(**pixels));
if (pixels[i] == (MagickPixelPacket *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) columns; j++)
GetMagickPixelPacket(images,&pixels[i][j]);
}
return(pixels);
}
| 169,595 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void PrintPreviewUI::OnPrintPreviewRequest(int request_id) {
g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, request_id);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void PrintPreviewUI::OnPrintPreviewRequest(int request_id) {
g_print_preview_request_id_map.Get().Set(id_, request_id);
}
| 170,839 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: ikev1_attrmap_print(netdissect_options *ndo,
const u_char *p, const u_char *ep,
const struct attrmap *map, size_t nmap)
{
int totlen;
uint32_t t, v;
if (p[0] & 0x80)
totlen = 4;
else
totlen = 4 + EXTRACT_16BITS(&p[2]);
if (ep < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep + 1;
}
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
if (map && t < nmap && map[t].type)
ND_PRINT((ndo,"type=%s ", map[t].type));
else
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
v = EXTRACT_16BITS(&p[2]);
if (map && t < nmap && v < map[t].nvalue && map[t].value[v])
ND_PRINT((ndo,"%s", map[t].value[v]));
else
rawprint(ndo, (const uint8_t *)&p[2], 2);
} else {
ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));
rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));
}
ND_PRINT((ndo,")"));
return p + totlen;
}
Commit Message: CVE-2017-13039/IKEv1: Do more bounds checking.
Have ikev1_attrmap_print() and ikev1_attr_print() do full bounds
checking, and return null on a bounds overflow. Have their callers
check for a null return.
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), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | ikev1_attrmap_print(netdissect_options *ndo,
const u_char *p, const u_char *ep2,
const struct attrmap *map, size_t nmap)
{
int totlen;
uint32_t t, v;
ND_TCHECK(p[0]);
if (p[0] & 0x80)
totlen = 4;
else {
ND_TCHECK_16BITS(&p[2]);
totlen = 4 + EXTRACT_16BITS(&p[2]);
}
if (ep2 < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep2 + 1;
}
ND_TCHECK_16BITS(&p[0]);
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
if (map && t < nmap && map[t].type)
ND_PRINT((ndo,"type=%s ", map[t].type));
else
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
ND_TCHECK_16BITS(&p[2]);
v = EXTRACT_16BITS(&p[2]);
if (map && t < nmap && v < map[t].nvalue && map[t].value[v])
ND_PRINT((ndo,"%s", map[t].value[v]));
else {
if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
} else {
ND_PRINT((ndo,"len=%d value=", totlen - 4));
if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
return p + totlen;
trunc:
return NULL;
}
| 167,840 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: mp_join_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_join *mpj = (const struct mp_join *) opt;
if (!(opt_len == 12 && flags & TH_SYN) &&
!(opt_len == 16 && (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) &&
!(opt_len == 24 && flags & TH_ACK))
return 0;
if (opt_len != 24) {
if (mpj->sub_b & MP_JOIN_B)
ND_PRINT((ndo, " backup"));
ND_PRINT((ndo, " id %u", mpj->addr_id));
}
switch (opt_len) {
case 12: /* SYN */
ND_PRINT((ndo, " token 0x%x" " nonce 0x%x",
EXTRACT_32BITS(mpj->u.syn.token),
EXTRACT_32BITS(mpj->u.syn.nonce)));
break;
case 16: /* SYN/ACK */
ND_PRINT((ndo, " hmac 0x%" PRIx64 " nonce 0x%x",
EXTRACT_64BITS(mpj->u.synack.mac),
EXTRACT_32BITS(mpj->u.synack.nonce)));
break;
case 24: {/* ACK */
size_t i;
ND_PRINT((ndo, " hmac 0x"));
for (i = 0; i < sizeof(mpj->u.ack.mac); ++i)
ND_PRINT((ndo, "%02x", mpj->u.ack.mac[i]));
}
default:
break;
}
return 1;
}
Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption.
Do the length checking inline; that means we print stuff up to the point
at which we run out of option data.
First check to make sure we have at least 4 bytes of option, so we have
flags to check.
This fixes a buffer over-read discovered by Kim Gwan Yeong.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | mp_join_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_join *mpj = (const struct mp_join *) opt;
if (!(opt_len == 12 && (flags & TH_SYN)) &&
!(opt_len == 16 && (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) &&
!(opt_len == 24 && (flags & TH_ACK)))
return 0;
if (opt_len != 24) {
if (mpj->sub_b & MP_JOIN_B)
ND_PRINT((ndo, " backup"));
ND_PRINT((ndo, " id %u", mpj->addr_id));
}
switch (opt_len) {
case 12: /* SYN */
ND_PRINT((ndo, " token 0x%x" " nonce 0x%x",
EXTRACT_32BITS(mpj->u.syn.token),
EXTRACT_32BITS(mpj->u.syn.nonce)));
break;
case 16: /* SYN/ACK */
ND_PRINT((ndo, " hmac 0x%" PRIx64 " nonce 0x%x",
EXTRACT_64BITS(mpj->u.synack.mac),
EXTRACT_32BITS(mpj->u.synack.nonce)));
break;
case 24: {/* ACK */
size_t i;
ND_PRINT((ndo, " hmac 0x"));
for (i = 0; i < sizeof(mpj->u.ack.mac); ++i)
ND_PRINT((ndo, "%02x", mpj->u.ack.mac[i]));
}
default:
break;
}
return 1;
}
| 167,838 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: PHP_METHOD(Phar, delete)
{
char *fname;
size_t fname_len;
char *error;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot write out phar archive, phar is read-only");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) {
if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) {
if (entry->is_deleted) {
/* entry is deleted, but has not been flushed to disk yet */
RETURN_TRUE;
} else {
entry->is_deleted = 1;
entry->is_modified = 1;
phar_obj->archive->is_modified = 1;
}
}
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname);
RETURN_FALSE;
}
phar_flush(phar_obj->archive, NULL, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, delete)
{
char *fname;
size_t fname_len;
char *error;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot write out phar archive, phar is read-only");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) {
if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) {
if (entry->is_deleted) {
/* entry is deleted, but has not been flushed to disk yet */
RETURN_TRUE;
} else {
entry->is_deleted = 1;
entry->is_modified = 1;
phar_obj->archive->is_modified = 1;
}
}
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname);
RETURN_FALSE;
}
phar_flush(phar_obj->archive, NULL, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
| 165,063 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: image_transform_png_set_strip_16_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_strip_16(pp);
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_strip_16_set(PNG_CONST image_transform *this,
image_transform_png_set_strip_16_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_strip_16(pp);
# if PNG_LIBPNG_VER < 10700
/* libpng will limit the gamma table size: */
that->max_gamma_8 = PNG_MAX_GAMMA_8;
# endif
this->next->set(this->next, that, pp, pi);
}
| 173,650 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: MagickExport int LocaleLowercase(const int c)
{
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(tolower_l((int) ((unsigned char) c),c_locale));
#endif
return(tolower((int) ((unsigned char) c)));
}
Commit Message: ...
CWE ID: CWE-125 | MagickExport int LocaleLowercase(const int c)
{
if (c < 0)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(tolower_l((int) ((unsigned char) c),c_locale));
#endif
return(tolower((int) ((unsigned char) c)));
}
| 169,711 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: status_t OMXNodeInstance::updateNativeHandleInMeta(
OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
return BAD_VALUE;
}
BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate);
sp<ABuffer> data = bufferMeta->getBuffer(
header, false /* backup */, false /* limit */);
bufferMeta->setNativeHandle(nativeHandle);
if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource
&& data->capacity() >= sizeof(VideoNativeHandleMetadata)) {
VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data());
metadata.eType = mMetadataType[portIndex];
metadata.pHandle =
nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle());
} else {
CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)",
portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity());
return BAD_VALUE;
}
CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p",
portString(portIndex), portIndex, buffer,
nativeHandle == NULL ? NULL : nativeHandle->handle());
return OK;
}
Commit Message: IOMX: do not convert ANWB to gralloc source in emptyBuffer
Bug: 29422020
Bug: 31412859
Change-Id: If48e3e0b6f1af99a459fdc3f6f03744bbf0dc375
(cherry picked from commit 534bb6132a6a664f90b42b3ef81298b42efb3dc2)
CWE ID: CWE-200 | status_t OMXNodeInstance::updateNativeHandleInMeta(
OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
return BAD_VALUE;
}
BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate);
// update backup buffer
sp<ABuffer> data = bufferMeta->getBuffer(
header, false /* backup */, false /* limit */);
bufferMeta->setNativeHandle(nativeHandle);
if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource
&& data->capacity() >= sizeof(VideoNativeHandleMetadata)) {
VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data());
metadata.eType = mMetadataType[portIndex];
metadata.pHandle =
nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle());
} else {
CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)",
portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity());
return BAD_VALUE;
}
CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p",
portString(portIndex), portIndex, buffer,
nativeHandle == NULL ? NULL : nativeHandle->handle());
return OK;
}
| 174,146 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static int hashtable_do_del(hashtable_t *hashtable,
const char *key, size_t hash)
{
pair_t *pair;
bucket_t *bucket;
size_t index;
index = hash % num_buckets(hashtable);
bucket = &hashtable->buckets[index];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
return -1;
if(&pair->list == bucket->first && &pair->list == bucket->last)
bucket->first = bucket->last = &hashtable->list;
else if(&pair->list == bucket->first)
bucket->first = pair->list.next;
else if(&pair->list == bucket->last)
bucket->last = pair->list.prev;
list_remove(&pair->list);
json_decref(pair->value);
jsonp_free(pair);
hashtable->size--;
return 0;
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310 | static int hashtable_do_del(hashtable_t *hashtable,
const char *key, size_t hash)
{
pair_t *pair;
bucket_t *bucket;
size_t index;
index = hash & hashmask(hashtable->order);
bucket = &hashtable->buckets[index];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
return -1;
if(&pair->list == bucket->first && &pair->list == bucket->last)
bucket->first = bucket->last = &hashtable->list;
else if(&pair->list == bucket->first)
bucket->first = pair->list.next;
else if(&pair->list == bucket->last)
bucket->last = pair->list.prev;
list_remove(&pair->list);
json_decref(pair->value);
jsonp_free(pair);
hashtable->size--;
return 0;
}
| 166,528 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static char *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. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static UINT drdynvc_process_close_request(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
int value;
UINT error;
UINT32 ChannelId;
wStream* data_out;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
WLog_Print(drdynvc->log, WLOG_DEBUG, "process_close_request: Sp=%d cbChId=%d, ChannelId=%"PRIu32"",
Sp,
cbChId, ChannelId);
if ((error = dvcman_close_channel(drdynvc->channel_mgr, ChannelId)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", error);
return error;
}
data_out = Stream_New(NULL, 4);
if (!data_out)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
value = (CLOSE_REQUEST_PDU << 4) | (cbChId & 0x03);
Stream_Write_UINT8(data_out, value);
drdynvc_write_variable_uint(data_out, ChannelId);
error = drdynvc_send(drdynvc, data_out);
if (error)
WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]",
WTSErrorToString(error), error);
return error;
}
Commit Message: Fix for #4866: Added additional length checks
CWE ID: | static UINT drdynvc_process_close_request(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
int value;
UINT error;
UINT32 ChannelId;
wStream* data_out;
if (Stream_GetRemainingLength(s) < drdynvc_cblen_to_bytes(cbChId))
return ERROR_INVALID_DATA;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
WLog_Print(drdynvc->log, WLOG_DEBUG, "process_close_request: Sp=%d cbChId=%d, ChannelId=%"PRIu32"",
Sp,
cbChId, ChannelId);
if ((error = dvcman_close_channel(drdynvc->channel_mgr, ChannelId)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", error);
return error;
}
data_out = Stream_New(NULL, 4);
if (!data_out)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
value = (CLOSE_REQUEST_PDU << 4) | (cbChId & 0x03);
Stream_Write_UINT8(data_out, value);
drdynvc_write_variable_uint(data_out, ChannelId);
error = drdynvc_send(drdynvc, data_out);
if (error)
WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]",
WTSErrorToString(error), error);
return error;
}
| 168,935 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: rpl_dao_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK(*dao);
if (length < ND_RPL_DAO_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAO_MIN_LEN;
length -= ND_RPL_DAO_MIN_LEN;
if(RPL_DAO_D(dao->rpl_flags)) {
ND_TCHECK2(dao->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, dao->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u%s%s,%02x]",
dagid_str,
dao->rpl_daoseq,
dao->rpl_instanceid,
RPL_DAO_K(dao->rpl_flags) ? ",acK":"",
RPL_DAO_D(dao->rpl_flags) ? ",Dagid":"",
dao->rpl_flags));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
tooshort:
ND_PRINT((ndo," [|length too short]"));
return;
}
Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.
CWE ID: CWE-125 | rpl_dao_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK(*dao);
if (length < ND_RPL_DAO_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAO_MIN_LEN;
length -= ND_RPL_DAO_MIN_LEN;
if(RPL_DAO_D(dao->rpl_flags)) {
ND_TCHECK2(dao->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, dao->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u%s%s,%02x]",
dagid_str,
dao->rpl_daoseq,
dao->rpl_instanceid,
RPL_DAO_K(dao->rpl_flags) ? ",acK":"",
RPL_DAO_D(dao->rpl_flags) ? ",Dagid":"",
dao->rpl_flags));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo, "%s", rpl_tstr));
return;
tooshort:
ND_PRINT((ndo," [|length too short]"));
return;
}
| 169,828 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride, tx_type_);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) {
void RunInvTxfm(const tran_low_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride, tx_type_);
}
| 174,553 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: bool NavigationRateLimiter::CanProceed() {
if (!enabled)
return true;
static constexpr int kStateUpdateLimit = 200;
static constexpr base::TimeDelta kStateUpdateLimitResetInterval =
base::TimeDelta::FromSeconds(10);
if (++count_ <= kStateUpdateLimit)
return true;
const base::TimeTicks now = base::TimeTicks::Now();
if (now - time_first_count_ > kStateUpdateLimitResetInterval) {
time_first_count_ = now;
count_ = 1;
error_message_sent_ = false;
return true;
}
if (!error_message_sent_) {
error_message_sent_ = true;
if (auto* local_frame = DynamicTo<LocalFrame>(frame_.Get())) {
local_frame->Console().AddMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kWarning,
"Throttling navigation to prevent the browser from hanging. See "
"https://crbug.com/882238. Command line switch "
"--disable-ipc-flooding-protection can be used to bypass the "
"protection"));
}
}
return false;
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416 | bool NavigationRateLimiter::CanProceed() {
if (!enabled)
return true;
static constexpr int kStateUpdateLimit = 200;
static constexpr base::TimeDelta kStateUpdateLimitResetInterval =
base::TimeDelta::FromSeconds(10);
if (++count_ <= kStateUpdateLimit)
return true;
const base::TimeTicks now = base::TimeTicks::Now();
if (now - time_first_count_ > kStateUpdateLimitResetInterval) {
time_first_count_ = now;
count_ = 1;
error_message_sent_ = false;
return true;
}
// the browser process with the DidAddMessageToConsole Mojo call.
if (!error_message_sent_) {
error_message_sent_ = true;
if (auto* local_frame = DynamicTo<LocalFrame>(frame_.Get())) {
local_frame->Console().AddMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kWarning,
"Throttling navigation to prevent the browser from hanging. See "
"https://crbug.com/882238. Command line switch "
"--disable-ipc-flooding-protection can be used to bypass the "
"protection"));
}
}
return false;
}
| 172,491 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static void svc_rdma_destroy_maps(struct svcxprt_rdma *xprt)
{
while (!list_empty(&xprt->sc_maps)) {
struct svc_rdma_req_map *map;
map = list_first_entry(&xprt->sc_maps,
struct svc_rdma_req_map, free);
list_del(&map->free);
kfree(map);
}
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | static void svc_rdma_destroy_maps(struct svcxprt_rdma *xprt)
| 168,180 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: ProxyChannelDelegate::~ProxyChannelDelegate() {
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | ProxyChannelDelegate::~ProxyChannelDelegate() {
| 170,740 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static void copyMultiCh24(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
{
for (unsigned i = 0; i < nSamples; ++i) {
for (unsigned c = 0; c < nChannels; ++c) {
*dst++ = src[c][i] >> 8;
}
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | static void copyMultiCh24(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
static void copyMultiCh24(short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned nChannels)
{
for (unsigned i = 0; i < nSamples; ++i) {
for (unsigned c = 0; c < nChannels; ++c) {
*dst++ = src[c][i] >> 8;
}
}
}
| 174,019 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: const Block* SimpleBlock::GetBlock() const
{
return &m_block;
}
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* SimpleBlock::GetBlock() const
| 174,285 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static struct inode *ext4_alloc_inode(struct super_block *sb)
{
struct ext4_inode_info *ei;
ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
if (!ei)
return NULL;
ei->vfs_inode.i_version = 1;
ei->vfs_inode.i_data.writeback_index = 0;
memset(&ei->i_cached_extent, 0, sizeof(struct ext4_ext_cache));
INIT_LIST_HEAD(&ei->i_prealloc_list);
spin_lock_init(&ei->i_prealloc_lock);
/*
* Note: We can be called before EXT4_SB(sb)->s_journal is set,
* therefore it can be null here. Don't check it, just initialize
* jinode.
*/
jbd2_journal_init_jbd_inode(&ei->jinode, &ei->vfs_inode);
ei->i_reserved_data_blocks = 0;
ei->i_reserved_meta_blocks = 0;
ei->i_allocated_meta_blocks = 0;
ei->i_da_metadata_calc_len = 0;
ei->i_delalloc_reserved_flag = 0;
spin_lock_init(&(ei->i_block_reservation_lock));
#ifdef CONFIG_QUOTA
ei->i_reserved_quota = 0;
#endif
INIT_LIST_HEAD(&ei->i_completed_io_list);
ei->cur_aio_dio = NULL;
ei->i_sync_tid = 0;
ei->i_datasync_tid = 0;
return &ei->vfs_inode;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: | static struct inode *ext4_alloc_inode(struct super_block *sb)
{
struct ext4_inode_info *ei;
ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
if (!ei)
return NULL;
ei->vfs_inode.i_version = 1;
ei->vfs_inode.i_data.writeback_index = 0;
memset(&ei->i_cached_extent, 0, sizeof(struct ext4_ext_cache));
INIT_LIST_HEAD(&ei->i_prealloc_list);
spin_lock_init(&ei->i_prealloc_lock);
/*
* Note: We can be called before EXT4_SB(sb)->s_journal is set,
* therefore it can be null here. Don't check it, just initialize
* jinode.
*/
jbd2_journal_init_jbd_inode(&ei->jinode, &ei->vfs_inode);
ei->i_reserved_data_blocks = 0;
ei->i_reserved_meta_blocks = 0;
ei->i_allocated_meta_blocks = 0;
ei->i_da_metadata_calc_len = 0;
ei->i_delalloc_reserved_flag = 0;
spin_lock_init(&(ei->i_block_reservation_lock));
#ifdef CONFIG_QUOTA
ei->i_reserved_quota = 0;
#endif
INIT_LIST_HEAD(&ei->i_completed_io_list);
spin_lock_init(&ei->i_completed_io_lock);
ei->cur_aio_dio = NULL;
ei->i_sync_tid = 0;
ei->i_datasync_tid = 0;
return &ei->vfs_inode;
}
| 167,554 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static void __local_bh_enable(unsigned int cnt)
{
lockdep_assert_irqs_disabled();
if (softirq_count() == (cnt & SOFTIRQ_MASK))
trace_softirqs_on(_RET_IP_);
preempt_count_sub(cnt);
}
Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace
Pull tracing fixes from Steven Rostedt:
"This contains a few fixes and a clean up.
- a bad merge caused an "endif" to go in the wrong place in
scripts/Makefile.build
- softirq tracing fix for tracing that corrupts lockdep and causes a
false splat
- histogram documentation typo fixes
- fix a bad memory reference when passing in no filter to the filter
code
- simplify code by using the swap macro instead of open coding the
swap"
* tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace:
tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount
tracing: Fix some errors in histogram documentation
tracing: Use swap macro in update_max_tr
softirq: Reorder trace_softirqs_on to prevent lockdep splat
tracing: Check for no filter when processing event filters
CWE ID: CWE-787 | static void __local_bh_enable(unsigned int cnt)
{
lockdep_assert_irqs_disabled();
if (preempt_count() == cnt)
trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
if (softirq_count() == (cnt & SOFTIRQ_MASK))
trace_softirqs_on(_RET_IP_);
__preempt_count_sub(cnt);
}
| 169,184 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: status_t OMXNodeInstance::updateGraphicBufferInMeta(
OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer,
OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
return updateGraphicBufferInMeta_l(
portIndex, graphicBuffer, buffer, header,
portIndex == kPortIndexOutput /* updateCodecBuffer */);
}
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::updateGraphicBufferInMeta(
OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer,
OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
return updateGraphicBufferInMeta_l(
portIndex, graphicBuffer, buffer, header,
true /* updateCodecBuffer */);
}
| 174,141 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
{
AVFilterContext *ctx = inlink->dst;
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
uint32_t plane_checksum[4] = {0}, checksum = 0;
int i, plane, vsub = desc->log2_chroma_h;
for (plane = 0; plane < 4 && frame->data[plane]; plane++) {
int64_t linesize = av_image_get_linesize(frame->format, frame->width, plane);
uint8_t *data = frame->data[plane];
int h = plane == 1 || plane == 2 ? FF_CEIL_RSHIFT(inlink->h, vsub) : inlink->h;
if (linesize < 0)
return linesize;
for (i = 0; i < h; i++) {
plane_checksum[plane] = av_adler32_update(plane_checksum[plane], data, linesize);
checksum = av_adler32_update(checksum, data, linesize);
data += frame->linesize[plane];
}
}
av_log(ctx, AV_LOG_INFO,
"n:%"PRId64" pts:%s pts_time:%s pos:%"PRId64" "
"fmt:%s sar:%d/%d s:%dx%d i:%c iskey:%d type:%c "
"checksum:%08X plane_checksum:[%08X",
inlink->frame_count,
av_ts2str(frame->pts), av_ts2timestr(frame->pts, &inlink->time_base), av_frame_get_pkt_pos(frame),
desc->name,
frame->sample_aspect_ratio.num, frame->sample_aspect_ratio.den,
frame->width, frame->height,
!frame->interlaced_frame ? 'P' : /* Progressive */
frame->top_field_first ? 'T' : 'B', /* Top / Bottom */
frame->key_frame,
av_get_picture_type_char(frame->pict_type),
checksum, plane_checksum[0]);
for (plane = 1; plane < 4 && frame->data[plane]; plane++)
av_log(ctx, AV_LOG_INFO, " %08X", plane_checksum[plane]);
av_log(ctx, AV_LOG_INFO, "]\n");
return ff_filter_frame(inlink->dst->outputs[0], frame);
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
{
AVFilterContext *ctx = inlink->dst;
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
uint32_t plane_checksum[4] = {0}, checksum = 0;
int i, plane, vsub = desc->log2_chroma_h;
for (plane = 0; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++) {
int64_t linesize = av_image_get_linesize(frame->format, frame->width, plane);
uint8_t *data = frame->data[plane];
int h = plane == 1 || plane == 2 ? FF_CEIL_RSHIFT(inlink->h, vsub) : inlink->h;
if (linesize < 0)
return linesize;
for (i = 0; i < h; i++) {
plane_checksum[plane] = av_adler32_update(plane_checksum[plane], data, linesize);
checksum = av_adler32_update(checksum, data, linesize);
data += frame->linesize[plane];
}
}
av_log(ctx, AV_LOG_INFO,
"n:%"PRId64" pts:%s pts_time:%s pos:%"PRId64" "
"fmt:%s sar:%d/%d s:%dx%d i:%c iskey:%d type:%c "
"checksum:%08X plane_checksum:[%08X",
inlink->frame_count,
av_ts2str(frame->pts), av_ts2timestr(frame->pts, &inlink->time_base), av_frame_get_pkt_pos(frame),
desc->name,
frame->sample_aspect_ratio.num, frame->sample_aspect_ratio.den,
frame->width, frame->height,
!frame->interlaced_frame ? 'P' : /* Progressive */
frame->top_field_first ? 'T' : 'B', /* Top / Bottom */
frame->key_frame,
av_get_picture_type_char(frame->pict_type),
checksum, plane_checksum[0]);
for (plane = 1; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++)
av_log(ctx, AV_LOG_INFO, " %08X", plane_checksum[plane]);
av_log(ctx, AV_LOG_INFO, "]\n");
return ff_filter_frame(inlink->dst->outputs[0], frame);
}
| 166,007 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void BrowserContextDestroyer::FinishDestroyContext() {
DCHECK_EQ(pending_hosts_, 0U);
delete context_;
context_ = nullptr;
delete this;
}
Commit Message:
CWE ID: CWE-20 | void BrowserContextDestroyer::FinishDestroyContext() {
DCHECK(finish_destroy_scheduled_);
CHECK_EQ(GetHostsForContext(context_.get()).size(), 0U)
<< "One or more RenderProcessHosts exist whilst its BrowserContext is "
<< "being deleted!";
g_contexts_pending_deletion.Get().remove(this);
if (context_->IsOffTheRecord()) {
// If this is an OTR context and its owner BrowserContext has been scheduled
// for deletion, update the owner's BrowserContextDestroyer
BrowserContextDestroyer* orig_destroyer =
GetForContext(context_->GetOriginalContext());
if (orig_destroyer) {
DCHECK_GT(orig_destroyer->otr_contexts_pending_deletion_, 0U);
DCHECK(!orig_destroyer->finish_destroy_scheduled_);
--orig_destroyer->otr_contexts_pending_deletion_;
orig_destroyer->MaybeScheduleFinishDestroyContext();
}
}
delete this;
}
| 165,420 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: QuotaTask::QuotaTask(QuotaTaskObserver* observer)
: observer_(observer),
original_task_runner_(base::MessageLoopProxy::current()) {
}
Commit Message: Quota double-delete fix
BUG=142310
Review URL: https://chromiumcodereview.appspot.com/10832407
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152532 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | QuotaTask::QuotaTask(QuotaTaskObserver* observer)
: observer_(observer),
original_task_runner_(base::MessageLoopProxy::current()),
delete_scheduled_(false) {
}
| 170,804 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void *load_device_tree(const char *filename_path, int *sizep)
{
int dt_size;
int dt_file_load_size;
int ret;
void *fdt = NULL;
*sizep = 0;
dt_size = get_image_size(filename_path);
if (dt_size < 0) {
error_report("Unable to get size of device tree file '%s'",
filename_path);
goto fail;
}
/* Expand to 2x size to give enough room for manipulation. */
dt_size += 10000;
dt_size *= 2;
/* First allocate space in qemu for device tree */
fdt = g_malloc0(dt_size);
dt_file_load_size = load_image(filename_path, fdt);
if (dt_file_load_size < 0) {
error_report("Unable to open device tree file '%s'",
filename_path);
goto fail;
}
ret = fdt_open_into(fdt, fdt, dt_size);
if (ret) {
error_report("Unable to copy device tree in memory");
goto fail;
}
/* Check sanity of device tree */
if (fdt_check_header(fdt)) {
error_report("Device tree file loaded into memory is invalid: %s",
filename_path);
goto fail;
}
*sizep = dt_size;
return fdt;
fail:
g_free(fdt);
return NULL;
}
Commit Message:
CWE ID: CWE-119 | void *load_device_tree(const char *filename_path, int *sizep)
{
int dt_size;
int dt_file_load_size;
int ret;
void *fdt = NULL;
*sizep = 0;
dt_size = get_image_size(filename_path);
if (dt_size < 0) {
error_report("Unable to get size of device tree file '%s'",
filename_path);
goto fail;
}
/* Expand to 2x size to give enough room for manipulation. */
dt_size += 10000;
dt_size *= 2;
/* First allocate space in qemu for device tree */
fdt = g_malloc0(dt_size);
dt_file_load_size = load_image_size(filename_path, fdt, dt_size);
if (dt_file_load_size < 0) {
error_report("Unable to open device tree file '%s'",
filename_path);
goto fail;
}
ret = fdt_open_into(fdt, fdt, dt_size);
if (ret) {
error_report("Unable to copy device tree in memory");
goto fail;
}
/* Check sanity of device tree */
if (fdt_check_header(fdt)) {
error_report("Device tree file loaded into memory is invalid: %s",
filename_path);
goto fail;
}
*sizep = dt_size;
return fdt;
fail:
g_free(fdt);
return NULL;
}
| 165,222 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void usb_serial_console_disconnect(struct usb_serial *serial)
{
if (serial->port[0] == usbcons_info.port) {
usb_serial_console_exit();
usb_serial_put(serial);
}
}
Commit Message: USB: serial: console: fix use-after-free on disconnect
A clean-up patch removing two redundant NULL-checks from the console
disconnect handler inadvertently also removed a third check. This could
lead to the struct usb_serial being prematurely freed by the console
code when a driver accepts but does not register any ports for an
interface which also lacks endpoint descriptors.
Fixes: 0e517c93dc02 ("USB: serial: console: clean up sanity checks")
Cc: stable <[email protected]> # 4.11
Reported-by: Andrey Konovalov <[email protected]>
Acked-by: Greg Kroah-Hartman <[email protected]>
Signed-off-by: Johan Hovold <[email protected]>
CWE ID: CWE-416 | void usb_serial_console_disconnect(struct usb_serial *serial)
{
if (serial->port[0] && serial->port[0] == usbcons_info.port) {
usb_serial_console_exit();
usb_serial_put(serial);
}
}
| 170,012 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static inline signed short ReadPropertySignedShort(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) ((buffer[1] << 8) | buffer[0]);
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |
((unsigned char *) buffer)[1]);
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline signed short ReadPropertySignedShort(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) buffer[1] << 8;
value|=(unsigned short) buffer[0];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
| 169,955 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: const extensions::Extension* GetExtension(Profile* profile,
const std::string& extension_id) {
const ExtensionService* service =
extensions::ExtensionSystem::Get(profile)->extension_service();
const extensions::Extension* extension =
service->GetInstalledExtension(extension_id);
return extension;
}
Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry
This CL adds GetInstalledExtension() method to ExtensionRegistry and
uses it instead of deprecated ExtensionService::GetInstalledExtension()
in chrome/browser/ui/app_list/.
Part of removing the deprecated GetInstalledExtension() call
from the ExtensionService.
BUG=489687
Review URL: https://codereview.chromium.org/1130353010
Cr-Commit-Position: refs/heads/master@{#333036}
CWE ID: | const extensions::Extension* GetExtension(Profile* profile,
const std::string& extension_id) {
const ExtensionRegistry* registry = ExtensionRegistry::Get(profile);
const extensions::Extension* extension =
registry->GetInstalledExtension(extension_id);
return extension;
}
| 171,720 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void PrintPreviewMessageHandler::OnMetafileReadyForPrinting(
const PrintHostMsg_DidPreviewDocument_Params& params) {
StopWorker(params.document_cookie);
if (params.expected_pages_count <= 0) {
NOTREACHED();
return;
}
PrintPreviewUI* print_preview_ui = GetPrintPreviewUI();
if (!print_preview_ui)
return;
scoped_refptr<base::RefCountedBytes> data_bytes =
GetDataFromHandle(params.metafile_data_handle, params.data_size);
if (!data_bytes || !data_bytes->size())
return;
print_preview_ui->SetPrintPreviewDataForIndex(COMPLETE_PREVIEW_DOCUMENT_INDEX,
std::move(data_bytes));
print_preview_ui->OnPreviewDataIsAvailable(
params.expected_pages_count, params.preview_request_id);
}
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
[email protected]
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511616}
CWE ID: CWE-254 | void PrintPreviewMessageHandler::OnMetafileReadyForPrinting(
const PrintHostMsg_DidPreviewDocument_Params& params) {
StopWorker(params.document_cookie);
if (params.expected_pages_count <= 0) {
NOTREACHED();
return;
}
PrintPreviewUI* print_preview_ui = GetPrintPreviewUI();
if (!print_preview_ui)
return;
if (IsOopifEnabled() && print_preview_ui->source_is_modifiable()) {
auto* client = PrintCompositeClient::FromWebContents(web_contents());
DCHECK(client);
client->DoComposite(
params.metafile_data_handle, params.data_size,
base::BindOnce(&PrintPreviewMessageHandler::OnCompositePdfDocumentDone,
weak_ptr_factory_.GetWeakPtr(),
params.expected_pages_count, params.preview_request_id));
} else {
NotifyUIPreviewDocumentReady(
params.expected_pages_count, params.preview_request_id,
GetDataFromHandle(params.metafile_data_handle, params.data_size));
}
}
| 171,890 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void BluetoothDeviceChromeOS::AuthorizeService(
const dbus::ObjectPath& device_path,
const std::string& uuid,
const ConfirmationCallback& callback) {
callback.Run(CANCELLED);
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::AuthorizeService(
| 171,216 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void PrintPreviewUI::GetCurrentPrintPreviewStatus(
const std::string& preview_ui_addr,
int request_id,
bool* cancel) {
int current_id = -1;
if (!g_print_preview_request_id_map.Get().Get(preview_ui_addr, ¤t_id)) {
*cancel = true;
return;
}
*cancel = (request_id != current_id);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void PrintPreviewUI::GetCurrentPrintPreviewStatus(
void PrintPreviewUI::GetCurrentPrintPreviewStatus(int32 preview_ui_id,
int request_id,
bool* cancel) {
int current_id = -1;
if (!g_print_preview_request_id_map.Get().Get(preview_ui_id, ¤t_id)) {
*cancel = true;
return;
}
*cancel = (request_id != current_id);
}
| 170,833 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: _prolog_error(batch_job_launch_msg_t *req, int rc)
{
char *err_name_ptr, err_name[256], path_name[MAXPATHLEN];
char *fmt_char;
int fd;
if (req->std_err || req->std_out) {
if (req->std_err)
strncpy(err_name, req->std_err, sizeof(err_name));
else
strncpy(err_name, req->std_out, sizeof(err_name));
if ((fmt_char = strchr(err_name, (int) '%')) &&
(fmt_char[1] == 'j') && !strchr(fmt_char+1, (int) '%')) {
char tmp_name[256];
fmt_char[1] = 'u';
snprintf(tmp_name, sizeof(tmp_name), err_name,
req->job_id);
strncpy(err_name, tmp_name, sizeof(err_name));
}
} else {
snprintf(err_name, sizeof(err_name), "slurm-%u.out",
req->job_id);
}
err_name_ptr = err_name;
if (err_name_ptr[0] == '/')
snprintf(path_name, MAXPATHLEN, "%s", err_name_ptr);
else if (req->work_dir)
snprintf(path_name, MAXPATHLEN, "%s/%s",
req->work_dir, err_name_ptr);
else
snprintf(path_name, MAXPATHLEN, "/%s", err_name_ptr);
if ((fd = open(path_name, (O_CREAT|O_APPEND|O_WRONLY), 0644)) == -1) {
error("Unable to open %s: %s", path_name,
slurm_strerror(errno));
return;
}
snprintf(err_name, sizeof(err_name),
"Error running slurm prolog: %d\n", WEXITSTATUS(rc));
safe_write(fd, err_name, strlen(err_name));
if (fchown(fd, (uid_t) req->uid, (gid_t) req->gid) == -1) {
snprintf(err_name, sizeof(err_name),
"Couldn't change fd owner to %u:%u: %m\n",
req->uid, req->gid);
}
rwfail:
close(fd);
}
Commit Message: Fix security issue in _prolog_error().
Fix security issue caused by insecure file path handling triggered by
the failure of a Prolog script. To exploit this a user needs to
anticipate or cause the Prolog to fail for their job.
(This commit is slightly different from the fix to the 15.08 branch.)
CVE-2016-10030.
CWE ID: CWE-284 | _prolog_error(batch_job_launch_msg_t *req, int rc)
{
char *err_name_ptr, err_name[256], path_name[MAXPATHLEN];
char *fmt_char;
int fd;
if (req->std_err || req->std_out) {
if (req->std_err)
strncpy(err_name, req->std_err, sizeof(err_name));
else
strncpy(err_name, req->std_out, sizeof(err_name));
if ((fmt_char = strchr(err_name, (int) '%')) &&
(fmt_char[1] == 'j') && !strchr(fmt_char+1, (int) '%')) {
char tmp_name[256];
fmt_char[1] = 'u';
snprintf(tmp_name, sizeof(tmp_name), err_name,
req->job_id);
strncpy(err_name, tmp_name, sizeof(err_name));
}
} else {
snprintf(err_name, sizeof(err_name), "slurm-%u.out",
req->job_id);
}
err_name_ptr = err_name;
if (err_name_ptr[0] == '/')
snprintf(path_name, MAXPATHLEN, "%s", err_name_ptr);
else if (req->work_dir)
snprintf(path_name, MAXPATHLEN, "%s/%s",
req->work_dir, err_name_ptr);
else
snprintf(path_name, MAXPATHLEN, "/%s", err_name_ptr);
if ((fd = _open_as_other(path_name, req)) == -1) {
error("Unable to open %s: Permission denied", path_name);
return;
}
snprintf(err_name, sizeof(err_name),
"Error running slurm prolog: %d\n", WEXITSTATUS(rc));
safe_write(fd, err_name, strlen(err_name));
if (fchown(fd, (uid_t) req->uid, (gid_t) req->gid) == -1) {
snprintf(err_name, sizeof(err_name),
"Couldn't change fd owner to %u:%u: %m\n",
req->uid, req->gid);
}
rwfail:
close(fd);
}
| 168,646 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: Cluster::~Cluster()
{
if (m_entries_count <= 0)
return;
BlockEntry** i = m_entries;
BlockEntry** const j = m_entries + m_entries_count;
while (i != j)
{
BlockEntry* p = *i++;
assert(p);
delete p;
}
delete[] m_entries;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | Cluster::~Cluster()
if (status < 0) { // error or underflow
len = 1;
return status;
}
++pos; // consume flags byte
assert(pos <= avail);
if (pos >= block_stop)
return E_FILE_FORMAT_INVALID;
const int lacing = int(flags & 0x06) >> 1;
if ((lacing != 0) && (block_stop > avail)) {
len = static_cast<long>(block_stop - pos);
return E_BUFFER_NOT_FULL;
}
pos = block_stop; // consume block-part of block group
assert(pos <= payload_stop);
}
assert(pos == payload_stop);
status = CreateBlock(0x20, // BlockGroup ID
payload_start, payload_size, discard_padding);
if (status != 0)
return status;
m_pos = payload_stop;
return 0; // success
}
| 174,458 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void Chapters::Edition::Clear()
{
while (m_atoms_count > 0)
{
Atom& a = m_atoms[--m_atoms_count];
a.Clear();
}
delete[] m_atoms;
m_atoms = NULL;
m_atoms_size = 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | void Chapters::Edition::Clear()
while (m_displays_count > 0) {
Display& d = m_displays[--m_displays_count];
d.Clear();
}
delete[] m_displays;
m_displays = NULL;
m_displays_size = 0;
}
long Chapters::Atom::Parse(IMkvReader* pReader, long long pos, long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x00) { // Display ID
status = ParseDisplay(pReader, pos, size);
if (status < 0) // error
return status;
} else if (id == 0x1654) { // StringUID ID
status = UnserializeString(pReader, pos, size, m_string_uid);
if (status < 0) // error
return status;
} else if (id == 0x33C4) { // UID ID
long long val;
status = UnserializeInt(pReader, pos, size, val);
if (val < 0) // error
return status;
m_uid = static_cast<unsigned long long>(val);
} else if (id == 0x11) { // TimeStart ID
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_start_timecode = val;
} else if (id == 0x12) { // TimeEnd ID
const long long val = UnserializeUInt(pReader, pos, size);
if (val < 0) // error
return static_cast<long>(val);
m_stop_timecode = val;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
| 174,244 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid= fs->cache.array[x].objectId.id;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count+=2;
}
}
return count;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid = fs->cache.array[x].objectId.id;
if (bufLen < 2)
break;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count += 2;
bufLen -= 2;
}
}
return count;
}
| 169,074 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void Label::SizeToFit(int max_width) {
DCHECK(is_multi_line_);
std::vector<std::wstring> lines;
base::SplitString(UTF16ToWideHack(text_), L'\n', &lines);
int label_width = 0;
for (std::vector<std::wstring>::const_iterator iter = lines.begin();
iter != lines.end(); ++iter) {
label_width = std::max(label_width,
font_.GetStringWidth(WideToUTF16Hack(*iter)));
}
label_width += GetInsets().width();
if (max_width > 0)
label_width = std::min(label_width, max_width);
SetBounds(x(), y(), label_width, 0);
SizeToPreferredSize();
}
Commit Message: wstring: remove wstring version of SplitString
Retry of r84336.
BUG=23581
Review URL: http://codereview.chromium.org/6930047
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@84355 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void Label::SizeToFit(int max_width) {
DCHECK(is_multi_line_);
std::vector<string16> lines;
base::SplitString(text_, '\n', &lines);
int label_width = 0;
for (std::vector<string16>::const_iterator iter = lines.begin();
iter != lines.end(); ++iter) {
label_width = std::max(label_width, font_.GetStringWidth(*iter));
}
label_width += GetInsets().width();
if (max_width > 0)
label_width = std::min(label_width, max_width);
SetBounds(x(), y(), label_width, 0);
SizeToPreferredSize();
}
| 170,556 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void WebContentsImpl::DetachInterstitialPage() {
if (node_.OuterContentsFrameTreeNode()) {
if (GetRenderManager()->GetProxyToOuterDelegate()) {
DCHECK(static_cast<RenderWidgetHostViewBase*>(
GetRenderManager()->current_frame_host()->GetView())
->IsRenderWidgetHostViewChildFrame());
RenderWidgetHostViewChildFrame* view =
static_cast<RenderWidgetHostViewChildFrame*>(
GetRenderManager()->current_frame_host()->GetView());
GetRenderManager()->SetRWHViewForInnerContents(view);
}
}
bool interstitial_pausing_throbber =
ShowingInterstitialPage() &&
GetRenderManager()->interstitial_page()->pause_throbber();
if (ShowingInterstitialPage())
GetRenderManager()->remove_interstitial_page();
for (auto& observer : observers_)
observer.DidDetachInterstitialPage();
if (interstitial_pausing_throbber && frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | void WebContentsImpl::DetachInterstitialPage() {
if (node_.OuterContentsFrameTreeNode()) {
if (GetRenderManager()->GetProxyToOuterDelegate()) {
DCHECK(static_cast<RenderWidgetHostViewBase*>(
GetRenderManager()->current_frame_host()->GetView())
->IsRenderWidgetHostViewChildFrame());
RenderWidgetHostViewChildFrame* view =
static_cast<RenderWidgetHostViewChildFrame*>(
GetRenderManager()->current_frame_host()->GetView());
GetRenderManager()->SetRWHViewForInnerContents(view);
}
}
bool interstitial_pausing_throbber =
ShowingInterstitialPage() && interstitial_page_->pause_throbber();
if (ShowingInterstitialPage())
interstitial_page_ = nullptr;
for (auto& observer : observers_)
observer.DidDetachInterstitialPage();
if (interstitial_pausing_throbber && frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
}
| 172,325 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static void scsi_read_data(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint32_t n;
if (r->sector_count == (uint32_t)-1) {
DPRINTF("Read buf_len=%zd\n", r->iov.iov_len);
r->sector_count = 0;
scsi_req_data(&r->req, r->iov.iov_len);
return;
}
DPRINTF("Read sector_count=%d\n", r->sector_count);
if (r->sector_count == 0) {
/* This also clears the sense buffer for REQUEST SENSE. */
scsi_req_complete(&r->req, GOOD);
return;
}
/* No data transfer may already be in progress */
assert(r->req.aiocb == NULL);
if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
DPRINTF("Data transfer direction invalid\n");
scsi_read_complete(r, -EINVAL);
return;
}
n = r->sector_count;
if (n > SCSI_DMA_BUF_SIZE / 512)
n = SCSI_DMA_BUF_SIZE / 512;
if (s->tray_open) {
scsi_read_complete(r, -ENOMEDIUM);
}
r->iov.iov_len = n * 512;
qemu_iovec_init_external(&r->qiov, &r->iov, 1);
bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n,
scsi_read_complete, r);
if (r->req.aiocb == NULL) {
scsi_read_complete(r, -EIO);
}
}
Commit Message: scsi-disk: commonize iovec creation between reads and writes
Also, consistently use qiov.size instead of iov.iov_len.
Signed-off-by: Paolo Bonzini <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
CWE ID: CWE-119 | static void scsi_read_data(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint32_t n;
if (r->sector_count == (uint32_t)-1) {
DPRINTF("Read buf_len=%zd\n", r->iov.iov_len);
r->sector_count = 0;
scsi_req_data(&r->req, r->iov.iov_len);
return;
}
DPRINTF("Read sector_count=%d\n", r->sector_count);
if (r->sector_count == 0) {
/* This also clears the sense buffer for REQUEST SENSE. */
scsi_req_complete(&r->req, GOOD);
return;
}
/* No data transfer may already be in progress */
assert(r->req.aiocb == NULL);
if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
DPRINTF("Data transfer direction invalid\n");
scsi_read_complete(r, -EINVAL);
return;
}
if (s->tray_open) {
scsi_read_complete(r, -ENOMEDIUM);
}
n = scsi_init_iovec(r);
bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n,
scsi_read_complete, r);
if (r->req.aiocb == NULL) {
scsi_read_complete(r, -EIO);
}
}
| 169,921 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) {
if (len > outHeader->nAllocLen) {
ALOGE("memset buffer too small: got %lu, expected %zu", (unsigned long)outHeader->nAllocLen, len);
android_errorWriteLog(0x534e4554, "29422022");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return NULL;
}
return memset(outHeader->pBuffer, c, len);
}
Commit Message: Fix build
Change-Id: I48ba34b3df9c9a896d4b18c3f48e41744b7dab54
CWE ID: CWE-264 | void *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) {
if (len > outHeader->nAllocLen) {
ALOGE("memset buffer too small: got %u, expected %zu", outHeader->nAllocLen, len);
android_errorWriteLog(0x534e4554, "29422022");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return NULL;
}
return memset(outHeader->pBuffer, c, len);
}
| 174,156 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void FileSystemOperation::GetUsageAndQuotaThenRunTask(
const GURL& origin, FileSystemType type,
const base::Closure& task,
const base::Closure& error_callback) {
quota::QuotaManagerProxy* quota_manager_proxy =
file_system_context()->quota_manager_proxy();
if (!quota_manager_proxy ||
!file_system_context()->GetQuotaUtil(type)) {
operation_context_.set_allowed_bytes_growth(kint64max);
task.Run();
return;
}
TaskParamsForDidGetQuota params;
params.origin = origin;
params.type = type;
params.task = task;
params.error_callback = error_callback;
DCHECK(quota_manager_proxy);
DCHECK(quota_manager_proxy->quota_manager());
quota_manager_proxy->quota_manager()->GetUsageAndQuota(
origin,
FileSystemTypeToQuotaStorageType(type),
base::Bind(&FileSystemOperation::DidGetUsageAndQuotaAndRunTask,
base::Unretained(this), params));
}
Commit Message: Crash fix in fileapi::FileSystemOperation::DidGetUsageAndQuotaAndRunTask
https://chromiumcodereview.appspot.com/10008047 introduced delete-with-inflight-tasks in Write sequence but I failed to convert this callback to use WeakPtr().
BUG=128178
TEST=manual test
Review URL: https://chromiumcodereview.appspot.com/10408006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137635 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void FileSystemOperation::GetUsageAndQuotaThenRunTask(
const GURL& origin, FileSystemType type,
const base::Closure& task,
const base::Closure& error_callback) {
quota::QuotaManagerProxy* quota_manager_proxy =
file_system_context()->quota_manager_proxy();
if (!quota_manager_proxy ||
!file_system_context()->GetQuotaUtil(type)) {
operation_context_.set_allowed_bytes_growth(kint64max);
task.Run();
return;
}
TaskParamsForDidGetQuota params;
params.origin = origin;
params.type = type;
params.task = task;
params.error_callback = error_callback;
DCHECK(quota_manager_proxy);
DCHECK(quota_manager_proxy->quota_manager());
quota_manager_proxy->quota_manager()->GetUsageAndQuota(
origin,
FileSystemTypeToQuotaStorageType(type),
base::Bind(&FileSystemOperation::DidGetUsageAndQuotaAndRunTask,
weak_factory_.GetWeakPtr(), params));
}
| 170,762 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: header_put_le_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++] = 0 ;
psf->header [psf->headindex++] = 0 ;
psf->header [psf->headindex++] = 0 ;
psf->header [psf->headindex++] = 0 ;
} ;
} /* 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)
| 170,055 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void ProfilingService::DumpProcessesForTracing(
bool keep_small_allocations,
bool strip_path_from_mapped_files,
DumpProcessesForTracingCallback callback) {
memory_instrumentation::MemoryInstrumentation::GetInstance()
->GetVmRegionsForHeapProfiler(base::Bind(
&ProfilingService::OnGetVmRegionsCompleteForDumpProcessesForTracing,
weak_factory_.GetWeakPtr(), keep_small_allocations,
strip_path_from_mapped_files, base::Passed(&callback)));
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: oysteine <[email protected]>
Reviewed-by: Albert J. Wong <[email protected]>
Reviewed-by: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529059}
CWE ID: CWE-269 | void ProfilingService::DumpProcessesForTracing(
bool keep_small_allocations,
bool strip_path_from_mapped_files,
DumpProcessesForTracingCallback callback) {
if (!helper_) {
context()->connector()->BindInterface(
resource_coordinator::mojom::kServiceName, &helper_);
}
helper_->GetVmRegionsForHeapProfiler(base::Bind(
&ProfilingService::OnGetVmRegionsCompleteForDumpProcessesForTracing,
weak_factory_.GetWeakPtr(), keep_small_allocations,
strip_path_from_mapped_files, base::Passed(&callback)));
}
| 172,913 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: int main(int argc, char *argv[])
{
char buff[1024];
int fd, nr, nw;
if (argc < 2) {
fprintf(stderr,
"usage: %s output-filename\n"
" %s |output-command\n"
" %s :host:port\n", argv[0], argv[0], argv[0]);
return 1;
}
fd = open_gen_fd(argv[1]);
if (fd < 0) {
perror("open_gen_fd");
exit(EXIT_FAILURE);
}
while ((nr = read(0, buff, sizeof (buff))) != 0) {
if (nr < 0) {
if (errno == EINTR)
continue;
perror("read");
exit(EXIT_FAILURE);
}
nw = write(fd, buff, nr);
if (nw < 0) {
perror("write");
exit(EXIT_FAILURE);
}
}
return 0;
}
Commit Message: misc oom and possible memory leak fix
CWE ID: | int main(int argc, char *argv[])
{
char buff[1024];
int fd, nr, nw;
if (argc < 2) {
fprintf(stderr,
"usage: %s output-filename\n"
" %s |output-command\n"
" %s :host:port\n", argv[0], argv[0], argv[0]);
return 1;
}
fd = open_gen_fd(argv[1]);
if (fd < 0) {
perror("open_gen_fd");
exit(EXIT_FAILURE);
}
while ((nr = read(0, buff, sizeof (buff))) != 0) {
if (nr < 0) {
if (errno == EINTR)
continue;
perror("read");
exit(EXIT_FAILURE);
}
nw = write(fd, buff, nr);
if (nw < 0) {
perror("write");
exit(EXIT_FAILURE);
}
}
close(fd);
return 0;
}
| 169,758 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: jbig2_decode_mmr_init(Jbig2MmrCtx *mmr, int width, int height, const byte *data, size_t size)
{
int i;
uint32_t word = 0;
mmr->width = width;
mmr->size = size;
mmr->data_index = 0;
mmr->bit_index = 0;
for (i = 0; i < size && i < 4; i++)
word |= (data[i] << ((3 - i) << 3));
mmr->word = word;
}
Commit Message:
CWE ID: CWE-119 | jbig2_decode_mmr_init(Jbig2MmrCtx *mmr, int width, int height, const byte *data, size_t size)
{
size_t i;
uint32_t word = 0;
mmr->width = width;
mmr->size = size;
mmr->data_index = 0;
mmr->bit_index = 0;
for (i = 0; i < size && i < 4; i++)
word |= (data[i] << ((3 - i) << 3));
mmr->word = word;
}
| 165,493 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void ProcessHeap::Init() {
total_allocated_space_ = 0;
total_allocated_object_size_ = 0;
total_marked_object_size_ = 0;
GCInfoTable::Init();
base::SamplingHeapProfiler::SetHooksInstallCallback([]() {
HeapAllocHooks::SetAllocationHook(&BlinkGCAllocHook);
HeapAllocHooks::SetFreeHook(&BlinkGCFreeHook);
});
}
Commit Message: [oilpan] Fix GCInfoTable for multiple threads
Previously, grow and access from different threads could lead to a race
on the table backing; see bug.
- Rework the table to work on an existing reservation.
- Commit upon growing, avoiding any copies.
Drive-by: Fix over-allocation of table.
Bug: chromium:841280
Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43
Reviewed-on: https://chromium-review.googlesource.com/1061525
Commit-Queue: Michael Lippautz <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#560434}
CWE ID: CWE-362 | void ProcessHeap::Init() {
total_allocated_space_ = 0;
total_allocated_object_size_ = 0;
total_marked_object_size_ = 0;
base::SamplingHeapProfiler::SetHooksInstallCallback([]() {
HeapAllocHooks::SetAllocationHook(&BlinkGCAllocHook);
HeapAllocHooks::SetFreeHook(&BlinkGCFreeHook);
});
}
| 173,142 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: const BlockEntry* Segment::GetBlock(const CuePoint& cp,
const CuePoint::TrackPosition& tp) {
Cluster** const ii = m_clusters;
Cluster** i = ii;
const long count = m_clusterCount + m_clusterPreloadCount;
Cluster** const jj = ii + count;
Cluster** j = jj;
while (i < j) {
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pCluster = *k;
assert(pCluster);
const long long pos = pCluster->GetPosition();
assert(pos >= 0);
if (pos < tp.m_pos)
i = k + 1;
else if (pos > tp.m_pos)
j = k;
else
return pCluster->GetEntry(cp, tp);
}
assert(i == j);
Cluster* const pCluster = Cluster::Create(this, -1, tp.m_pos); //, -1);
assert(pCluster);
const ptrdiff_t idx = i - m_clusters;
PreloadCluster(pCluster, idx);
assert(m_clusters);
assert(m_clusterPreloadCount > 0);
assert(m_clusters[idx] == pCluster);
return pCluster->GetEntry(cp, tp);
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | const BlockEntry* Segment::GetBlock(const CuePoint& cp,
const CuePoint::TrackPosition& tp) {
Cluster** const ii = m_clusters;
Cluster** i = ii;
const long count = m_clusterCount + m_clusterPreloadCount;
Cluster** const jj = ii + count;
Cluster** j = jj;
while (i < j) {
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pCluster = *k;
assert(pCluster);
const long long pos = pCluster->GetPosition();
assert(pos >= 0);
if (pos < tp.m_pos)
i = k + 1;
else if (pos > tp.m_pos)
j = k;
else
return pCluster->GetEntry(cp, tp);
}
assert(i == j);
Cluster* const pCluster = Cluster::Create(this, -1, tp.m_pos); //, -1);
if (pCluster == NULL)
return NULL;
const ptrdiff_t idx = i - m_clusters;
if (!PreloadCluster(pCluster, idx)) {
delete pCluster;
return NULL;
}
assert(m_clusters);
assert(m_clusterPreloadCount > 0);
assert(m_clusters[idx] == pCluster);
return pCluster->GetEntry(cp, tp);
}
| 173,814 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: header_put_byte (SF_PRIVATE *psf, char x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 1)
psf->header [psf->headindex++] = x ;
} /* header_put_byte */
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_byte (SF_PRIVATE *psf, char x)
{ psf->header.ptr [psf->header.indx++] = x ;
} /* header_put_byte */
| 170,053 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: AriaCurrentState AXNodeObject::ariaCurrentState() const {
const AtomicString& attributeValue =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kCurrent);
if (attributeValue.isNull())
return AriaCurrentStateUndefined;
if (attributeValue.isEmpty() || equalIgnoringCase(attributeValue, "false"))
return AriaCurrentStateFalse;
if (equalIgnoringCase(attributeValue, "true"))
return AriaCurrentStateTrue;
if (equalIgnoringCase(attributeValue, "page"))
return AriaCurrentStatePage;
if (equalIgnoringCase(attributeValue, "step"))
return AriaCurrentStateStep;
if (equalIgnoringCase(attributeValue, "location"))
return AriaCurrentStateLocation;
if (equalIgnoringCase(attributeValue, "date"))
return AriaCurrentStateDate;
if (equalIgnoringCase(attributeValue, "time"))
return AriaCurrentStateTime;
if (!attributeValue.isEmpty())
return AriaCurrentStateTrue;
return AXObject::ariaCurrentState();
}
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 | AriaCurrentState AXNodeObject::ariaCurrentState() const {
const AtomicString& attributeValue =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kCurrent);
if (attributeValue.isNull())
return AriaCurrentStateUndefined;
if (attributeValue.isEmpty() ||
equalIgnoringASCIICase(attributeValue, "false"))
return AriaCurrentStateFalse;
if (equalIgnoringASCIICase(attributeValue, "true"))
return AriaCurrentStateTrue;
if (equalIgnoringASCIICase(attributeValue, "page"))
return AriaCurrentStatePage;
if (equalIgnoringASCIICase(attributeValue, "step"))
return AriaCurrentStateStep;
if (equalIgnoringASCIICase(attributeValue, "location"))
return AriaCurrentStateLocation;
if (equalIgnoringASCIICase(attributeValue, "date"))
return AriaCurrentStateDate;
if (equalIgnoringASCIICase(attributeValue, "time"))
return AriaCurrentStateTime;
if (!attributeValue.isEmpty())
return AriaCurrentStateTrue;
return AXObject::ariaCurrentState();
}
| 171,908 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: WebContext* WebContext::FromBrowserContext(oxide::BrowserContext* context) {
BrowserContextDelegate* delegate =
static_cast<BrowserContextDelegate*>(context->GetDelegate());
if (!delegate) {
return nullptr;
}
return delegate->context();
}
Commit Message:
CWE ID: CWE-20 | WebContext* WebContext::FromBrowserContext(oxide::BrowserContext* context) {
WebContext* WebContext::FromBrowserContext(BrowserContext* context) {
BrowserContextDelegate* delegate =
static_cast<BrowserContextDelegate*>(context->GetDelegate());
if (!delegate) {
return nullptr;
}
return delegate->context();
}
| 165,411 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static __net_init int setup_net(struct net *net, struct user_namespace *user_ns)
{
/* Must be called with pernet_ops_rwsem held */
const struct pernet_operations *ops, *saved_ops;
int error = 0;
LIST_HEAD(net_exit_list);
refcount_set(&net->count, 1);
refcount_set(&net->passive, 1);
net->dev_base_seq = 1;
net->user_ns = user_ns;
idr_init(&net->netns_ids);
spin_lock_init(&net->nsid_lock);
mutex_init(&net->ipv4.ra_mutex);
list_for_each_entry(ops, &pernet_list, list) {
error = ops_init(ops, net);
if (error < 0)
goto out_undo;
}
down_write(&net_rwsem);
list_add_tail_rcu(&net->list, &net_namespace_list);
up_write(&net_rwsem);
out:
return error;
out_undo:
/* Walk through the list backwards calling the exit functions
* for the pernet modules whose init functions did not fail.
*/
list_add(&net->exit_list, &net_exit_list);
saved_ops = ops;
list_for_each_entry_continue_reverse(ops, &pernet_list, list)
ops_exit_list(ops, &net_exit_list);
ops = saved_ops;
list_for_each_entry_continue_reverse(ops, &pernet_list, list)
ops_free_list(ops, &net_exit_list);
rcu_barrier();
goto out;
}
Commit Message: netns: provide pure entropy for net_hash_mix()
net_hash_mix() currently uses kernel address of a struct net,
and is used in many places that could be used to reveal this
address to a patient attacker, thus defeating KASLR, for
the typical case (initial net namespace, &init_net is
not dynamically allocated)
I believe the original implementation tried to avoid spending
too many cycles in this function, but security comes first.
Also provide entropy regardless of CONFIG_NET_NS.
Fixes: 0b4419162aa6 ("netns: introduce the net_hash_mix "salt" for hashes")
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Amit Klein <[email protected]>
Reported-by: Benny Pinkas <[email protected]>
Cc: Pavel Emelyanov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static __net_init int setup_net(struct net *net, struct user_namespace *user_ns)
{
/* Must be called with pernet_ops_rwsem held */
const struct pernet_operations *ops, *saved_ops;
int error = 0;
LIST_HEAD(net_exit_list);
refcount_set(&net->count, 1);
refcount_set(&net->passive, 1);
get_random_bytes(&net->hash_mix, sizeof(u32));
net->dev_base_seq = 1;
net->user_ns = user_ns;
idr_init(&net->netns_ids);
spin_lock_init(&net->nsid_lock);
mutex_init(&net->ipv4.ra_mutex);
list_for_each_entry(ops, &pernet_list, list) {
error = ops_init(ops, net);
if (error < 0)
goto out_undo;
}
down_write(&net_rwsem);
list_add_tail_rcu(&net->list, &net_namespace_list);
up_write(&net_rwsem);
out:
return error;
out_undo:
/* Walk through the list backwards calling the exit functions
* for the pernet modules whose init functions did not fail.
*/
list_add(&net->exit_list, &net_exit_list);
saved_ops = ops;
list_for_each_entry_continue_reverse(ops, &pernet_list, list)
ops_exit_list(ops, &net_exit_list);
ops = saved_ops;
list_for_each_entry_continue_reverse(ops, &pernet_list, list)
ops_free_list(ops, &net_exit_list);
rcu_barrier();
goto out;
}
| 169,715 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: bool InputWindowInfo::isTrustedOverlay() const {
return layoutParamsType == TYPE_INPUT_METHOD
|| layoutParamsType == TYPE_INPUT_METHOD_DIALOG
|| layoutParamsType == TYPE_MAGNIFICATION_OVERLAY
|| layoutParamsType == TYPE_SECURE_SYSTEM_OVERLAY;
}
Commit Message: Add new MotionEvent flag for partially obscured windows.
Due to more complex window layouts resulting in lots of overlapping
windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to
only be set when the point at which the window was touched is
obscured. Unfortunately, this doesn't prevent tapjacking attacks that
overlay the dialog's text, making a potentially dangerous operation
seem innocuous. To avoid this on particularly sensitive dialogs,
introduce a new flag that really does tell you when your window is
being even partially overlapped.
We aren't exposing this as API since we plan on making the original
flag more robust. This is really a workaround for system dialogs
since we generally know their layout and screen position, and that
they're unlikely to be overlapped by other applications.
Bug: 26677796
Change-Id: I9e336afe90f262ba22015876769a9c510048fd47
CWE ID: CWE-264 | bool InputWindowInfo::isTrustedOverlay() const {
return layoutParamsType == TYPE_INPUT_METHOD
|| layoutParamsType == TYPE_INPUT_METHOD_DIALOG
|| layoutParamsType == TYPE_MAGNIFICATION_OVERLAY
|| layoutParamsType == TYPE_STATUS_BAR
|| layoutParamsType == TYPE_NAVIGATION_BAR
|| layoutParamsType == TYPE_SECURE_SYSTEM_OVERLAY;
}
| 174,170 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: bool WebDriverCommand::Init(Response* const response) {
std::string session_id = GetPathVariable(2);
if (session_id.length() == 0) {
response->SetError(
new Error(kBadRequest, "No session ID specified"));
return false;
}
VLOG(1) << "Fetching session: " << session_id;
session_ = SessionManager::GetInstance()->GetSession(session_id);
if (session_ == NULL) {
response->SetError(
new Error(kSessionNotFound, "Session not found: " + session_id));
return false;
}
scoped_ptr<Error> error(session_->WaitForAllTabsToStopLoading());
if (error.get()) {
LOG(WARNING) << error->ToString();
}
error.reset(session_->SwitchToTopFrameIfCurrentFrameInvalid());
if (error.get()) {
LOG(WARNING) << error->ToString();
}
response->SetField("sessionId", Value::CreateStringValue(session_id));
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 WebDriverCommand::Init(Response* const response) {
std::string session_id = GetPathVariable(2);
if (session_id.length() == 0) {
response->SetError(
new Error(kBadRequest, "No session ID specified"));
return false;
}
session_ = SessionManager::GetInstance()->GetSession(session_id);
if (session_ == NULL) {
response->SetError(
new Error(kSessionNotFound, "Session not found: " + session_id));
return false;
}
LOG(INFO) << "Waiting for the page to stop loading";
Error* error = session_->WaitForAllTabsToStopLoading();
if (error) {
response->SetError(error);
return false;
}
LOG(INFO) << "Done waiting for the page to stop loading";
error = session_->SwitchToTopFrameIfCurrentFrameInvalid();
if (error) {
response->SetError(error);
return false;
}
response->SetField("sessionId", Value::CreateStringValue(session_id));
return true;
}
| 170,454 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void set_scl(int state)
{
qrio_set_opendrain_gpio(DEBLOCK_PORT1, DEBLOCK_SCL1, state);
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787 | void set_scl(int state)
| 169,632 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void RenderWidgetHostViewAura::RemovingFromRootWindow() {
host_->ParentChanged(0);
ui::Compositor* compositor = GetCompositor();
RunCompositingDidCommitCallbacks(compositor);
locks_pending_commit_.clear();
if (compositor && compositor->HasObserver(this))
compositor->RemoveObserver(this);
DetachFromInputMethod();
}
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
[email protected]
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 RenderWidgetHostViewAura::RemovingFromRootWindow() {
host_->ParentChanged(0);
ui::Compositor* compositor = GetCompositor();
RunCompositingDidCommitCallbacks();
locks_pending_commit_.clear();
if (compositor && compositor->HasObserver(this))
compositor->RemoveObserver(this);
DetachFromInputMethod();
}
| 171,382 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static bool write_hci_command(hci_packet_t type, const void *packet, size_t length) {
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_FD)
goto error;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(0x7F000001);
addr.sin_port = htons(8873);
if (connect(sock, (const struct sockaddr *)&addr, sizeof(addr)) == -1)
goto error;
if (send(sock, &type, 1, 0) != 1)
goto error;
if (send(sock, &length, 2, 0) != 2)
goto error;
if (send(sock, packet, length, 0) != (ssize_t)length)
goto error;
close(sock);
return true;
error:;
close(sock);
return false;
}
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 bool write_hci_command(hci_packet_t type, const void *packet, size_t length) {
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_FD)
goto error;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(0x7F000001);
addr.sin_port = htons(8873);
if (TEMP_FAILURE_RETRY(connect(sock, (const struct sockaddr *)&addr, sizeof(addr))) == -1)
goto error;
if (TEMP_FAILURE_RETRY(send(sock, &type, 1, 0)) != 1)
goto error;
if (TEMP_FAILURE_RETRY(send(sock, &length, 2, 0)) != 2)
goto error;
if (TEMP_FAILURE_RETRY(send(sock, packet, length, 0)) != (ssize_t)length)
goto error;
close(sock);
return true;
error:;
close(sock);
return false;
}
| 173,492 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: bool 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 <[email protected]>
Commit-Queue: Rune Lillesveen <[email protected]>
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. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: X11SurfaceFactory::GetAllowedGLImplementations() {
std::vector<gl::GLImplementation> impls;
impls.push_back(gl::kGLImplementationEGLGLES2);
impls.push_back(gl::kGLImplementationDesktopGL);
impls.push_back(gl::kGLImplementationOSMesaGL);
return impls;
}
Commit Message: Add ThreadChecker for Ozone X11 GPU.
Ensure Ozone X11 tests the same thread constraints we have in Ozone GBM.
BUG=none
Review-Url: https://codereview.chromium.org/2366643002
Cr-Commit-Position: refs/heads/master@{#421817}
CWE ID: CWE-284 | X11SurfaceFactory::GetAllowedGLImplementations() {
DCHECK(thread_checker_.CalledOnValidThread());
std::vector<gl::GLImplementation> impls;
impls.push_back(gl::kGLImplementationEGLGLES2);
impls.push_back(gl::kGLImplementationDesktopGL);
impls.push_back(gl::kGLImplementationOSMesaGL);
return impls;
}
| 171,602 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: WM_SYMBOL midi *WildMidi_Open(const char *midifile) {
uint8_t *mididata = NULL;
uint32_t midisize = 0;
uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A };
uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' };
midi * ret = NULL;
if (!WM_Initialized) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0);
return (NULL);
}
if (midifile == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL filename)", 0);
return (NULL);
}
if ((mididata = (uint8_t *) _WM_BufferFile(midifile, &midisize)) == NULL) {
return (NULL);
}
if (memcmp(mididata,"HMIMIDIP", 8) == 0) {
ret = (void *) _WM_ParseNewHmp(mididata, midisize);
} else if (memcmp(mididata, "HMI-MIDISONG061595", 18) == 0) {
ret = (void *) _WM_ParseNewHmi(mididata, midisize);
} else if (memcmp(mididata, mus_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewMus(mididata, midisize);
} else if (memcmp(mididata, xmi_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewXmi(mididata, midisize);
} else {
ret = (void *) _WM_ParseNewMidi(mididata, midisize);
}
free(mididata);
if (ret) {
if (add_handle(ret) != 0) {
WildMidi_Close(ret);
ret = NULL;
}
}
return (ret);
}
Commit Message: wildmidi_lib.c (WildMidi_Open, WildMidi_OpenBuffer): refuse to proceed if less then 18 bytes of input
Fixes bug #178.
CWE ID: CWE-119 | WM_SYMBOL midi *WildMidi_Open(const char *midifile) {
uint8_t *mididata = NULL;
uint32_t midisize = 0;
uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A };
uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' };
midi * ret = NULL;
if (!WM_Initialized) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0);
return (NULL);
}
if (midifile == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL filename)", 0);
return (NULL);
}
if ((mididata = (uint8_t *) _WM_BufferFile(midifile, &midisize)) == NULL) {
return (NULL);
}
if (midisize < 18) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
return (NULL);
}
if (memcmp(mididata,"HMIMIDIP", 8) == 0) {
ret = (void *) _WM_ParseNewHmp(mididata, midisize);
} else if (memcmp(mididata, "HMI-MIDISONG061595", 18) == 0) {
ret = (void *) _WM_ParseNewHmi(mididata, midisize);
} else if (memcmp(mididata, mus_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewMus(mididata, midisize);
} else if (memcmp(mididata, xmi_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewXmi(mididata, midisize);
} else {
ret = (void *) _WM_ParseNewMidi(mididata, midisize);
}
free(mididata);
if (ret) {
if (add_handle(ret) != 0) {
WildMidi_Close(ret);
ret = NULL;
}
}
return (ret);
}
| 169,369 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void Block::SetKey(bool bKey)
{
if (bKey)
m_flags |= static_cast<unsigned char>(1 << 7);
else
m_flags &= 0x7F;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | void Block::SetKey(bool bKey)
Block::Lacing Block::GetLacing() const {
const int value = int(m_flags & 0x06) >> 1;
return static_cast<Lacing>(value);
}
| 174,440 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: OMX_ERRORTYPE SoftVideoDecoderOMXComponent::getConfig(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexConfigCommonOutputCrop:
{
OMX_CONFIG_RECTTYPE *rectParams = (OMX_CONFIG_RECTTYPE *)params;
if (rectParams->nPortIndex != kOutputPortIndex) {
return OMX_ErrorUndefined;
}
rectParams->nLeft = mCropLeft;
rectParams->nTop = mCropTop;
rectParams->nWidth = mCropWidth;
rectParams->nHeight = mCropHeight;
return OMX_ErrorNone;
}
default:
return OMX_ErrorUnsupportedIndex;
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftVideoDecoderOMXComponent::getConfig(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexConfigCommonOutputCrop:
{
OMX_CONFIG_RECTTYPE *rectParams = (OMX_CONFIG_RECTTYPE *)params;
if (!isValidOMXParam(rectParams)) {
return OMX_ErrorBadParameter;
}
if (rectParams->nPortIndex != kOutputPortIndex) {
return OMX_ErrorUndefined;
}
rectParams->nLeft = mCropLeft;
rectParams->nTop = mCropTop;
rectParams->nWidth = mCropWidth;
rectParams->nHeight = mCropHeight;
return OMX_ErrorNone;
}
default:
return OMX_ErrorUnsupportedIndex;
}
}
| 174,224 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static void frag_kfree_skb(struct netns_frags *nf, struct sk_buff *skb)
{
atomic_sub(skb->truesize, &nf->mem);
kfree_skb(skb);
}
Commit Message: ipv6: discard overlapping fragment
RFC5722 prohibits reassembling fragments when some data overlaps.
Bug spotted by Zhang Zuotao <[email protected]>.
Signed-off-by: Nicolas Dichtel <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static void frag_kfree_skb(struct netns_frags *nf, struct sk_buff *skb)
| 165,538 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) {
for (int page_index : visible_pages_) {
if (pages_[page_index]->GetPage() == page)
return page_index;
}
return -1;
}
Commit Message: Copy visible_pages_ when iterating over it.
On this case, a call inside the loop may cause visible_pages_ to
change.
Bug: 822091
Change-Id: I41b0715faa6fe3e39203cd9142cf5ea38e59aefb
Reviewed-on: https://chromium-review.googlesource.com/964592
Reviewed-by: dsinclair <[email protected]>
Commit-Queue: Henrique Nakashima <[email protected]>
Cr-Commit-Position: refs/heads/master@{#543494}
CWE ID: CWE-20 | int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) {
// Copy visible_pages_ since it can change as a result of loading the page in
// GetPage(). See https://crbug.com/822091.
std::vector<int> visible_pages_copy(visible_pages_);
for (int page_index : visible_pages_copy) {
if (pages_[page_index]->GetPage() == page)
return page_index;
}
return -1;
}
| 172,701 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: nautilus_file_mark_desktop_file_trusted (GFile *file,
GtkWindow *parent_window,
gboolean interactive,
NautilusOpCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
MarkTrustedJob *job;
job = op_job_new (MarkTrustedJob, parent_window);
job->file = g_object_ref (file);
job->interactive = interactive;
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
task = g_task_new (NULL, NULL, mark_trusted_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, mark_trusted_task_thread_func);
g_object_unref (task);
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20 | nautilus_file_mark_desktop_file_trusted (GFile *file,
nautilus_file_mark_desktop_file_executable (GFile *file,
GtkWindow *parent_window,
gboolean interactive,
NautilusOpCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
MarkTrustedJob *job;
job = op_job_new (MarkTrustedJob, parent_window);
job->file = g_object_ref (file);
job->interactive = interactive;
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
task = g_task_new (NULL, NULL, mark_desktop_file_executable_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, mark_desktop_file_executable_task_thread_func);
g_object_unref (task);
}
| 167,751 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: bool FileUtilProxy::Read(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
PlatformFile file,
int64 offset,
int bytes_to_read,
ReadCallback* callback) {
if (bytes_to_read < 0)
return false;
return Start(FROM_HERE, message_loop_proxy,
new RelayRead(file, offset, bytes_to_read, callback));
}
Commit Message: Fix a small leak in FileUtilProxy
BUG=none
TEST=green mem bots
Review URL: http://codereview.chromium.org/7669046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97451 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool FileUtilProxy::Read(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
PlatformFile file,
int64 offset,
int bytes_to_read,
ReadCallback* callback) {
if (bytes_to_read < 0) {
delete callback;
return false;
}
return Start(FROM_HERE, message_loop_proxy,
new RelayRead(file, offset, bytes_to_read, callback));
}
| 170,273 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: SPL_METHOD(DirectoryIterator, next)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern->u.dir.index++;
do {
spl_filesystem_dir_read(intern TSRMLS_CC);
} while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name));
if (intern->file_name) {
efree(intern->file_name);
intern->file_name = NULL;
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(DirectoryIterator, next)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern->u.dir.index++;
do {
spl_filesystem_dir_read(intern TSRMLS_CC);
} while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name));
if (intern->file_name) {
efree(intern->file_name);
intern->file_name = NULL;
}
}
| 167,029 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static sk_sp<SkImage> newSkImageFromRaster(const SkImageInfo& info,
PassRefPtr<Uint8Array> imagePixels,
size_t imageRowBytes) {
SkPixmap pixmap(info, imagePixels->data(), imageRowBytes);
return SkImage::MakeFromRaster(pixmap,
[](const void*, void* pixels) {
static_cast<Uint8Array*>(pixels)->deref();
},
imagePixels.leakRef());
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787 | static sk_sp<SkImage> newSkImageFromRaster(const SkImageInfo& info,
PassRefPtr<Uint8Array> imagePixels,
unsigned imageRowBytes) {
SkPixmap pixmap(info, imagePixels->data(), imageRowBytes);
return SkImage::MakeFromRaster(pixmap,
[](const void*, void* pixels) {
static_cast<Uint8Array*>(pixels)->deref();
},
imagePixels.leakRef());
}
| 172,503 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) {
if (U_FAILURE(*status))
return;
const icu::UnicodeSet* recommended_set =
uspoof_getRecommendedUnicodeSet(status);
icu::UnicodeSet allowed_set;
allowed_set.addAll(*recommended_set);
const icu::UnicodeSet* inclusion_set = uspoof_getInclusionUnicodeSet(status);
allowed_set.addAll(*inclusion_set);
allowed_set.remove(0x338u);
allowed_set.remove(0x58au); // Armenian Hyphen
allowed_set.remove(0x2010u);
allowed_set.remove(0x2019u); // Right Single Quotation Mark
allowed_set.remove(0x2027u);
allowed_set.remove(0x30a0u); // Katakana-Hiragana Double Hyphen
allowed_set.remove(0x2bbu); // Modifier Letter Turned Comma
allowed_set.remove(0x2bcu); // Modifier Letter Apostrophe
#if defined(OS_MACOSX)
allowed_set.remove(0x0620u);
allowed_set.remove(0x0F8Cu);
allowed_set.remove(0x0F8Du);
allowed_set.remove(0x0F8Eu);
allowed_set.remove(0x0F8Fu);
#endif
allowed_set.remove(0x01CDu, 0x01DCu); // Latin Ext B; Pinyin
allowed_set.remove(0x1C80u, 0x1C8Fu); // Cyrillic Extended-C
allowed_set.remove(0x1E00u, 0x1E9Bu); // Latin Extended Additional
allowed_set.remove(0x1F00u, 0x1FFFu); // Greek Extended
allowed_set.remove(0xA640u, 0xA69Fu); // Cyrillic Extended-B
allowed_set.remove(0xA720u, 0xA7FFu); // Latin Extended-D
uspoof_setAllowedUnicodeSet(checker_, &allowed_set, status);
}
Commit Message: Block modifier-letter-voicing character from domain names
This character (ˬ) is easy to miss between other characters. It's one of the three characters from Spacing-Modifier-Letters block that ICU lists in its recommended set in uspoof.cpp. Two of these characters (modifier-letter-turned-comma and modifier-letter-apostrophe) are already blocked in crbug/678812.
Bug: 896717
Change-Id: I24b2b591de8cc7822cd55aa005b15676be91175e
Reviewed-on: https://chromium-review.googlesource.com/c/1303037
Commit-Queue: Mustafa Emre Acer <[email protected]>
Reviewed-by: Tommy Li <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604128}
CWE ID: CWE-20 | void IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) {
if (U_FAILURE(*status))
return;
const icu::UnicodeSet* recommended_set =
uspoof_getRecommendedUnicodeSet(status);
icu::UnicodeSet allowed_set;
allowed_set.addAll(*recommended_set);
const icu::UnicodeSet* inclusion_set = uspoof_getInclusionUnicodeSet(status);
allowed_set.addAll(*inclusion_set);
allowed_set.remove(0x338u);
allowed_set.remove(0x58au); // Armenian Hyphen
allowed_set.remove(0x2010u);
allowed_set.remove(0x2019u); // Right Single Quotation Mark
allowed_set.remove(0x2027u);
allowed_set.remove(0x30a0u); // Katakana-Hiragana Double Hyphen
allowed_set.remove(0x2bbu); // Modifier Letter Turned Comma
allowed_set.remove(0x2bcu); // Modifier Letter Apostrophe
// Block modifier letter voicing.
allowed_set.remove(0x2ecu);
#if defined(OS_MACOSX)
allowed_set.remove(0x0620u);
allowed_set.remove(0x0F8Cu);
allowed_set.remove(0x0F8Du);
allowed_set.remove(0x0F8Eu);
allowed_set.remove(0x0F8Fu);
#endif
allowed_set.remove(0x01CDu, 0x01DCu); // Latin Ext B; Pinyin
allowed_set.remove(0x1C80u, 0x1C8Fu); // Cyrillic Extended-C
allowed_set.remove(0x1E00u, 0x1E9Bu); // Latin Extended Additional
allowed_set.remove(0x1F00u, 0x1FFFu); // Greek Extended
allowed_set.remove(0xA640u, 0xA69Fu); // Cyrillic Extended-B
allowed_set.remove(0xA720u, 0xA7FFu); // Latin Extended-D
uspoof_setAllowedUnicodeSet(checker_, &allowed_set, status);
}
| 172,638 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void ReportPreconnectAccuracy(
const PreconnectStats& stats,
const std::map<GURL, OriginRequestSummary>& requests) {
if (stats.requests_stats.empty())
return;
int preresolve_hits_count = 0;
int preresolve_misses_count = 0;
int preconnect_hits_count = 0;
int preconnect_misses_count = 0;
for (const auto& request_stats : stats.requests_stats) {
bool hit = requests.find(request_stats.origin) != requests.end();
bool preconnect = request_stats.was_preconnected;
preresolve_hits_count += hit;
preresolve_misses_count += !hit;
preconnect_hits_count += preconnect && hit;
preconnect_misses_count += preconnect && !hit;
}
int total_preresolves = preresolve_hits_count + preresolve_misses_count;
int total_preconnects = preconnect_hits_count + preconnect_misses_count;
DCHECK_EQ(static_cast<int>(stats.requests_stats.size()),
preresolve_hits_count + preresolve_misses_count);
DCHECK_GT(total_preresolves, 0);
size_t preresolve_hits_percentage =
(100 * preresolve_hits_count) / total_preresolves;
if (total_preconnects > 0) {
size_t preconnect_hits_percentage =
(100 * preconnect_hits_count) / total_preconnects;
UMA_HISTOGRAM_PERCENTAGE(
internal::kLoadingPredictorPreconnectHitsPercentage,
preconnect_hits_percentage);
}
UMA_HISTOGRAM_PERCENTAGE(internal::kLoadingPredictorPreresolveHitsPercentage,
preresolve_hits_percentage);
UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreresolveCount,
total_preresolves);
UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreconnectCount,
total_preconnects);
}
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 <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125 | void ReportPreconnectAccuracy(
const PreconnectStats& stats,
const std::map<url::Origin, OriginRequestSummary>& requests) {
if (stats.requests_stats.empty())
return;
int preresolve_hits_count = 0;
int preresolve_misses_count = 0;
int preconnect_hits_count = 0;
int preconnect_misses_count = 0;
for (const auto& request_stats : stats.requests_stats) {
bool hit = requests.find(request_stats.origin) != requests.end();
bool preconnect = request_stats.was_preconnected;
preresolve_hits_count += hit;
preresolve_misses_count += !hit;
preconnect_hits_count += preconnect && hit;
preconnect_misses_count += preconnect && !hit;
}
int total_preresolves = preresolve_hits_count + preresolve_misses_count;
int total_preconnects = preconnect_hits_count + preconnect_misses_count;
DCHECK_EQ(static_cast<int>(stats.requests_stats.size()),
preresolve_hits_count + preresolve_misses_count);
DCHECK_GT(total_preresolves, 0);
size_t preresolve_hits_percentage =
(100 * preresolve_hits_count) / total_preresolves;
if (total_preconnects > 0) {
size_t preconnect_hits_percentage =
(100 * preconnect_hits_count) / total_preconnects;
UMA_HISTOGRAM_PERCENTAGE(
internal::kLoadingPredictorPreconnectHitsPercentage,
preconnect_hits_percentage);
}
UMA_HISTOGRAM_PERCENTAGE(internal::kLoadingPredictorPreresolveHitsPercentage,
preresolve_hits_percentage);
UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreresolveCount,
total_preresolves);
UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreconnectCount,
total_preconnects);
}
| 172,372 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: 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 <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
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. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: z_check_file_permissions(gs_memory_t *mem, const char *fname, const int len, const char *permission)
{
i_ctx_t *i_ctx_p = get_minst_from_memory(mem)->i_ctx_p;
gs_parsed_file_name_t pname;
const char *permitgroup = permission[0] == 'r' ? "PermitFileReading" : "PermitFileWriting";
int code = gs_parse_file_name(&pname, fname, len, imemory);
if (code < 0)
return code;
if (pname.iodev && i_ctx_p->LockFilePermissions && strcmp(pname.iodev->dname, "%pipe%") == 0)
return gs_error_invalidfileaccess;
code = check_file_permissions(i_ctx_p, fname, len, permitgroup);
return code;
}
Commit Message:
CWE ID: CWE-200 | z_check_file_permissions(gs_memory_t *mem, const char *fname, const int len, const char *permission)
{
i_ctx_t *i_ctx_p = get_minst_from_memory(mem)->i_ctx_p;
gs_parsed_file_name_t pname;
const char *permitgroup = permission[0] == 'r' ? "PermitFileReading" : "PermitFileWriting";
int code = gs_parse_file_name(&pname, fname, len, imemory);
if (code < 0)
return code;
if (pname.iodev && i_ctx_p->LockFilePermissions
&& strcmp(pname.iodev->dname, "%pipe%") == 0) {
code = gs_note_error(gs_error_invalidfileaccess);
}
else {
code = check_file_permissions(i_ctx_p, fname, len, permitgroup);
}
return code;
}
| 164,828 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static void nfs4_open_prepare(struct rpc_task *task, void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state_owner *sp = data->owner;
if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0)
return;
/*
* Check if we still need to send an OPEN call, or if we can use
* a delegation instead.
*/
if (data->state != NULL) {
struct nfs_delegation *delegation;
if (can_open_cached(data->state, data->o_arg.open_flags & (FMODE_READ|FMODE_WRITE|O_EXCL)))
goto out_no_action;
rcu_read_lock();
delegation = rcu_dereference(NFS_I(data->state->inode)->delegation);
if (delegation != NULL &&
test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) == 0) {
rcu_read_unlock();
goto out_no_action;
}
rcu_read_unlock();
}
/* Update sequence id. */
data->o_arg.id = sp->so_owner_id.id;
data->o_arg.clientid = sp->so_client->cl_clientid;
if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS) {
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR];
nfs_copy_fh(&data->o_res.fh, data->o_arg.fh);
}
data->timestamp = jiffies;
rpc_call_start(task);
return;
out_no_action:
task->tk_action = NULL;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static void nfs4_open_prepare(struct rpc_task *task, void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state_owner *sp = data->owner;
if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0)
return;
/*
* Check if we still need to send an OPEN call, or if we can use
* a delegation instead.
*/
if (data->state != NULL) {
struct nfs_delegation *delegation;
if (can_open_cached(data->state, data->o_arg.fmode, data->o_arg.open_flags))
goto out_no_action;
rcu_read_lock();
delegation = rcu_dereference(NFS_I(data->state->inode)->delegation);
if (delegation != NULL &&
test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) == 0) {
rcu_read_unlock();
goto out_no_action;
}
rcu_read_unlock();
}
/* Update sequence id. */
data->o_arg.id = sp->so_owner_id.id;
data->o_arg.clientid = sp->so_client->cl_clientid;
if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS) {
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR];
nfs_copy_fh(&data->o_res.fh, data->o_arg.fh);
}
data->timestamp = jiffies;
rpc_call_start(task);
return;
out_no_action:
task->tk_action = NULL;
}
| 165,695 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: long long Chapters::Atom::GetStopTimecode() const
{
return m_stop_timecode;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Chapters::Atom::GetStopTimecode() const
| 174,358 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: create_response(const char *nurl, const char *method, unsigned int *rp_code)
{
char *page, *fpath;
struct MHD_Response *resp = NULL;
if (!strncmp(nurl, URL_BASE_API_1_1, strlen(URL_BASE_API_1_1))) {
resp = create_response_api(nurl, method, rp_code);
} else {
fpath = get_path(nurl, server_data.www_dir);
resp = create_response_file(nurl, method, rp_code, fpath);
free(fpath);
}
}
Commit Message:
CWE ID: CWE-22 | create_response(const char *nurl, const char *method, unsigned int *rp_code)
{
char *page, *fpath, *rpath;
struct MHD_Response *resp = NULL;
int n;
if (!strncmp(nurl, URL_BASE_API_1_1, strlen(URL_BASE_API_1_1))) {
resp = create_response_api(nurl, method, rp_code);
} else {
fpath = get_path(nurl, server_data.www_dir);
rpath = realpath(fpath, NULL);
if (rpath) {
n = strlen(server_data.www_dir);
if (!strncmp(server_data.www_dir, rpath, n))
resp = create_response_file(nurl,
method,
rp_code,
fpath);
free(rpath);
}
free(fpath);
}
}
| 165,509 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: Chapters::Atom::~Atom()
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | Chapters::Atom::~Atom()
const char* SegmentInfo::GetMuxingAppAsUTF8() const {
return m_pMuxingAppAsUTF8;
}
| 174,454 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void TypingCommand::insertText(Document& document,
const String& text,
Options options,
TextCompositionType composition,
const bool isIncrementalInsertion) {
LocalFrame* frame = document.frame();
DCHECK(frame);
if (!text.isEmpty())
document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
insertText(document, text,
frame->selection().computeVisibleSelectionInDOMTreeDeprecated(),
options, composition, isIncrementalInsertion);
}
Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection
This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree|
instead of |VisibleSelection| to reduce usage of |VisibleSelection| for
improving code health.
BUG=657237
TEST=n/a
Review-Url: https://codereview.chromium.org/2733183002
Cr-Commit-Position: refs/heads/master@{#455368}
CWE ID: | void TypingCommand::insertText(Document& document,
const String& text,
Options options,
TextCompositionType composition,
const bool isIncrementalInsertion) {
LocalFrame* frame = document.frame();
DCHECK(frame);
if (!text.isEmpty())
document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
insertText(document, text, frame->selection().selectionInDOMTree(), options,
composition, isIncrementalInsertion);
}
| 172,031 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void GaiaOAuthClient::Core::RefreshToken(
const OAuthClientInfo& oauth_client_info,
const std::string& refresh_token,
GaiaOAuthClient::Delegate* delegate) {
DCHECK(!request_.get()) << "Tried to fetch two things at once!";
delegate_ = delegate;
access_token_.clear();
expires_in_seconds_ = 0;
std::string post_body =
"refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) +
"&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id,
true) +
"&client_secret=" +
net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) +
"&grant_type=refresh_token";
request_.reset(new UrlFetcher(GURL(provider_info_.access_token_url),
UrlFetcher::POST));
request_->SetRequestContext(request_context_getter_);
request_->SetUploadData("application/x-www-form-urlencoded", post_body);
request_->Start(
base::Bind(&GaiaOAuthClient::Core::OnAuthTokenFetchComplete, this));
}
Commit Message: Remove UrlFetcher from remoting and use the one in net instead.
BUG=133790
TEST=Stop and restart the Me2Me host. It should still work.
Review URL: https://chromiumcodereview.appspot.com/10637008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void GaiaOAuthClient::Core::RefreshToken(
const OAuthClientInfo& oauth_client_info,
const std::string& refresh_token,
GaiaOAuthClient::Delegate* delegate) {
DCHECK(!request_.get()) << "Tried to fetch two things at once!";
delegate_ = delegate;
access_token_.clear();
expires_in_seconds_ = 0;
std::string post_body =
"refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) +
"&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id,
true) +
"&client_secret=" +
net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) +
"&grant_type=refresh_token";
request_.reset(net::URLFetcher::Create(
GURL(provider_info_.access_token_url), net::URLFetcher::POST, this));
request_->SetRequestContext(request_context_getter_);
request_->SetUploadData("application/x-www-form-urlencoded", post_body);
url_fetcher_type_ = URL_FETCHER_REFRESH_TOKEN;
request_->Start();
}
void GaiaOAuthClient::Core::OnURLFetchComplete(
const net::URLFetcher* source) {
std::string response_string;
source->GetResponseAsString(&response_string);
switch (url_fetcher_type_) {
case URL_FETCHER_REFRESH_TOKEN:
OnAuthTokenFetchComplete(source->GetStatus(),
source->GetResponseCode(),
response_string);
break;
case URL_FETCHER_GET_USER_INFO:
OnUserInfoFetchComplete(source->GetStatus(),
source->GetResponseCode(),
response_string);
break;
default:
LOG(ERROR) << "Unrecognised URLFetcher type: " << url_fetcher_type_;
}
}
| 170,809 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static int 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. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: jbig2_end_of_stripe(Jbig2Ctx *ctx, Jbig2Segment *segment, const uint8_t *segment_data)
{
Jbig2Page page = ctx->pages[ctx->current_page];
int end_row;
end_row = jbig2_get_int32(segment_data);
if (end_row < page.end_row) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number,
"end of stripe segment with non-positive end row advance" " (new end row %d vs current end row %d)", end_row, page.end_row);
} else {
jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "end of stripe: advancing end row to %d", end_row);
}
page.end_row = end_row;
return 0;
}
Commit Message:
CWE ID: CWE-119 | jbig2_end_of_stripe(Jbig2Ctx *ctx, Jbig2Segment *segment, const uint8_t *segment_data)
{
Jbig2Page page = ctx->pages[ctx->current_page];
uint32_t end_row;
end_row = jbig2_get_uint32(segment_data);
if (end_row < page.end_row) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number,
"end of stripe segment with non-positive end row advance" " (new end row %d vs current end row %d)", end_row, page.end_row);
} else {
jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "end of stripe: advancing end row to %d", end_row);
}
page.end_row = end_row;
return 0;
}
| 165,495 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: int FFmpegVideoDecoder::GetVideoBuffer(AVCodecContext* codec_context,
AVFrame* frame) {
VideoFrame::Format format = PixelFormatToVideoFormat(codec_context->pix_fmt);
if (format == VideoFrame::UNKNOWN)
return AVERROR(EINVAL);
DCHECK(format == VideoFrame::YV12 || format == VideoFrame::YV16 ||
format == VideoFrame::YV12J);
gfx::Size size(codec_context->width, codec_context->height);
int ret;
if ((ret = av_image_check_size(size.width(), size.height(), 0, NULL)) < 0)
return ret;
gfx::Size natural_size;
if (codec_context->sample_aspect_ratio.num > 0) {
natural_size = GetNaturalSize(size,
codec_context->sample_aspect_ratio.num,
codec_context->sample_aspect_ratio.den);
} else {
natural_size = config_.natural_size();
}
if (!VideoFrame::IsValidConfig(format, size, gfx::Rect(size), natural_size))
return AVERROR(EINVAL);
scoped_refptr<VideoFrame> video_frame =
frame_pool_.CreateFrame(format, size, gfx::Rect(size),
natural_size, kNoTimestamp());
for (int i = 0; i < 3; i++) {
frame->base[i] = video_frame->data(i);
frame->data[i] = video_frame->data(i);
frame->linesize[i] = video_frame->stride(i);
}
frame->opaque = NULL;
video_frame.swap(reinterpret_cast<VideoFrame**>(&frame->opaque));
frame->type = FF_BUFFER_TYPE_USER;
frame->width = codec_context->width;
frame->height = codec_context->height;
frame->format = codec_context->pix_fmt;
return 0;
}
Commit Message: Replicate FFmpeg's video frame allocation strategy.
This should avoid accidental overreads and overwrites due to our
VideoFrame's not being as large as FFmpeg expects.
BUG=368980
TEST=new regression test
Review URL: https://codereview.chromium.org/270193002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268831 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | int FFmpegVideoDecoder::GetVideoBuffer(AVCodecContext* codec_context,
AVFrame* frame) {
VideoFrame::Format format = PixelFormatToVideoFormat(codec_context->pix_fmt);
if (format == VideoFrame::UNKNOWN)
return AVERROR(EINVAL);
DCHECK(format == VideoFrame::YV12 || format == VideoFrame::YV16 ||
format == VideoFrame::YV12J);
gfx::Size size(codec_context->width, codec_context->height);
const int ret = av_image_check_size(size.width(), size.height(), 0, NULL);
if (ret < 0)
return ret;
gfx::Size natural_size;
if (codec_context->sample_aspect_ratio.num > 0) {
natural_size = GetNaturalSize(size,
codec_context->sample_aspect_ratio.num,
codec_context->sample_aspect_ratio.den);
} else {
natural_size = config_.natural_size();
}
// FFmpeg has specific requirements on the allocation size of the frame. The
// following logic replicates FFmpeg's allocation strategy to ensure buffers
// are not overread / overwritten. See ff_init_buffer_info() for details.
//
// When lowres is non-zero, dimensions should be divided by 2^(lowres), but
// since we don't use this, just DCHECK that it's zero.
DCHECK_EQ(codec_context->lowres, 0);
gfx::Size coded_size(std::max(size.width(), codec_context->coded_width),
std::max(size.height(), codec_context->coded_height));
if (!VideoFrame::IsValidConfig(
format, coded_size, gfx::Rect(size), natural_size))
return AVERROR(EINVAL);
scoped_refptr<VideoFrame> video_frame = frame_pool_.CreateFrame(
format, coded_size, gfx::Rect(size), natural_size, kNoTimestamp());
for (int i = 0; i < 3; i++) {
frame->base[i] = video_frame->data(i);
frame->data[i] = video_frame->data(i);
frame->linesize[i] = video_frame->stride(i);
}
frame->opaque = NULL;
video_frame.swap(reinterpret_cast<VideoFrame**>(&frame->opaque));
frame->type = FF_BUFFER_TYPE_USER;
frame->width = coded_size.width();
frame->height = coded_size.height();
frame->format = codec_context->pix_fmt;
return 0;
}
| 171,677 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: bool DoTouchScroll(const gfx::Point& point,
const gfx::Vector2d& distance,
bool wait_until_scrolled) {
EXPECT_EQ(0, GetScrollTop());
int scrollHeight = ExecuteScriptAndExtractInt(
"document.documentElement.scrollHeight");
EXPECT_EQ(1200, scrollHeight);
scoped_refptr<FrameWatcher> frame_watcher(new FrameWatcher());
frame_watcher->AttachTo(shell()->web_contents());
SyntheticSmoothScrollGestureParams params;
params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT;
params.anchor = gfx::PointF(point);
params.distances.push_back(-distance);
runner_ = new MessageLoopRunner();
std::unique_ptr<SyntheticSmoothScrollGesture> gesture(
new SyntheticSmoothScrollGesture(params));
GetWidgetHost()->QueueSyntheticGesture(
std::move(gesture),
base::Bind(&TouchActionBrowserTest::OnSyntheticGestureCompleted,
base::Unretained(this)));
runner_->Run();
runner_ = NULL;
while (wait_until_scrolled &&
frame_watcher->LastMetadata().root_scroll_offset.y() <= 0) {
frame_watcher->WaitFrames(1);
}
int scrollTop = GetScrollTop();
if (scrollTop == 0)
return false;
EXPECT_EQ(distance.y(), scrollTop);
return true;
}
Commit Message: Drive out additional flakiness of TouchAction browser test.
It is relatively stable but it has flaked a couple of times specifically
with this:
Actual: 44
Expected: distance.y()
Which is: 45
I presume that the failure is either we aren't waiting for the additional
frame or a subpixel scrolling problem. As a speculative fix wait for the
pixel item we are waiting to scroll for.
BUG=376668
Review-Url: https://codereview.chromium.org/2281613002
Cr-Commit-Position: refs/heads/master@{#414525}
CWE ID: CWE-119 | bool DoTouchScroll(const gfx::Point& point,
const gfx::Vector2d& distance,
bool wait_until_scrolled) {
EXPECT_EQ(0, GetScrollTop());
int scrollHeight = ExecuteScriptAndExtractInt(
"document.documentElement.scrollHeight");
EXPECT_EQ(1200, scrollHeight);
scoped_refptr<FrameWatcher> frame_watcher(new FrameWatcher());
frame_watcher->AttachTo(shell()->web_contents());
SyntheticSmoothScrollGestureParams params;
params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT;
params.anchor = gfx::PointF(point);
params.distances.push_back(-distance);
runner_ = new MessageLoopRunner();
std::unique_ptr<SyntheticSmoothScrollGesture> gesture(
new SyntheticSmoothScrollGesture(params));
GetWidgetHost()->QueueSyntheticGesture(
std::move(gesture),
base::Bind(&TouchActionBrowserTest::OnSyntheticGestureCompleted,
base::Unretained(this)));
runner_->Run();
runner_ = NULL;
while (wait_until_scrolled &&
frame_watcher->LastMetadata().root_scroll_offset.y() <
distance.y()) {
frame_watcher->WaitFrames(1);
}
int scrollTop = GetScrollTop();
if (scrollTop == 0)
return false;
EXPECT_EQ(distance.y(), scrollTop);
return true;
}
| 171,600 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: log2vis_encoded_string (PyObject * string, const char *encoding,
FriBidiParType base_direction, int clean, int reordernsm)
{
PyObject *logical = NULL; /* logical unicode object */
PyObject *result = NULL; /* output string object */
/* Always needed for the string length */
logical = PyUnicode_Decode (PyString_AS_STRING (string),
PyString_GET_SIZE (string),
encoding, "strict");
if (logical == NULL)
return NULL;
if (strcmp (encoding, "utf-8") == 0)
/* Shortcut for utf8 strings (little faster) */
result = log2vis_utf8 (string,
PyUnicode_GET_SIZE (logical),
base_direction, clean, reordernsm);
else
{
/* Invoke log2vis_unicode and encode back to encoding */
PyObject *visual = log2vis_unicode (logical, base_direction, clean, reordernsm);
if (visual)
{
result = PyUnicode_Encode (PyUnicode_AS_UNICODE
(visual),
PyUnicode_GET_SIZE (visual),
encoding, "strict");
Py_DECREF (visual);
}
}
Py_DECREF (logical);
return result;
}
Commit Message: refactor pyfribidi.c module
pyfribidi.c is now compiled as _pyfribidi. This module only handles
unicode internally and doesn't use the fribidi_utf8_to_unicode
function (which can't handle 4 byte utf-8 sequences). This fixes the
buffer overflow in issue #2.
The code is now also much simpler: pyfribidi.c is down from 280 to 130
lines of code.
We now ship a pure python pyfribidi that handles the case when
non-unicode strings are passed in.
We now also adapt the size of the output string if clean=True is
passed.
CWE ID: CWE-119 | log2vis_encoded_string (PyObject * string, const char *encoding,
| 165,640 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void BufferQueueConsumer::dump(String8& result, const char* prefix) const {
const IPCThreadState* ipc = IPCThreadState::self();
const pid_t pid = ipc->getCallingPid();
const uid_t uid = ipc->getCallingUid();
if ((uid != AID_SHELL)
&& !PermissionCache::checkPermission(String16(
"android.permission.DUMP"), pid, uid)) {
result.appendFormat("Permission Denial: can't dump BufferQueueConsumer "
"from pid=%d, uid=%d\n", pid, uid);
} else {
mCore->dump(result, prefix);
}
}
Commit Message: Add SN logging
Bug 27046057
Change-Id: Iede7c92e59e60795df1ec7768ebafd6b090f1c27
CWE ID: CWE-264 | void BufferQueueConsumer::dump(String8& result, const char* prefix) const {
const IPCThreadState* ipc = IPCThreadState::self();
const pid_t pid = ipc->getCallingPid();
const uid_t uid = ipc->getCallingUid();
if ((uid != AID_SHELL)
&& !PermissionCache::checkPermission(String16(
"android.permission.DUMP"), pid, uid)) {
result.appendFormat("Permission Denial: can't dump BufferQueueConsumer "
"from pid=%d, uid=%d\n", pid, uid);
android_errorWriteWithInfoLog(0x534e4554, "27046057", uid, NULL, 0);
} else {
mCore->dump(result, prefix);
}
}
| 173,894 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: bool InputWindowInfo::frameContainsPoint(int32_t x, int32_t y) const {
return x >= frameLeft && x <= frameRight
&& y >= frameTop && y <= frameBottom;
}
Commit Message: Add new MotionEvent flag for partially obscured windows.
Due to more complex window layouts resulting in lots of overlapping
windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to
only be set when the point at which the window was touched is
obscured. Unfortunately, this doesn't prevent tapjacking attacks that
overlay the dialog's text, making a potentially dangerous operation
seem innocuous. To avoid this on particularly sensitive dialogs,
introduce a new flag that really does tell you when your window is
being even partially overlapped.
We aren't exposing this as API since we plan on making the original
flag more robust. This is really a workaround for system dialogs
since we generally know their layout and screen position, and that
they're unlikely to be overlapped by other applications.
Bug: 26677796
Change-Id: I9e336afe90f262ba22015876769a9c510048fd47
CWE ID: CWE-264 | bool InputWindowInfo::frameContainsPoint(int32_t x, int32_t y) const {
return x >= frameLeft && x < frameRight
&& y >= frameTop && y < frameBottom;
}
| 174,169 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static CURLcode imap_parse_url_path(struct connectdata *conn)
{
/* the imap struct is already inited in imap_connect() */
struct imap_conn *imapc = &conn->proto.imapc;
struct SessionHandle *data = conn->data;
const char *path = data->state.path;
int len;
if(!*path)
path = "INBOX";
/* url decode the path and use this mailbox */
imapc->mailbox = curl_easy_unescape(data, path, 0, &len);
if(!imapc->mailbox)
return CURLE_OUT_OF_MEMORY;
return CURLE_OK;
}
Commit Message: URL sanitize: reject URLs containing bad data
Protocols (IMAP, POP3 and SMTP) that use the path part of a URL in a
decoded manner now use the new Curl_urldecode() function to reject URLs
with embedded control codes (anything that is or decodes to a byte value
less than 32).
URLs containing such codes could easily otherwise be used to do harm and
allow users to do unintended actions with otherwise innocent tools and
applications. Like for example using a URL like
pop3://pop3.example.com/1%0d%0aDELE%201 when the app wants a URL to get
a mail and instead this would delete one.
This flaw is considered a security vulnerability: CVE-2012-0036
Security advisory at: http://curl.haxx.se/docs/adv_20120124.html
Reported by: Dan Fandrich
CWE ID: CWE-89 | static CURLcode imap_parse_url_path(struct connectdata *conn)
{
/* the imap struct is already inited in imap_connect() */
struct imap_conn *imapc = &conn->proto.imapc;
struct SessionHandle *data = conn->data;
const char *path = data->state.path;
if(!*path)
path = "INBOX";
/* url decode the path and use this mailbox */
return Curl_urldecode(data, path, 0, &imapc->mailbox, NULL, TRUE);
}
| 165,666 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void MockRenderThread::AddRoute(int32 routing_id,
IPC::Channel::Listener* listener) {
EXPECT_EQ(routing_id_, routing_id);
widget_ = listener;
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | void MockRenderThread::AddRoute(int32 routing_id,
IPC::Channel::Listener* listener) {
// We may hear this for views created from OnMsgCreateWindow as well,
// in which case we don't want to track the new widget.
if (routing_id_ == routing_id)
widget_ = listener;
}
| 171,021 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static void mcf_fec_do_tx(mcf_fec_state *s)
{
uint32_t addr;
uint32_t addr;
mcf_fec_bd bd;
int frame_size;
int len;
uint8_t frame[FEC_MAX_FRAME_SIZE];
uint8_t *ptr;
ptr = frame;
ptr = frame;
frame_size = 0;
addr = s->tx_descriptor;
while (1) {
mcf_fec_read_bd(&bd, addr);
DPRINTF("tx_bd %x flags %04x len %d data %08x\n",
addr, bd.flags, bd.length, bd.data);
/* Run out of descriptors to transmit. */
break;
}
len = bd.length;
if (frame_size + len > FEC_MAX_FRAME_SIZE) {
len = FEC_MAX_FRAME_SIZE - frame_size;
s->eir |= FEC_INT_BABT;
}
cpu_physical_memory_read(bd.data, ptr, len);
ptr += len;
frame_size += len;
if (bd.flags & FEC_BD_L) {
/* Last buffer in frame. */
DPRINTF("Sending packet\n");
qemu_send_packet(qemu_get_queue(s->nic), frame, len);
ptr = frame;
frame_size = 0;
s->eir |= FEC_INT_TXF;
}
s->eir |= FEC_INT_TXB;
bd.flags &= ~FEC_BD_R;
/* Write back the modified descriptor. */
mcf_fec_write_bd(&bd, addr);
/* Advance to the next descriptor. */
if ((bd.flags & FEC_BD_W) != 0) {
addr = s->etdsr;
} else {
addr += 8;
}
}
Commit Message:
CWE ID: CWE-399 | static void mcf_fec_do_tx(mcf_fec_state *s)
{
uint32_t addr;
uint32_t addr;
mcf_fec_bd bd;
int frame_size;
int len, descnt = 0;
uint8_t frame[FEC_MAX_FRAME_SIZE];
uint8_t *ptr;
ptr = frame;
ptr = frame;
frame_size = 0;
addr = s->tx_descriptor;
while (descnt++ < FEC_MAX_DESC) {
mcf_fec_read_bd(&bd, addr);
DPRINTF("tx_bd %x flags %04x len %d data %08x\n",
addr, bd.flags, bd.length, bd.data);
/* Run out of descriptors to transmit. */
break;
}
len = bd.length;
if (frame_size + len > FEC_MAX_FRAME_SIZE) {
len = FEC_MAX_FRAME_SIZE - frame_size;
s->eir |= FEC_INT_BABT;
}
cpu_physical_memory_read(bd.data, ptr, len);
ptr += len;
frame_size += len;
if (bd.flags & FEC_BD_L) {
/* Last buffer in frame. */
DPRINTF("Sending packet\n");
qemu_send_packet(qemu_get_queue(s->nic), frame, len);
ptr = frame;
frame_size = 0;
s->eir |= FEC_INT_TXF;
}
s->eir |= FEC_INT_TXB;
bd.flags &= ~FEC_BD_R;
/* Write back the modified descriptor. */
mcf_fec_write_bd(&bd, addr);
/* Advance to the next descriptor. */
if ((bd.flags & FEC_BD_W) != 0) {
addr = s->etdsr;
} else {
addr += 8;
}
}
| 164,925 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: const Cluster* Segment::GetLast() const
{
if ((m_clusters == NULL) || (m_clusterCount <= 0))
return &m_eos;
const long idx = m_clusterCount - 1;
Cluster* const pCluster = m_clusters[idx];
assert(pCluster);
return pCluster;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Cluster* Segment::GetLast() const
const long idx = m_clusterCount - 1;
Cluster* const pCluster = m_clusters[idx];
assert(pCluster);
return pCluster;
}
| 174,340 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: SocketStream::SocketStream(const GURL& url, Delegate* delegate)
: delegate_(delegate),
url_(url),
max_pending_send_allowed_(kMaxPendingSendAllowed),
next_state_(STATE_NONE),
factory_(ClientSocketFactory::GetDefaultFactory()),
proxy_mode_(kDirectConnection),
proxy_url_(url),
pac_request_(NULL),
privacy_mode_(kPrivacyModeDisabled),
io_callback_(base::Bind(&SocketStream::OnIOCompleted,
base::Unretained(this))),
read_buf_(NULL),
current_write_buf_(NULL),
waiting_for_write_completion_(false),
closing_(false),
server_closed_(false),
metrics_(new SocketStreamMetrics(url)) {
DCHECK(base::MessageLoop::current())
<< "The current base::MessageLoop must exist";
DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
<< "The current base::MessageLoop must be TYPE_IO";
DCHECK(delegate_);
}
Commit Message: Revert a workaround commit for a Use-After-Free crash.
Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed.
URLRequestContext does not inherit SupportsWeakPtr now.
R=mmenke
BUG=244746
Review URL: https://chromiumcodereview.appspot.com/16870008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | SocketStream::SocketStream(const GURL& url, Delegate* delegate)
: delegate_(delegate),
url_(url),
max_pending_send_allowed_(kMaxPendingSendAllowed),
context_(NULL),
next_state_(STATE_NONE),
factory_(ClientSocketFactory::GetDefaultFactory()),
proxy_mode_(kDirectConnection),
proxy_url_(url),
pac_request_(NULL),
privacy_mode_(kPrivacyModeDisabled),
io_callback_(base::Bind(&SocketStream::OnIOCompleted,
base::Unretained(this))),
read_buf_(NULL),
current_write_buf_(NULL),
waiting_for_write_completion_(false),
closing_(false),
server_closed_(false),
metrics_(new SocketStreamMetrics(url)) {
DCHECK(base::MessageLoop::current())
<< "The current base::MessageLoop must exist";
DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
<< "The current base::MessageLoop must be TYPE_IO";
DCHECK(delegate_);
}
| 171,256 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void CoordinatorImpl::GetVmRegionsForHeapProfiler(
const GetVmRegionsForHeapProfilerCallback& callback) {
RequestGlobalMemoryDump(
MemoryDumpType::EXPLICITLY_TRIGGERED,
MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER, {}, callback);
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: oysteine <[email protected]>
Reviewed-by: Albert J. Wong <[email protected]>
Reviewed-by: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529059}
CWE ID: CWE-269 | void CoordinatorImpl::GetVmRegionsForHeapProfiler(
const GetVmRegionsForHeapProfilerCallback& callback) {
// This merely strips out the |dump_guid| argument.
auto adapter = [](const RequestGlobalMemoryDumpCallback& callback,
bool success, uint64_t dump_guid,
mojom::GlobalMemoryDumpPtr global_memory_dump) {
callback.Run(success, std::move(global_memory_dump));
};
QueuedRequest::Args args(
MemoryDumpType::EXPLICITLY_TRIGGERED,
MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER, {},
false /* add_to_trace */, base::kNullProcessId);
RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback));
}
| 172,914 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: bool FindAndUpdateProperty(const chromeos::ImeProperty& new_prop,
chromeos::ImePropertyList* prop_list) {
for (size_t i = 0; i < prop_list->size(); ++i) {
chromeos::ImeProperty& prop = prop_list->at(i);
if (prop.key == new_prop.key) {
const int saved_id = prop.selection_item_id;
prop = new_prop;
prop.selection_item_id = saved_id;
return true;
}
}
return false;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool FindAndUpdateProperty(const chromeos::ImeProperty& new_prop,
bool FindAndUpdateProperty(
const chromeos::input_method::ImeProperty& new_prop,
chromeos::input_method::ImePropertyList* prop_list) {
for (size_t i = 0; i < prop_list->size(); ++i) {
chromeos::input_method::ImeProperty& prop = prop_list->at(i);
if (prop.key == new_prop.key) {
const int saved_id = prop.selection_item_id;
prop = new_prop;
prop.selection_item_id = saved_id;
return true;
}
}
return false;
}
| 170,484 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: image_transform_png_set_tRNS_to_alpha_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* We don't know yet whether there will be a tRNS chunk, but we know that
* this transformation should do nothing if there already is an alpha
* channel.
*/
return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_tRNS_to_alpha_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* We don't know yet whether there will be a tRNS chunk, but we know that
* this transformation should do nothing if there already is an alpha
* channel. In addition, after the bug fix in 1.7.0, there is no longer
* any action on a palette image.
*/
return
# if PNG_LIBPNG_VER >= 10700
colour_type != PNG_COLOR_TYPE_PALETTE &&
# endif
(colour_type & PNG_COLOR_MASK_ALPHA) == 0;
}
| 173,654 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: bool MediaStreamDevicesController::IsRequestAllowedByDefault() const {
if (ShouldAlwaysAllowOrigin())
return true;
struct {
bool has_capability;
const char* policy_name;
const char* list_policy_name;
ContentSettingsType settings_type;
} device_checks[] = {
{ microphone_requested_, prefs::kAudioCaptureAllowed,
prefs::kAudioCaptureAllowedUrls, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC },
{ webcam_requested_, prefs::kVideoCaptureAllowed,
prefs::kVideoCaptureAllowedUrls,
CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(device_checks); ++i) {
if (!device_checks[i].has_capability)
continue;
DevicePolicy policy = GetDevicePolicy(device_checks[i].policy_name,
device_checks[i].list_policy_name);
if (policy == ALWAYS_DENY ||
(policy == POLICY_NOT_SET &&
profile_->GetHostContentSettingsMap()->GetContentSetting(
request_.security_origin, request_.security_origin,
device_checks[i].settings_type, NO_RESOURCE_IDENTIFIER) !=
CONTENT_SETTING_ALLOW)) {
return false;
}
}
return true;
}
Commit Message: Make the content setting for webcam/mic sticky for Pepper requests.
This makes the content setting sticky for webcam/mic requests from Pepper from non-https origins.
BUG=249335
[email protected], [email protected]
Review URL: https://codereview.chromium.org/17060006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@206479 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool MediaStreamDevicesController::IsRequestAllowedByDefault() const {
if (ShouldAlwaysAllowOrigin())
return true;
struct {
bool has_capability;
const char* policy_name;
const char* list_policy_name;
ContentSettingsType settings_type;
} device_checks[] = {
{ microphone_requested_, prefs::kAudioCaptureAllowed,
prefs::kAudioCaptureAllowedUrls, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC },
{ webcam_requested_, prefs::kVideoCaptureAllowed,
prefs::kVideoCaptureAllowedUrls,
CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(device_checks); ++i) {
if (!device_checks[i].has_capability)
continue;
DevicePolicy policy = GetDevicePolicy(device_checks[i].policy_name,
device_checks[i].list_policy_name);
if (policy == ALWAYS_DENY)
return false;
if (policy == POLICY_NOT_SET) {
// Only load content settings from secure origins unless it is a
// content::MEDIA_OPEN_DEVICE (Pepper) request.
if (!IsSchemeSecure() &&
request_.request_type != content::MEDIA_OPEN_DEVICE) {
return false;
}
if (profile_->GetHostContentSettingsMap()->GetContentSetting(
request_.security_origin, request_.security_origin,
device_checks[i].settings_type, NO_RESOURCE_IDENTIFIER) !=
CONTENT_SETTING_ALLOW) {
return false;
}
}
}
return true;
}
| 171,313 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: bool IsSystemModal(aura::Window* window) {
return window->transient_parent() &&
window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM;
}
Commit Message: Removed requirement for ash::Window::transient_parent() presence for system modal dialogs.
BUG=130420
TEST=SystemModalContainerLayoutManagerTest.ModalTransientAndNonTransient
Review URL: https://chromiumcodereview.appspot.com/10514012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@140647 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool IsSystemModal(aura::Window* window) {
return window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM;
}
| 170,801 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: static cJSON *cJSON_New_Item( void )
{
cJSON* node = (cJSON*) cJSON_malloc( sizeof(cJSON) );
if ( node )
memset( node, 0, sizeof(cJSON) );
return node;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | static cJSON *cJSON_New_Item( void )
static cJSON *cJSON_New_Item(void)
{
cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
if (node) memset(node,0,sizeof(cJSON));
return node;
}
| 167,291 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: void PrintPreviewUI::OnPreviewDataIsAvailable(int expected_pages_count,
int preview_request_id) {
VLOG(1) << "Print preview request finished with "
<< expected_pages_count << " pages";
if (!initial_preview_start_time_.is_null()) {
UMA_HISTOGRAM_TIMES("PrintPreview.InitialDisplayTime",
base::TimeTicks::Now() - initial_preview_start_time_);
UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.Initial",
expected_pages_count);
initial_preview_start_time_ = base::TimeTicks();
}
base::StringValue ui_identifier(preview_ui_addr_str_);
base::FundamentalValue ui_preview_request_id(preview_request_id);
web_ui()->CallJavascriptFunction("updatePrintPreview", ui_identifier,
ui_preview_request_id);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void PrintPreviewUI::OnPreviewDataIsAvailable(int expected_pages_count,
int preview_request_id) {
VLOG(1) << "Print preview request finished with "
<< expected_pages_count << " pages";
if (!initial_preview_start_time_.is_null()) {
UMA_HISTOGRAM_TIMES("PrintPreview.InitialDisplayTime",
base::TimeTicks::Now() - initial_preview_start_time_);
UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.Initial",
expected_pages_count);
initial_preview_start_time_ = base::TimeTicks();
}
base::FundamentalValue ui_identifier(id_);
base::FundamentalValue ui_preview_request_id(preview_request_id);
web_ui()->CallJavascriptFunction("updatePrintPreview", ui_identifier,
ui_preview_request_id);
}
| 170,838 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: int vp8_remove_decoder_instances(struct frame_buffers *fb)
{
if(!fb->use_frame_threads)
{
VP8D_COMP *pbi = fb->pbi[0];
if (!pbi)
return VPX_CODEC_ERROR;
#if CONFIG_MULTITHREAD
if (pbi->b_multithreaded_rd)
vp8mt_de_alloc_temp_buffers(pbi, pbi->common.mb_rows);
vp8_decoder_remove_threads(pbi);
#endif
/* decoder instance for single thread mode */
remove_decompressor(pbi);
}
else
{
/* TODO : remove frame threads and decoder instances for each
* thread here */
}
return VPX_CODEC_OK;
}
Commit Message: vp8:fix threading issues
1 - stops de allocating before threads are closed.
2 - limits threads to mb_rows when mb_rows < partitions
BUG=webm:851
Bug: 30436808
Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b
(cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e)
CWE ID: | int vp8_remove_decoder_instances(struct frame_buffers *fb)
{
if(!fb->use_frame_threads)
{
VP8D_COMP *pbi = fb->pbi[0];
if (!pbi)
return VPX_CODEC_ERROR;
#if CONFIG_MULTITHREAD
vp8_decoder_remove_threads(pbi);
#endif
/* decoder instance for single thread mode */
remove_decompressor(pbi);
}
else
{
/* TODO : remove frame threads and decoder instances for each
* thread here */
}
return VPX_CODEC_OK;
}
| 174,065 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation. | Code: MediaRecorder::MediaRecorder(const String16& opPackageName) : mSurfaceMediaSource(NULL)
{
ALOGV("constructor");
const sp<IMediaPlayerService>& service(getMediaPlayerService());
if (service != NULL) {
mMediaRecorder = service->createMediaRecorder(opPackageName);
}
if (mMediaRecorder != NULL) {
mCurrentState = MEDIA_RECORDER_IDLE;
}
doCleanUp();
}
Commit Message: Don't use sp<>&
because they may end up pointing to NULL after a NULL check was performed.
Bug: 28166152
Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe
CWE ID: CWE-476 | MediaRecorder::MediaRecorder(const String16& opPackageName) : mSurfaceMediaSource(NULL)
{
ALOGV("constructor");
const sp<IMediaPlayerService> service(getMediaPlayerService());
if (service != NULL) {
mMediaRecorder = service->createMediaRecorder(opPackageName);
}
if (mMediaRecorder != NULL) {
mCurrentState = MEDIA_RECORDER_IDLE;
}
doCleanUp();
}
| 173,540 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.