instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::enableNativeBuffers(
OMX_U32 portIndex, OMX_BOOL graphic, OMX_BOOL enable) {
Mutex::Autolock autoLock(mLock);
CLOG_CONFIG(enableNativeBuffers, "%s:%u%s, %d", portString(portIndex), portIndex,
graphic ? ", graphic" : "", enable);
OMX_STRING name = const_cast<OMX_STRING>(
graphic ? "OMX.google.android.index.enableAndroidNativeBuffers"
: "OMX.google.android.index.allocateNativeHandle");
OMX_INDEXTYPE index;
OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index);
if (err == OMX_ErrorNone) {
EnableAndroidNativeBuffersParams params;
InitOMXParams(¶ms);
params.nPortIndex = portIndex;
params.enable = enable;
err = OMX_SetParameter(mHandle, index, ¶ms);
CLOG_IF_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d", name, index,
portString(portIndex), portIndex, enable);
if (!graphic) {
if (err == OMX_ErrorNone) {
mSecureBufferType[portIndex] =
enable ? kSecureBufferTypeNativeHandle : kSecureBufferTypeOpaque;
} else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) {
mSecureBufferType[portIndex] = kSecureBufferTypeOpaque;
}
}
} else {
CLOG_ERROR_IF(enable, getExtensionIndex, err, "%s", name);
if (!graphic) {
char value[PROPERTY_VALUE_MAX];
if (property_get("media.mediadrmservice.enable", value, NULL)
&& (!strcmp("1", value) || !strcasecmp("true", value))) {
CLOG_CONFIG(enableNativeBuffers, "system property override: using native-handles");
mSecureBufferType[portIndex] = kSecureBufferTypeNativeHandle;
} else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) {
mSecureBufferType[portIndex] = kSecureBufferTypeOpaque;
}
err = OMX_ErrorNone;
}
}
return StatusFromOMXError(err);
}
Commit Message: OMXNodeInstance: sanity check portIndex.
Bug: 31385713
Change-Id: Ib91d00eb5cc8c51c84d37f5d36d6b7ca594d201f
(cherry picked from commit f80a1f5075a7c6e1982d37c68bfed7c9a611bb20)
CWE ID: CWE-264 | status_t OMXNodeInstance::enableNativeBuffers(
OMX_U32 portIndex, OMX_BOOL graphic, OMX_BOOL enable) {
if (portIndex >= NELEM(mSecureBufferType)) {
ALOGE("b/31385713, portIndex(%u)", portIndex);
android_errorWriteLog(0x534e4554, "31385713");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
CLOG_CONFIG(enableNativeBuffers, "%s:%u%s, %d", portString(portIndex), portIndex,
graphic ? ", graphic" : "", enable);
OMX_STRING name = const_cast<OMX_STRING>(
graphic ? "OMX.google.android.index.enableAndroidNativeBuffers"
: "OMX.google.android.index.allocateNativeHandle");
OMX_INDEXTYPE index;
OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index);
if (err == OMX_ErrorNone) {
EnableAndroidNativeBuffersParams params;
InitOMXParams(¶ms);
params.nPortIndex = portIndex;
params.enable = enable;
err = OMX_SetParameter(mHandle, index, ¶ms);
CLOG_IF_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d", name, index,
portString(portIndex), portIndex, enable);
if (!graphic) {
if (err == OMX_ErrorNone) {
mSecureBufferType[portIndex] =
enable ? kSecureBufferTypeNativeHandle : kSecureBufferTypeOpaque;
} else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) {
mSecureBufferType[portIndex] = kSecureBufferTypeOpaque;
}
}
} else {
CLOG_ERROR_IF(enable, getExtensionIndex, err, "%s", name);
if (!graphic) {
char value[PROPERTY_VALUE_MAX];
if (property_get("media.mediadrmservice.enable", value, NULL)
&& (!strcmp("1", value) || !strcasecmp("true", value))) {
CLOG_CONFIG(enableNativeBuffers, "system property override: using native-handles");
mSecureBufferType[portIndex] = kSecureBufferTypeNativeHandle;
} else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) {
mSecureBufferType[portIndex] = kSecureBufferTypeOpaque;
}
err = OMX_ErrorNone;
}
}
return StatusFromOMXError(err);
}
| 173,385 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: jas_image_t *jpg_decode(jas_stream_t *in, char *optstr)
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE *input_file;
jpg_dest_t dest_mgr_buf;
jpg_dest_t *dest_mgr = &dest_mgr_buf;
JDIMENSION num_scanlines;
jas_image_t *image;
int ret;
jpg_dec_importopts_t opts;
size_t size;
if (jpg_dec_parseopts(optstr, &opts)) {
goto error;
}
memset(&cinfo, 0, sizeof(struct jpeg_decompress_struct));
memset(dest_mgr, 0, sizeof(jpg_dest_t));
dest_mgr->data = 0;
image = 0;
input_file = 0;
if (!(input_file = tmpfile())) {
jas_eprintf("cannot make temporary file\n");
goto error;
}
if (jpg_copystreamtofile(input_file, in)) {
jas_eprintf("cannot copy stream\n");
goto error;
}
rewind(input_file);
/* Allocate and initialize a JPEG decompression object. */
JAS_DBGLOG(10, ("jpeg_std_error(%p)\n", &jerr));
cinfo.err = jpeg_std_error(&jerr);
JAS_DBGLOG(10, ("jpeg_create_decompress(%p)\n", &cinfo));
jpeg_create_decompress(&cinfo);
/* Specify the data source for decompression. */
JAS_DBGLOG(10, ("jpeg_stdio_src(%p, %p)\n", &cinfo, input_file));
jpeg_stdio_src(&cinfo, input_file);
/* Read the file header to obtain the image information. */
JAS_DBGLOG(10, ("jpeg_read_header(%p, TRUE)\n", &cinfo));
ret = jpeg_read_header(&cinfo, TRUE);
JAS_DBGLOG(10, ("jpeg_read_header return value %d\n", ret));
if (ret != JPEG_HEADER_OK) {
jas_eprintf("jpeg_read_header did not return JPEG_HEADER_OK\n");
}
JAS_DBGLOG(10, (
"header: image_width %d; image_height %d; num_components %d\n",
cinfo.image_width, cinfo.image_height, cinfo.num_components)
);
/* Start the decompressor. */
JAS_DBGLOG(10, ("jpeg_start_decompress(%p)\n", &cinfo));
ret = jpeg_start_decompress(&cinfo);
JAS_DBGLOG(10, ("jpeg_start_decompress return value %d\n", ret));
JAS_DBGLOG(10, (
"header: output_width %d; output_height %d; output_components %d\n",
cinfo.output_width, cinfo.output_height, cinfo.output_components)
);
if (opts.max_size) {
if (!jas_safe_size_mul(cinfo.output_width, cinfo.output_height,
&size) ||
!jas_safe_size_mul(size, cinfo.output_components, &size)) {
goto error;
}
if (size > opts.max_size) {
jas_eprintf("image is too large\n");
goto error;
}
}
/* Create an image object to hold the decoded data. */
if (!(image = jpg_mkimage(&cinfo))) {
jas_eprintf("jpg_mkimage failed\n");
goto error;
}
/* Initialize the data sink object. */
dest_mgr->image = image;
if (!(dest_mgr->data = jas_matrix_create(1, cinfo.output_width))) {
jas_eprintf("jas_matrix_create failed\n");
goto error;
}
dest_mgr->start_output = jpg_start_output;
dest_mgr->put_pixel_rows = jpg_put_pixel_rows;
dest_mgr->finish_output = jpg_finish_output;
dest_mgr->buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE,
cinfo.output_width * cinfo.output_components, (JDIMENSION) 1);
dest_mgr->buffer_height = 1;
dest_mgr->error = 0;
/* Process the compressed data. */
(*dest_mgr->start_output)(&cinfo, dest_mgr);
while (cinfo.output_scanline < cinfo.output_height) {
JAS_DBGLOG(10, ("jpeg_read_scanlines(%p, %p, %lu)\n", &cinfo,
dest_mgr->buffer, JAS_CAST(unsigned long, dest_mgr->buffer_height)));
num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
dest_mgr->buffer_height);
JAS_DBGLOG(10, ("jpeg_read_scanlines return value %lu\n",
JAS_CAST(unsigned long, num_scanlines)));
(*dest_mgr->put_pixel_rows)(&cinfo, dest_mgr, num_scanlines);
}
(*dest_mgr->finish_output)(&cinfo, dest_mgr);
/* Complete the decompression process. */
JAS_DBGLOG(10, ("jpeg_finish_decompress(%p)\n", &cinfo));
jpeg_finish_decompress(&cinfo);
/* Destroy the JPEG decompression object. */
JAS_DBGLOG(10, ("jpeg_destroy_decompress(%p)\n", &cinfo));
jpeg_destroy_decompress(&cinfo);
jas_matrix_destroy(dest_mgr->data);
JAS_DBGLOG(10, ("fclose(%p)\n", input_file));
fclose(input_file);
input_file = 0;
if (dest_mgr->error) {
jas_eprintf("error during decoding\n");
goto error;
}
return image;
error:
if (dest_mgr->data) {
jas_matrix_destroy(dest_mgr->data);
}
if (image) {
jas_image_destroy(image);
}
if (input_file) {
fclose(input_file);
}
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | jas_image_t *jpg_decode(jas_stream_t *in, char *optstr)
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE *input_file;
jpg_dest_t dest_mgr_buf;
jpg_dest_t *dest_mgr = &dest_mgr_buf;
JDIMENSION num_scanlines;
jas_image_t *image;
int ret;
jpg_dec_importopts_t opts;
size_t num_samples;
JAS_DBGLOG(100, ("jpg_decode(%p, \"%s\")\n", in, optstr));
if (jpg_dec_parseopts(optstr, &opts)) {
goto error;
}
memset(&cinfo, 0, sizeof(struct jpeg_decompress_struct));
memset(dest_mgr, 0, sizeof(jpg_dest_t));
dest_mgr->data = 0;
image = 0;
input_file = 0;
if (!(input_file = tmpfile())) {
jas_eprintf("cannot make temporary file\n");
goto error;
}
if (jpg_copystreamtofile(input_file, in)) {
jas_eprintf("cannot copy stream\n");
goto error;
}
rewind(input_file);
/* Allocate and initialize a JPEG decompression object. */
JAS_DBGLOG(10, ("jpeg_std_error(%p)\n", &jerr));
cinfo.err = jpeg_std_error(&jerr);
JAS_DBGLOG(10, ("jpeg_create_decompress(%p)\n", &cinfo));
jpeg_create_decompress(&cinfo);
/* Specify the data source for decompression. */
JAS_DBGLOG(10, ("jpeg_stdio_src(%p, %p)\n", &cinfo, input_file));
jpeg_stdio_src(&cinfo, input_file);
/* Read the file header to obtain the image information. */
JAS_DBGLOG(10, ("jpeg_read_header(%p, TRUE)\n", &cinfo));
ret = jpeg_read_header(&cinfo, TRUE);
JAS_DBGLOG(10, ("jpeg_read_header return value %d\n", ret));
if (ret != JPEG_HEADER_OK) {
jas_eprintf("jpeg_read_header did not return JPEG_HEADER_OK\n");
}
JAS_DBGLOG(10, (
"header: image_width %d; image_height %d; num_components %d\n",
cinfo.image_width, cinfo.image_height, cinfo.num_components)
);
if (opts.max_samples > 0) {
if (!jas_safe_size_mul3(cinfo.image_width, cinfo.image_height,
cinfo.num_components, &num_samples)) {
goto error;
}
if (num_samples > opts.max_samples) {
jas_eprintf("image is too large (%zu > %zu)\n", num_samples,
opts.max_samples);
goto error;
}
}
/* Start the decompressor. */
JAS_DBGLOG(10, ("jpeg_start_decompress(%p)\n", &cinfo));
ret = jpeg_start_decompress(&cinfo);
JAS_DBGLOG(10, ("jpeg_start_decompress return value %d\n", ret));
JAS_DBGLOG(10, (
"header: output_width %d; output_height %d; output_components %d\n",
cinfo.output_width, cinfo.output_height, cinfo.output_components)
);
/* Create an image object to hold the decoded data. */
if (!(image = jpg_mkimage(&cinfo))) {
jas_eprintf("jpg_mkimage failed\n");
goto error;
}
/* Initialize the data sink object. */
dest_mgr->image = image;
if (!(dest_mgr->data = jas_matrix_create(1, cinfo.output_width))) {
jas_eprintf("jas_matrix_create failed\n");
goto error;
}
dest_mgr->start_output = jpg_start_output;
dest_mgr->put_pixel_rows = jpg_put_pixel_rows;
dest_mgr->finish_output = jpg_finish_output;
dest_mgr->buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE,
cinfo.output_width * cinfo.output_components, (JDIMENSION) 1);
dest_mgr->buffer_height = 1;
dest_mgr->error = 0;
/* Process the compressed data. */
(*dest_mgr->start_output)(&cinfo, dest_mgr);
while (cinfo.output_scanline < cinfo.output_height) {
JAS_DBGLOG(10, ("jpeg_read_scanlines(%p, %p, %lu)\n", &cinfo,
dest_mgr->buffer, JAS_CAST(unsigned long, dest_mgr->buffer_height)));
num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
dest_mgr->buffer_height);
JAS_DBGLOG(10, ("jpeg_read_scanlines return value %lu\n",
JAS_CAST(unsigned long, num_scanlines)));
(*dest_mgr->put_pixel_rows)(&cinfo, dest_mgr, num_scanlines);
}
(*dest_mgr->finish_output)(&cinfo, dest_mgr);
/* Complete the decompression process. */
JAS_DBGLOG(10, ("jpeg_finish_decompress(%p)\n", &cinfo));
jpeg_finish_decompress(&cinfo);
/* Destroy the JPEG decompression object. */
JAS_DBGLOG(10, ("jpeg_destroy_decompress(%p)\n", &cinfo));
jpeg_destroy_decompress(&cinfo);
jas_matrix_destroy(dest_mgr->data);
JAS_DBGLOG(10, ("fclose(%p)\n", input_file));
fclose(input_file);
input_file = 0;
if (dest_mgr->error) {
jas_eprintf("error during decoding\n");
goto error;
}
return image;
error:
if (dest_mgr->data) {
jas_matrix_destroy(dest_mgr->data);
}
if (image) {
jas_image_destroy(image);
}
if (input_file) {
fclose(input_file);
}
return 0;
}
| 168,722 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PaymentRequest::Retry(mojom::PaymentValidationErrorsPtr errors) {
if (!client_.is_bound() || !binding_.is_bound()) {
DLOG(ERROR) << "Attempted Retry(), but binding(s) missing.";
OnConnectionTerminated();
return;
}
if (!display_handle_) {
DLOG(ERROR) << "Attempted Retry(), but display_handle_ is nullptr.";
OnConnectionTerminated();
return;
}
std::string error;
if (!PaymentsValidators::IsValidPaymentValidationErrorsFormat(errors,
&error)) {
DLOG(ERROR) << error;
client_->OnError(mojom::PaymentErrorReason::USER_CANCEL);
OnConnectionTerminated();
return;
}
spec()->Retry(std::move(errors));
display_handle_->Retry();
}
Commit Message: [Payment Request][Desktop] Prevent use after free.
Before this patch, a compromised renderer on desktop could make IPC
methods into Payment Request in an unexpected ordering and cause use
after free in the browser.
This patch will disconnect the IPC pipes if:
- Init() is called more than once.
- Any other method is called before Init().
- Show() is called more than once.
- Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or
Complete() are called before Show().
This patch re-orders the IPC methods in payment_request.cc to match the
order in payment_request.h, which eases verifying correctness of their
error handling.
This patch prints more errors to the developer console, if available, to
improve debuggability by web developers, who rarely check where LOG
prints.
After this patch, unexpected ordering of calls into the Payment Request
IPC from the renderer to the browser on desktop will print an error in
the developer console and disconnect the IPC pipes. The binary might
increase slightly in size because more logs are included in the release
version instead of being stripped at compile time.
Bug: 912947
Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a
Reviewed-on: https://chromium-review.googlesource.com/c/1370198
Reviewed-by: anthonyvd <[email protected]>
Commit-Queue: Rouslan Solomakhin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616822}
CWE ID: CWE-189 | void PaymentRequest::Retry(mojom::PaymentValidationErrorsPtr errors) {
if (!IsInitialized()) {
log_.Error("Attempted retry without initialization");
OnConnectionTerminated();
return;
}
if (!IsThisPaymentRequestShowing()) {
log_.Error("Attempted retry without show");
OnConnectionTerminated();
return;
}
std::string error;
if (!PaymentsValidators::IsValidPaymentValidationErrorsFormat(errors,
&error)) {
log_.Error(error);
client_->OnError(mojom::PaymentErrorReason::USER_CANCEL);
OnConnectionTerminated();
return;
}
spec()->Retry(std::move(errors));
display_handle_->Retry();
}
| 173,085 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ZEND_API void zend_object_store_ctor_failed(zval *zobject TSRMLS_DC)
{
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
zend_object_store_bucket *obj_bucket = &EG(objects_store).object_buckets[handle];
obj_bucket->bucket.obj.handlers = Z_OBJ_HT_P(zobject);;
obj_bucket->destructor_called = 1;
}
Commit Message: Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction
CWE ID: CWE-119 | ZEND_API void zend_object_store_ctor_failed(zval *zobject TSRMLS_DC)
{
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
zend_object_store_bucket *obj_bucket = &EG(objects_store).object_buckets[handle];
obj_bucket->bucket.obj.handlers = Z_OBJ_HT_P(zobject);
obj_bucket->destructor_called = 1;
}
| 166,938 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void InitializeOriginStatFromOriginRequestSummary(
OriginStat* origin,
const OriginRequestSummary& summary) {
origin->set_origin(summary.origin.spec());
origin->set_number_of_hits(1);
origin->set_average_position(summary.first_occurrence + 1);
origin->set_always_access_network(summary.always_access_network);
origin->set_accessed_network(summary.accessed_network);
}
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 InitializeOriginStatFromOriginRequestSummary(
OriginStat* origin,
const OriginRequestSummary& summary) {
origin->set_origin(summary.origin.GetURL().spec());
origin->set_number_of_hits(1);
origin->set_average_position(summary.first_occurrence + 1);
origin->set_always_access_network(summary.always_access_network);
origin->set_accessed_network(summary.accessed_network);
}
| 172,379 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void ifb_setup(struct net_device *dev)
{
/* Initialize the device structure. */
dev->destructor = free_netdev;
dev->netdev_ops = &ifb_netdev_ops;
/* Fill in device structure with ethernet-generic values. */
ether_setup(dev);
dev->tx_queue_len = TX_Q_LIMIT;
dev->features |= IFB_FEATURES;
dev->vlan_features |= IFB_FEATURES;
dev->flags |= IFF_NOARP;
dev->flags &= ~IFF_MULTICAST;
dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;
random_ether_addr(dev->dev_addr);
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | static void ifb_setup(struct net_device *dev)
{
/* Initialize the device structure. */
dev->destructor = free_netdev;
dev->netdev_ops = &ifb_netdev_ops;
/* Fill in device structure with ethernet-generic values. */
ether_setup(dev);
dev->tx_queue_len = TX_Q_LIMIT;
dev->features |= IFB_FEATURES;
dev->vlan_features |= IFB_FEATURES;
dev->flags |= IFF_NOARP;
dev->flags &= ~IFF_MULTICAST;
dev->priv_flags &= ~(IFF_XMIT_DST_RELEASE | IFF_TX_SKB_SHARING);
random_ether_addr(dev->dev_addr);
}
| 165,728 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void testRandomFrameDecode(const char* gifFile)
{
SCOPED_TRACE(gifFile);
RefPtr<SharedBuffer> fullData = readFile(gifFile);
ASSERT_TRUE(fullData.get());
Vector<unsigned> baselineHashes;
createDecodingBaseline(fullData.get(), &baselineHashes);
size_t frameCount = baselineHashes.size();
OwnPtr<GIFImageDecoder> decoder = createDecoder();
decoder->setData(fullData.get(), true);
const size_t skippingStep = 5;
for (size_t i = 0; i < skippingStep; ++i) {
for (size_t j = i; j < frameCount; j += skippingStep) {
SCOPED_TRACE(testing::Message() << "Random i:" << i << " j:" << j);
ImageFrame* frame = decoder->frameBufferAtIndex(j);
EXPECT_EQ(baselineHashes[j], hashSkBitmap(frame->getSkBitmap()));
}
}
decoder = createDecoder();
decoder->setData(fullData.get(), true);
for (size_t i = frameCount; i; --i) {
SCOPED_TRACE(testing::Message() << "Reverse i:" << i);
ImageFrame* frame = decoder->frameBufferAtIndex(i - 1);
EXPECT_EQ(baselineHashes[i - 1], hashSkBitmap(frame->getSkBitmap()));
}
}
Commit Message: Fix handling of broken GIFs with weird frame sizes
Code didn't handle well if a GIF frame has dimension greater than the
"screen" dimension. This will break deferred image decoding.
This change reports the size as final only when the first frame is
encountered.
Added a test to verify this behavior. Frame size reported by the decoder
should be constant.
BUG=437651
[email protected], [email protected]
Review URL: https://codereview.chromium.org/813943003
git-svn-id: svn://svn.chromium.org/blink/trunk@188423 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void testRandomFrameDecode(const char* gifFile)
void testRandomFrameDecode(const char* dir, const char* gifFile)
{
SCOPED_TRACE(gifFile);
RefPtr<SharedBuffer> fullData = readFile(dir, gifFile);
ASSERT_TRUE(fullData.get());
Vector<unsigned> baselineHashes;
createDecodingBaseline(fullData.get(), &baselineHashes);
size_t frameCount = baselineHashes.size();
OwnPtr<GIFImageDecoder> decoder = createDecoder();
decoder->setData(fullData.get(), true);
const size_t skippingStep = 5;
for (size_t i = 0; i < skippingStep; ++i) {
for (size_t j = i; j < frameCount; j += skippingStep) {
SCOPED_TRACE(testing::Message() << "Random i:" << i << " j:" << j);
ImageFrame* frame = decoder->frameBufferAtIndex(j);
EXPECT_EQ(baselineHashes[j], hashSkBitmap(frame->getSkBitmap()));
}
}
decoder = createDecoder();
decoder->setData(fullData.get(), true);
for (size_t i = frameCount; i; --i) {
SCOPED_TRACE(testing::Message() << "Reverse i:" << i);
ImageFrame* frame = decoder->frameBufferAtIndex(i - 1);
EXPECT_EQ(baselineHashes[i - 1], hashSkBitmap(frame->getSkBitmap()));
}
}
| 172,028 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void InputMethodBase::OnInputMethodChanged() const {
TextInputClient* client = GetTextInputClient();
if (client && client->GetTextInputType() != TEXT_INPUT_TYPE_NONE)
client->OnInputMethodChanged();
}
Commit Message: cleanup: Use IsTextInputTypeNone() in OnInputMethodChanged().
BUG=None
TEST=None
Review URL: http://codereview.chromium.org/8986010
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116461 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void InputMethodBase::OnInputMethodChanged() const {
TextInputClient* client = GetTextInputClient();
if (!IsTextInputTypeNone())
client->OnInputMethodChanged();
}
| 171,062 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_imagepolygon(INTERNAL_FUNCTION_PARAMETERS, int filled)
{
zval *IM, *POINTS;
long NPOINTS, COL;
zval **var = NULL;
gdImagePtr im;
gdPointPtr points;
int npoints, col, nelem, i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rall", &IM, &POINTS, &NPOINTS, &COL) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
npoints = NPOINTS;
col = COL;
nelem = zend_hash_num_elements(Z_ARRVAL_P(POINTS));
if (nelem < 6) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have at least 3 points in your array");
RETURN_FALSE;
}
if (npoints <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must give a positive number of points");
RETURN_FALSE;
}
if (nelem < npoints * 2) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to use %d points in array with only %d points", npoints, nelem/2);
RETURN_FALSE;
}
points = (gdPointPtr) safe_emalloc(npoints, sizeof(gdPoint), 0);
for (i = 0; i < npoints; i++) {
if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2), (void **) &var) == SUCCESS) {
SEPARATE_ZVAL((var));
convert_to_long(*var);
points[i].x = Z_LVAL_PP(var);
}
if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2) + 1, (void **) &var) == SUCCESS) {
SEPARATE_ZVAL(var);
convert_to_long(*var);
points[i].y = Z_LVAL_PP(var);
}
}
if (filled) {
gdImageFilledPolygon(im, points, npoints, col);
} else {
gdImagePolygon(im, points, npoints, col);
}
efree(points);
RETURN_TRUE;
}
Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())
And also fixed the bug: arguments are altered after some calls
CWE ID: CWE-189 | static void php_imagepolygon(INTERNAL_FUNCTION_PARAMETERS, int filled)
{
zval *IM, *POINTS;
long NPOINTS, COL;
zval **var = NULL;
gdImagePtr im;
gdPointPtr points;
int npoints, col, nelem, i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rall", &IM, &POINTS, &NPOINTS, &COL) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
npoints = NPOINTS;
col = COL;
nelem = zend_hash_num_elements(Z_ARRVAL_P(POINTS));
if (nelem < 6) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have at least 3 points in your array");
RETURN_FALSE;
}
if (npoints <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must give a positive number of points");
RETURN_FALSE;
}
if (nelem < npoints * 2) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to use %d points in array with only %d points", npoints, nelem/2);
RETURN_FALSE;
}
points = (gdPointPtr) safe_emalloc(npoints, sizeof(gdPoint), 0);
for (i = 0; i < npoints; i++) {
if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2), (void **) &var) == SUCCESS) {
if (Z_TYPE_PP(var) != IS_LONG) {
zval lval;
lval = **var;
zval_copy_ctor(&lval);
convert_to_long(&lval);
points[i].x = Z_LVAL(lval);
} else {
points[i].x = Z_LVAL_PP(var);
}
}
if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2) + 1, (void **) &var) == SUCCESS) {
if (Z_TYPE_PP(var) != IS_LONG) {
zval lval;
lval = **var;
zval_copy_ctor(&lval);
convert_to_long(&lval);
points[i].y = Z_LVAL(lval);
} else {
points[i].y = Z_LVAL_PP(var);
}
}
}
if (filled) {
gdImageFilledPolygon(im, points, npoints, col);
} else {
gdImagePolygon(im, points, npoints, col);
}
efree(points);
RETURN_TRUE;
}
| 166,431 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gss_wrap( OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
gss_buffer_t input_message_buffer,
int *conf_state,
gss_buffer_t output_message_buffer)
{
/* EXPORT DELETE START */
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
status = val_wrap_args(minor_status, context_handle,
conf_req_flag, qop_req,
input_message_buffer, conf_state,
output_message_buffer);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_wrap) {
status = mech->gss_wrap(minor_status,
ctx->internal_ctx_id,
conf_req_flag,
qop_req,
input_message_buffer,
conf_state,
output_message_buffer);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else if (mech->gss_wrap_aead ||
(mech->gss_wrap_iov && mech->gss_wrap_iov_length)) {
status = gssint_wrap_aead(mech,
minor_status,
ctx,
conf_req_flag,
(gss_qop_t)qop_req,
GSS_C_NO_BUFFER,
input_message_buffer,
conf_state,
output_message_buffer);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
/* EXPORT DELETE END */
return (GSS_S_BAD_MECH);
}
Commit Message: Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-415 | gss_wrap( OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
gss_buffer_t input_message_buffer,
int *conf_state,
gss_buffer_t output_message_buffer)
{
/* EXPORT DELETE START */
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
status = val_wrap_args(minor_status, context_handle,
conf_req_flag, qop_req,
input_message_buffer, conf_state,
output_message_buffer);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_wrap) {
status = mech->gss_wrap(minor_status,
ctx->internal_ctx_id,
conf_req_flag,
qop_req,
input_message_buffer,
conf_state,
output_message_buffer);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else if (mech->gss_wrap_aead ||
(mech->gss_wrap_iov && mech->gss_wrap_iov_length)) {
status = gssint_wrap_aead(mech,
minor_status,
ctx,
conf_req_flag,
(gss_qop_t)qop_req,
GSS_C_NO_BUFFER,
input_message_buffer,
conf_state,
output_message_buffer);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
/* EXPORT DELETE END */
return (GSS_S_BAD_MECH);
}
| 168,020 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CoordinatorImpl::RequestGlobalMemoryDump(
MemoryDumpType dump_type,
MemoryDumpLevelOfDetail level_of_detail,
const std::vector<std::string>& allocator_dump_names,
const RequestGlobalMemoryDumpCallback& callback) {
auto adapter = [](const RequestGlobalMemoryDumpCallback& callback,
bool success, uint64_t,
mojom::GlobalMemoryDumpPtr global_memory_dump) {
callback.Run(success, std::move(global_memory_dump));
};
QueuedRequest::Args args(dump_type, level_of_detail, allocator_dump_names,
false /* add_to_trace */, base::kNullProcessId);
RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback));
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <[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::RequestGlobalMemoryDump(
MemoryDumpType dump_type,
MemoryDumpLevelOfDetail level_of_detail,
const std::vector<std::string>& allocator_dump_names,
const RequestGlobalMemoryDumpCallback& callback) {
// Don't allow arbitary processes to obtain VM regions. Only the heap profiler
// is allowed to obtain them using the special method on the different
// interface.
if (level_of_detail ==
MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER) {
bindings_.ReportBadMessage(
"Requested global memory dump using level of detail reserved for the "
"heap profiler.");
return;
}
auto adapter = [](const RequestGlobalMemoryDumpCallback& callback,
bool success, uint64_t,
mojom::GlobalMemoryDumpPtr global_memory_dump) {
callback.Run(success, std::move(global_memory_dump));
};
QueuedRequest::Args args(dump_type, level_of_detail, allocator_dump_names,
false /* add_to_trace */, base::kNullProcessId);
RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback));
}
| 172,915 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_netscreen_hex_dump(FILE_T fh, int pkt_len, const char *cap_int,
const char *cap_dst, struct wtap_pkthdr *phdr, Buffer* buf,
int *err, gchar **err_info)
{
guint8 *pd;
gchar line[NETSCREEN_LINE_LENGTH];
gchar *p;
int n, i = 0, offset = 0;
gchar dststr[13];
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, NETSCREEN_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
while(1) {
/* The last packet is not delimited by an empty line, but by EOF
* So accept EOF as a valid delimiter too
*/
if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) {
break;
}
/*
* Skip blanks.
* The number of blanks is not fixed - for wireless
* interfaces, there may be 14 extra spaces before
* the hex data.
*/
for (p = &line[0]; g_ascii_isspace(*p); p++)
;
/* packets are delimited with empty lines */
if (*p == '\0') {
break;
}
n = parse_single_hex_dump_line(p, pd, offset);
/* the smallest packet has a length of 6 bytes, if
* the first hex-data is less then check whether
* it is a info-line and act accordingly
*/
if (offset == 0 && n < 6) {
if (info_line(line)) {
if (++i <= NETSCREEN_MAX_INFOLINES) {
continue;
}
} else {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
}
/* If there is no more data and the line was not empty,
* then there must be an error in the file
*/
if(n == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
/* Adjust the offset to the data that was just added to the buffer */
offset += n;
/* If there was more hex-data than was announced in the len=x
* header, then then there must be an error in the file
*/
if(offset > pkt_len) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: too much hex-data");
return FALSE;
}
}
/*
* Determine the encapsulation type, based on the
* first 4 characters of the interface name
*
* XXX convert this to a 'case' structure when adding more
* (non-ethernet) interfacetypes
*/
if (strncmp(cap_int, "adsl", 4) == 0) {
/* The ADSL interface can be bridged with or without
* PPP encapsulation. Check whether the first six bytes
* of the hex data are the same as the destination mac
* address in the header. If they are, assume ethernet
* LinkLayer or else PPP
*/
g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x",
pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]);
if (strncmp(dststr, cap_dst, 12) == 0)
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
else
phdr->pkt_encap = WTAP_ENCAP_PPP;
}
else if (strncmp(cap_int, "seri", 4) == 0)
phdr->pkt_encap = WTAP_ENCAP_PPP;
else
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
phdr->caplen = offset;
return TRUE;
}
Commit Message: Fix packet length handling.
Treat the packet length as unsigned - it shouldn't be negative in the
file. If it is, that'll probably cause the sscanf to fail, so we'll
report the file as bad.
Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to
allocate a huge amount of memory, just as we do in other file readers.
Use the now-validated packet size as the length in
ws_buffer_assure_space(), so we are certain to have enough space, and
don't allocate too much space.
Merge the header and packet data parsing routines while we're at it.
Bug: 12396
Change-Id: I7f981f9cdcbea7ecdeb88bfff2f12d875de2244f
Reviewed-on: https://code.wireshark.org/review/15176
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-20 | parse_netscreen_hex_dump(FILE_T fh, int pkt_len, const char *cap_int,
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
while(1) {
/* The last packet is not delimited by an empty line, but by EOF
* So accept EOF as a valid delimiter too
*/
if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) {
break;
}
/*
* Skip blanks.
* The number of blanks is not fixed - for wireless
* interfaces, there may be 14 extra spaces before
* the hex data.
*/
for (p = &line[0]; g_ascii_isspace(*p); p++)
;
/* packets are delimited with empty lines */
if (*p == '\0') {
break;
}
n = parse_single_hex_dump_line(p, pd, offset);
/* the smallest packet has a length of 6 bytes, if
* the first hex-data is less then check whether
* it is a info-line and act accordingly
*/
if (offset == 0 && n < 6) {
if (info_line(line)) {
if (++i <= NETSCREEN_MAX_INFOLINES) {
continue;
}
} else {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
}
/* If there is no more data and the line was not empty,
* then there must be an error in the file
*/
if (n == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
/* Adjust the offset to the data that was just added to the buffer */
offset += n;
/* If there was more hex-data than was announced in the len=x
* header, then then there must be an error in the file
*/
if (offset > pkt_len) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: too much hex-data");
return FALSE;
}
}
/*
* Determine the encapsulation type, based on the
* first 4 characters of the interface name
*
* XXX convert this to a 'case' structure when adding more
* (non-ethernet) interfacetypes
*/
if (strncmp(cap_int, "adsl", 4) == 0) {
/* The ADSL interface can be bridged with or without
* PPP encapsulation. Check whether the first six bytes
* of the hex data are the same as the destination mac
* address in the header. If they are, assume ethernet
* LinkLayer or else PPP
*/
g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x",
pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]);
if (strncmp(dststr, cap_dst, 12) == 0)
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
else
phdr->pkt_encap = WTAP_ENCAP_PPP;
}
else if (strncmp(cap_int, "seri", 4) == 0)
phdr->pkt_encap = WTAP_ENCAP_PPP;
else
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
phdr->caplen = offset;
return TRUE;
}
| 167,148 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ContainerNode::parserInsertBefore(PassRefPtrWillBeRawPtr<Node> newChild, Node& nextChild)
{
ASSERT(newChild);
ASSERT(nextChild.parentNode() == this);
ASSERT(!newChild->isDocumentFragment());
ASSERT(!isHTMLTemplateElement(this));
if (nextChild.previousSibling() == newChild || &nextChild == newChild) // nothing to do
return;
if (!checkParserAcceptChild(*newChild))
return;
RefPtrWillBeRawPtr<Node> protect(this);
while (RefPtrWillBeRawPtr<ContainerNode> parent = newChild->parentNode())
parent->parserRemoveChild(*newChild);
if (document() != newChild->document())
document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
{
EventDispatchForbiddenScope assertNoEventDispatch;
ScriptForbiddenScope forbidScript;
treeScope().adoptIfNeeded(*newChild);
insertBeforeCommon(nextChild, *newChild);
newChild->updateAncestorConnectedSubframeCountForInsertion();
ChildListMutationScope(*this).childAdded(*newChild);
}
notifyNodeInserted(*newChild, ChildrenChangeSourceParser);
}
Commit Message: parserInsertBefore: Bail out if the parent no longer contains the child.
nextChild may be removed from the DOM tree during the
|parserRemoveChild(*newChild)| call which triggers unload events of newChild's
descendant iframes. In order to maintain the integrity of the DOM tree, the
insertion of newChild must be aborted in this case.
This patch adds a return statement that rectifies the behavior in this
edge case.
BUG=519558
Review URL: https://codereview.chromium.org/1283263002
git-svn-id: svn://svn.chromium.org/blink/trunk@200690 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264 | void ContainerNode::parserInsertBefore(PassRefPtrWillBeRawPtr<Node> newChild, Node& nextChild)
{
ASSERT(newChild);
ASSERT(nextChild.parentNode() == this);
ASSERT(!newChild->isDocumentFragment());
ASSERT(!isHTMLTemplateElement(this));
if (nextChild.previousSibling() == newChild || &nextChild == newChild) // nothing to do
return;
if (!checkParserAcceptChild(*newChild))
return;
RefPtrWillBeRawPtr<Node> protect(this);
while (RefPtrWillBeRawPtr<ContainerNode> parent = newChild->parentNode())
parent->parserRemoveChild(*newChild);
if (nextChild.parentNode() != this)
return;
if (document() != newChild->document())
document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
{
EventDispatchForbiddenScope assertNoEventDispatch;
ScriptForbiddenScope forbidScript;
treeScope().adoptIfNeeded(*newChild);
insertBeforeCommon(nextChild, *newChild);
newChild->updateAncestorConnectedSubframeCountForInsertion();
ChildListMutationScope(*this).childAdded(*newChild);
}
notifyNodeInserted(*newChild, ChildrenChangeSourceParser);
}
| 171,850 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ImageResource::IsAccessAllowed(
const SecurityOrigin* security_origin,
ImageResourceInfo::DoesCurrentFrameHaveSingleSecurityOrigin
does_current_frame_has_single_security_origin) const {
if (GetCORSStatus() == CORSStatus::kServiceWorkerOpaque)
return false;
if (does_current_frame_has_single_security_origin !=
ImageResourceInfo::kHasSingleSecurityOrigin)
return false;
if (IsSameOriginOrCORSSuccessful())
return true;
return !security_origin->TaintsCanvas(GetResponse().Url());
}
Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin
Partial revert of https://chromium-review.googlesource.com/535694.
Bug: 799477
Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3
Reviewed-on: https://chromium-review.googlesource.com/898427
Commit-Queue: Hiroshige Hayashizaki <[email protected]>
Reviewed-by: Kouhei Ueno <[email protected]>
Reviewed-by: Yutaka Hirano <[email protected]>
Reviewed-by: Takeshi Yoshino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#535176}
CWE ID: CWE-200 | bool ImageResource::IsAccessAllowed(
const SecurityOrigin* security_origin,
ImageResourceInfo::DoesCurrentFrameHaveSingleSecurityOrigin
does_current_frame_has_single_security_origin) const {
if (GetResponse().WasFetchedViaServiceWorker())
return GetCORSStatus() != CORSStatus::kServiceWorkerOpaque;
if (does_current_frame_has_single_security_origin !=
ImageResourceInfo::kHasSingleSecurityOrigin)
return false;
DCHECK(security_origin);
if (PassesAccessControlCheck(*security_origin))
return true;
return !security_origin->TaintsCanvas(GetResponse().Url());
}
| 172,888 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: asmlinkage long compat_sys_recvmmsg(int fd, struct compat_mmsghdr __user *mmsg,
unsigned int vlen, unsigned int flags,
struct compat_timespec __user *timeout)
{
int datagrams;
struct timespec ktspec;
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
if (COMPAT_USE_64BIT_TIME)
return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT,
(struct timespec *) timeout);
if (timeout == NULL)
return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT, NULL);
if (get_compat_timespec(&ktspec, timeout))
return -EFAULT;
datagrams = __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT, &ktspec);
if (datagrams > 0 && put_compat_timespec(&ktspec, timeout))
datagrams = -EFAULT;
return datagrams;
}
Commit Message: x86, x32: Correct invalid use of user timespec in the kernel
The x32 case for the recvmsg() timout handling is broken:
asmlinkage long compat_sys_recvmmsg(int fd, struct compat_mmsghdr __user *mmsg,
unsigned int vlen, unsigned int flags,
struct compat_timespec __user *timeout)
{
int datagrams;
struct timespec ktspec;
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
if (COMPAT_USE_64BIT_TIME)
return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT,
(struct timespec *) timeout);
...
The timeout pointer parameter is provided by userland (hence the __user
annotation) but for x32 syscalls it's simply cast to a kernel pointer
and is passed to __sys_recvmmsg which will eventually directly
dereference it for both reading and writing. Other callers to
__sys_recvmmsg properly copy from userland to the kernel first.
The bug was introduced by commit ee4fa23c4bfc ("compat: Use
COMPAT_USE_64BIT_TIME in net/compat.c") and should affect all kernels
since 3.4 (and perhaps vendor kernels if they backported x32 support
along with this code).
Note that CONFIG_X86_X32_ABI gets enabled at build time and only if
CONFIG_X86_X32 is enabled and ld can build x32 executables.
Other uses of COMPAT_USE_64BIT_TIME seem fine.
This addresses CVE-2014-0038.
Signed-off-by: PaX Team <[email protected]>
Signed-off-by: H. Peter Anvin <[email protected]>
Cc: <[email protected]> # v3.4+
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-20 | asmlinkage long compat_sys_recvmmsg(int fd, struct compat_mmsghdr __user *mmsg,
unsigned int vlen, unsigned int flags,
struct compat_timespec __user *timeout)
{
int datagrams;
struct timespec ktspec;
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
if (timeout == NULL)
return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT, NULL);
if (compat_get_timespec(&ktspec, timeout))
return -EFAULT;
datagrams = __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT, &ktspec);
if (datagrams > 0 && compat_put_timespec(&ktspec, timeout))
datagrams = -EFAULT;
return datagrams;
}
| 166,467 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: XRRGetOutputInfo (Display *dpy, XRRScreenResources *resources, RROutput output)
{
XExtDisplayInfo *info = XRRFindDisplay(dpy);
xRRGetOutputInfoReply rep;
xRRGetOutputInfoReq *req;
int nbytes, nbytesRead, rbytes;
XRROutputInfo *xoi;
RRCheckExtension (dpy, info, NULL);
LockDisplay (dpy);
GetReq (RRGetOutputInfo, req);
req->reqType = info->codes->major_opcode;
req->randrReqType = X_RRGetOutputInfo;
req->output = output;
req->configTimestamp = resources->configTimestamp;
if (!_XReply (dpy, (xReply *) &rep, OutputInfoExtra >> 2, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
return NULL;
}
nbytes = ((long) (rep.length) << 2) - OutputInfoExtra;
nbytesRead = (long) (rep.nCrtcs * 4 +
rep.nCrtcs * sizeof (RRCrtc) +
rep.nModes * sizeof (RRMode) +
rep.nClones * sizeof (RROutput) +
rep.nameLength + 1); /* '\0' terminate name */
xoi = (XRROutputInfo *) Xmalloc(rbytes);
if (xoi == NULL) {
_XEatDataWords (dpy, rep.length - (OutputInfoExtra >> 2));
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
xoi->timestamp = rep.timestamp;
xoi->crtc = rep.crtc;
xoi->mm_width = rep.mmWidth;
xoi->mm_height = rep.mmHeight;
xoi->connection = rep.connection;
xoi->subpixel_order = rep.subpixelOrder;
xoi->ncrtc = rep.nCrtcs;
xoi->crtcs = (RRCrtc *) (xoi + 1);
xoi->nmode = rep.nModes;
xoi->npreferred = rep.nPreferred;
xoi->modes = (RRMode *) (xoi->crtcs + rep.nCrtcs);
xoi->nclone = rep.nClones;
xoi->clones = (RROutput *) (xoi->modes + rep.nModes);
xoi->name = (char *) (xoi->clones + rep.nClones);
_XRead32 (dpy, (long *) xoi->crtcs, rep.nCrtcs << 2);
_XRead32 (dpy, (long *) xoi->modes, rep.nModes << 2);
_XRead32 (dpy, (long *) xoi->clones, rep.nClones << 2);
/*
* Read name and '\0' terminate
*/
_XReadPad (dpy, xoi->name, rep.nameLength);
xoi->name[rep.nameLength] = '\0';
xoi->nameLen = rep.nameLength;
/*
* Skip any extra data
*/
if (nbytes > nbytesRead)
_XEatData (dpy, (unsigned long) (nbytes - nbytesRead));
UnlockDisplay (dpy);
SyncHandle ();
return (XRROutputInfo *) xoi;
}
Commit Message:
CWE ID: CWE-787 | XRRGetOutputInfo (Display *dpy, XRRScreenResources *resources, RROutput output)
{
XExtDisplayInfo *info = XRRFindDisplay(dpy);
xRRGetOutputInfoReply rep;
xRRGetOutputInfoReq *req;
int nbytes, nbytesRead, rbytes;
XRROutputInfo *xoi;
RRCheckExtension (dpy, info, NULL);
LockDisplay (dpy);
GetReq (RRGetOutputInfo, req);
req->reqType = info->codes->major_opcode;
req->randrReqType = X_RRGetOutputInfo;
req->output = output;
req->configTimestamp = resources->configTimestamp;
if (!_XReply (dpy, (xReply *) &rep, OutputInfoExtra >> 2, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
return NULL;
}
if (rep.length > INT_MAX >> 2 || rep.length < (OutputInfoExtra >> 2))
{
if (rep.length > (OutputInfoExtra >> 2))
_XEatDataWords (dpy, rep.length - (OutputInfoExtra >> 2));
else
_XEatDataWords (dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
nbytes = ((long) (rep.length) << 2) - OutputInfoExtra;
nbytesRead = (long) (rep.nCrtcs * 4 +
rep.nCrtcs * sizeof (RRCrtc) +
rep.nModes * sizeof (RRMode) +
rep.nClones * sizeof (RROutput) +
rep.nameLength + 1); /* '\0' terminate name */
xoi = (XRROutputInfo *) Xmalloc(rbytes);
if (xoi == NULL) {
_XEatDataWords (dpy, rep.length - (OutputInfoExtra >> 2));
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
xoi->timestamp = rep.timestamp;
xoi->crtc = rep.crtc;
xoi->mm_width = rep.mmWidth;
xoi->mm_height = rep.mmHeight;
xoi->connection = rep.connection;
xoi->subpixel_order = rep.subpixelOrder;
xoi->ncrtc = rep.nCrtcs;
xoi->crtcs = (RRCrtc *) (xoi + 1);
xoi->nmode = rep.nModes;
xoi->npreferred = rep.nPreferred;
xoi->modes = (RRMode *) (xoi->crtcs + rep.nCrtcs);
xoi->nclone = rep.nClones;
xoi->clones = (RROutput *) (xoi->modes + rep.nModes);
xoi->name = (char *) (xoi->clones + rep.nClones);
_XRead32 (dpy, (long *) xoi->crtcs, rep.nCrtcs << 2);
_XRead32 (dpy, (long *) xoi->modes, rep.nModes << 2);
_XRead32 (dpy, (long *) xoi->clones, rep.nClones << 2);
/*
* Read name and '\0' terminate
*/
_XReadPad (dpy, xoi->name, rep.nameLength);
xoi->name[rep.nameLength] = '\0';
xoi->nameLen = rep.nameLength;
/*
* Skip any extra data
*/
if (nbytes > nbytesRead)
_XEatData (dpy, (unsigned long) (nbytes - nbytesRead));
UnlockDisplay (dpy);
SyncHandle ();
return (XRROutputInfo *) xoi;
}
| 164,915 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,
size_t minimum)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
ssize_t bytes_avail;
if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {
/* Copy mode. */
/*
* Note: '1' here is a performance optimization.
* Recall that the decompression layer returns a count of
* available bytes; asking for more than that forces the
* decompressor to combine reads by copying data.
*/
*buff = __archive_read_ahead(a, 1, &bytes_avail);
if (bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file data");
return (ARCHIVE_FATAL);
}
if ((size_t)bytes_avail >
zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
if ((size_t)bytes_avail > size)
bytes_avail = (ssize_t)size;
zip->pack_stream_bytes_unconsumed = bytes_avail;
} else if (zip->uncompressed_buffer_pointer == NULL) {
/* Decompression has failed. */
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
} else {
/* Packed mode. */
if (minimum > zip->uncompressed_buffer_bytes_remaining) {
/*
* If remaining uncompressed data size is less than
* the minimum size, fill the buffer up to the
* minimum size.
*/
if (extract_pack_stream(a, minimum) < 0)
return (ARCHIVE_FATAL);
}
if (size > zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
else
bytes_avail = (ssize_t)size;
*buff = zip->uncompressed_buffer_pointer;
zip->uncompressed_buffer_pointer += bytes_avail;
}
zip->uncompressed_buffer_bytes_remaining -= bytes_avail;
return (bytes_avail);
}
Commit Message: 7zip: fix crash when parsing certain archives
Fuzzing with CRCs disabled revealed that a call to get_uncompressed_data()
would sometimes fail to return at least 'minimum' bytes. This can cause
the crc32() invocation in header_bytes to read off into invalid memory.
A specially crafted archive can use this to cause a crash.
An ASAN trace is below, but ASAN is not required - an uninstrumented
binary will also crash.
==7719==ERROR: AddressSanitizer: SEGV on unknown address 0x631000040000 (pc 0x7fbdb3b3ec1d bp 0x7ffe77a51310 sp 0x7ffe77a51150 T0)
==7719==The signal is caused by a READ memory access.
#0 0x7fbdb3b3ec1c in crc32_z (/lib/x86_64-linux-gnu/libz.so.1+0x2c1c)
#1 0x84f5eb in header_bytes (/tmp/libarchive/bsdtar+0x84f5eb)
#2 0x856156 in read_Header (/tmp/libarchive/bsdtar+0x856156)
#3 0x84e134 in slurp_central_directory (/tmp/libarchive/bsdtar+0x84e134)
#4 0x849690 in archive_read_format_7zip_read_header (/tmp/libarchive/bsdtar+0x849690)
#5 0x5713b7 in _archive_read_next_header2 (/tmp/libarchive/bsdtar+0x5713b7)
#6 0x570e63 in _archive_read_next_header (/tmp/libarchive/bsdtar+0x570e63)
#7 0x6f08bd in archive_read_next_header (/tmp/libarchive/bsdtar+0x6f08bd)
#8 0x52373f in read_archive (/tmp/libarchive/bsdtar+0x52373f)
#9 0x5257be in tar_mode_x (/tmp/libarchive/bsdtar+0x5257be)
#10 0x51daeb in main (/tmp/libarchive/bsdtar+0x51daeb)
#11 0x7fbdb27cab96 in __libc_start_main /build/glibc-OTsEL5/glibc-2.27/csu/../csu/libc-start.c:310
#12 0x41dd09 in _start (/tmp/libarchive/bsdtar+0x41dd09)
This was primarly done with afl and FairFuzz. Some early corpus entries
may have been generated by qsym.
CWE ID: CWE-125 | get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,
size_t minimum)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
ssize_t bytes_avail;
if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {
/* Copy mode. */
*buff = __archive_read_ahead(a, minimum, &bytes_avail);
if (bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file data");
return (ARCHIVE_FATAL);
}
if ((size_t)bytes_avail >
zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
if ((size_t)bytes_avail > size)
bytes_avail = (ssize_t)size;
zip->pack_stream_bytes_unconsumed = bytes_avail;
} else if (zip->uncompressed_buffer_pointer == NULL) {
/* Decompression has failed. */
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
} else {
/* Packed mode. */
if (minimum > zip->uncompressed_buffer_bytes_remaining) {
/*
* If remaining uncompressed data size is less than
* the minimum size, fill the buffer up to the
* minimum size.
*/
if (extract_pack_stream(a, minimum) < 0)
return (ARCHIVE_FATAL);
}
if (size > zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
else
bytes_avail = (ssize_t)size;
*buff = zip->uncompressed_buffer_pointer;
zip->uncompressed_buffer_pointer += bytes_avail;
}
zip->uncompressed_buffer_bytes_remaining -= bytes_avail;
return (bytes_avail);
}
| 169,484 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DecoderTest::RunLoop(CompressedVideoSource *video) {
vpx_codec_dec_cfg_t dec_cfg = {0};
Decoder* const decoder = codec_->CreateDecoder(dec_cfg, 0);
ASSERT_TRUE(decoder != NULL);
for (video->Begin(); video->cxdata(); video->Next()) {
PreDecodeFrameHook(*video, decoder);
vpx_codec_err_t res_dec = decoder->DecodeFrame(video->cxdata(),
video->frame_size());
ASSERT_EQ(VPX_CODEC_OK, res_dec) << decoder->DecodeError();
DxDataIterator dec_iter = decoder->GetDxData();
const vpx_image_t *img = NULL;
while ((img = dec_iter.Next()))
DecompressedFrameHook(*img, video->frame_number());
}
delete decoder;
}
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 DecoderTest::RunLoop(CompressedVideoSource *video) {
bool Decoder::IsVP8() const {
const char *codec_name = GetDecoderName();
return strncmp(kVP8Name, codec_name, sizeof(kVP8Name) - 1) == 0;
}
void DecoderTest::HandlePeekResult(Decoder *const decoder,
CompressedVideoSource *video,
const vpx_codec_err_t res_peek) {
const bool is_vp8 = decoder->IsVP8();
if (is_vp8) {
/* Vp8's implementation of PeekStream returns an error if the frame you
* pass it is not a keyframe, so we only expect VPX_CODEC_OK on the first
* frame, which must be a keyframe. */
if (video->frame_number() == 0)
ASSERT_EQ(VPX_CODEC_OK, res_peek) << "Peek return failed: "
<< vpx_codec_err_to_string(res_peek);
} else {
/* The Vp9 implementation of PeekStream returns an error only if the
* data passed to it isn't a valid Vp9 chunk. */
ASSERT_EQ(VPX_CODEC_OK, res_peek) << "Peek return failed: "
<< vpx_codec_err_to_string(res_peek);
}
}
void DecoderTest::RunLoop(CompressedVideoSource *video,
const vpx_codec_dec_cfg_t &dec_cfg) {
Decoder* const decoder = codec_->CreateDecoder(dec_cfg, flags_, 0);
ASSERT_TRUE(decoder != NULL);
bool end_of_file = false;
for (video->Begin(); !::testing::Test::HasFailure() && !end_of_file;
video->Next()) {
PreDecodeFrameHook(*video, decoder);
vpx_codec_stream_info_t stream_info;
stream_info.sz = sizeof(stream_info);
if (video->cxdata() != NULL) {
const vpx_codec_err_t res_peek = decoder->PeekStream(video->cxdata(),
video->frame_size(),
&stream_info);
HandlePeekResult(decoder, video, res_peek);
ASSERT_FALSE(::testing::Test::HasFailure());
vpx_codec_err_t res_dec = decoder->DecodeFrame(video->cxdata(),
video->frame_size());
if (!HandleDecodeResult(res_dec, *video, decoder))
break;
} else {
// Signal end of the file to the decoder.
const vpx_codec_err_t res_dec = decoder->DecodeFrame(NULL, 0);
ASSERT_EQ(VPX_CODEC_OK, res_dec) << decoder->DecodeError();
end_of_file = true;
}
DxDataIterator dec_iter = decoder->GetDxData();
const vpx_image_t *img = NULL;
while ((img = dec_iter.Next()))
DecompressedFrameHook(*img, video->frame_number());
}
delete decoder;
}
| 174,535 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PassRefPtr<DocumentFragment> createFragmentFromSource(const String& markup, Element* contextElement, ExceptionCode& ec)
{
Document* document = contextElement->document();
RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
if (document->isHTMLDocument()) {
fragment->parseHTML(markup, contextElement);
return fragment;
}
bool wasValid = fragment->parseXML(markup, contextElement);
if (!wasValid) {
ec = INVALID_STATE_ERR;
return 0;
}
return fragment.release();
}
Commit Message: There are too many poorly named functions to create a fragment from markup
https://bugs.webkit.org/show_bug.cgi?id=87339
Reviewed by Eric Seidel.
Source/WebCore:
Moved all functions that create a fragment from markup to markup.h/cpp.
There should be no behavioral change.
* dom/Range.cpp:
(WebCore::Range::createContextualFragment):
* dom/Range.h: Removed createDocumentFragmentForElement.
* dom/ShadowRoot.cpp:
(WebCore::ShadowRoot::setInnerHTML):
* editing/markup.cpp:
(WebCore::createFragmentFromMarkup):
(WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource.
(WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor.
(WebCore::removeElementPreservingChildren): Moved from Range.
(WebCore::createContextualFragment): Ditto.
* editing/markup.h:
* html/HTMLElement.cpp:
(WebCore::HTMLElement::setInnerHTML):
(WebCore::HTMLElement::setOuterHTML):
(WebCore::HTMLElement::insertAdjacentHTML):
* inspector/DOMPatchSupport.cpp:
(WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using
one of the functions listed in markup.h
* xml/XSLTProcessor.cpp:
(WebCore::XSLTProcessor::transformToFragment):
Source/WebKit/qt:
Replace calls to Range::createDocumentFragmentForElement by calls to
createContextualDocumentFragment.
* Api/qwebelement.cpp:
(QWebElement::appendInside):
(QWebElement::prependInside):
(QWebElement::prependOutside):
(QWebElement::appendOutside):
(QWebElement::encloseContentsWith):
(QWebElement::encloseWith):
git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264 | PassRefPtr<DocumentFragment> createFragmentFromSource(const String& markup, Element* contextElement, ExceptionCode& ec)
PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ExceptionCode& ec)
{
Document* document = contextElement->document();
RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
if (document->isHTMLDocument()) {
fragment->parseHTML(markup, contextElement);
return fragment;
}
bool wasValid = fragment->parseXML(markup, contextElement);
if (!wasValid) {
ec = INVALID_STATE_ERR;
return 0;
}
return fragment.release();
}
| 170,439 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool NavigateToUrlWithEdge(const base::string16& url) {
base::string16 protocol_url = L"microsoft-edge:" + url;
SHELLEXECUTEINFO info = { sizeof(info) };
info.fMask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI;
info.lpVerb = L"open";
info.lpFile = protocol_url.c_str();
info.nShow = SW_SHOWNORMAL;
if (::ShellExecuteEx(&info))
return true;
PLOG(ERROR) << "Failed to launch Edge for uninstall survey";
return false;
}
Commit Message: Remove use of SEE_MASK_FLAG_NO_UI from Chrome Windows installer.
This flag was originally added to ui::base::win to suppress a specific
error message when attempting to open a file via the shell using the
"open" verb. The flag has additional side-effects and shouldn't be used
when invoking ShellExecute().
[email protected]
Bug: 819809
Change-Id: I7db2344982dd206c85a73928e906c21e06a47a9e
Reviewed-on: https://chromium-review.googlesource.com/966964
Commit-Queue: Greg Thompson <[email protected]>
Reviewed-by: Greg Thompson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#544012}
CWE ID: CWE-20 | bool NavigateToUrlWithEdge(const base::string16& url) {
base::string16 protocol_url = L"microsoft-edge:" + url;
SHELLEXECUTEINFO info = { sizeof(info) };
info.fMask = SEE_MASK_NOASYNC;
info.lpVerb = L"open";
info.lpFile = protocol_url.c_str();
info.nShow = SW_SHOWNORMAL;
if (::ShellExecuteEx(&info))
return true;
PLOG(ERROR) << "Failed to launch Edge for uninstall survey";
return false;
}
| 172,793 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PlatformSensorAndroid::PlatformSensorAndroid(
mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
PlatformSensorProvider* provider,
const JavaRef<jobject>& java_sensor)
: PlatformSensor(type, std::move(mapping), provider) {
JNIEnv* env = AttachCurrentThread();
j_object_.Reset(java_sensor);
Java_PlatformSensor_initPlatformSensorAndroid(env, j_object_,
reinterpret_cast<jlong>(this));
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | PlatformSensorAndroid::PlatformSensorAndroid(
mojom::SensorType type,
SensorReadingSharedBuffer* reading_buffer,
PlatformSensorProvider* provider,
const JavaRef<jobject>& java_sensor)
: PlatformSensor(type, reading_buffer, provider) {
JNIEnv* env = AttachCurrentThread();
j_object_.Reset(java_sensor);
Java_PlatformSensor_initPlatformSensorAndroid(env, j_object_,
reinterpret_cast<jlong>(this));
}
| 172,826 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: size_t OpenMP4SourceUDTA(char *filename)
{
mp4object *mp4 = (mp4object *)malloc(sizeof(mp4object));
if (mp4 == NULL) return 0;
memset(mp4, 0, sizeof(mp4object));
#ifdef _WINDOWS
fopen_s(&mp4->mediafp, filename, "rb");
#else
mp4->mediafp = fopen(filename, "rb");
#endif
if (mp4->mediafp)
{
uint32_t qttag, qtsize32, len;
int32_t nest = 0;
uint64_t nestsize[MAX_NEST_LEVEL] = { 0 };
uint64_t lastsize = 0, qtsize;
do
{
len = fread(&qtsize32, 1, 4, mp4->mediafp);
len += fread(&qttag, 1, 4, mp4->mediafp);
if (len == 8)
{
if (!GPMF_VALID_FOURCC(qttag))
{
LONGSEEK(mp4->mediafp, lastsize - 8 - 8, SEEK_CUR);
NESTSIZE(lastsize - 8);
continue;
}
qtsize32 = BYTESWAP32(qtsize32);
if (qtsize32 == 1) // 64-bit Atom
{
fread(&qtsize, 1, 8, mp4->mediafp);
qtsize = BYTESWAP64(qtsize) - 8;
}
else
qtsize = qtsize32;
nest++;
if (qtsize < 8) break;
if (nest >= MAX_NEST_LEVEL) break;
nestsize[nest] = qtsize;
lastsize = qtsize;
if (qttag == MAKEID('m', 'd', 'a', 't') ||
qttag == MAKEID('f', 't', 'y', 'p'))
{
LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);
NESTSIZE(qtsize);
continue;
}
if (qttag == MAKEID('G', 'P', 'M', 'F'))
{
mp4->videolength += 1.0;
mp4->metadatalength += 1.0;
mp4->indexcount = (int)mp4->metadatalength;
mp4->metasizes = (uint32_t *)malloc(mp4->indexcount * 4 + 4); memset(mp4->metasizes, 0, mp4->indexcount * 4 + 4);
mp4->metaoffsets = (uint64_t *)malloc(mp4->indexcount * 8 + 8); memset(mp4->metaoffsets, 0, mp4->indexcount * 8 + 8);
mp4->metasizes[0] = (int)qtsize - 8;
mp4->metaoffsets[0] = ftell(mp4->mediafp);
mp4->metasize_count = 1;
return (size_t)mp4; // not an MP4, RAW GPMF which has not inherent timing, assigning a during of 1second.
}
if (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms
qttag != MAKEID('u', 'd', 't', 'a'))
{
LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR);
NESTSIZE(qtsize);
continue;
}
else
{
NESTSIZE(8);
}
}
} while (len > 0);
}
return (size_t)mp4;
}
Commit Message: fixed many security issues with the too crude mp4 reader
CWE ID: CWE-787 | size_t OpenMP4SourceUDTA(char *filename)
{
mp4object *mp4 = (mp4object *)malloc(sizeof(mp4object));
if (mp4 == NULL) return 0;
memset(mp4, 0, sizeof(mp4object));
#ifdef _WINDOWS
fopen_s(&mp4->mediafp, filename, "rb");
#else
mp4->mediafp = fopen(filename, "rb");
#endif
if (mp4->mediafp)
{
uint32_t qttag, qtsize32;
size_t len;
int32_t nest = 0;
uint64_t nestsize[MAX_NEST_LEVEL] = { 0 };
uint64_t lastsize = 0, qtsize;
do
{
len = fread(&qtsize32, 1, 4, mp4->mediafp);
len += fread(&qttag, 1, 4, mp4->mediafp);
if (len == 8)
{
if (!GPMF_VALID_FOURCC(qttag))
{
LongSeek(mp4, lastsize - 8 - 8);
NESTSIZE(lastsize - 8);
continue;
}
qtsize32 = BYTESWAP32(qtsize32);
if (qtsize32 == 1) // 64-bit Atom
{
fread(&qtsize, 1, 8, mp4->mediafp);
qtsize = BYTESWAP64(qtsize) - 8;
}
else
qtsize = qtsize32;
nest++;
if (qtsize < 8) break;
if (nest >= MAX_NEST_LEVEL) break;
nestsize[nest] = qtsize;
lastsize = qtsize;
if (qttag == MAKEID('m', 'd', 'a', 't') ||
qttag == MAKEID('f', 't', 'y', 'p'))
{
LongSeek(mp4, qtsize - 8);
NESTSIZE(qtsize);
continue;
}
if (qttag == MAKEID('G', 'P', 'M', 'F'))
{
mp4->videolength += 1.0;
mp4->metadatalength += 1.0;
mp4->indexcount = (int)mp4->metadatalength;
mp4->metasizes = (uint32_t *)malloc(mp4->indexcount * 4 + 4); memset(mp4->metasizes, 0, mp4->indexcount * 4 + 4);
mp4->metaoffsets = (uint64_t *)malloc(mp4->indexcount * 8 + 8); memset(mp4->metaoffsets, 0, mp4->indexcount * 8 + 8);
mp4->metasizes[0] = (int)qtsize - 8;
mp4->metaoffsets[0] = ftell(mp4->mediafp);
mp4->metasize_count = 1;
return (size_t)mp4; // not an MP4, RAW GPMF which has not inherent timing, assigning a during of 1second.
}
if (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms
qttag != MAKEID('u', 'd', 't', 'a'))
{
LongSeek(mp4, qtsize - 8);
NESTSIZE(qtsize);
continue;
}
else
{
NESTSIZE(8);
}
}
} while (len > 0);
}
return (size_t)mp4;
}
| 169,551 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ModuleExport MagickBooleanType ReadPSDLayers(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count,
j,
number_layers;
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
status=MagickFalse;
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
return(MagickTrue);
else
{
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0))
size=GetPSDSize(psd_info,image);
else
return(MagickTrue);
}
}
status=MagickTrue;
if (size != 0)
{
layer_info=(LayerInfo *) NULL;
number_layers=(short) ReadBlobShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->matte=MagickTrue;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(layer_info,0,(size_t) number_layers*
sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
x,
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
layer_info[i].page.y=ReadBlobSignedLong(image);
layer_info[i].page.x=ReadBlobSignedLong(image);
y=ReadBlobSignedLong(image);
x=ReadBlobSignedLong(image);
layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);
layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
(void) ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
ReversePSDString(image,layer_info[i].blendkey,4);
layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=ReadBlobSignedLong(image);
layer_info[i].mask.page.x=ReadBlobSignedLong(image);
layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,
(double) layer_info[i].mask.page.height,(double)
((MagickOffsetType) length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
/*
We read it, but don't use it...
*/
for (j=0; j < (ssize_t) length; j+=8)
{
size_t blend_source=ReadBlobLong(image);
size_t blend_dest=ReadBlobLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" source(%x), dest(%x)",(unsigned int)
blend_source,(unsigned int) blend_dest);
}
}
/*
Layer name.
*/
length=(MagickSizeType) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
if ((length % 4) != 0)
{
length=4-(length % 4);
combined_length+=length;
/* Skip over the padding of the layer name */
if (DiscardBlobBytes(image,length) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
length=(MagickSizeType) size-combined_length;
if (length > 0)
{
unsigned char
*info;
layer_info[i].info=AcquireStringInfo((const size_t) length);
info=GetStringInfoDatum(layer_info[i].info);
(void) ReadBlob(image,(const size_t) length,info);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) ||
(layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
if (layer_info[i].info != (StringInfo *) NULL)
{
(void) SetImageProfile(layer_info[i].image,"psd:additional-info",
layer_info[i].info);
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
}
if (image_info->ping == MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=0; j < layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],
exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)
number_layers);
if (status == MagickFalse)
break;
}
}
if (status != MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers > 0)
{
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
}
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
}
return(status);
}
Commit Message: Fixed memory leak.
CWE ID: CWE-400 | ModuleExport MagickBooleanType ReadPSDLayers(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count,
j,
number_layers;
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
status=MagickFalse;
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
return(MagickTrue);
else
{
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0))
size=GetPSDSize(psd_info,image);
else
return(MagickTrue);
}
}
status=MagickTrue;
if (size != 0)
{
layer_info=(LayerInfo *) NULL;
number_layers=(short) ReadBlobShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->matte=MagickTrue;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(layer_info,0,(size_t) number_layers*
sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
x,
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
layer_info[i].page.y=ReadBlobSignedLong(image);
layer_info[i].page.x=ReadBlobSignedLong(image);
y=ReadBlobSignedLong(image);
x=ReadBlobSignedLong(image);
layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);
layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
(void) ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
ReversePSDString(image,layer_info[i].blendkey,4);
layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=ReadBlobSignedLong(image);
layer_info[i].mask.page.x=ReadBlobSignedLong(image);
layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,
(double) layer_info[i].mask.page.height,(double)
((MagickOffsetType) length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
/*
We read it, but don't use it...
*/
for (j=0; j < (ssize_t) length; j+=8)
{
size_t blend_source=ReadBlobLong(image);
size_t blend_dest=ReadBlobLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" source(%x), dest(%x)",(unsigned int)
blend_source,(unsigned int) blend_dest);
}
}
/*
Layer name.
*/
length=(MagickSizeType) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
if ((length % 4) != 0)
{
length=4-(length % 4);
combined_length+=length;
/* Skip over the padding of the layer name */
if (DiscardBlobBytes(image,length) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
length=(MagickSizeType) size-combined_length;
if (length > 0)
{
unsigned char
*info;
layer_info[i].info=AcquireStringInfo((const size_t) length);
info=GetStringInfoDatum(layer_info[i].info);
(void) ReadBlob(image,(const size_t) length,info);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) ||
(layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
if (layer_info[i].info != (StringInfo *) NULL)
{
(void) SetImageProfile(layer_info[i].image,"psd:additional-info",
layer_info[i].info);
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
}
if (image_info->ping == MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=0; j < layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],
exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)
number_layers);
if (status == MagickFalse)
break;
}
}
if (status != MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers > 0)
{
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
}
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
}
return(status);
}
| 168,631 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (mTimeToSample != NULL || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
mTimeToSample = new uint32_t[mTimeToSampleCount * 2];
size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2;
if (mDataSource->readAt(
data_offset + 8, mTimeToSample, size) < (ssize_t)size) {
return ERROR_IO;
}
for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) {
mTimeToSample[i] = ntohl(mTimeToSample[i]);
}
return OK;
}
Commit Message: SampleTable: check integer overflow during table alloc
Bug: 15328708
Bug: 15342615
Bug: 15342751
Change-Id: I6bb110a1eba46506799c73be8ff9a4f71c7e7053
CWE ID: CWE-189 | status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (mTimeToSample != NULL || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
uint64_t allocSize = mTimeToSampleCount * 2 * sizeof(uint32_t);
if (allocSize > SIZE_MAX) {
return ERROR_OUT_OF_RANGE;
}
mTimeToSample = new uint32_t[mTimeToSampleCount * 2];
size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2;
if (mDataSource->readAt(
data_offset + 8, mTimeToSample, size) < (ssize_t)size) {
return ERROR_IO;
}
for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) {
mTimeToSample[i] = ntohl(mTimeToSample[i]);
}
return OK;
}
| 173,377 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_METHOD(snmp, setSecurity)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = "";
int a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0;
int argc = ZEND_NUM_ARGS();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) {
RETURN_FALSE;
}
if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7 TSRMLS_CC)) {
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-416 | PHP_METHOD(snmp, setSecurity)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = "";
int a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0;
int argc = ZEND_NUM_ARGS();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) {
RETURN_FALSE;
}
if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7 TSRMLS_CC)) {
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
RETURN_TRUE;
}
| 164,973 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int walk_hugetlb_range(unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->vma;
struct hstate *h = hstate_vma(vma);
unsigned long next;
unsigned long hmask = huge_page_mask(h);
unsigned long sz = huge_page_size(h);
pte_t *pte;
int err = 0;
do {
next = hugetlb_entry_end(h, addr, end);
pte = huge_pte_offset(walk->mm, addr & hmask, sz);
if (pte && walk->hugetlb_entry)
err = walk->hugetlb_entry(pte, hmask, addr, next, walk);
if (err)
break;
} while (addr = next, addr != end);
return err;
}
Commit Message: mm/pagewalk.c: report holes in hugetlb ranges
This matters at least for the mincore syscall, which will otherwise copy
uninitialized memory from the page allocator to userspace. It is
probably also a correctness error for /proc/$pid/pagemap, but I haven't
tested that.
Removing the `walk->hugetlb_entry` condition in walk_hugetlb_range() has
no effect because the caller already checks for that.
This only reports holes in hugetlb ranges to callers who have specified
a hugetlb_entry callback.
This issue was found using an AFL-based fuzzer.
v2:
- don't crash on ->pte_hole==NULL (Andrew Morton)
- add Cc stable (Andrew Morton)
Fixes: 1e25a271c8ac ("mincore: apply page table walker on do_mincore()")
Signed-off-by: Jann Horn <[email protected]>
Cc: <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200 | static int walk_hugetlb_range(unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->vma;
struct hstate *h = hstate_vma(vma);
unsigned long next;
unsigned long hmask = huge_page_mask(h);
unsigned long sz = huge_page_size(h);
pte_t *pte;
int err = 0;
do {
next = hugetlb_entry_end(h, addr, end);
pte = huge_pte_offset(walk->mm, addr & hmask, sz);
if (pte)
err = walk->hugetlb_entry(pte, hmask, addr, next, walk);
else if (walk->pte_hole)
err = walk->pte_hole(addr, next, walk);
if (err)
break;
} while (addr = next, addr != end);
return err;
}
| 167,661 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TestFlashMessageLoop::RunTests(const std::string& filter) {
RUN_TEST(Basics, filter);
RUN_TEST(RunWithoutQuit, filter);
}
Commit Message: Fix PPB_Flash_MessageLoop.
This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop.
BUG=569496
Review URL: https://codereview.chromium.org/1559113002
Cr-Commit-Position: refs/heads/master@{#374529}
CWE ID: CWE-264 | void TestFlashMessageLoop::RunTests(const std::string& filter) {
RUN_TEST(Basics, filter);
RUN_TEST(RunWithoutQuit, filter);
RUN_TEST(SuspendScriptCallbackWhileRunning, filter);
}
void TestFlashMessageLoop::DidRunScriptCallback() {
// Script callbacks are not supposed to run while the Flash message loop is
// running.
if (message_loop_)
suspend_script_callback_result_ = false;
}
pp::deprecated::ScriptableObject* TestFlashMessageLoop::CreateTestObject() {
if (!instance_so_)
instance_so_ = new InstanceSO(this);
return instance_so_;
}
| 172,125 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: method_invocation_get_uid (GDBusMethodInvocation *context)
{
const gchar *sender;
PolkitSubject *busname;
PolkitSubject *process;
uid_t uid;
sender = g_dbus_method_invocation_get_sender (context);
busname = polkit_system_bus_name_new (sender);
process = polkit_system_bus_name_get_process_sync (POLKIT_SYSTEM_BUS_NAME (busname), NULL, NULL);
uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (process));
g_object_unref (busname);
g_object_unref (process);
return uid;
}
Commit Message:
CWE ID: CWE-362 | method_invocation_get_uid (GDBusMethodInvocation *context)
| 165,010 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: exsltFuncRegisterImportFunc (exsltFuncFunctionData *data,
exsltFuncImportRegData *ch,
const xmlChar *URI, const xmlChar *name,
ATTRIBUTE_UNUSED const xmlChar *ignored) {
exsltFuncFunctionData *func=NULL;
if ((data == NULL) || (ch == NULL) || (URI == NULL) || (name == NULL))
return;
if (ch->ctxt == NULL || ch->hash == NULL)
return;
/* Check if already present */
func = (exsltFuncFunctionData*)xmlHashLookup2(ch->hash, URI, name);
if (func == NULL) { /* Not yet present - copy it in */
func = exsltFuncNewFunctionData();
memcpy(func, data, sizeof(exsltFuncFunctionData));
if (xmlHashAddEntry2(ch->hash, URI, name, func) < 0) {
xsltGenericError(xsltGenericErrorContext,
"Failed to register function {%s}%s\n",
URI, name);
} else { /* Do the registration */
xsltGenericDebug(xsltGenericDebugContext,
"exsltFuncRegisterImportFunc: register {%s}%s\n",
URI, name);
xsltRegisterExtFunction(ch->ctxt, name, URI,
exsltFuncFunctionFunction);
}
}
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | exsltFuncRegisterImportFunc (exsltFuncFunctionData *data,
exsltFuncImportRegData *ch,
const xmlChar *URI, const xmlChar *name,
ATTRIBUTE_UNUSED const xmlChar *ignored) {
exsltFuncFunctionData *func=NULL;
if ((data == NULL) || (ch == NULL) || (URI == NULL) || (name == NULL))
return;
if (ch->ctxt == NULL || ch->hash == NULL)
return;
/* Check if already present */
func = (exsltFuncFunctionData*)xmlHashLookup2(ch->hash, URI, name);
if (func == NULL) { /* Not yet present - copy it in */
func = exsltFuncNewFunctionData();
if (func == NULL)
return;
memcpy(func, data, sizeof(exsltFuncFunctionData));
if (xmlHashAddEntry2(ch->hash, URI, name, func) < 0) {
xsltGenericError(xsltGenericErrorContext,
"Failed to register function {%s}%s\n",
URI, name);
} else { /* Do the registration */
xsltGenericDebug(xsltGenericDebugContext,
"exsltFuncRegisterImportFunc: register {%s}%s\n",
URI, name);
xsltRegisterExtFunction(ch->ctxt, name, URI,
exsltFuncFunctionFunction);
}
}
}
| 173,294 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_do_nothing (MyObject *obj, GError **error)
{
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_do_nothing (MyObject *obj, GError **error)
| 165,092 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual size_t GetNumActiveInputMethods() {
scoped_ptr<InputMethodDescriptors> descriptors(GetActiveInputMethods());
return descriptors->size();
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | virtual size_t GetNumActiveInputMethods() {
scoped_ptr<input_method::InputMethodDescriptors> descriptors(
GetActiveInputMethods());
return descriptors->size();
}
| 170,491 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RegisterProperties(IBusPropList* ibus_prop_list) {
DLOG(INFO) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
ImePropertyList prop_list; // our representation.
if (ibus_prop_list) {
if (!FlattenPropertyList(ibus_prop_list, &prop_list)) {
RegisterProperties(NULL);
return;
}
}
register_ime_properties_(language_library_, prop_list);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void RegisterProperties(IBusPropList* ibus_prop_list) {
void DoRegisterProperties(IBusPropList* ibus_prop_list) {
VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
ImePropertyList prop_list; // our representation.
if (ibus_prop_list) {
if (!FlattenPropertyList(ibus_prop_list, &prop_list)) {
DoRegisterProperties(NULL);
return;
}
}
VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
| 170,544 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ip4_datagram_release_cb(struct sock *sk)
{
const struct inet_sock *inet = inet_sk(sk);
const struct ip_options_rcu *inet_opt;
__be32 daddr = inet->inet_daddr;
struct flowi4 fl4;
struct rtable *rt;
if (! __sk_dst_get(sk) || __sk_dst_check(sk, 0))
return;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt && inet_opt->opt.srr)
daddr = inet_opt->opt.faddr;
rt = ip_route_output_ports(sock_net(sk), &fl4, sk, daddr,
inet->inet_saddr, inet->inet_dport,
inet->inet_sport, sk->sk_protocol,
RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);
if (!IS_ERR(rt))
__sk_dst_set(sk, &rt->dst);
rcu_read_unlock();
}
Commit Message: ipv4: fix a race in ip4_datagram_release_cb()
Alexey gave a AddressSanitizer[1] report that finally gave a good hint
at where was the origin of various problems already reported by Dormando
in the past [2]
Problem comes from the fact that UDP can have a lockless TX path, and
concurrent threads can manipulate sk_dst_cache, while another thread,
is holding socket lock and calls __sk_dst_set() in
ip4_datagram_release_cb() (this was added in linux-3.8)
It seems that all we need to do is to use sk_dst_check() and
sk_dst_set() so that all the writers hold same spinlock
(sk->sk_dst_lock) to prevent corruptions.
TCP stack do not need this protection, as all sk_dst_cache writers hold
the socket lock.
[1]
https://code.google.com/p/address-sanitizer/wiki/AddressSanitizerForKernel
AddressSanitizer: heap-use-after-free in ipv4_dst_check
Read of size 2 by thread T15453:
[<ffffffff817daa3a>] ipv4_dst_check+0x1a/0x90 ./net/ipv4/route.c:1116
[<ffffffff8175b789>] __sk_dst_check+0x89/0xe0 ./net/core/sock.c:531
[<ffffffff81830a36>] ip4_datagram_release_cb+0x46/0x390 ??:0
[<ffffffff8175eaea>] release_sock+0x17a/0x230 ./net/core/sock.c:2413
[<ffffffff81830882>] ip4_datagram_connect+0x462/0x5d0 ??:0
[<ffffffff81846d06>] inet_dgram_connect+0x76/0xd0 ./net/ipv4/af_inet.c:534
[<ffffffff817580ac>] SYSC_connect+0x15c/0x1c0 ./net/socket.c:1701
[<ffffffff817596ce>] SyS_connect+0xe/0x10 ./net/socket.c:1682
[<ffffffff818b0a29>] system_call_fastpath+0x16/0x1b
./arch/x86/kernel/entry_64.S:629
Freed by thread T15455:
[<ffffffff8178d9b8>] dst_destroy+0xa8/0x160 ./net/core/dst.c:251
[<ffffffff8178de25>] dst_release+0x45/0x80 ./net/core/dst.c:280
[<ffffffff818304c1>] ip4_datagram_connect+0xa1/0x5d0 ??:0
[<ffffffff81846d06>] inet_dgram_connect+0x76/0xd0 ./net/ipv4/af_inet.c:534
[<ffffffff817580ac>] SYSC_connect+0x15c/0x1c0 ./net/socket.c:1701
[<ffffffff817596ce>] SyS_connect+0xe/0x10 ./net/socket.c:1682
[<ffffffff818b0a29>] system_call_fastpath+0x16/0x1b
./arch/x86/kernel/entry_64.S:629
Allocated by thread T15453:
[<ffffffff8178d291>] dst_alloc+0x81/0x2b0 ./net/core/dst.c:171
[<ffffffff817db3b7>] rt_dst_alloc+0x47/0x50 ./net/ipv4/route.c:1406
[< inlined >] __ip_route_output_key+0x3e8/0xf70
__mkroute_output ./net/ipv4/route.c:1939
[<ffffffff817dde08>] __ip_route_output_key+0x3e8/0xf70 ./net/ipv4/route.c:2161
[<ffffffff817deb34>] ip_route_output_flow+0x14/0x30 ./net/ipv4/route.c:2249
[<ffffffff81830737>] ip4_datagram_connect+0x317/0x5d0 ??:0
[<ffffffff81846d06>] inet_dgram_connect+0x76/0xd0 ./net/ipv4/af_inet.c:534
[<ffffffff817580ac>] SYSC_connect+0x15c/0x1c0 ./net/socket.c:1701
[<ffffffff817596ce>] SyS_connect+0xe/0x10 ./net/socket.c:1682
[<ffffffff818b0a29>] system_call_fastpath+0x16/0x1b
./arch/x86/kernel/entry_64.S:629
[2]
<4>[196727.311203] general protection fault: 0000 [#1] SMP
<4>[196727.311224] Modules linked in: xt_TEE xt_dscp xt_DSCP macvlan bridge coretemp crc32_pclmul ghash_clmulni_intel gpio_ich microcode ipmi_watchdog ipmi_devintf sb_edac edac_core lpc_ich mfd_core tpm_tis tpm tpm_bios ipmi_si ipmi_msghandler isci igb libsas i2c_algo_bit ixgbe ptp pps_core mdio
<4>[196727.311333] CPU: 17 PID: 0 Comm: swapper/17 Not tainted 3.10.26 #1
<4>[196727.311344] Hardware name: Supermicro X9DRi-LN4+/X9DR3-LN4+/X9DRi-LN4+/X9DR3-LN4+, BIOS 3.0 07/05/2013
<4>[196727.311364] task: ffff885e6f069700 ti: ffff885e6f072000 task.ti: ffff885e6f072000
<4>[196727.311377] RIP: 0010:[<ffffffff815f8c7f>] [<ffffffff815f8c7f>] ipv4_dst_destroy+0x4f/0x80
<4>[196727.311399] RSP: 0018:ffff885effd23a70 EFLAGS: 00010282
<4>[196727.311409] RAX: dead000000200200 RBX: ffff8854c398ecc0 RCX: 0000000000000040
<4>[196727.311423] RDX: dead000000100100 RSI: dead000000100100 RDI: dead000000200200
<4>[196727.311437] RBP: ffff885effd23a80 R08: ffffffff815fd9e0 R09: ffff885d5a590800
<4>[196727.311451] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000000
<4>[196727.311464] R13: ffffffff81c8c280 R14: 0000000000000000 R15: ffff880e85ee16ce
<4>[196727.311510] FS: 0000000000000000(0000) GS:ffff885effd20000(0000) knlGS:0000000000000000
<4>[196727.311554] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
<4>[196727.311581] CR2: 00007a46751eb000 CR3: 0000005e65688000 CR4: 00000000000407e0
<4>[196727.311625] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
<4>[196727.311669] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
<4>[196727.311713] Stack:
<4>[196727.311733] ffff8854c398ecc0 ffff8854c398ecc0 ffff885effd23ab0 ffffffff815b7f42
<4>[196727.311784] ffff88be6595bc00 ffff8854c398ecc0 0000000000000000 ffff8854c398ecc0
<4>[196727.311834] ffff885effd23ad0 ffffffff815b86c6 ffff885d5a590800 ffff8816827821c0
<4>[196727.311885] Call Trace:
<4>[196727.311907] <IRQ>
<4>[196727.311912] [<ffffffff815b7f42>] dst_destroy+0x32/0xe0
<4>[196727.311959] [<ffffffff815b86c6>] dst_release+0x56/0x80
<4>[196727.311986] [<ffffffff81620bd5>] tcp_v4_do_rcv+0x2a5/0x4a0
<4>[196727.312013] [<ffffffff81622b5a>] tcp_v4_rcv+0x7da/0x820
<4>[196727.312041] [<ffffffff815fd9e0>] ? ip_rcv_finish+0x360/0x360
<4>[196727.312070] [<ffffffff815de02d>] ? nf_hook_slow+0x7d/0x150
<4>[196727.312097] [<ffffffff815fd9e0>] ? ip_rcv_finish+0x360/0x360
<4>[196727.312125] [<ffffffff815fda92>] ip_local_deliver_finish+0xb2/0x230
<4>[196727.312154] [<ffffffff815fdd9a>] ip_local_deliver+0x4a/0x90
<4>[196727.312183] [<ffffffff815fd799>] ip_rcv_finish+0x119/0x360
<4>[196727.312212] [<ffffffff815fe00b>] ip_rcv+0x22b/0x340
<4>[196727.312242] [<ffffffffa0339680>] ? macvlan_broadcast+0x160/0x160 [macvlan]
<4>[196727.312275] [<ffffffff815b0c62>] __netif_receive_skb_core+0x512/0x640
<4>[196727.312308] [<ffffffff811427fb>] ? kmem_cache_alloc+0x13b/0x150
<4>[196727.312338] [<ffffffff815b0db1>] __netif_receive_skb+0x21/0x70
<4>[196727.312368] [<ffffffff815b0fa1>] netif_receive_skb+0x31/0xa0
<4>[196727.312397] [<ffffffff815b1ae8>] napi_gro_receive+0xe8/0x140
<4>[196727.312433] [<ffffffffa00274f1>] ixgbe_poll+0x551/0x11f0 [ixgbe]
<4>[196727.312463] [<ffffffff815fe00b>] ? ip_rcv+0x22b/0x340
<4>[196727.312491] [<ffffffff815b1691>] net_rx_action+0x111/0x210
<4>[196727.312521] [<ffffffff815b0db1>] ? __netif_receive_skb+0x21/0x70
<4>[196727.312552] [<ffffffff810519d0>] __do_softirq+0xd0/0x270
<4>[196727.312583] [<ffffffff816cef3c>] call_softirq+0x1c/0x30
<4>[196727.312613] [<ffffffff81004205>] do_softirq+0x55/0x90
<4>[196727.312640] [<ffffffff81051c85>] irq_exit+0x55/0x60
<4>[196727.312668] [<ffffffff816cf5c3>] do_IRQ+0x63/0xe0
<4>[196727.312696] [<ffffffff816c5aaa>] common_interrupt+0x6a/0x6a
<4>[196727.312722] <EOI>
<1>[196727.313071] RIP [<ffffffff815f8c7f>] ipv4_dst_destroy+0x4f/0x80
<4>[196727.313100] RSP <ffff885effd23a70>
<4>[196727.313377] ---[ end trace 64b3f14fae0f2e29 ]---
<0>[196727.380908] Kernel panic - not syncing: Fatal exception in interrupt
Reported-by: Alexey Preobrazhensky <[email protected]>
Reported-by: dormando <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Fixes: 8141ed9fcedb2 ("ipv4: Add a socket release callback for datagram sockets")
Cc: Steffen Klassert <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | void ip4_datagram_release_cb(struct sock *sk)
{
const struct inet_sock *inet = inet_sk(sk);
const struct ip_options_rcu *inet_opt;
__be32 daddr = inet->inet_daddr;
struct dst_entry *dst;
struct flowi4 fl4;
struct rtable *rt;
rcu_read_lock();
dst = __sk_dst_get(sk);
if (!dst || !dst->obsolete || dst->ops->check(dst, 0)) {
rcu_read_unlock();
return;
}
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt && inet_opt->opt.srr)
daddr = inet_opt->opt.faddr;
rt = ip_route_output_ports(sock_net(sk), &fl4, sk, daddr,
inet->inet_saddr, inet->inet_dport,
inet->inet_sport, sk->sk_protocol,
RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);
dst = !IS_ERR(rt) ? &rt->dst : NULL;
sk_dst_set(sk, dst);
rcu_read_unlock();
}
| 168,897 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void SetUpTestCase() {
input_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1;
output_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kOutputBufferSize));
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | static void SetUpTestCase() {
input_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1;
output_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kOutputBufferSize));
output_ref_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kOutputBufferSize));
#if CONFIG_VP9_HIGHBITDEPTH
input16_ = reinterpret_cast<uint16_t*>(
vpx_memalign(kDataAlignment,
(kInputBufferSize + 1) * sizeof(uint16_t))) + 1;
output16_ = reinterpret_cast<uint16_t*>(
vpx_memalign(kDataAlignment, (kOutputBufferSize) * sizeof(uint16_t)));
output16_ref_ = reinterpret_cast<uint16_t*>(
vpx_memalign(kDataAlignment, (kOutputBufferSize) * sizeof(uint16_t)));
#endif
}
| 174,506 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GLboolean WebGLRenderingContextBase::isProgram(WebGLProgram* program) {
if (!program || isContextLost())
return 0;
return ContextGL()->IsProgram(program->Object());
}
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565016}
CWE ID: CWE-119 | GLboolean WebGLRenderingContextBase::isProgram(WebGLProgram* program) {
if (!program || isContextLost() || !program->Validate(ContextGroup(), this))
return 0;
return ContextGL()->IsProgram(program->Object());
}
| 173,130 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AssertObserverCount(int added_count, int removed_count,
int changed_count) {
ASSERT_EQ(added_count, added_count_);
ASSERT_EQ(removed_count, removed_count_);
ASSERT_EQ(changed_count, changed_count_);
}
Commit Message: Add OVERRIDE to ui::TreeModelObserver overridden methods.
BUG=None
TEST=None
[email protected]
Review URL: http://codereview.chromium.org/7046093
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void AssertObserverCount(int added_count, int removed_count,
void AssertObserverCount(int added_count,
int removed_count,
int changed_count) {
ASSERT_EQ(added_count, added_count_);
ASSERT_EQ(removed_count, removed_count_);
ASSERT_EQ(changed_count, changed_count_);
}
| 170,468 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) {
BufferInfo *inInfo = NULL;
OMX_BUFFERHEADERTYPE *inHeader = NULL;
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
if (inHeader) {
if (inHeader->nOffset == 0 && inHeader->nFilledLen) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumFramesOutput = 0;
}
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEos = true;
}
mConfig->pInputBuffer =
inHeader->pBuffer + inHeader->nOffset;
mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
} else {
mConfig->pInputBuffer = NULL;
mConfig->inputBufferCurrentLength = 0;
}
mConfig->inputBufferMaxLength = 0;
mConfig->inputBufferUsedLength = 0;
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
if ((int32)outHeader->nAllocLen < mConfig->outputFrameSize) {
ALOGE("input buffer too small: got %u, expected %u",
outHeader->nAllocLen, mConfig->outputFrameSize);
android_errorWriteLog(0x534e4554, "27793371");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return;
}
mConfig->pOutputBuffer =
reinterpret_cast<int16_t *>(outHeader->pBuffer);
ERROR_CODE decoderErr;
if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
!= NO_DECODING_ERROR) {
ALOGV("mp3 decoder returned error %d", decoderErr);
if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
&& decoderErr != SIDE_INFO_ERROR) {
ALOGE("mp3 decoder returned error %d", decoderErr);
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
mSignalledError = true;
return;
}
if (mConfig->outputFrameSize == 0) {
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
}
if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) {
if (!mIsFirst) {
outHeader->nOffset = 0;
outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
memset(outHeader->pBuffer, 0, outHeader->nFilledLen);
}
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mSignalledOutputEos = true;
} else {
ALOGV_IF(mIsFirst, "insufficient data for first frame, sending silence");
memset(outHeader->pBuffer,
0,
mConfig->outputFrameSize * sizeof(int16_t));
if (inHeader) {
mConfig->inputBufferUsedLength = inHeader->nFilledLen;
}
}
} else if (mConfig->samplingRate != mSamplingRate
|| mConfig->num_channels != mNumChannels) {
mSamplingRate = mConfig->samplingRate;
mNumChannels = mConfig->num_channels;
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
return;
}
if (mIsFirst) {
mIsFirst = false;
outHeader->nOffset =
kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
outHeader->nFilledLen =
mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset;
} else if (!mSignalledOutputEos) {
outHeader->nOffset = 0;
outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);
}
outHeader->nTimeStamp =
mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
if (inHeader) {
CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);
inHeader->nOffset += mConfig->inputBufferUsedLength;
inHeader->nFilledLen -= mConfig->inputBufferUsedLength;
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
Commit Message: SoftMP3: memset safely
Bug: 29422022
Change-Id: I70c9e33269d16bf8c163815706ac24e18e34fe97
CWE ID: CWE-264 | void SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) {
BufferInfo *inInfo = NULL;
OMX_BUFFERHEADERTYPE *inHeader = NULL;
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
if (inHeader) {
if (inHeader->nOffset == 0 && inHeader->nFilledLen) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumFramesOutput = 0;
}
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEos = true;
}
mConfig->pInputBuffer =
inHeader->pBuffer + inHeader->nOffset;
mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
} else {
mConfig->pInputBuffer = NULL;
mConfig->inputBufferCurrentLength = 0;
}
mConfig->inputBufferMaxLength = 0;
mConfig->inputBufferUsedLength = 0;
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
if ((int32)outHeader->nAllocLen < mConfig->outputFrameSize) {
ALOGE("input buffer too small: got %u, expected %u",
outHeader->nAllocLen, mConfig->outputFrameSize);
android_errorWriteLog(0x534e4554, "27793371");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return;
}
mConfig->pOutputBuffer =
reinterpret_cast<int16_t *>(outHeader->pBuffer);
ERROR_CODE decoderErr;
if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
!= NO_DECODING_ERROR) {
ALOGV("mp3 decoder returned error %d", decoderErr);
if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
&& decoderErr != SIDE_INFO_ERROR) {
ALOGE("mp3 decoder returned error %d", decoderErr);
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
mSignalledError = true;
return;
}
if (mConfig->outputFrameSize == 0) {
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
}
if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) {
if (!mIsFirst) {
outHeader->nOffset = 0;
outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
if (!memsetSafe(outHeader, 0, outHeader->nFilledLen)) {
return;
}
}
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mSignalledOutputEos = true;
} else {
ALOGV_IF(mIsFirst, "insufficient data for first frame, sending silence");
if (!memsetSafe(outHeader, 0, mConfig->outputFrameSize * sizeof(int16_t))) {
return;
}
if (inHeader) {
mConfig->inputBufferUsedLength = inHeader->nFilledLen;
}
}
} else if (mConfig->samplingRate != mSamplingRate
|| mConfig->num_channels != mNumChannels) {
mSamplingRate = mConfig->samplingRate;
mNumChannels = mConfig->num_channels;
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
return;
}
if (mIsFirst) {
mIsFirst = false;
outHeader->nOffset =
kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
outHeader->nFilledLen =
mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset;
} else if (!mSignalledOutputEos) {
outHeader->nOffset = 0;
outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);
}
outHeader->nTimeStamp =
mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
if (inHeader) {
CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);
inHeader->nOffset += mConfig->inputBufferUsedLength;
inHeader->nFilledLen -= mConfig->inputBufferUsedLength;
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
| 173,415 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: HeadlessWebContentsImpl::HeadlessWebContentsImpl(
content::WebContents* web_contents,
HeadlessBrowserContextImpl* browser_context)
: content::WebContentsObserver(web_contents),
web_contents_delegate_(new HeadlessWebContentsImpl::Delegate(this)),
web_contents_(web_contents),
agent_host_(content::DevToolsAgentHost::GetOrCreateFor(web_contents)),
inject_mojo_services_into_isolated_world_(false),
browser_context_(browser_context),
render_process_host_(web_contents->GetMainFrame()->GetProcess()),
weak_ptr_factory_(this) {
#if BUILDFLAG(ENABLE_BASIC_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD)
HeadlessPrintManager::CreateForWebContents(web_contents);
//// TODO(weili): Add support for printing OOPIFs.
#endif
web_contents->GetMutableRendererPrefs()->accept_languages =
browser_context->options()->accept_language();
web_contents_->SetDelegate(web_contents_delegate_.get());
render_process_host_->AddObserver(this);
agent_host_->AddObserver(this);
}
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 | HeadlessWebContentsImpl::HeadlessWebContentsImpl(
content::WebContents* web_contents,
HeadlessBrowserContextImpl* browser_context)
: content::WebContentsObserver(web_contents),
web_contents_delegate_(new HeadlessWebContentsImpl::Delegate(this)),
web_contents_(web_contents),
agent_host_(content::DevToolsAgentHost::GetOrCreateFor(web_contents)),
inject_mojo_services_into_isolated_world_(false),
browser_context_(browser_context),
render_process_host_(web_contents->GetMainFrame()->GetProcess()),
weak_ptr_factory_(this) {
#if BUILDFLAG(ENABLE_BASIC_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD)
HeadlessPrintManager::CreateForWebContents(web_contents);
//// TODO(weili): Add support for printing OOPIFs.
#endif
web_contents->GetMutableRendererPrefs()->accept_languages =
browser_context->options()->accept_language();
web_contents_->SetDelegate(web_contents_delegate_.get());
render_process_host_->AddObserver(this);
agent_host_->AddObserver(this);
}
| 171,896 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebDevToolsAgentImpl::clearBrowserCookies()
{
m_client->clearBrowserCookies();
}
Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser.
BUG=366585
Review URL: https://codereview.chromium.org/251183005
git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void WebDevToolsAgentImpl::clearBrowserCookies()
| 171,349 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int snd_usb_create_streams(struct snd_usb_audio *chip, int ctrlif)
{
struct usb_device *dev = chip->dev;
struct usb_host_interface *host_iface;
struct usb_interface_descriptor *altsd;
void *control_header;
int i, protocol;
/* find audiocontrol interface */
host_iface = &usb_ifnum_to_if(dev, ctrlif)->altsetting[0];
control_header = snd_usb_find_csint_desc(host_iface->extra,
host_iface->extralen,
NULL, UAC_HEADER);
altsd = get_iface_desc(host_iface);
protocol = altsd->bInterfaceProtocol;
if (!control_header) {
dev_err(&dev->dev, "cannot find UAC_HEADER\n");
return -EINVAL;
}
switch (protocol) {
default:
dev_warn(&dev->dev,
"unknown interface protocol %#02x, assuming v1\n",
protocol);
/* fall through */
case UAC_VERSION_1: {
struct uac1_ac_header_descriptor *h1 = control_header;
if (!h1->bInCollection) {
dev_info(&dev->dev, "skipping empty audio interface (v1)\n");
return -EINVAL;
}
if (h1->bLength < sizeof(*h1) + h1->bInCollection) {
dev_err(&dev->dev, "invalid UAC_HEADER (v1)\n");
return -EINVAL;
}
for (i = 0; i < h1->bInCollection; i++)
snd_usb_create_stream(chip, ctrlif, h1->baInterfaceNr[i]);
break;
}
case UAC_VERSION_2: {
struct usb_interface_assoc_descriptor *assoc =
usb_ifnum_to_if(dev, ctrlif)->intf_assoc;
if (!assoc) {
/*
* Firmware writers cannot count to three. So to find
* the IAD on the NuForce UDH-100, also check the next
* interface.
*/
struct usb_interface *iface =
usb_ifnum_to_if(dev, ctrlif + 1);
if (iface &&
iface->intf_assoc &&
iface->intf_assoc->bFunctionClass == USB_CLASS_AUDIO &&
iface->intf_assoc->bFunctionProtocol == UAC_VERSION_2)
assoc = iface->intf_assoc;
}
if (!assoc) {
dev_err(&dev->dev, "Audio class v2 interfaces need an interface association\n");
return -EINVAL;
}
for (i = 0; i < assoc->bInterfaceCount; i++) {
int intf = assoc->bFirstInterface + i;
if (intf != ctrlif)
snd_usb_create_stream(chip, ctrlif, intf);
}
break;
}
}
return 0;
}
Commit Message: ALSA: usb-audio: Check out-of-bounds access by corrupted buffer descriptor
When a USB-audio device receives a maliciously adjusted or corrupted
buffer descriptor, the USB-audio driver may access an out-of-bounce
value at its parser. This was detected by syzkaller, something like:
BUG: KASAN: slab-out-of-bounds in usb_audio_probe+0x27b2/0x2ab0
Read of size 1 at addr ffff88006b83a9e8 by task kworker/0:1/24
CPU: 0 PID: 24 Comm: kworker/0:1 Not tainted 4.14.0-rc1-42251-gebb2c2437d80 #224
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
Workqueue: usb_hub_wq hub_event
Call Trace:
__dump_stack lib/dump_stack.c:16
dump_stack+0x292/0x395 lib/dump_stack.c:52
print_address_description+0x78/0x280 mm/kasan/report.c:252
kasan_report_error mm/kasan/report.c:351
kasan_report+0x22f/0x340 mm/kasan/report.c:409
__asan_report_load1_noabort+0x19/0x20 mm/kasan/report.c:427
snd_usb_create_streams sound/usb/card.c:248
usb_audio_probe+0x27b2/0x2ab0 sound/usb/card.c:605
usb_probe_interface+0x35d/0x8e0 drivers/usb/core/driver.c:361
really_probe drivers/base/dd.c:413
driver_probe_device+0x610/0xa00 drivers/base/dd.c:557
__device_attach_driver+0x230/0x290 drivers/base/dd.c:653
bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463
__device_attach+0x26e/0x3d0 drivers/base/dd.c:710
device_initial_probe+0x1f/0x30 drivers/base/dd.c:757
bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523
device_add+0xd0b/0x1660 drivers/base/core.c:1835
usb_set_configuration+0x104e/0x1870 drivers/usb/core/message.c:1932
generic_probe+0x73/0xe0 drivers/usb/core/generic.c:174
usb_probe_device+0xaf/0xe0 drivers/usb/core/driver.c:266
really_probe drivers/base/dd.c:413
driver_probe_device+0x610/0xa00 drivers/base/dd.c:557
__device_attach_driver+0x230/0x290 drivers/base/dd.c:653
bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463
__device_attach+0x26e/0x3d0 drivers/base/dd.c:710
device_initial_probe+0x1f/0x30 drivers/base/dd.c:757
bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523
device_add+0xd0b/0x1660 drivers/base/core.c:1835
usb_new_device+0x7b8/0x1020 drivers/usb/core/hub.c:2457
hub_port_connect drivers/usb/core/hub.c:4903
hub_port_connect_change drivers/usb/core/hub.c:5009
port_event drivers/usb/core/hub.c:5115
hub_event+0x194d/0x3740 drivers/usb/core/hub.c:5195
process_one_work+0xc7f/0x1db0 kernel/workqueue.c:2119
worker_thread+0x221/0x1850 kernel/workqueue.c:2253
kthread+0x3a1/0x470 kernel/kthread.c:231
ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431
This patch adds the checks of out-of-bounce accesses at appropriate
places and bails out when it goes out of the given buffer.
Reported-by: Andrey Konovalov <[email protected]>
Tested-by: Andrey Konovalov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-125 | static int snd_usb_create_streams(struct snd_usb_audio *chip, int ctrlif)
{
struct usb_device *dev = chip->dev;
struct usb_host_interface *host_iface;
struct usb_interface_descriptor *altsd;
void *control_header;
int i, protocol;
int rest_bytes;
/* find audiocontrol interface */
host_iface = &usb_ifnum_to_if(dev, ctrlif)->altsetting[0];
control_header = snd_usb_find_csint_desc(host_iface->extra,
host_iface->extralen,
NULL, UAC_HEADER);
altsd = get_iface_desc(host_iface);
protocol = altsd->bInterfaceProtocol;
if (!control_header) {
dev_err(&dev->dev, "cannot find UAC_HEADER\n");
return -EINVAL;
}
rest_bytes = (void *)(host_iface->extra + host_iface->extralen) -
control_header;
/* just to be sure -- this shouldn't hit at all */
if (rest_bytes <= 0) {
dev_err(&dev->dev, "invalid control header\n");
return -EINVAL;
}
switch (protocol) {
default:
dev_warn(&dev->dev,
"unknown interface protocol %#02x, assuming v1\n",
protocol);
/* fall through */
case UAC_VERSION_1: {
struct uac1_ac_header_descriptor *h1 = control_header;
if (rest_bytes < sizeof(*h1)) {
dev_err(&dev->dev, "too short v1 buffer descriptor\n");
return -EINVAL;
}
if (!h1->bInCollection) {
dev_info(&dev->dev, "skipping empty audio interface (v1)\n");
return -EINVAL;
}
if (rest_bytes < h1->bLength) {
dev_err(&dev->dev, "invalid buffer length (v1)\n");
return -EINVAL;
}
if (h1->bLength < sizeof(*h1) + h1->bInCollection) {
dev_err(&dev->dev, "invalid UAC_HEADER (v1)\n");
return -EINVAL;
}
for (i = 0; i < h1->bInCollection; i++)
snd_usb_create_stream(chip, ctrlif, h1->baInterfaceNr[i]);
break;
}
case UAC_VERSION_2: {
struct usb_interface_assoc_descriptor *assoc =
usb_ifnum_to_if(dev, ctrlif)->intf_assoc;
if (!assoc) {
/*
* Firmware writers cannot count to three. So to find
* the IAD on the NuForce UDH-100, also check the next
* interface.
*/
struct usb_interface *iface =
usb_ifnum_to_if(dev, ctrlif + 1);
if (iface &&
iface->intf_assoc &&
iface->intf_assoc->bFunctionClass == USB_CLASS_AUDIO &&
iface->intf_assoc->bFunctionProtocol == UAC_VERSION_2)
assoc = iface->intf_assoc;
}
if (!assoc) {
dev_err(&dev->dev, "Audio class v2 interfaces need an interface association\n");
return -EINVAL;
}
for (i = 0; i < assoc->bInterfaceCount; i++) {
int intf = assoc->bFirstInterface + i;
if (intf != ctrlif)
snd_usb_create_stream(chip, ctrlif, intf);
}
break;
}
}
return 0;
}
| 167,681 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BlobURLRequestJob::DidGetFileItemLength(size_t index, int64 result) {
if (error_)
return;
if (result == net::ERR_UPLOAD_FILE_CHANGED) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
} else if (result < 0) {
NotifyFailure(result);
return;
}
DCHECK_LT(index, blob_data_->items().size());
const BlobData::Item& item = blob_data_->items().at(index);
DCHECK(IsFileType(item.type()));
int64 item_length = static_cast<int64>(item.length());
if (item_length == -1)
item_length = result - item.offset();
DCHECK_LT(index, item_length_list_.size());
item_length_list_[index] = item_length;
total_size_ += item_length;
if (--pending_get_file_info_count_ == 0)
DidCountSize(net::OK);
}
Commit Message: Avoid integer overflows in BlobURLRequestJob.
BUG=169685
Review URL: https://chromiumcodereview.appspot.com/12047012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@179154 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | void BlobURLRequestJob::DidGetFileItemLength(size_t index, int64 result) {
if (error_)
return;
if (result == net::ERR_UPLOAD_FILE_CHANGED) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
} else if (result < 0) {
NotifyFailure(result);
return;
}
DCHECK_LT(index, blob_data_->items().size());
const BlobData::Item& item = blob_data_->items().at(index);
DCHECK(IsFileType(item.type()));
uint64 file_length = result;
uint64 item_offset = item.offset();
uint64 item_length = item.length();
if (item_offset > file_length) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
}
uint64 max_length = file_length - item_offset;
if (item_length == static_cast<uint64>(-1)) {
item_length = max_length;
} else if (item_length > max_length) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
}
if (!AddItemLength(index, item_length))
return;
if (--pending_get_file_info_count_ == 0)
DidCountSize(net::OK);
}
| 171,399 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SoftVPX::outputBuffers(bool flushDecoder, bool display, bool eos, bool *portWillReset) {
List<BufferInfo *> &outQueue = getPortQueue(1);
BufferInfo *outInfo = NULL;
OMX_BUFFERHEADERTYPE *outHeader = NULL;
vpx_codec_iter_t iter = NULL;
if (flushDecoder && mFrameParallelMode) {
if (vpx_codec_decode((vpx_codec_ctx_t *)mCtx, NULL, 0, NULL, 0)) {
ALOGE("Failed to flush on2 decoder.");
return false;
}
}
if (!display) {
if (!flushDecoder) {
ALOGE("Invalid operation.");
return false;
}
while ((mImg = vpx_codec_get_frame((vpx_codec_ctx_t *)mCtx, &iter))) {
}
return true;
}
while (!outQueue.empty()) {
if (mImg == NULL) {
mImg = vpx_codec_get_frame((vpx_codec_ctx_t *)mCtx, &iter);
if (mImg == NULL) {
break;
}
}
uint32_t width = mImg->d_w;
uint32_t height = mImg->d_h;
outInfo = *outQueue.begin();
outHeader = outInfo->mHeader;
CHECK_EQ(mImg->fmt, VPX_IMG_FMT_I420);
handlePortSettingsChange(portWillReset, width, height);
if (*portWillReset) {
return true;
}
outHeader->nOffset = 0;
outHeader->nFlags = 0;
outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2;
outHeader->nTimeStamp = *(OMX_TICKS *)mImg->user_priv;
if (outHeader->nAllocLen >= outHeader->nFilledLen) {
uint8_t *dst = outHeader->pBuffer;
const uint8_t *srcY = (const uint8_t *)mImg->planes[VPX_PLANE_Y];
const uint8_t *srcU = (const uint8_t *)mImg->planes[VPX_PLANE_U];
const uint8_t *srcV = (const uint8_t *)mImg->planes[VPX_PLANE_V];
size_t srcYStride = mImg->stride[VPX_PLANE_Y];
size_t srcUStride = mImg->stride[VPX_PLANE_U];
size_t srcVStride = mImg->stride[VPX_PLANE_V];
copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride);
} else {
ALOGE("b/27597103, buffer too small");
android_errorWriteLog(0x534e4554, "27597103");
outHeader->nFilledLen = 0;
}
mImg = NULL;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
if (!eos) {
return true;
}
if (!outQueue.empty()) {
outInfo = *outQueue.begin();
outQueue.erase(outQueue.begin());
outHeader = outInfo->mHeader;
outHeader->nTimeStamp = 0;
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
mEOSStatus = OUTPUT_FRAMES_FLUSHED;
}
return true;
}
Commit Message: SoftVPX: fix nFilledLen overflow
Bug: 29421675
Change-Id: I25d4cf54a5df22c2130c37e95c7c7f75063111f3
CWE ID: CWE-119 | bool SoftVPX::outputBuffers(bool flushDecoder, bool display, bool eos, bool *portWillReset) {
List<BufferInfo *> &outQueue = getPortQueue(1);
BufferInfo *outInfo = NULL;
OMX_BUFFERHEADERTYPE *outHeader = NULL;
vpx_codec_iter_t iter = NULL;
if (flushDecoder && mFrameParallelMode) {
if (vpx_codec_decode((vpx_codec_ctx_t *)mCtx, NULL, 0, NULL, 0)) {
ALOGE("Failed to flush on2 decoder.");
return false;
}
}
if (!display) {
if (!flushDecoder) {
ALOGE("Invalid operation.");
return false;
}
while ((mImg = vpx_codec_get_frame((vpx_codec_ctx_t *)mCtx, &iter))) {
}
return true;
}
while (!outQueue.empty()) {
if (mImg == NULL) {
mImg = vpx_codec_get_frame((vpx_codec_ctx_t *)mCtx, &iter);
if (mImg == NULL) {
break;
}
}
uint32_t width = mImg->d_w;
uint32_t height = mImg->d_h;
outInfo = *outQueue.begin();
outHeader = outInfo->mHeader;
CHECK_EQ(mImg->fmt, VPX_IMG_FMT_I420);
handlePortSettingsChange(portWillReset, width, height);
if (*portWillReset) {
return true;
}
outHeader->nOffset = 0;
outHeader->nFlags = 0;
outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2;
outHeader->nTimeStamp = *(OMX_TICKS *)mImg->user_priv;
if (outputBufferSafe(outHeader)) {
uint8_t *dst = outHeader->pBuffer;
const uint8_t *srcY = (const uint8_t *)mImg->planes[VPX_PLANE_Y];
const uint8_t *srcU = (const uint8_t *)mImg->planes[VPX_PLANE_U];
const uint8_t *srcV = (const uint8_t *)mImg->planes[VPX_PLANE_V];
size_t srcYStride = mImg->stride[VPX_PLANE_Y];
size_t srcUStride = mImg->stride[VPX_PLANE_U];
size_t srcVStride = mImg->stride[VPX_PLANE_V];
copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride);
} else {
outHeader->nFilledLen = 0;
}
mImg = NULL;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
if (!eos) {
return true;
}
if (!outQueue.empty()) {
outInfo = *outQueue.begin();
outQueue.erase(outQueue.begin());
outHeader = outInfo->mHeader;
outHeader->nTimeStamp = 0;
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
mEOSStatus = OUTPUT_FRAMES_FLUSHED;
}
return true;
}
| 174,155 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: read_file(gchar* filepath)
{
FILE * f;
size_t length;
gchar *ret = NULL;
f = fopen(filepath, "rb");
if (f) {
fseek(f, 0, SEEK_END);
length = (size_t)ftell(f);
fseek(f, 0, SEEK_SET);
/* We can't use MALLOC since it isn't thread safe */
ret = MALLOC(length + 1);
if (ret) {
if (fread(ret, length, 1, f) != 1) {
log_message(LOG_INFO, "Failed to read all of %s", filepath);
}
ret[length] = '\0';
}
else
log_message(LOG_INFO, "Unable to read Dbus file %s", filepath);
fclose(f);
}
return ret;
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59 | read_file(gchar* filepath)
{
FILE * f;
size_t length;
gchar *ret = NULL;
f = fopen(filepath, "r");
if (f) {
fseek(f, 0, SEEK_END);
length = (size_t)ftell(f);
fseek(f, 0, SEEK_SET);
/* We can't use MALLOC since it isn't thread safe */
ret = MALLOC(length + 1);
if (ret) {
if (fread(ret, length, 1, f) != 1) {
log_message(LOG_INFO, "Failed to read all of %s", filepath);
}
ret[length] = '\0';
}
else
log_message(LOG_INFO, "Unable to read Dbus file %s", filepath);
fclose(f);
}
return ret;
}
| 168,988 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_expand_gray_1_2_4_to_8_mod(
PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
image_transform_png_set_expand_mod(this, that, pp, display);
}
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_expand_gray_1_2_4_to_8_mod(
const image_transform *this, image_pixel *that, png_const_structp pp,
const transform_display *display)
{
#if PNG_LIBPNG_VER < 10700
image_transform_png_set_expand_mod(this, that, pp, display);
#else
/* Only expand grayscale of bit depth less than 8: */
if (that->colour_type == PNG_COLOR_TYPE_GRAY &&
that->bit_depth < 8)
that->sample_depth = that->bit_depth = 8;
this->next->mod(this->next, that, pp, display);
#endif /* 1.7 or later */
}
| 173,631 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GDataCacheMetadataMap::ScanCacheDirectory(
const std::vector<FilePath>& cache_paths,
GDataCache::CacheSubDirectoryType sub_dir_type,
CacheMap* cache_map,
ResourceIdToFilePathMap* processed_file_map) {
DCHECK(cache_map);
DCHECK(processed_file_map);
file_util::FileEnumerator enumerator(
cache_paths[sub_dir_type],
false, // not recursive
static_cast<file_util::FileEnumerator::FileType>(
file_util::FileEnumerator::FILES |
file_util::FileEnumerator::SHOW_SYM_LINKS),
util::kWildCard);
for (FilePath current = enumerator.Next(); !current.empty();
current = enumerator.Next()) {
std::string resource_id;
std::string md5;
std::string extra_extension;
util::ParseCacheFilePath(current, &resource_id, &md5, &extra_extension);
int cache_state = GDataCache::CACHE_STATE_NONE;
if (sub_dir_type == GDataCache::CACHE_TYPE_PINNED) {
std::string reason;
if (!IsValidSymbolicLink(current, sub_dir_type, cache_paths, &reason)) {
LOG(WARNING) << "Removing an invalid symlink: " << current.value()
<< ": " << reason;
util::DeleteSymlink(current);
continue;
}
CacheMap::iterator iter = cache_map->find(resource_id);
if (iter != cache_map->end()) { // Entry exists, update pinned state.
iter->second.cache_state =
GDataCache::SetCachePinned(iter->second.cache_state);
processed_file_map->insert(std::make_pair(resource_id, current));
continue;
}
cache_state = GDataCache::SetCachePinned(cache_state);
} else if (sub_dir_type == GDataCache::CACHE_TYPE_OUTGOING) {
std::string reason;
if (!IsValidSymbolicLink(current, sub_dir_type, cache_paths, &reason)) {
LOG(WARNING) << "Removing an invalid symlink: " << current.value()
<< ": " << reason;
util::DeleteSymlink(current);
continue;
}
CacheMap::iterator iter = cache_map->find(resource_id);
if (iter == cache_map->end() || !iter->second.IsDirty()) {
LOG(WARNING) << "Removing an symlink to a non-dirty file: "
<< current.value();
util::DeleteSymlink(current);
continue;
}
processed_file_map->insert(std::make_pair(resource_id, current));
continue;
} else if (sub_dir_type == GDataCache::CACHE_TYPE_PERSISTENT ||
sub_dir_type == GDataCache::CACHE_TYPE_TMP) {
FilePath unused;
if (file_util::ReadSymbolicLink(current, &unused)) {
LOG(WARNING) << "Removing a symlink in persistent/tmp directory"
<< current.value();
util::DeleteSymlink(current);
continue;
}
if (extra_extension == util::kMountedArchiveFileExtension) {
DCHECK(sub_dir_type == GDataCache::CACHE_TYPE_PERSISTENT);
file_util::Delete(current, false);
} else {
cache_state = GDataCache::SetCachePresent(cache_state);
if (md5 == util::kLocallyModifiedFileExtension) {
if (sub_dir_type == GDataCache::CACHE_TYPE_PERSISTENT) {
cache_state |= GDataCache::SetCacheDirty(cache_state);
} else {
LOG(WARNING) << "Removing a dirty file in tmp directory: "
<< current.value();
file_util::Delete(current, false);
continue;
}
}
}
} else {
NOTREACHED() << "Unexpected sub directory type: " << sub_dir_type;
}
cache_map->insert(std::make_pair(
resource_id, GDataCache::CacheEntry(md5, sub_dir_type, cache_state)));
processed_file_map->insert(std::make_pair(resource_id, current));
}
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void GDataCacheMetadataMap::ScanCacheDirectory(
const std::vector<FilePath>& cache_paths,
GDataCache::CacheSubDirectoryType sub_dir_type,
CacheMap* cache_map) {
file_util::FileEnumerator enumerator(
cache_paths[sub_dir_type],
false, // not recursive
static_cast<file_util::FileEnumerator::FileType>(
file_util::FileEnumerator::FILES |
file_util::FileEnumerator::SHOW_SYM_LINKS),
util::kWildCard);
for (FilePath current = enumerator.Next(); !current.empty();
current = enumerator.Next()) {
std::string resource_id;
std::string md5;
std::string extra_extension;
util::ParseCacheFilePath(current, &resource_id, &md5, &extra_extension);
int cache_state = GDataCache::CACHE_STATE_NONE;
if (sub_dir_type == GDataCache::CACHE_TYPE_PINNED) {
CacheMap::iterator iter = cache_map->find(resource_id);
if (iter != cache_map->end()) { // Entry exists, update pinned state.
iter->second.cache_state =
GDataCache::SetCachePinned(iter->second.cache_state);
continue;
}
cache_state = GDataCache::SetCachePinned(cache_state);
} else if (sub_dir_type == GDataCache::CACHE_TYPE_OUTGOING) {
// If we're scanning outgoing directory, entry must exist, update its
// dirty state.
// If entry doesn't exist, it's a logic error from previous execution,
// ignore this outgoing symlink and move on.
CacheMap::iterator iter = cache_map->find(resource_id);
if (iter != cache_map->end()) { // Entry exists, update dirty state.
iter->second.cache_state =
GDataCache::SetCacheDirty(iter->second.cache_state);
} else {
NOTREACHED() << "Dirty cache file MUST have actual file blob";
}
continue;
} else if (extra_extension == util::kMountedArchiveFileExtension) {
// Mounted archives in cache should be unmounted upon logout/shutdown.
// But if we encounter a mounted file at start, delete it and create an
// entry with not PRESENT state.
DCHECK(sub_dir_type == GDataCache::CACHE_TYPE_PERSISTENT);
file_util::Delete(current, false);
} else {
// Scanning other directories means that cache file is actually present.
cache_state = GDataCache::SetCachePresent(cache_state);
}
cache_map->insert(std::make_pair(
resource_id, GDataCache::CacheEntry(md5, sub_dir_type, cache_state)));
}
}
| 170,868 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)
{
if (file->f_flags & O_DSYNC)
return 0;
if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
return 1;
if (nfs_write_pageuptodate(page, inode) && (inode->i_flock == NULL ||
(inode->i_flock->fl_start == 0 &&
inode->i_flock->fl_end == OFFSET_MAX &&
inode->i_flock->fl_type != F_RDLCK)))
return 1;
return 0;
}
Commit Message: nfs: always make sure page is up-to-date before extending a write to cover the entire page
We should always make sure the cached page is up-to-date when we're
determining whether we can extend a write to cover the full page -- even
if we've received a write delegation from the server.
Commit c7559663 added logic to skip this check if we have a write
delegation, which can lead to data corruption such as the following
scenario if client B receives a write delegation from the NFS server:
Client A:
# echo 123456789 > /mnt/file
Client B:
# echo abcdefghi >> /mnt/file
# cat /mnt/file
0�D0�abcdefghi
Just because we hold a write delegation doesn't mean that we've read in
the entire page contents.
Cc: <[email protected]> # v3.11+
Signed-off-by: Scott Mayhew <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-20 | static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)
{
if (file->f_flags & O_DSYNC)
return 0;
if (!nfs_write_pageuptodate(page, inode))
return 0;
if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
return 1;
if (inode->i_flock == NULL || (inode->i_flock->fl_start == 0 &&
inode->i_flock->fl_end == OFFSET_MAX &&
inode->i_flock->fl_type != F_RDLCK))
return 1;
return 0;
}
| 166,424 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Location::SetLocation(const String& url,
LocalDOMWindow* current_window,
LocalDOMWindow* entered_window,
ExceptionState* exception_state,
SetLocationPolicy set_location_policy) {
if (!IsAttached())
return;
if (!current_window->GetFrame())
return;
Document* entered_document = entered_window->document();
if (!entered_document)
return;
KURL completed_url = entered_document->CompleteURL(url);
if (completed_url.IsNull())
return;
if (!current_window->GetFrame()->CanNavigate(*dom_window_->GetFrame(),
completed_url)) {
if (exception_state) {
exception_state->ThrowSecurityError(
"The current window does not have permission to navigate the target "
"frame to '" +
url + "'.");
}
return;
}
if (exception_state && !completed_url.IsValid()) {
exception_state->ThrowDOMException(DOMExceptionCode::kSyntaxError,
"'" + url + "' is not a valid URL.");
return;
}
if (dom_window_->IsInsecureScriptAccess(*current_window, completed_url))
return;
V8DOMActivityLogger* activity_logger =
V8DOMActivityLogger::CurrentActivityLoggerIfIsolatedWorld();
if (activity_logger) {
Vector<String> argv;
argv.push_back("LocalDOMWindow");
argv.push_back("url");
argv.push_back(entered_document->Url());
argv.push_back(completed_url);
activity_logger->LogEvent("blinkSetAttribute", argv.size(), argv.data());
}
WebFrameLoadType frame_load_type = WebFrameLoadType::kStandard;
if (set_location_policy == SetLocationPolicy::kReplaceThisFrame)
frame_load_type = WebFrameLoadType::kReplaceCurrentItem;
dom_window_->GetFrame()->ScheduleNavigation(*current_window->document(),
completed_url, frame_load_type,
UserGestureStatus::kNone);
}
Commit Message: Check the source browsing context's CSP in Location::SetLocation prior to dispatching a navigation to a `javascript:` URL.
Makes `javascript:` navigations via window.location.href compliant with
https://html.spec.whatwg.org/#navigate, which states that the source
browsing context must be checked (rather than the current browsing
context).
Bug: 909865
Change-Id: Id6aef6eef56865e164816c67eb9fe07ea1cb1b4e
Reviewed-on: https://chromium-review.googlesource.com/c/1359823
Reviewed-by: Andy Paicu <[email protected]>
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andrew Comminos <[email protected]>
Cr-Commit-Position: refs/heads/master@{#614451}
CWE ID: CWE-20 | void Location::SetLocation(const String& url,
LocalDOMWindow* current_window,
LocalDOMWindow* entered_window,
ExceptionState* exception_state,
SetLocationPolicy set_location_policy) {
if (!IsAttached())
return;
if (!current_window->GetFrame())
return;
Document* entered_document = entered_window->document();
if (!entered_document)
return;
KURL completed_url = entered_document->CompleteURL(url);
if (completed_url.IsNull())
return;
if (!current_window->GetFrame()->CanNavigate(*dom_window_->GetFrame(),
completed_url)) {
if (exception_state) {
exception_state->ThrowSecurityError(
"The current window does not have permission to navigate the target "
"frame to '" +
url + "'.");
}
return;
}
if (exception_state && !completed_url.IsValid()) {
exception_state->ThrowDOMException(DOMExceptionCode::kSyntaxError,
"'" + url + "' is not a valid URL.");
return;
}
if (dom_window_->IsInsecureScriptAccess(*current_window, completed_url))
return;
// Check the source browsing context's CSP to fulfill the CSP check
// requirement of https://html.spec.whatwg.org/#navigate for javascript URLs.
// Although the spec states we should perform this check on task execution,
// we do this prior to dispatch since the parent frame's CSP may be
// inaccessible if the target frame is out of process.
Document* current_document = current_window->document();
if (current_document && completed_url.ProtocolIsJavaScript() &&
!ContentSecurityPolicy::ShouldBypassMainWorld(current_document)) {
String script_source = DecodeURLEscapeSequences(completed_url.GetString());
if (!current_document->GetContentSecurityPolicy()->AllowJavaScriptURLs(
nullptr, script_source, current_document->Url(), OrdinalNumber())) {
return;
}
}
V8DOMActivityLogger* activity_logger =
V8DOMActivityLogger::CurrentActivityLoggerIfIsolatedWorld();
if (activity_logger) {
Vector<String> argv;
argv.push_back("LocalDOMWindow");
argv.push_back("url");
argv.push_back(entered_document->Url());
argv.push_back(completed_url);
activity_logger->LogEvent("blinkSetAttribute", argv.size(), argv.data());
}
WebFrameLoadType frame_load_type = WebFrameLoadType::kStandard;
if (set_location_policy == SetLocationPolicy::kReplaceThisFrame)
frame_load_type = WebFrameLoadType::kReplaceCurrentItem;
dom_window_->GetFrame()->ScheduleNavigation(*current_window->document(),
completed_url, frame_load_type,
UserGestureStatus::kNone);
}
| 173,061 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::MaybeLocal<v8::Value> V8Debugger::functionScopes(v8::Local<v8::Function> function)
{
if (!enabled()) {
NOTREACHED();
return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
}
v8::Local<v8::Value> argv[] = { function };
v8::Local<v8::Value> scopesValue;
if (!callDebuggerMethod("getFunctionScopes", 1, argv).ToLocal(&scopesValue) || !scopesValue->IsArray())
return v8::MaybeLocal<v8::Value>();
v8::Local<v8::Array> scopes = scopesValue.As<v8::Array>();
v8::Local<v8::Context> context = m_debuggerContext.Get(m_isolate);
if (!markAsInternal(context, scopes, V8InternalValueType::kScopeList))
return v8::MaybeLocal<v8::Value>();
if (!markArrayEntriesAsInternal(context, scopes, V8InternalValueType::kScope))
return v8::MaybeLocal<v8::Value>();
if (!scopes->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false))
return v8::Undefined(m_isolate);
return scopes;
}
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
CWE ID: CWE-79 | v8::MaybeLocal<v8::Value> V8Debugger::functionScopes(v8::Local<v8::Function> function)
v8::MaybeLocal<v8::Value> V8Debugger::functionScopes(v8::Local<v8::Context> context, v8::Local<v8::Function> function)
{
if (!enabled()) {
NOTREACHED();
return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
}
v8::Local<v8::Value> argv[] = { function };
v8::Local<v8::Value> scopesValue;
if (!callDebuggerMethod("getFunctionScopes", 1, argv).ToLocal(&scopesValue))
return v8::MaybeLocal<v8::Value>();
v8::Local<v8::Value> copied;
if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context, scopesValue).ToLocal(&copied) || !copied->IsArray())
return v8::MaybeLocal<v8::Value>();
if (!markAsInternal(context, v8::Local<v8::Array>::Cast(copied), V8InternalValueType::kScopeList))
return v8::MaybeLocal<v8::Value>();
if (!markArrayEntriesAsInternal(context, v8::Local<v8::Array>::Cast(copied), V8InternalValueType::kScope))
return v8::MaybeLocal<v8::Value>();
return copied;
}
| 172,066 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int vrend_create_shader(struct vrend_context *ctx,
uint32_t handle,
const struct pipe_stream_output_info *so_info,
const char *shd_text, uint32_t offlen, uint32_t num_tokens,
uint32_t type, uint32_t pkt_length)
{
struct vrend_shader_selector *sel = NULL;
int ret_handle;
bool new_shader = true, long_shader = false;
bool finished = false;
int ret;
if (type > PIPE_SHADER_GEOMETRY)
return EINVAL;
if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT)
new_shader = false;
else if (((offlen + 3) / 4) > pkt_length)
long_shader = true;
/* if we have an in progress one - don't allow a new shader
of that type or a different handle. */
if (ctx->sub->long_shader_in_progress_handle[type]) {
if (new_shader == true)
return EINVAL;
if (handle != ctx->sub->long_shader_in_progress_handle[type])
return EINVAL;
}
if (new_shader) {
sel = vrend_create_shader_state(ctx, so_info, type);
if (sel == NULL)
return ENOMEM;
if (long_shader) {
sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */
sel->tmp_buf = malloc(sel->buf_len);
if (!sel->tmp_buf) {
ret = ENOMEM;
goto error;
}
memcpy(sel->tmp_buf, shd_text, pkt_length * 4);
sel->buf_offset = pkt_length * 4;
ctx->sub->long_shader_in_progress_handle[type] = handle;
} else
finished = true;
} else {
sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER);
if (!sel) {
fprintf(stderr, "got continuation without original shader %d\n", handle);
ret = EINVAL;
goto error;
}
offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT;
if (offlen != sel->buf_offset) {
fprintf(stderr, "Got mismatched shader continuation %d vs %d\n",
offlen, sel->buf_offset);
ret = EINVAL;
goto error;
}
if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) {
fprintf(stderr, "Got too large shader continuation %d vs %d\n",
pkt_length * 4 + sel->buf_offset, sel->buf_len);
shd_text = sel->tmp_buf;
}
}
if (finished) {
struct tgsi_token *tokens;
tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token));
if (!tokens) {
ret = ENOMEM;
goto error;
}
if (vrend_dump_shaders)
fprintf(stderr,"shader\n%s\n", shd_text);
if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) {
free(tokens);
ret = EINVAL;
goto error;
}
if (vrend_finish_shader(ctx, sel, tokens)) {
free(tokens);
ret = EINVAL;
goto error;
} else {
free(sel->tmp_buf);
sel->tmp_buf = NULL;
}
free(tokens);
ctx->sub->long_shader_in_progress_handle[type] = 0;
}
if (new_shader) {
ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER);
if (ret_handle == 0) {
ret = ENOMEM;
goto error;
}
}
return 0;
error:
if (new_shader)
vrend_destroy_shader_selector(sel);
else
vrend_renderer_object_destroy(ctx, handle);
return ret;
}
Commit Message:
CWE ID: CWE-190 | int vrend_create_shader(struct vrend_context *ctx,
uint32_t handle,
const struct pipe_stream_output_info *so_info,
const char *shd_text, uint32_t offlen, uint32_t num_tokens,
uint32_t type, uint32_t pkt_length)
{
struct vrend_shader_selector *sel = NULL;
int ret_handle;
bool new_shader = true, long_shader = false;
bool finished = false;
int ret;
if (type > PIPE_SHADER_GEOMETRY)
return EINVAL;
if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT)
new_shader = false;
else if (((offlen + 3) / 4) > pkt_length)
long_shader = true;
/* if we have an in progress one - don't allow a new shader
of that type or a different handle. */
if (ctx->sub->long_shader_in_progress_handle[type]) {
if (new_shader == true)
return EINVAL;
if (handle != ctx->sub->long_shader_in_progress_handle[type])
return EINVAL;
}
if (new_shader) {
sel = vrend_create_shader_state(ctx, so_info, type);
if (sel == NULL)
return ENOMEM;
if (long_shader) {
sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */
sel->tmp_buf = malloc(sel->buf_len);
if (!sel->tmp_buf) {
ret = ENOMEM;
goto error;
}
memcpy(sel->tmp_buf, shd_text, pkt_length * 4);
sel->buf_offset = pkt_length * 4;
ctx->sub->long_shader_in_progress_handle[type] = handle;
} else
finished = true;
} else {
sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER);
if (!sel) {
fprintf(stderr, "got continuation without original shader %d\n", handle);
ret = EINVAL;
goto error;
}
offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT;
if (offlen != sel->buf_offset) {
fprintf(stderr, "Got mismatched shader continuation %d vs %d\n",
offlen, sel->buf_offset);
ret = EINVAL;
goto error;
}
/*make sure no overflow */
if (pkt_length * 4 < pkt_length ||
pkt_length * 4 + sel->buf_offset < pkt_length * 4 ||
pkt_length * 4 + sel->buf_offset < sel->buf_offset) {
ret = EINVAL;
goto error;
}
if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) {
fprintf(stderr, "Got too large shader continuation %d vs %d\n",
pkt_length * 4 + sel->buf_offset, sel->buf_len);
shd_text = sel->tmp_buf;
}
}
if (finished) {
struct tgsi_token *tokens;
tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token));
if (!tokens) {
ret = ENOMEM;
goto error;
}
if (vrend_dump_shaders)
fprintf(stderr,"shader\n%s\n", shd_text);
if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) {
free(tokens);
ret = EINVAL;
goto error;
}
if (vrend_finish_shader(ctx, sel, tokens)) {
free(tokens);
ret = EINVAL;
goto error;
} else {
free(sel->tmp_buf);
sel->tmp_buf = NULL;
}
free(tokens);
ctx->sub->long_shader_in_progress_handle[type] = 0;
}
if (new_shader) {
ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER);
if (ret_handle == 0) {
ret = ENOMEM;
goto error;
}
}
return 0;
error:
if (new_shader)
vrend_destroy_shader_selector(sel);
else
vrend_renderer_object_destroy(ctx, handle);
return ret;
}
| 164,945 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: pimv1_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
register const u_char *ep;
register u_char type;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
ND_TCHECK(bp[1]);
type = bp[1];
ND_PRINT((ndo, " %s", tok2str(pimv1_type_str, "[type %u]", type)));
switch (type) {
case PIMV1_TYPE_QUERY:
if (ND_TTEST(bp[8])) {
switch (bp[8] >> 4) {
case 0:
ND_PRINT((ndo, " Dense-mode"));
break;
case 1:
ND_PRINT((ndo, " Sparse-mode"));
break;
case 2:
ND_PRINT((ndo, " Sparse-Dense-mode"));
break;
default:
ND_PRINT((ndo, " mode-%d", bp[8] >> 4));
break;
}
}
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[10],2);
ND_PRINT((ndo, " (Hold-time "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[10]));
ND_PRINT((ndo, ")"));
}
break;
case PIMV1_TYPE_REGISTER:
ND_TCHECK2(bp[8], 20); /* ip header */
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[20]),
ipaddr_string(ndo, &bp[24])));
break;
case PIMV1_TYPE_REGISTER_STOP:
ND_TCHECK2(bp[12], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[8]),
ipaddr_string(ndo, &bp[12])));
break;
case PIMV1_TYPE_RP_REACHABILITY:
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[22], 2);
ND_PRINT((ndo, " group %s", ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_PRINT((ndo, " RP %s hold ", ipaddr_string(ndo, &bp[16])));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[22]));
}
break;
case PIMV1_TYPE_ASSERT:
ND_TCHECK2(bp[16], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[16]),
ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_TCHECK2(bp[24], 4);
ND_PRINT((ndo, " %s pref %d metric %d",
(bp[20] & 0x80) ? "RP-tree" : "SPT",
EXTRACT_32BITS(&bp[20]) & 0x7fffffff,
EXTRACT_32BITS(&bp[24])));
break;
case PIMV1_TYPE_JOIN_PRUNE:
case PIMV1_TYPE_GRAFT:
case PIMV1_TYPE_GRAFT_ACK:
if (ndo->ndo_vflag)
pimv1_join_prune_print(ndo, &bp[8], len - 8);
break;
}
ND_TCHECK(bp[4]);
if ((bp[4] >> 4) != 1)
ND_PRINT((ndo, " [v%d]", bp[4] >> 4));
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
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.
Update one test output file to reflect the changes.
CWE ID: CWE-125 | pimv1_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
register u_char type;
ND_TCHECK(bp[1]);
type = bp[1];
ND_PRINT((ndo, " %s", tok2str(pimv1_type_str, "[type %u]", type)));
switch (type) {
case PIMV1_TYPE_QUERY:
if (ND_TTEST(bp[8])) {
switch (bp[8] >> 4) {
case 0:
ND_PRINT((ndo, " Dense-mode"));
break;
case 1:
ND_PRINT((ndo, " Sparse-mode"));
break;
case 2:
ND_PRINT((ndo, " Sparse-Dense-mode"));
break;
default:
ND_PRINT((ndo, " mode-%d", bp[8] >> 4));
break;
}
}
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[10],2);
ND_PRINT((ndo, " (Hold-time "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[10]));
ND_PRINT((ndo, ")"));
}
break;
case PIMV1_TYPE_REGISTER:
ND_TCHECK2(bp[8], 20); /* ip header */
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[20]),
ipaddr_string(ndo, &bp[24])));
break;
case PIMV1_TYPE_REGISTER_STOP:
ND_TCHECK2(bp[12], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[8]),
ipaddr_string(ndo, &bp[12])));
break;
case PIMV1_TYPE_RP_REACHABILITY:
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[22], 2);
ND_PRINT((ndo, " group %s", ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_PRINT((ndo, " RP %s hold ", ipaddr_string(ndo, &bp[16])));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[22]));
}
break;
case PIMV1_TYPE_ASSERT:
ND_TCHECK2(bp[16], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[16]),
ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_TCHECK2(bp[24], 4);
ND_PRINT((ndo, " %s pref %d metric %d",
(bp[20] & 0x80) ? "RP-tree" : "SPT",
EXTRACT_32BITS(&bp[20]) & 0x7fffffff,
EXTRACT_32BITS(&bp[24])));
break;
case PIMV1_TYPE_JOIN_PRUNE:
case PIMV1_TYPE_GRAFT:
case PIMV1_TYPE_GRAFT_ACK:
if (ndo->ndo_vflag) {
if (len < 8)
goto trunc;
pimv1_join_prune_print(ndo, &bp[8], len - 8);
}
break;
}
ND_TCHECK(bp[4]);
if ((bp[4] >> 4) != 1)
ND_PRINT((ndo, " [v%d]", bp[4] >> 4));
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
| 167,856 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport Image *MeanShiftImage(const Image *image,const size_t width,
const size_t height,const double color_distance,ExceptionInfo *exception)
{
#define MaxMeanShiftIterations 100
#define MeanShiftImageTag "MeanShift/Image"
CacheView
*image_view,
*mean_view,
*pixel_view;
Image
*mean_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
mean_image=CloneImage(image,0,0,MagickTrue,exception);
if (mean_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(mean_image,DirectClass) == MagickFalse)
{
InheritException(exception,&mean_image->exception);
mean_image=DestroyImage(mean_image);
return((Image *) NULL);
}
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
pixel_view=AcquireVirtualCacheView(image,exception);
mean_view=AcquireAuthenticCacheView(mean_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status,progress) \
magick_number_threads(mean_image,mean_image,mean_image->rows,1)
#endif
for (y=0; y < (ssize_t) mean_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) mean_image->columns; x++)
{
MagickPixelPacket
mean_pixel,
previous_pixel;
PointInfo
mean_location,
previous_location;
register ssize_t
i;
GetMagickPixelPacket(image,&mean_pixel);
SetMagickPixelPacket(image,p,indexes+x,&mean_pixel);
mean_location.x=(double) x;
mean_location.y=(double) y;
for (i=0; i < MaxMeanShiftIterations; i++)
{
double
distance,
gamma;
MagickPixelPacket
sum_pixel;
PointInfo
sum_location;
ssize_t
count,
v;
sum_location.x=0.0;
sum_location.y=0.0;
GetMagickPixelPacket(image,&sum_pixel);
previous_location=mean_location;
previous_pixel=mean_pixel;
count=0;
for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++)
{
ssize_t
u;
for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++)
{
if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2)))
{
PixelPacket
pixel;
status=GetOneCacheViewVirtualPixel(pixel_view,(ssize_t)
MagickRound(mean_location.x+u),(ssize_t) MagickRound(
mean_location.y+v),&pixel,exception);
distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+
(mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+
(mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue);
if (distance <= (color_distance*color_distance))
{
sum_location.x+=mean_location.x+u;
sum_location.y+=mean_location.y+v;
sum_pixel.red+=pixel.red;
sum_pixel.green+=pixel.green;
sum_pixel.blue+=pixel.blue;
sum_pixel.opacity+=pixel.opacity;
count++;
}
}
}
}
gamma=1.0/count;
mean_location.x=gamma*sum_location.x;
mean_location.y=gamma*sum_location.y;
mean_pixel.red=gamma*sum_pixel.red;
mean_pixel.green=gamma*sum_pixel.green;
mean_pixel.blue=gamma*sum_pixel.blue;
mean_pixel.opacity=gamma*sum_pixel.opacity;
distance=(mean_location.x-previous_location.x)*
(mean_location.x-previous_location.x)+
(mean_location.y-previous_location.y)*
(mean_location.y-previous_location.y)+
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)*
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)*
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)*
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue);
if (distance <= 3.0)
break;
}
q->red=ClampToQuantum(mean_pixel.red);
q->green=ClampToQuantum(mean_pixel.green);
q->blue=ClampToQuantum(mean_pixel.blue);
q->opacity=ClampToQuantum(mean_pixel.opacity);
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
mean_view=DestroyCacheView(mean_view);
pixel_view=DestroyCacheView(pixel_view);
image_view=DestroyCacheView(image_view);
return(mean_image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1552
CWE ID: CWE-369 | MagickExport Image *MeanShiftImage(const Image *image,const size_t width,
const size_t height,const double color_distance,ExceptionInfo *exception)
{
#define MaxMeanShiftIterations 100
#define MeanShiftImageTag "MeanShift/Image"
CacheView
*image_view,
*mean_view,
*pixel_view;
Image
*mean_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
mean_image=CloneImage(image,0,0,MagickTrue,exception);
if (mean_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(mean_image,DirectClass) == MagickFalse)
{
InheritException(exception,&mean_image->exception);
mean_image=DestroyImage(mean_image);
return((Image *) NULL);
}
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
pixel_view=AcquireVirtualCacheView(image,exception);
mean_view=AcquireAuthenticCacheView(mean_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status,progress) \
magick_number_threads(mean_image,mean_image,mean_image->rows,1)
#endif
for (y=0; y < (ssize_t) mean_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) mean_image->columns; x++)
{
MagickPixelPacket
mean_pixel,
previous_pixel;
PointInfo
mean_location,
previous_location;
register ssize_t
i;
GetMagickPixelPacket(image,&mean_pixel);
SetMagickPixelPacket(image,p,indexes+x,&mean_pixel);
mean_location.x=(double) x;
mean_location.y=(double) y;
for (i=0; i < MaxMeanShiftIterations; i++)
{
double
distance,
gamma;
MagickPixelPacket
sum_pixel;
PointInfo
sum_location;
ssize_t
count,
v;
sum_location.x=0.0;
sum_location.y=0.0;
GetMagickPixelPacket(image,&sum_pixel);
previous_location=mean_location;
previous_pixel=mean_pixel;
count=0;
for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++)
{
ssize_t
u;
for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++)
{
if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2)))
{
PixelPacket
pixel;
status=GetOneCacheViewVirtualPixel(pixel_view,(ssize_t)
MagickRound(mean_location.x+u),(ssize_t) MagickRound(
mean_location.y+v),&pixel,exception);
distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+
(mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+
(mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue);
if (distance <= (color_distance*color_distance))
{
sum_location.x+=mean_location.x+u;
sum_location.y+=mean_location.y+v;
sum_pixel.red+=pixel.red;
sum_pixel.green+=pixel.green;
sum_pixel.blue+=pixel.blue;
sum_pixel.opacity+=pixel.opacity;
count++;
}
}
}
}
gamma=PerceptibleReciprocal(count);
mean_location.x=gamma*sum_location.x;
mean_location.y=gamma*sum_location.y;
mean_pixel.red=gamma*sum_pixel.red;
mean_pixel.green=gamma*sum_pixel.green;
mean_pixel.blue=gamma*sum_pixel.blue;
mean_pixel.opacity=gamma*sum_pixel.opacity;
distance=(mean_location.x-previous_location.x)*
(mean_location.x-previous_location.x)+
(mean_location.y-previous_location.y)*
(mean_location.y-previous_location.y)+
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)*
255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)*
255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)*
255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue);
if (distance <= 3.0)
break;
}
q->red=ClampToQuantum(mean_pixel.red);
q->green=ClampToQuantum(mean_pixel.green);
q->blue=ClampToQuantum(mean_pixel.blue);
q->opacity=ClampToQuantum(mean_pixel.opacity);
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
mean_view=DestroyCacheView(mean_view);
pixel_view=DestroyCacheView(pixel_view);
image_view=DestroyCacheView(image_view);
return(mean_image);
}
| 169,562 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RilSapSocket::sendDisconnect() {
size_t encoded_size = 0;
uint32_t written_size;
size_t buffer_size = 0;
pb_ostream_t ostream;
bool success = false;
RIL_SIM_SAP_DISCONNECT_REQ disconnectReq;
if ((success = pb_get_encoded_size(&encoded_size, RIL_SIM_SAP_DISCONNECT_REQ_fields,
&disconnectReq)) && encoded_size <= INT32_MAX) {
buffer_size = encoded_size + sizeof(uint32_t);
uint8_t buffer[buffer_size];
written_size = htonl((uint32_t) encoded_size);
ostream = pb_ostream_from_buffer(buffer, buffer_size);
pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size));
success = pb_encode(&ostream, RIL_SIM_SAP_DISCONNECT_REQ_fields, buffer);
if(success) {
pb_bytes_array_t *payload = (pb_bytes_array_t *)calloc(1,
sizeof(pb_bytes_array_t) + written_size);
if (!payload) {
RLOGE("sendDisconnect: OOM");
return;
}
memcpy(payload->bytes, buffer, written_size);
payload->size = written_size;
MsgHeader *hdr = (MsgHeader *)malloc(sizeof(MsgHeader));
if (!hdr) {
RLOGE("sendDisconnect: OOM");
free(payload);
return;
}
hdr->payload = payload;
hdr->type = MsgType_REQUEST;
hdr->id = MsgId_RIL_SIM_SAP_DISCONNECT;
hdr->error = Error_RIL_E_SUCCESS;
dispatchDisconnect(hdr);
}
else {
RLOGE("Encode failed in send disconnect!");
}
}
}
Commit Message: Replace variable-length arrays on stack with malloc.
Bug: 30202619
Change-Id: Ib95e08a1c009d88a4b4fd8d8fdba0641c6129008
(cherry picked from commit 943905bb9f99e3caa856b42c531e2be752da8834)
CWE ID: CWE-264 | void RilSapSocket::sendDisconnect() {
size_t encoded_size = 0;
uint32_t written_size;
size_t buffer_size = 0;
pb_ostream_t ostream;
bool success = false;
RIL_SIM_SAP_DISCONNECT_REQ disconnectReq;
if ((success = pb_get_encoded_size(&encoded_size, RIL_SIM_SAP_DISCONNECT_REQ_fields,
&disconnectReq)) && encoded_size <= INT32_MAX) {
buffer_size = encoded_size + sizeof(uint32_t);
uint8_t* buffer = (uint8_t*)malloc(buffer_size);
if (!buffer) {
RLOGE("sendDisconnect: OOM");
return;
}
written_size = htonl((uint32_t) encoded_size);
ostream = pb_ostream_from_buffer(buffer, buffer_size);
pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size));
success = pb_encode(&ostream, RIL_SIM_SAP_DISCONNECT_REQ_fields, buffer);
if(success) {
pb_bytes_array_t *payload = (pb_bytes_array_t *)calloc(1,
sizeof(pb_bytes_array_t) + written_size);
if (!payload) {
RLOGE("sendDisconnect: OOM");
return;
}
memcpy(payload->bytes, buffer, written_size);
payload->size = written_size;
MsgHeader *hdr = (MsgHeader *)malloc(sizeof(MsgHeader));
if (!hdr) {
RLOGE("sendDisconnect: OOM");
free(payload);
return;
}
hdr->payload = payload;
hdr->type = MsgType_REQUEST;
hdr->id = MsgId_RIL_SIM_SAP_DISCONNECT;
hdr->error = Error_RIL_E_SUCCESS;
dispatchDisconnect(hdr);
}
else {
RLOGE("Encode failed in send disconnect!");
}
free(buffer);
}
}
| 173,388 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline bool unconditional(const struct ipt_ip *ip)
{
static const struct ipt_ip uncond;
return memcmp(ip, &uncond, sizeof(uncond)) == 0;
#undef FWINV
}
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | static inline bool unconditional(const struct ipt_ip *ip)
static inline bool unconditional(const struct ipt_entry *e)
{
static const struct ipt_ip uncond;
return e->target_offset == sizeof(struct ipt_entry) &&
memcmp(&e->ip, &uncond, sizeof(uncond)) == 0;
#undef FWINV
}
| 167,371 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SplashOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref,
Stream *str, int width, int height,
GfxImageColorMap *colorMap,
Stream *maskStr,
int maskWidth, int maskHeight,
GfxImageColorMap *maskColorMap) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashOutImageData imgMaskData;
SplashColorMode srcMode;
SplashBitmap *maskBitmap;
Splash *maskSplash;
SplashColor maskColor;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgMaskData.imgStr = new ImageStream(maskStr, maskWidth,
maskColorMap->getNumPixelComps(),
maskColorMap->getBits());
imgMaskData.imgStr->reset();
imgMaskData.colorMap = maskColorMap;
imgMaskData.maskColors = NULL;
imgMaskData.colorMode = splashModeMono8;
imgMaskData.width = maskWidth;
imgMaskData.height = maskHeight;
imgMaskData.y = 0;
n = 1 << maskColorMap->getBits();
imgMaskData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
maskColorMap->getGray(&pix, &gray);
imgMaskData.lookup[i] = colToByte(gray);
}
maskBitmap = new SplashBitmap(bitmap->getWidth(), bitmap->getHeight(),
1, splashModeMono8, gFalse);
maskSplash = new Splash(maskBitmap, vectorAntialias);
maskColor[0] = 0;
maskSplash->clear(maskColor);
maskSplash->drawImage(&imageSrc, &imgMaskData, splashModeMono8, gFalse,
maskWidth, maskHeight, mat);
delete imgMaskData.imgStr;
maskStr->close();
gfree(imgMaskData.lookup);
delete maskSplash;
splash->setSoftMask(maskBitmap);
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = NULL;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmalloc(3 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
splash->drawImage(&imageSrc, &imgData, srcMode, gFalse, width, height, mat);
splash->setSoftMask(NULL);
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
Commit Message:
CWE ID: CWE-189 | void SplashOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref,
Stream *str, int width, int height,
GfxImageColorMap *colorMap,
Stream *maskStr,
int maskWidth, int maskHeight,
GfxImageColorMap *maskColorMap) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashOutImageData imgMaskData;
SplashColorMode srcMode;
SplashBitmap *maskBitmap;
Splash *maskSplash;
SplashColor maskColor;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgMaskData.imgStr = new ImageStream(maskStr, maskWidth,
maskColorMap->getNumPixelComps(),
maskColorMap->getBits());
imgMaskData.imgStr->reset();
imgMaskData.colorMap = maskColorMap;
imgMaskData.maskColors = NULL;
imgMaskData.colorMode = splashModeMono8;
imgMaskData.width = maskWidth;
imgMaskData.height = maskHeight;
imgMaskData.y = 0;
n = 1 << maskColorMap->getBits();
imgMaskData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
maskColorMap->getGray(&pix, &gray);
imgMaskData.lookup[i] = colToByte(gray);
}
maskBitmap = new SplashBitmap(bitmap->getWidth(), bitmap->getHeight(),
1, splashModeMono8, gFalse);
maskSplash = new Splash(maskBitmap, vectorAntialias);
maskColor[0] = 0;
maskSplash->clear(maskColor);
maskSplash->drawImage(&imageSrc, &imgMaskData, splashModeMono8, gFalse,
maskWidth, maskHeight, mat);
delete imgMaskData.imgStr;
maskStr->close();
gfree(imgMaskData.lookup);
delete maskSplash;
splash->setSoftMask(maskBitmap);
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = NULL;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
splash->drawImage(&imageSrc, &imgData, srcMode, gFalse, width, height, mat);
splash->setSoftMask(NULL);
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
| 164,616 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void sock_release(struct socket *sock)
{
if (sock->ops) {
struct module *owner = sock->ops->owner;
sock->ops->release(sock);
sock->ops = NULL;
module_put(owner);
}
if (rcu_dereference_protected(sock->wq, 1)->fasync_list)
pr_err("%s: fasync list not empty!\n", __func__);
if (!sock->file) {
iput(SOCK_INODE(sock));
return;
}
sock->file = NULL;
}
Commit Message: socket: close race condition between sock_close() and sockfs_setattr()
fchownat() doesn't even hold refcnt of fd until it figures out
fd is really needed (otherwise is ignored) and releases it after
it resolves the path. This means sock_close() could race with
sockfs_setattr(), which leads to a NULL pointer dereference
since typically we set sock->sk to NULL in ->release().
As pointed out by Al, this is unique to sockfs. So we can fix this
in socket layer by acquiring inode_lock in sock_close() and
checking against NULL in sockfs_setattr().
sock_release() is called in many places, only the sock_close()
path matters here. And fortunately, this should not affect normal
sock_close() as it is only called when the last fd refcnt is gone.
It only affects sock_close() with a parallel sockfs_setattr() in
progress, which is not common.
Fixes: 86741ec25462 ("net: core: Add a UID field to struct sock.")
Reported-by: shankarapailoor <[email protected]>
Cc: Tetsuo Handa <[email protected]>
Cc: Lorenzo Colitti <[email protected]>
Cc: Al Viro <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | void sock_release(struct socket *sock)
static void __sock_release(struct socket *sock, struct inode *inode)
{
if (sock->ops) {
struct module *owner = sock->ops->owner;
if (inode)
inode_lock(inode);
sock->ops->release(sock);
if (inode)
inode_unlock(inode);
sock->ops = NULL;
module_put(owner);
}
if (rcu_dereference_protected(sock->wq, 1)->fasync_list)
pr_err("%s: fasync list not empty!\n", __func__);
if (!sock->file) {
iput(SOCK_INODE(sock));
return;
}
sock->file = NULL;
}
| 169,204 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns)
{
struct mnt_namespace *new_ns;
struct ucounts *ucounts;
int ret;
ucounts = inc_mnt_namespaces(user_ns);
if (!ucounts)
return ERR_PTR(-ENOSPC);
new_ns = kmalloc(sizeof(struct mnt_namespace), GFP_KERNEL);
if (!new_ns) {
dec_mnt_namespaces(ucounts);
return ERR_PTR(-ENOMEM);
}
ret = ns_alloc_inum(&new_ns->ns);
if (ret) {
kfree(new_ns);
dec_mnt_namespaces(ucounts);
return ERR_PTR(ret);
}
new_ns->ns.ops = &mntns_operations;
new_ns->seq = atomic64_add_return(1, &mnt_ns_seq);
atomic_set(&new_ns->count, 1);
new_ns->root = NULL;
INIT_LIST_HEAD(&new_ns->list);
init_waitqueue_head(&new_ns->poll);
new_ns->event = 0;
new_ns->user_ns = get_user_ns(user_ns);
new_ns->ucounts = ucounts;
return new_ns;
}
Commit Message: mnt: Add a per mount namespace limit on the number of mounts
CAI Qian <[email protected]> pointed out that the semantics
of shared subtrees make it possible to create an exponentially
increasing number of mounts in a mount namespace.
mkdir /tmp/1 /tmp/2
mount --make-rshared /
for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done
Will create create 2^20 or 1048576 mounts, which is a practical problem
as some people have managed to hit this by accident.
As such CVE-2016-6213 was assigned.
Ian Kent <[email protected]> described the situation for autofs users
as follows:
> The number of mounts for direct mount maps is usually not very large because of
> the way they are implemented, large direct mount maps can have performance
> problems. There can be anywhere from a few (likely case a few hundred) to less
> than 10000, plus mounts that have been triggered and not yet expired.
>
> Indirect mounts have one autofs mount at the root plus the number of mounts that
> have been triggered and not yet expired.
>
> The number of autofs indirect map entries can range from a few to the common
> case of several thousand and in rare cases up to between 30000 and 50000. I've
> not heard of people with maps larger than 50000 entries.
>
> The larger the number of map entries the greater the possibility for a large
> number of active mounts so it's not hard to expect cases of a 1000 or somewhat
> more active mounts.
So I am setting the default number of mounts allowed per mount
namespace at 100,000. This is more than enough for any use case I
know of, but small enough to quickly stop an exponential increase
in mounts. Which should be perfect to catch misconfigurations and
malfunctioning programs.
For anyone who needs a higher limit this can be changed by writing
to the new /proc/sys/fs/mount-max sysctl.
Tested-by: CAI Qian <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-400 | static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns)
{
struct mnt_namespace *new_ns;
struct ucounts *ucounts;
int ret;
ucounts = inc_mnt_namespaces(user_ns);
if (!ucounts)
return ERR_PTR(-ENOSPC);
new_ns = kmalloc(sizeof(struct mnt_namespace), GFP_KERNEL);
if (!new_ns) {
dec_mnt_namespaces(ucounts);
return ERR_PTR(-ENOMEM);
}
ret = ns_alloc_inum(&new_ns->ns);
if (ret) {
kfree(new_ns);
dec_mnt_namespaces(ucounts);
return ERR_PTR(ret);
}
new_ns->ns.ops = &mntns_operations;
new_ns->seq = atomic64_add_return(1, &mnt_ns_seq);
atomic_set(&new_ns->count, 1);
new_ns->root = NULL;
INIT_LIST_HEAD(&new_ns->list);
init_waitqueue_head(&new_ns->poll);
new_ns->event = 0;
new_ns->user_ns = get_user_ns(user_ns);
new_ns->ucounts = ucounts;
new_ns->mounts = 0;
new_ns->pending_mounts = 0;
return new_ns;
}
| 167,006 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_hidp_sock_ioctl(struct socket *sock, unsigned int cmd, void __user *argp)
{
struct hidp_connadd_req ca;
struct hidp_conndel_req cd;
struct hidp_connlist_req cl;
struct hidp_conninfo ci;
struct socket *csock;
struct socket *isock;
int err;
BT_DBG("cmd %x arg %p", cmd, argp);
switch (cmd) {
case HIDPCONNADD:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&ca, argp, sizeof(ca)))
return -EFAULT;
csock = sockfd_lookup(ca.ctrl_sock, &err);
if (!csock)
return err;
isock = sockfd_lookup(ca.intr_sock, &err);
if (!isock) {
sockfd_put(csock);
return err;
}
err = hidp_connection_add(&ca, csock, isock);
if (!err && copy_to_user(argp, &ca, sizeof(ca)))
err = -EFAULT;
sockfd_put(csock);
sockfd_put(isock);
return err;
case HIDPCONNDEL:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&cd, argp, sizeof(cd)))
return -EFAULT;
return hidp_connection_del(&cd);
case HIDPGETCONNLIST:
if (copy_from_user(&cl, argp, sizeof(cl)))
return -EFAULT;
if (cl.cnum <= 0)
return -EINVAL;
err = hidp_get_connlist(&cl);
if (!err && copy_to_user(argp, &cl, sizeof(cl)))
return -EFAULT;
return err;
case HIDPGETCONNINFO:
if (copy_from_user(&ci, argp, sizeof(ci)))
return -EFAULT;
err = hidp_get_conninfo(&ci);
if (!err && copy_to_user(argp, &ci, sizeof(ci)))
return -EFAULT;
return err;
}
return -EINVAL;
}
Commit Message: Bluetooth: hidp: fix buffer overflow
Struct ca is copied from userspace. It is not checked whether the "name"
field is NULL terminated, which allows local users to obtain potentially
sensitive information from kernel stack memory, via a HIDPCONNADD command.
This vulnerability is similar to CVE-2011-1079.
Signed-off-by: Young Xiao <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
Cc: [email protected]
CWE ID: CWE-77 | static int do_hidp_sock_ioctl(struct socket *sock, unsigned int cmd, void __user *argp)
{
struct hidp_connadd_req ca;
struct hidp_conndel_req cd;
struct hidp_connlist_req cl;
struct hidp_conninfo ci;
struct socket *csock;
struct socket *isock;
int err;
BT_DBG("cmd %x arg %p", cmd, argp);
switch (cmd) {
case HIDPCONNADD:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&ca, argp, sizeof(ca)))
return -EFAULT;
csock = sockfd_lookup(ca.ctrl_sock, &err);
if (!csock)
return err;
isock = sockfd_lookup(ca.intr_sock, &err);
if (!isock) {
sockfd_put(csock);
return err;
}
ca.name[sizeof(ca.name)-1] = 0;
err = hidp_connection_add(&ca, csock, isock);
if (!err && copy_to_user(argp, &ca, sizeof(ca)))
err = -EFAULT;
sockfd_put(csock);
sockfd_put(isock);
return err;
case HIDPCONNDEL:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&cd, argp, sizeof(cd)))
return -EFAULT;
return hidp_connection_del(&cd);
case HIDPGETCONNLIST:
if (copy_from_user(&cl, argp, sizeof(cl)))
return -EFAULT;
if (cl.cnum <= 0)
return -EINVAL;
err = hidp_get_connlist(&cl);
if (!err && copy_to_user(argp, &cl, sizeof(cl)))
return -EFAULT;
return err;
case HIDPGETCONNINFO:
if (copy_from_user(&ci, argp, sizeof(ci)))
return -EFAULT;
err = hidp_get_conninfo(&ci);
if (!err && copy_to_user(argp, &ci, sizeof(ci)))
return -EFAULT;
return err;
}
return -EINVAL;
}
| 169,676 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderMessageFilter::OnCreateWindow(
const ViewHostMsg_CreateWindow_Params& params,
int* route_id,
int* surface_id,
int64* cloned_session_storage_namespace_id) {
bool no_javascript_access;
bool can_create_window =
GetContentClient()->browser()->CanCreateWindow(
GURL(params.opener_url),
GURL(params.opener_security_origin),
params.window_container_type,
resource_context_,
render_process_id_,
&no_javascript_access);
if (!can_create_window) {
*route_id = MSG_ROUTING_NONE;
*surface_id = 0;
return;
}
scoped_refptr<SessionStorageNamespaceImpl> cloned_namespace =
new SessionStorageNamespaceImpl(dom_storage_context_,
params.session_storage_namespace_id);
*cloned_session_storage_namespace_id = cloned_namespace->id();
render_widget_helper_->CreateNewWindow(params,
no_javascript_access,
peer_handle(),
route_id,
surface_id,
cloned_namespace);
}
Commit Message: Filter more incoming URLs in the CreateWindow path.
BUG=170532
Review URL: https://chromiumcodereview.appspot.com/12036002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderMessageFilter::OnCreateWindow(
const ViewHostMsg_CreateWindow_Params& params,
int* route_id,
int* surface_id,
int64* cloned_session_storage_namespace_id) {
bool no_javascript_access;
bool can_create_window =
GetContentClient()->browser()->CanCreateWindow(
params.opener_url,
params.opener_security_origin,
params.window_container_type,
resource_context_,
render_process_id_,
&no_javascript_access);
if (!can_create_window) {
*route_id = MSG_ROUTING_NONE;
*surface_id = 0;
return;
}
scoped_refptr<SessionStorageNamespaceImpl> cloned_namespace =
new SessionStorageNamespaceImpl(dom_storage_context_,
params.session_storage_namespace_id);
*cloned_session_storage_namespace_id = cloned_namespace->id();
render_widget_helper_->CreateNewWindow(params,
no_javascript_access,
peer_handle(),
route_id,
surface_id,
cloned_namespace);
}
| 171,497 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context)
: ObjectBackedNativeHandler(context), weak_ptr_factory_(this) {
RouteFunction(
"OnDocumentElementCreated",
base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated,
base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284 | RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context)
: ObjectBackedNativeHandler(context), weak_ptr_factory_(this) {
RouteFunction(
"OnDocumentElementCreated", "app.window",
base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated,
base::Unretained(this)));
}
| 172,252 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int decode_getacl(struct xdr_stream *xdr, struct rpc_rqst *req,
size_t *acl_len)
{
__be32 *savep;
uint32_t attrlen,
bitmap[3] = {0};
struct kvec *iov = req->rq_rcv_buf.head;
int status;
*acl_len = 0;
if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0)
goto out;
if ((status = decode_attr_bitmap(xdr, bitmap)) != 0)
goto out;
if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0)
goto out;
if (unlikely(bitmap[0] & (FATTR4_WORD0_ACL - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_ACL)) {
size_t hdrlen;
u32 recvd;
/* We ignore &savep and don't do consistency checks on
* the attr length. Let userspace figure it out.... */
hdrlen = (u8 *)xdr->p - (u8 *)iov->iov_base;
recvd = req->rq_rcv_buf.len - hdrlen;
if (attrlen > recvd) {
dprintk("NFS: server cheating in getattr"
" acl reply: attrlen %u > recvd %u\n",
attrlen, recvd);
return -EINVAL;
}
xdr_read_pages(xdr, attrlen);
*acl_len = attrlen;
} else
status = -EOPNOTSUPP;
out:
return status;
}
Commit Message: NFSv4: include bitmap in nfsv4 get acl data
The NFSv4 bitmap size is unbounded: a server can return an arbitrary
sized bitmap in an FATTR4_WORD0_ACL request. Replace using the
nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server
with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data
xdr length to the (cached) acl page data.
This is a general solution to commit e5012d1f "NFSv4.1: update
nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead
when getting ACLs.
Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr
was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved.
Cc: [email protected]
Signed-off-by: Andy Adamson <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-189 | static int decode_getacl(struct xdr_stream *xdr, struct rpc_rqst *req,
struct nfs_getaclres *res)
{
__be32 *savep, *bm_p;
uint32_t attrlen,
bitmap[3] = {0};
struct kvec *iov = req->rq_rcv_buf.head;
int status;
res->acl_len = 0;
if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0)
goto out;
bm_p = xdr->p;
if ((status = decode_attr_bitmap(xdr, bitmap)) != 0)
goto out;
if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0)
goto out;
if (unlikely(bitmap[0] & (FATTR4_WORD0_ACL - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_ACL)) {
size_t hdrlen;
u32 recvd;
/* The bitmap (xdr len + bitmaps) and the attr xdr len words
* are stored with the acl data to handle the problem of
* variable length bitmaps.*/
xdr->p = bm_p;
res->acl_data_offset = be32_to_cpup(bm_p) + 2;
res->acl_data_offset <<= 2;
/* We ignore &savep and don't do consistency checks on
* the attr length. Let userspace figure it out.... */
hdrlen = (u8 *)xdr->p - (u8 *)iov->iov_base;
attrlen += res->acl_data_offset;
recvd = req->rq_rcv_buf.len - hdrlen;
if (attrlen > recvd) {
if (res->acl_flags & NFS4_ACL_LEN_REQUEST) {
/* getxattr interface called with a NULL buf */
res->acl_len = attrlen;
goto out;
}
dprintk("NFS: acl reply: attrlen %u > recvd %u\n",
attrlen, recvd);
return -EINVAL;
}
xdr_read_pages(xdr, attrlen);
res->acl_len = attrlen;
} else
status = -EOPNOTSUPP;
out:
return status;
}
| 165,719 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int venc_dev::venc_output_log_buffers(const char *buffer_addr, int buffer_len)
{
if (!m_debug.outfile) {
int size = 0;
if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.m4v",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H264) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.264",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_HEVC) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%ld_%ld_%p.265",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H263) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.263",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_VP8) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.ivf",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
}
if ((size > PROPERTY_VALUE_MAX) && (size < 0)) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d",
m_debug.outfile_name, size);
}
m_debug.outfile = fopen(m_debug.outfile_name, "ab");
if (!m_debug.outfile) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging errno:%d",
m_debug.outfile_name, errno);
m_debug.outfile_name[0] = '\0';
return -1;
}
}
if (m_debug.outfile && buffer_len) {
DEBUG_PRINT_LOW("%s buffer_len:%d", __func__, buffer_len);
fwrite(buffer_addr, buffer_len, 1, m_debug.outfile);
}
return 0;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers
Heap pointers do not point to user virtual addresses in case
of secure session.
Set them to NULL and add checks to avoid accesing them
Bug: 28815329
Bug: 28920116
Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26
CWE ID: CWE-200 | int venc_dev::venc_output_log_buffers(const char *buffer_addr, int buffer_len)
{
if (venc_handle->is_secure_session()) {
DEBUG_PRINT_ERROR("logging secure output buffers is not allowed!");
return -1;
}
if (!m_debug.outfile) {
int size = 0;
if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.m4v",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H264) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.264",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_HEVC) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%ld_%ld_%p.265",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H263) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.263",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_VP8) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.ivf",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
}
if ((size > PROPERTY_VALUE_MAX) && (size < 0)) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d",
m_debug.outfile_name, size);
}
m_debug.outfile = fopen(m_debug.outfile_name, "ab");
if (!m_debug.outfile) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging errno:%d",
m_debug.outfile_name, errno);
m_debug.outfile_name[0] = '\0';
return -1;
}
}
if (m_debug.outfile && buffer_len) {
DEBUG_PRINT_LOW("%s buffer_len:%d", __func__, buffer_len);
fwrite(buffer_addr, buffer_len, 1, m_debug.outfile);
}
return 0;
}
| 173,507 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_init (MyObject *obj)
{
obj->val = 0;
}
Commit Message:
CWE ID: CWE-264 | my_object_init (MyObject *obj)
| 165,109 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void update_exception_bitmap(struct kvm_vcpu *vcpu)
{
u32 eb;
eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
(1u << NM_VECTOR) | (1u << DB_VECTOR);
if ((vcpu->guest_debug &
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
eb |= 1u << BP_VECTOR;
if (to_vmx(vcpu)->rmode.vm86_active)
eb = ~0;
if (enable_ept)
eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
if (vcpu->fpu_active)
eb &= ~(1u << NM_VECTOR);
/* When we are running a nested L2 guest and L1 specified for it a
* certain exception bitmap, we must trap the same exceptions and pass
* them to L1. When running L2, we will only handle the exceptions
* specified above if L1 did not want them.
*/
if (is_guest_mode(vcpu))
eb |= get_vmcs12(vcpu)->exception_bitmap;
vmcs_write32(EXCEPTION_BITMAP, eb);
}
Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered
It was found that a guest can DoS a host by triggering an infinite
stream of "alignment check" (#AC) exceptions. This causes the
microcode to enter an infinite loop where the core never receives
another interrupt. The host kernel panics pretty quickly due to the
effects (CVE-2015-5307).
Signed-off-by: Eric Northup <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-399 | static void update_exception_bitmap(struct kvm_vcpu *vcpu)
{
u32 eb;
eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
(1u << NM_VECTOR) | (1u << DB_VECTOR) | (1u << AC_VECTOR);
if ((vcpu->guest_debug &
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
eb |= 1u << BP_VECTOR;
if (to_vmx(vcpu)->rmode.vm86_active)
eb = ~0;
if (enable_ept)
eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
if (vcpu->fpu_active)
eb &= ~(1u << NM_VECTOR);
/* When we are running a nested L2 guest and L1 specified for it a
* certain exception bitmap, we must trap the same exceptions and pass
* them to L1. When running L2, we will only handle the exceptions
* specified above if L1 did not want them.
*/
if (is_guest_mode(vcpu))
eb |= get_vmcs12(vcpu)->exception_bitmap;
vmcs_write32(EXCEPTION_BITMAP, eb);
}
| 166,600 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Handle<v8::Value> V8WebKitMutationObserver::constructorCallback(const v8::Arguments& args)
{
INC_STATS("DOM.WebKitMutationObserver.Constructor");
if (!args.IsConstructCall())
return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function.");
if (ConstructorMode::current() == ConstructorMode::WrapExistingObject)
return args.Holder();
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
v8::Local<v8::Value> arg = args[0];
if (!arg->IsObject())
return throwError(TYPE_MISMATCH_ERR, args.GetIsolate());
ScriptExecutionContext* context = getScriptExecutionContext();
if (!context)
return V8Proxy::throwError(V8Proxy::ReferenceError, "WebKitMutationObserver constructor's associated frame unavailable", args.GetIsolate());
RefPtr<MutationCallback> callback = V8MutationCallback::create(arg, context);
RefPtr<WebKitMutationObserver> observer = WebKitMutationObserver::create(callback.release());
V8DOMWrapper::setDOMWrapper(args.Holder(), &info, observer.get());
V8DOMWrapper::setJSWrapperForDOMObject(observer.release(), v8::Persistent<v8::Object>::New(args.Holder()));
return args.Holder();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | v8::Handle<v8::Value> V8WebKitMutationObserver::constructorCallback(const v8::Arguments& args)
{
INC_STATS("DOM.WebKitMutationObserver.Constructor");
if (!args.IsConstructCall())
return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function.");
if (ConstructorMode::current() == ConstructorMode::WrapExistingObject)
return args.Holder();
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
v8::Local<v8::Value> arg = args[0];
if (!arg->IsObject())
return throwError(TYPE_MISMATCH_ERR, args.GetIsolate());
ScriptExecutionContext* context = getScriptExecutionContext();
if (!context)
return V8Proxy::throwError(V8Proxy::ReferenceError, "WebKitMutationObserver constructor's associated frame unavailable", args.GetIsolate());
RefPtr<MutationCallback> callback = V8MutationCallback::create(arg, context);
RefPtr<WebKitMutationObserver> observer = WebKitMutationObserver::create(callback.release());
V8DOMWrapper::setDOMWrapper(args.Holder(), &info, observer.get());
V8DOMWrapper::setJSWrapperForDOMObject(observer.release(), v8::Persistent<v8::Object>::New(args.Holder()));
return args.Holder();
}
| 171,131 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t o2nm_node_local_store(struct config_item *item, const char *page,
size_t count)
{
struct o2nm_node *node = to_o2nm_node(item);
struct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node);
unsigned long tmp;
char *p = (char *)page;
ssize_t ret;
tmp = simple_strtoul(p, &p, 0);
if (!p || (*p && (*p != '\n')))
return -EINVAL;
tmp = !!tmp; /* boolean of whether this node wants to be local */
/* setting local turns on networking rx for now so we require having
* set everything else first */
if (!test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes) ||
!test_bit(O2NM_NODE_ATTR_NUM, &node->nd_set_attributes) ||
!test_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes))
return -EINVAL; /* XXX */
/* the only failure case is trying to set a new local node
* when a different one is already set */
if (tmp && tmp == cluster->cl_has_local &&
cluster->cl_local_node != node->nd_num)
return -EBUSY;
/* bring up the rx thread if we're setting the new local node. */
if (tmp && !cluster->cl_has_local) {
ret = o2net_start_listening(node);
if (ret)
return ret;
}
if (!tmp && cluster->cl_has_local &&
cluster->cl_local_node == node->nd_num) {
o2net_stop_listening(node);
cluster->cl_local_node = O2NM_INVALID_NODE_NUM;
}
node->nd_local = tmp;
if (node->nd_local) {
cluster->cl_has_local = tmp;
cluster->cl_local_node = node->nd_num;
}
return count;
}
Commit Message: ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent
The subsystem.su_mutex is required while accessing the item->ci_parent,
otherwise, NULL pointer dereference to the item->ci_parent will be
triggered in the following situation:
add node delete node
sys_write
vfs_write
configfs_write_file
o2nm_node_store
o2nm_node_local_write
do_rmdir
vfs_rmdir
configfs_rmdir
mutex_lock(&subsys->su_mutex);
unlink_obj
item->ci_group = NULL;
item->ci_parent = NULL;
to_o2nm_cluster_from_node
node->nd_item.ci_parent->ci_parent
BUG since of NULL pointer dereference to nd_item.ci_parent
Moreover, the o2nm_cluster also should be protected by the
subsystem.su_mutex.
[[email protected]: v2]
Link: http://lkml.kernel.org/r/[email protected]
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Alex Chen <[email protected]>
Reviewed-by: Jun Piao <[email protected]>
Reviewed-by: Joseph Qi <[email protected]>
Cc: Mark Fasheh <[email protected]>
Cc: Joel Becker <[email protected]>
Cc: Junxiao Bi <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-476 | static ssize_t o2nm_node_local_store(struct config_item *item, const char *page,
size_t count)
{
struct o2nm_node *node = to_o2nm_node(item);
struct o2nm_cluster *cluster;
unsigned long tmp;
char *p = (char *)page;
ssize_t ret;
tmp = simple_strtoul(p, &p, 0);
if (!p || (*p && (*p != '\n')))
return -EINVAL;
tmp = !!tmp; /* boolean of whether this node wants to be local */
/* setting local turns on networking rx for now so we require having
* set everything else first */
if (!test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes) ||
!test_bit(O2NM_NODE_ATTR_NUM, &node->nd_set_attributes) ||
!test_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes))
return -EINVAL; /* XXX */
o2nm_lock_subsystem();
cluster = to_o2nm_cluster_from_node(node);
if (!cluster) {
ret = -EINVAL;
goto out;
}
/* the only failure case is trying to set a new local node
* when a different one is already set */
if (tmp && tmp == cluster->cl_has_local &&
cluster->cl_local_node != node->nd_num) {
ret = -EBUSY;
goto out;
}
/* bring up the rx thread if we're setting the new local node. */
if (tmp && !cluster->cl_has_local) {
ret = o2net_start_listening(node);
if (ret)
goto out;
}
if (!tmp && cluster->cl_has_local &&
cluster->cl_local_node == node->nd_num) {
o2net_stop_listening(node);
cluster->cl_local_node = O2NM_INVALID_NODE_NUM;
}
node->nd_local = tmp;
if (node->nd_local) {
cluster->cl_has_local = tmp;
cluster->cl_local_node = node->nd_num;
}
ret = count;
out:
o2nm_unlock_subsystem();
return ret;
}
| 169,406 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
u32 *sid, u32 def_sid, gfp_t gfp_flags,
int force)
{
char *scontext2, *str = NULL;
struct context context;
int rc = 0;
if (!ss_initialized) {
int i;
for (i = 1; i < SECINITSID_NUM; i++) {
if (!strcmp(initial_sid_to_string[i], scontext)) {
*sid = i;
return 0;
}
}
*sid = SECINITSID_KERNEL;
return 0;
}
*sid = SECSID_NULL;
/* Copy the string so that we can modify the copy as we parse it. */
scontext2 = kmalloc(scontext_len + 1, gfp_flags);
if (!scontext2)
return -ENOMEM;
memcpy(scontext2, scontext, scontext_len);
scontext2[scontext_len] = 0;
if (force) {
/* Save another copy for storing in uninterpreted form */
rc = -ENOMEM;
str = kstrdup(scontext2, gfp_flags);
if (!str)
goto out;
}
read_lock(&policy_rwlock);
rc = string_to_context_struct(&policydb, &sidtab, scontext2,
scontext_len, &context, def_sid);
if (rc == -EINVAL && force) {
context.str = str;
context.len = scontext_len;
str = NULL;
} else if (rc)
goto out_unlock;
rc = sidtab_context_to_sid(&sidtab, &context, sid);
context_destroy(&context);
out_unlock:
read_unlock(&policy_rwlock);
out:
kfree(scontext2);
kfree(str);
return rc;
}
Commit Message: SELinux: Fix kernel BUG on empty security contexts.
Setting an empty security context (length=0) on a file will
lead to incorrectly dereferencing the type and other fields
of the security context structure, yielding a kernel BUG.
As a zero-length security context is never valid, just reject
all such security contexts whether coming from userspace
via setxattr or coming from the filesystem upon a getxattr
request by SELinux.
Setting a security context value (empty or otherwise) unknown to
SELinux in the first place is only possible for a root process
(CAP_MAC_ADMIN), and, if running SELinux in enforcing mode, only
if the corresponding SELinux mac_admin permission is also granted
to the domain by policy. In Fedora policies, this is only allowed for
specific domains such as livecd for setting down security contexts
that are not defined in the build host policy.
Reproducer:
su
setenforce 0
touch foo
setfattr -n security.selinux foo
Caveat:
Relabeling or removing foo after doing the above may not be possible
without booting with SELinux disabled. Any subsequent access to foo
after doing the above will also trigger the BUG.
BUG output from Matthew Thode:
[ 473.893141] ------------[ cut here ]------------
[ 473.962110] kernel BUG at security/selinux/ss/services.c:654!
[ 473.995314] invalid opcode: 0000 [#6] SMP
[ 474.027196] Modules linked in:
[ 474.058118] CPU: 0 PID: 8138 Comm: ls Tainted: G D I
3.13.0-grsec #1
[ 474.116637] Hardware name: Supermicro X8ST3/X8ST3, BIOS 2.0
07/29/10
[ 474.149768] task: ffff8805f50cd010 ti: ffff8805f50cd488 task.ti:
ffff8805f50cd488
[ 474.183707] RIP: 0010:[<ffffffff814681c7>] [<ffffffff814681c7>]
context_struct_compute_av+0xce/0x308
[ 474.219954] RSP: 0018:ffff8805c0ac3c38 EFLAGS: 00010246
[ 474.252253] RAX: 0000000000000000 RBX: ffff8805c0ac3d94 RCX:
0000000000000100
[ 474.287018] RDX: ffff8805e8aac000 RSI: 00000000ffffffff RDI:
ffff8805e8aaa000
[ 474.321199] RBP: ffff8805c0ac3cb8 R08: 0000000000000010 R09:
0000000000000006
[ 474.357446] R10: 0000000000000000 R11: ffff8805c567a000 R12:
0000000000000006
[ 474.419191] R13: ffff8805c2b74e88 R14: 00000000000001da R15:
0000000000000000
[ 474.453816] FS: 00007f2e75220800(0000) GS:ffff88061fc00000(0000)
knlGS:0000000000000000
[ 474.489254] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 474.522215] CR2: 00007f2e74716090 CR3: 00000005c085e000 CR4:
00000000000207f0
[ 474.556058] Stack:
[ 474.584325] ffff8805c0ac3c98 ffffffff811b549b ffff8805c0ac3c98
ffff8805f1190a40
[ 474.618913] ffff8805a6202f08 ffff8805c2b74e88 00068800d0464990
ffff8805e8aac860
[ 474.653955] ffff8805c0ac3cb8 000700068113833a ffff880606c75060
ffff8805c0ac3d94
[ 474.690461] Call Trace:
[ 474.723779] [<ffffffff811b549b>] ? lookup_fast+0x1cd/0x22a
[ 474.778049] [<ffffffff81468824>] security_compute_av+0xf4/0x20b
[ 474.811398] [<ffffffff8196f419>] avc_compute_av+0x2a/0x179
[ 474.843813] [<ffffffff8145727b>] avc_has_perm+0x45/0xf4
[ 474.875694] [<ffffffff81457d0e>] inode_has_perm+0x2a/0x31
[ 474.907370] [<ffffffff81457e76>] selinux_inode_getattr+0x3c/0x3e
[ 474.938726] [<ffffffff81455cf6>] security_inode_getattr+0x1b/0x22
[ 474.970036] [<ffffffff811b057d>] vfs_getattr+0x19/0x2d
[ 475.000618] [<ffffffff811b05e5>] vfs_fstatat+0x54/0x91
[ 475.030402] [<ffffffff811b063b>] vfs_lstat+0x19/0x1b
[ 475.061097] [<ffffffff811b077e>] SyS_newlstat+0x15/0x30
[ 475.094595] [<ffffffff8113c5c1>] ? __audit_syscall_entry+0xa1/0xc3
[ 475.148405] [<ffffffff8197791e>] system_call_fastpath+0x16/0x1b
[ 475.179201] Code: 00 48 85 c0 48 89 45 b8 75 02 0f 0b 48 8b 45 a0 48
8b 3d 45 d0 b6 00 8b 40 08 89 c6 ff ce e8 d1 b0 06 00 48 85 c0 49 89 c7
75 02 <0f> 0b 48 8b 45 b8 4c 8b 28 eb 1e 49 8d 7d 08 be 80 01 00 00 e8
[ 475.255884] RIP [<ffffffff814681c7>]
context_struct_compute_av+0xce/0x308
[ 475.296120] RSP <ffff8805c0ac3c38>
[ 475.328734] ---[ end trace f076482e9d754adc ]---
Reported-by: Matthew Thode <[email protected]>
Signed-off-by: Stephen Smalley <[email protected]>
Cc: [email protected]
Signed-off-by: Paul Moore <[email protected]>
CWE ID: CWE-20 | static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
u32 *sid, u32 def_sid, gfp_t gfp_flags,
int force)
{
char *scontext2, *str = NULL;
struct context context;
int rc = 0;
/* An empty security context is never valid. */
if (!scontext_len)
return -EINVAL;
if (!ss_initialized) {
int i;
for (i = 1; i < SECINITSID_NUM; i++) {
if (!strcmp(initial_sid_to_string[i], scontext)) {
*sid = i;
return 0;
}
}
*sid = SECINITSID_KERNEL;
return 0;
}
*sid = SECSID_NULL;
/* Copy the string so that we can modify the copy as we parse it. */
scontext2 = kmalloc(scontext_len + 1, gfp_flags);
if (!scontext2)
return -ENOMEM;
memcpy(scontext2, scontext, scontext_len);
scontext2[scontext_len] = 0;
if (force) {
/* Save another copy for storing in uninterpreted form */
rc = -ENOMEM;
str = kstrdup(scontext2, gfp_flags);
if (!str)
goto out;
}
read_lock(&policy_rwlock);
rc = string_to_context_struct(&policydb, &sidtab, scontext2,
scontext_len, &context, def_sid);
if (rc == -EINVAL && force) {
context.str = str;
context.len = scontext_len;
str = NULL;
} else if (rc)
goto out_unlock;
rc = sidtab_context_to_sid(&sidtab, &context, sid);
context_destroy(&context);
out_unlock:
read_unlock(&policy_rwlock);
out:
kfree(scontext2);
kfree(str);
return rc;
}
| 166,432 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static netdev_tx_t hns_nic_net_xmit(struct sk_buff *skb,
struct net_device *ndev)
{
struct hns_nic_priv *priv = netdev_priv(ndev);
int ret;
assert(skb->queue_mapping < ndev->ae_handle->q_num);
ret = hns_nic_net_xmit_hw(ndev, skb,
&tx_ring_data(priv, skb->queue_mapping));
if (ret == NETDEV_TX_OK) {
netif_trans_update(ndev);
ndev->stats.tx_bytes += skb->len;
ndev->stats.tx_packets++;
}
return (netdev_tx_t)ret;
}
Commit Message: net: hns: Fix a skb used after free bug
skb maybe freed in hns_nic_net_xmit_hw() and return NETDEV_TX_OK,
which cause hns_nic_net_xmit to use a freed skb.
BUG: KASAN: use-after-free in hns_nic_net_xmit_hw+0x62c/0x940...
[17659.112635] alloc_debug_processing+0x18c/0x1a0
[17659.117208] __slab_alloc+0x52c/0x560
[17659.120909] kmem_cache_alloc_node+0xac/0x2c0
[17659.125309] __alloc_skb+0x6c/0x260
[17659.128837] tcp_send_ack+0x8c/0x280
[17659.132449] __tcp_ack_snd_check+0x9c/0xf0
[17659.136587] tcp_rcv_established+0x5a4/0xa70
[17659.140899] tcp_v4_do_rcv+0x27c/0x620
[17659.144687] tcp_prequeue_process+0x108/0x170
[17659.149085] tcp_recvmsg+0x940/0x1020
[17659.152787] inet_recvmsg+0x124/0x180
[17659.156488] sock_recvmsg+0x64/0x80
[17659.160012] SyS_recvfrom+0xd8/0x180
[17659.163626] __sys_trace_return+0x0/0x4
[17659.167506] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=23 cpu=1 pid=13
[17659.174000] free_debug_processing+0x1d4/0x2c0
[17659.178486] __slab_free+0x240/0x390
[17659.182100] kmem_cache_free+0x24c/0x270
[17659.186062] kfree_skbmem+0xa0/0xb0
[17659.189587] __kfree_skb+0x28/0x40
[17659.193025] napi_gro_receive+0x168/0x1c0
[17659.197074] hns_nic_rx_up_pro+0x58/0x90
[17659.201038] hns_nic_rx_poll_one+0x518/0xbc0
[17659.205352] hns_nic_common_poll+0x94/0x140
[17659.209576] net_rx_action+0x458/0x5e0
[17659.213363] __do_softirq+0x1b8/0x480
[17659.217062] run_ksoftirqd+0x64/0x80
[17659.220679] smpboot_thread_fn+0x224/0x310
[17659.224821] kthread+0x150/0x170
[17659.228084] ret_from_fork+0x10/0x40
BUG: KASAN: use-after-free in hns_nic_net_xmit+0x8c/0xc0...
[17751.080490] __slab_alloc+0x52c/0x560
[17751.084188] kmem_cache_alloc+0x244/0x280
[17751.088238] __build_skb+0x40/0x150
[17751.091764] build_skb+0x28/0x100
[17751.095115] __alloc_rx_skb+0x94/0x150
[17751.098900] __napi_alloc_skb+0x34/0x90
[17751.102776] hns_nic_rx_poll_one+0x180/0xbc0
[17751.107097] hns_nic_common_poll+0x94/0x140
[17751.111333] net_rx_action+0x458/0x5e0
[17751.115123] __do_softirq+0x1b8/0x480
[17751.118823] run_ksoftirqd+0x64/0x80
[17751.122437] smpboot_thread_fn+0x224/0x310
[17751.126575] kthread+0x150/0x170
[17751.129838] ret_from_fork+0x10/0x40
[17751.133454] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=19 cpu=7 pid=43
[17751.139951] free_debug_processing+0x1d4/0x2c0
[17751.144436] __slab_free+0x240/0x390
[17751.148051] kmem_cache_free+0x24c/0x270
[17751.152014] kfree_skbmem+0xa0/0xb0
[17751.155543] __kfree_skb+0x28/0x40
[17751.159022] napi_gro_receive+0x168/0x1c0
[17751.163074] hns_nic_rx_up_pro+0x58/0x90
[17751.167041] hns_nic_rx_poll_one+0x518/0xbc0
[17751.171358] hns_nic_common_poll+0x94/0x140
[17751.175585] net_rx_action+0x458/0x5e0
[17751.179373] __do_softirq+0x1b8/0x480
[17751.183076] run_ksoftirqd+0x64/0x80
[17751.186691] smpboot_thread_fn+0x224/0x310
[17751.190826] kthread+0x150/0x170
[17751.194093] ret_from_fork+0x10/0x40
Fixes: 13ac695e7ea1 ("net:hns: Add support of Hip06 SoC to the Hislicon Network Subsystem")
Signed-off-by: Yunsheng Lin <[email protected]>
Signed-off-by: lipeng <[email protected]>
Reported-by: Jun He <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | static netdev_tx_t hns_nic_net_xmit(struct sk_buff *skb,
struct net_device *ndev)
{
struct hns_nic_priv *priv = netdev_priv(ndev);
assert(skb->queue_mapping < ndev->ae_handle->q_num);
return hns_nic_net_xmit_hw(ndev, skb,
&tx_ring_data(priv, skb->queue_mapping));
}
| 169,403 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ztype(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
ref tnref;
int code = array_get(imemory, op, (long)r_btype(op - 1), &tnref);
if (code < 0)
return code;
if (!r_has_type(&tnref, t_name)) {
/* Must be either a stack underflow or a t_[a]struct. */
check_op(2);
{ /* Get the type name from the structure. */
if (op[-1].value.pstruct != 0x00) {
const char *sname =
gs_struct_type_name_string(gs_object_type(imemory,
op[-1].value.pstruct));
int code = name_ref(imemory, (const byte *)sname, strlen(sname),
(ref *) (op - 1), 0);
if (code < 0)
return code;
} else
return_error(gs_error_stackunderflow);
}
r_set_attrs(op - 1, a_executable);
} else {
ref_assign(op - 1, &tnref);
}
pop(1);
return 0;
}
Commit Message:
CWE ID: CWE-704 | ztype(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
ref tnref;
int code = array_get(imemory, op, (long)r_btype(op - 1), &tnref);
if (code < 0)
return code;
if (!r_has_type(&tnref, t_name)) {
/* Must be either a stack underflow or a t_[a]struct. */
check_op(2);
{ /* Get the type name from the structure. */
if ((r_has_type(&op[-1], t_struct) || r_has_type(&op[-1], t_astruct)) && op[-1].value.pstruct != 0x00) {
const char *sname =
gs_struct_type_name_string(gs_object_type(imemory,
op[-1].value.pstruct));
int code = name_ref(imemory, (const byte *)sname, strlen(sname),
(ref *) (op - 1), 0);
if (code < 0)
return code;
} else
return_error(gs_error_stackunderflow);
}
r_set_attrs(op - 1, a_executable);
} else {
ref_assign(op - 1, &tnref);
}
pop(1);
return 0;
}
| 164,698 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::emptyBuffer(
OMX::buffer_id buffer,
OMX_U32 rangeOffset, OMX_U32 rangeLength,
OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer);
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(header->pAppPrivate);
sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */);
sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */);
if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource
&& backup->capacity() >= sizeof(VideoNativeMetadata)
&& codec->capacity() >= sizeof(VideoGrallocMetadata)
&& ((VideoNativeMetadata *)backup->base())->eType
== kMetadataBufferTypeANWBuffer) {
VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base();
VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base();
CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p",
backupMeta.pBuffer, backupMeta.pBuffer->handle);
codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL;
codecMeta.eType = kMetadataBufferTypeGrallocSource;
header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0;
header->nOffset = 0;
} else {
if (rangeOffset > header->nAllocLen
|| rangeLength > header->nAllocLen - rangeOffset) {
CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd));
if (fenceFd >= 0) {
::close(fenceFd);
}
return BAD_VALUE;
}
header->nFilledLen = rangeLength;
header->nOffset = rangeOffset;
buffer_meta->CopyToOMX(header);
}
return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd);
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | status_t OMXNodeInstance::emptyBuffer(
OMX::buffer_id buffer,
OMX_U32 rangeOffset, OMX_U32 rangeLength,
OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput);
if (header == NULL) {
return BAD_VALUE;
}
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(header->pAppPrivate);
sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */);
sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */);
if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource
&& backup->capacity() >= sizeof(VideoNativeMetadata)
&& codec->capacity() >= sizeof(VideoGrallocMetadata)
&& ((VideoNativeMetadata *)backup->base())->eType
== kMetadataBufferTypeANWBuffer) {
VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base();
VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base();
CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p",
backupMeta.pBuffer, backupMeta.pBuffer->handle);
codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL;
codecMeta.eType = kMetadataBufferTypeGrallocSource;
header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0;
header->nOffset = 0;
} else {
if (rangeOffset > header->nAllocLen
|| rangeLength > header->nAllocLen - rangeOffset) {
CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd));
if (fenceFd >= 0) {
::close(fenceFd);
}
return BAD_VALUE;
}
header->nFilledLen = rangeLength;
header->nOffset = rangeOffset;
buffer_meta->CopyToOMX(header);
}
return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd);
}
| 173,526 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadUYVYImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
unsigned char
u,
v,
y1,
y2;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
if ((image->columns % 2) != 0)
image->columns++;
(void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
image->depth=8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Accumulate UYVY, then unpack into two pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) (image->columns >> 1); x++)
{
u=(unsigned char) ReadBlobByte(image);
y1=(unsigned char) ReadBlobByte(image);
v=(unsigned char) ReadBlobByte(image);
y2=(unsigned char) ReadBlobByte(image);
SetPixelRed(q,ScaleCharToQuantum(y1));
SetPixelGreen(q,ScaleCharToQuantum(u));
SetPixelBlue(q,ScaleCharToQuantum(v));
q++;
SetPixelRed(q,ScaleCharToQuantum(y2));
SetPixelGreen(q,ScaleCharToQuantum(u));
SetPixelBlue(q,ScaleCharToQuantum(v));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetImageColorspace(image,YCbCrColorspace);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadUYVYImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
unsigned char
u,
v,
y1,
y2;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
if ((image->columns % 2) != 0)
image->columns++;
(void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
image->depth=8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Accumulate UYVY, then unpack into two pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) (image->columns >> 1); x++)
{
u=(unsigned char) ReadBlobByte(image);
y1=(unsigned char) ReadBlobByte(image);
v=(unsigned char) ReadBlobByte(image);
y2=(unsigned char) ReadBlobByte(image);
SetPixelRed(q,ScaleCharToQuantum(y1));
SetPixelGreen(q,ScaleCharToQuantum(u));
SetPixelBlue(q,ScaleCharToQuantum(v));
q++;
SetPixelRed(q,ScaleCharToQuantum(y2));
SetPixelGreen(q,ScaleCharToQuantum(u));
SetPixelBlue(q,ScaleCharToQuantum(v));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetImageColorspace(image,YCbCrColorspace);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,615 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GLES2DecoderPassthroughImpl::IsEmulatedQueryTarget(GLenum target) const {
switch (target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
case GL_COMMANDS_ISSUED_CHROMIUM:
case GL_LATENCY_QUERY_CHROMIUM:
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
case GL_GET_ERROR_QUERY_CHROMIUM:
return true;
default:
return false;
}
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416 | bool GLES2DecoderPassthroughImpl::IsEmulatedQueryTarget(GLenum target) const {
switch (target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
case GL_COMMANDS_ISSUED_CHROMIUM:
case GL_LATENCY_QUERY_CHROMIUM:
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
case GL_GET_ERROR_QUERY_CHROMIUM:
case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM:
return true;
default:
return false;
}
}
| 172,530 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: psh_glyph_find_strong_points( PSH_Glyph glyph,
FT_Int dimension )
{
/* a point is `strong' if it is located on a stem edge and */
/* has an `in' or `out' tangent parallel to the hint's direction */
PSH_Hint_Table table = &glyph->hint_tables[dimension];
PS_Mask mask = table->hint_masks->masks;
FT_UInt num_masks = table->hint_masks->num_masks;
FT_UInt first = 0;
FT_Int major_dir = dimension == 0 ? PSH_DIR_VERTICAL
: PSH_DIR_HORIZONTAL;
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Int threshold;
threshold = (FT_Int)FT_DivFix( PSH_STRONG_THRESHOLD, scale );
if ( threshold > PSH_STRONG_THRESHOLD_MAXIMUM )
threshold = PSH_STRONG_THRESHOLD_MAXIMUM;
/* process secondary hints to `selected' points */
/* process secondary hints to `selected' points */
if ( num_masks > 1 && glyph->num_points > 0 )
{
first = mask->end_point;
mask++;
for ( ; num_masks > 1; num_masks--, mask++ )
{
next = mask->end_point;
FT_Int count;
next = mask->end_point;
count = next - first;
if ( count > 0 )
{
threshold, major_dir );
}
first = next;
}
}
/* process primary hints for all points */
if ( num_masks == 1 )
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
psh_hint_table_activate_mask( table, table->hint_masks->masks );
psh_hint_table_find_strong_points( table, point, count,
threshold, major_dir );
}
/* now, certain points may have been attached to a hint and */
/* not marked as strong; update their flags then */
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
for ( ; count > 0; count--, point++ )
if ( point->hint && !psh_point_is_strong( point ) )
psh_point_set_strong( point );
}
}
Commit Message:
CWE ID: CWE-399 | psh_glyph_find_strong_points( PSH_Glyph glyph,
FT_Int dimension )
{
/* a point is `strong' if it is located on a stem edge and */
/* has an `in' or `out' tangent parallel to the hint's direction */
PSH_Hint_Table table = &glyph->hint_tables[dimension];
PS_Mask mask = table->hint_masks->masks;
FT_UInt num_masks = table->hint_masks->num_masks;
FT_UInt first = 0;
FT_Int major_dir = dimension == 0 ? PSH_DIR_VERTICAL
: PSH_DIR_HORIZONTAL;
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Int threshold;
threshold = (FT_Int)FT_DivFix( PSH_STRONG_THRESHOLD, scale );
if ( threshold > PSH_STRONG_THRESHOLD_MAXIMUM )
threshold = PSH_STRONG_THRESHOLD_MAXIMUM;
/* process secondary hints to `selected' points */
/* process secondary hints to `selected' points */
if ( num_masks > 1 && glyph->num_points > 0 )
{
/* the `endchar' op can reduce the number of points */
first = mask->end_point > glyph->num_points
? glyph->num_points
: mask->end_point;
mask++;
for ( ; num_masks > 1; num_masks--, mask++ )
{
next = mask->end_point;
FT_Int count;
next = mask->end_point > glyph->num_points
? glyph->num_points
: mask->end_point;
count = next - first;
if ( count > 0 )
{
threshold, major_dir );
}
first = next;
}
}
/* process primary hints for all points */
if ( num_masks == 1 )
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
psh_hint_table_activate_mask( table, table->hint_masks->masks );
psh_hint_table_find_strong_points( table, point, count,
threshold, major_dir );
}
/* now, certain points may have been attached to a hint and */
/* not marked as strong; update their flags then */
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
for ( ; count > 0; count--, point++ )
if ( point->hint && !psh_point_is_strong( point ) )
psh_point_set_strong( point );
}
}
| 165,007 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void tg3_read_vpd(struct tg3 *tp)
{
u8 *vpd_data;
unsigned int block_end, rosize, len;
u32 vpdlen;
int j, i = 0;
vpd_data = (u8 *)tg3_vpd_readblock(tp, &vpdlen);
if (!vpd_data)
goto out_no_vpd;
i = pci_vpd_find_tag(vpd_data, 0, vpdlen, PCI_VPD_LRDT_RO_DATA);
if (i < 0)
goto out_not_found;
rosize = pci_vpd_lrdt_size(&vpd_data[i]);
block_end = i + PCI_VPD_LRDT_TAG_SIZE + rosize;
i += PCI_VPD_LRDT_TAG_SIZE;
if (block_end > vpdlen)
goto out_not_found;
j = pci_vpd_find_info_keyword(vpd_data, i, rosize,
PCI_VPD_RO_KEYWORD_MFR_ID);
if (j > 0) {
len = pci_vpd_info_field_size(&vpd_data[j]);
j += PCI_VPD_INFO_FLD_HDR_SIZE;
if (j + len > block_end || len != 4 ||
memcmp(&vpd_data[j], "1028", 4))
goto partno;
j = pci_vpd_find_info_keyword(vpd_data, i, rosize,
PCI_VPD_RO_KEYWORD_VENDOR0);
if (j < 0)
goto partno;
len = pci_vpd_info_field_size(&vpd_data[j]);
j += PCI_VPD_INFO_FLD_HDR_SIZE;
if (j + len > block_end)
goto partno;
memcpy(tp->fw_ver, &vpd_data[j], len);
strncat(tp->fw_ver, " bc ", vpdlen - len - 1);
}
partno:
i = pci_vpd_find_info_keyword(vpd_data, i, rosize,
PCI_VPD_RO_KEYWORD_PARTNO);
if (i < 0)
goto out_not_found;
len = pci_vpd_info_field_size(&vpd_data[i]);
i += PCI_VPD_INFO_FLD_HDR_SIZE;
if (len > TG3_BPN_SIZE ||
(len + i) > vpdlen)
goto out_not_found;
memcpy(tp->board_part_number, &vpd_data[i], len);
out_not_found:
kfree(vpd_data);
if (tp->board_part_number[0])
return;
out_no_vpd:
if (tg3_asic_rev(tp) == ASIC_REV_5717) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717_C)
strcpy(tp->board_part_number, "BCM5717");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718)
strcpy(tp->board_part_number, "BCM5718");
else
goto nomatch;
} else if (tg3_asic_rev(tp) == ASIC_REV_57780) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57780)
strcpy(tp->board_part_number, "BCM57780");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57760)
strcpy(tp->board_part_number, "BCM57760");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57790)
strcpy(tp->board_part_number, "BCM57790");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57788)
strcpy(tp->board_part_number, "BCM57788");
else
goto nomatch;
} else if (tg3_asic_rev(tp) == ASIC_REV_57765) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57761)
strcpy(tp->board_part_number, "BCM57761");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57765)
strcpy(tp->board_part_number, "BCM57765");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57781)
strcpy(tp->board_part_number, "BCM57781");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57785)
strcpy(tp->board_part_number, "BCM57785");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791)
strcpy(tp->board_part_number, "BCM57791");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795)
strcpy(tp->board_part_number, "BCM57795");
else
goto nomatch;
} else if (tg3_asic_rev(tp) == ASIC_REV_57766) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57762)
strcpy(tp->board_part_number, "BCM57762");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57766)
strcpy(tp->board_part_number, "BCM57766");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57782)
strcpy(tp->board_part_number, "BCM57782");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57786)
strcpy(tp->board_part_number, "BCM57786");
else
goto nomatch;
} else if (tg3_asic_rev(tp) == ASIC_REV_5906) {
strcpy(tp->board_part_number, "BCM95906");
} else {
nomatch:
strcpy(tp->board_part_number, "none");
}
}
Commit Message: tg3: fix length overflow in VPD firmware parsing
Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version
when present") introduced VPD parsing that contained a potential length
overflow.
Limit the hardware's reported firmware string length (max 255 bytes) to
stay inside the driver's firmware string length (32 bytes). On overflow,
truncate the formatted firmware string instead of potentially overwriting
portions of the tg3 struct.
http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf
Signed-off-by: Kees Cook <[email protected]>
Reported-by: Oded Horovitz <[email protected]>
Reported-by: Brad Spengler <[email protected]>
Cc: [email protected]
Cc: Matt Carlson <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static void tg3_read_vpd(struct tg3 *tp)
{
u8 *vpd_data;
unsigned int block_end, rosize, len;
u32 vpdlen;
int j, i = 0;
vpd_data = (u8 *)tg3_vpd_readblock(tp, &vpdlen);
if (!vpd_data)
goto out_no_vpd;
i = pci_vpd_find_tag(vpd_data, 0, vpdlen, PCI_VPD_LRDT_RO_DATA);
if (i < 0)
goto out_not_found;
rosize = pci_vpd_lrdt_size(&vpd_data[i]);
block_end = i + PCI_VPD_LRDT_TAG_SIZE + rosize;
i += PCI_VPD_LRDT_TAG_SIZE;
if (block_end > vpdlen)
goto out_not_found;
j = pci_vpd_find_info_keyword(vpd_data, i, rosize,
PCI_VPD_RO_KEYWORD_MFR_ID);
if (j > 0) {
len = pci_vpd_info_field_size(&vpd_data[j]);
j += PCI_VPD_INFO_FLD_HDR_SIZE;
if (j + len > block_end || len != 4 ||
memcmp(&vpd_data[j], "1028", 4))
goto partno;
j = pci_vpd_find_info_keyword(vpd_data, i, rosize,
PCI_VPD_RO_KEYWORD_VENDOR0);
if (j < 0)
goto partno;
len = pci_vpd_info_field_size(&vpd_data[j]);
j += PCI_VPD_INFO_FLD_HDR_SIZE;
if (j + len > block_end)
goto partno;
if (len >= sizeof(tp->fw_ver))
len = sizeof(tp->fw_ver) - 1;
memset(tp->fw_ver, 0, sizeof(tp->fw_ver));
snprintf(tp->fw_ver, sizeof(tp->fw_ver), "%.*s bc ", len,
&vpd_data[j]);
}
partno:
i = pci_vpd_find_info_keyword(vpd_data, i, rosize,
PCI_VPD_RO_KEYWORD_PARTNO);
if (i < 0)
goto out_not_found;
len = pci_vpd_info_field_size(&vpd_data[i]);
i += PCI_VPD_INFO_FLD_HDR_SIZE;
if (len > TG3_BPN_SIZE ||
(len + i) > vpdlen)
goto out_not_found;
memcpy(tp->board_part_number, &vpd_data[i], len);
out_not_found:
kfree(vpd_data);
if (tp->board_part_number[0])
return;
out_no_vpd:
if (tg3_asic_rev(tp) == ASIC_REV_5717) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717_C)
strcpy(tp->board_part_number, "BCM5717");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718)
strcpy(tp->board_part_number, "BCM5718");
else
goto nomatch;
} else if (tg3_asic_rev(tp) == ASIC_REV_57780) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57780)
strcpy(tp->board_part_number, "BCM57780");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57760)
strcpy(tp->board_part_number, "BCM57760");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57790)
strcpy(tp->board_part_number, "BCM57790");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57788)
strcpy(tp->board_part_number, "BCM57788");
else
goto nomatch;
} else if (tg3_asic_rev(tp) == ASIC_REV_57765) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57761)
strcpy(tp->board_part_number, "BCM57761");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57765)
strcpy(tp->board_part_number, "BCM57765");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57781)
strcpy(tp->board_part_number, "BCM57781");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57785)
strcpy(tp->board_part_number, "BCM57785");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791)
strcpy(tp->board_part_number, "BCM57791");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795)
strcpy(tp->board_part_number, "BCM57795");
else
goto nomatch;
} else if (tg3_asic_rev(tp) == ASIC_REV_57766) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57762)
strcpy(tp->board_part_number, "BCM57762");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57766)
strcpy(tp->board_part_number, "BCM57766");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57782)
strcpy(tp->board_part_number, "BCM57782");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57786)
strcpy(tp->board_part_number, "BCM57786");
else
goto nomatch;
} else if (tg3_asic_rev(tp) == ASIC_REV_5906) {
strcpy(tp->board_part_number, "BCM95906");
} else {
nomatch:
strcpy(tp->board_part_number, "none");
}
}
| 166,101 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length)
{
int v, i;
if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
if (length > 256 || !(s->state & PNG_PLTE))
return AVERROR_INVALIDDATA;
for (i = 0; i < length; i++) {
v = bytestream2_get_byte(&s->gb);
s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
}
} else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
(s->color_type == PNG_COLOR_TYPE_RGB && length != 6))
return AVERROR_INVALIDDATA;
for (i = 0; i < length / 2; i++) {
/* only use the least significant bits */
v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
if (s->bit_depth > 8)
AV_WB16(&s->transparent_color_be[2 * i], v);
else
s->transparent_color_be[i] = v;
}
} else {
return AVERROR_INVALIDDATA;
}
bytestream2_skip(&s->gb, 4); /* crc */
s->has_trns = 1;
return 0;
}
Commit Message: avcodec/pngdec: Check trns more completely
Fixes out of array access
Fixes: 546/clusterfuzz-testcase-4809433909559296
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-787 | static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,
uint32_t length)
{
int v, i;
if (!(s->state & PNG_IHDR)) {
av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n");
return AVERROR_INVALIDDATA;
}
if (s->state & PNG_IDAT) {
av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n");
return AVERROR_INVALIDDATA;
}
if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
if (length > 256 || !(s->state & PNG_PLTE))
return AVERROR_INVALIDDATA;
for (i = 0; i < length; i++) {
v = bytestream2_get_byte(&s->gb);
s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);
}
} else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {
if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||
(s->color_type == PNG_COLOR_TYPE_RGB && length != 6) ||
s->bit_depth == 1)
return AVERROR_INVALIDDATA;
for (i = 0; i < length / 2; i++) {
/* only use the least significant bits */
v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);
if (s->bit_depth > 8)
AV_WB16(&s->transparent_color_be[2 * i], v);
else
s->transparent_color_be[i] = v;
}
} else {
return AVERROR_INVALIDDATA;
}
bytestream2_skip(&s->gb, 4); /* crc */
s->has_trns = 1;
return 0;
}
| 168,248 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality)
{
uint8_t *argb;
int x, y;
uint8_t *p;
uint8_t *out;
size_t out_size;
if (im == NULL) {
return;
}
if (!gdImageTrueColor(im)) {
gd_error("Paletter image not supported by webp");
return;
}
if (quality == -1) {
quality = 80;
}
argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im));
if (!argb) {
return;
}
p = argb;
for (y = 0; y < gdImageSY(im); y++) {
for (x = 0; x < gdImageSX(im); x++) {
register int c;
register char a;
c = im->tpixels[y][x];
a = gdTrueColorGetAlpha(c);
if (a == 127) {
a = 0;
} else {
a = 255 - ((a << 1) + (a >> 6));
}
*(p++) = gdTrueColorGetRed(c);
*(p++) = gdTrueColorGetGreen(c);
*(p++) = gdTrueColorGetBlue(c);
*(p++) = a;
}
}
out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quality, &out);
if (out_size == 0) {
gd_error("gd-webp encoding failed");
goto freeargb;
}
gdPutBuf(out, out_size, outfile);
free(out);
freeargb:
gdFree(argb);
}
Commit Message: Merge branch 'pull-request/296'
CWE ID: CWE-190 | BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality)
{
uint8_t *argb;
int x, y;
uint8_t *p;
uint8_t *out;
size_t out_size;
if (im == NULL) {
return;
}
if (!gdImageTrueColor(im)) {
gd_error("Paletter image not supported by webp");
return;
}
if (quality == -1) {
quality = 80;
}
if (overflow2(gdImageSX(im), 4)) {
return;
}
if (overflow2(gdImageSX(im) * 4, gdImageSY(im))) {
return;
}
argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im));
if (!argb) {
return;
}
p = argb;
for (y = 0; y < gdImageSY(im); y++) {
for (x = 0; x < gdImageSX(im); x++) {
register int c;
register char a;
c = im->tpixels[y][x];
a = gdTrueColorGetAlpha(c);
if (a == 127) {
a = 0;
} else {
a = 255 - ((a << 1) + (a >> 6));
}
*(p++) = gdTrueColorGetRed(c);
*(p++) = gdTrueColorGetGreen(c);
*(p++) = gdTrueColorGetBlue(c);
*(p++) = a;
}
}
out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quality, &out);
if (out_size == 0) {
gd_error("gd-webp encoding failed");
goto freeargb;
}
gdPutBuf(out, out_size, outfile);
free(out);
freeargb:
gdFree(argb);
}
| 166,927 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)
{
unsigned int first = 0;
unsigned int last = ARR_SIZE(insn_regs_intel) - 1;
unsigned int mid = ARR_SIZE(insn_regs_intel) / 2;
if (!intel_regs_sorted) {
memcpy(insn_regs_intel_sorted, insn_regs_intel,
sizeof(insn_regs_intel_sorted));
qsort(insn_regs_intel_sorted,
ARR_SIZE(insn_regs_intel_sorted),
sizeof(struct insn_reg), regs_cmp);
intel_regs_sorted = true;
}
while (first <= last) {
if (insn_regs_intel_sorted[mid].insn < id) {
first = mid + 1;
} else if (insn_regs_intel_sorted[mid].insn == id) {
if (access) {
*access = insn_regs_intel_sorted[mid].access;
}
return insn_regs_intel_sorted[mid].reg;
} else {
if (mid == 0)
break;
last = mid - 1;
}
mid = (first + last) / 2;
}
return 0;
}
Commit Message: x86: fast path checking for X86_insn_reg_intel()
CWE ID: CWE-125 | x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)
{
static bool intel_regs_sorted = false;
unsigned int first = 0;
unsigned int last = ARR_SIZE(insn_regs_intel) - 1;
unsigned int mid;
if (!intel_regs_sorted) {
memcpy(insn_regs_intel_sorted, insn_regs_intel,
sizeof(insn_regs_intel_sorted));
qsort(insn_regs_intel_sorted,
ARR_SIZE(insn_regs_intel_sorted),
sizeof(struct insn_reg), regs_cmp);
intel_regs_sorted = true;
}
if (insn_regs_intel_sorted[0].insn > id ||
insn_regs_intel_sorted[last].insn < id) {
return 0;
}
while (first <= last) {
mid = (first + last) / 2;
if (insn_regs_intel_sorted[mid].insn < id) {
first = mid + 1;
} else if (insn_regs_intel_sorted[mid].insn == id) {
if (access) {
*access = insn_regs_intel_sorted[mid].access;
}
return insn_regs_intel_sorted[mid].reg;
} else {
if (mid == 0)
break;
last = mid - 1;
}
}
return 0;
}
| 169,866 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport,
int32_t *opcode)
{
int i;
struct rx_cache_entry *rxent;
uint32_t clip;
uint32_t sip;
UNALIGNED_MEMCPY(&clip, &ip->ip_dst, sizeof(uint32_t));
UNALIGNED_MEMCPY(&sip, &ip->ip_src, sizeof(uint32_t));
/* Start the search where we last left off */
i = rx_cache_hint;
do {
rxent = &rx_cache[i];
if (rxent->callnum == EXTRACT_32BITS(&rxh->callNumber) &&
rxent->client.s_addr == clip &&
rxent->server.s_addr == sip &&
rxent->serviceId == EXTRACT_32BITS(&rxh->serviceId) &&
rxent->dport == sport) {
/* We got a match! */
rx_cache_hint = i;
*opcode = rxent->opcode;
return(1);
}
if (++i >= RX_CACHE_SIZE)
i = 0;
} while (i != rx_cache_hint);
/* Our search failed */
return(0);
}
Commit Message: (for 4.9.3) CVE-2018-14466/Rx: fix an over-read bug
In rx_cache_insert() and rx_cache_find() properly read the serviceId
field of the rx_header structure as a 16-bit integer. When those
functions tried to read 32 bits the extra 16 bits could be outside of
the bounds checked in rx_print() for the rx_header structure, as
serviceId is the last field in that structure.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport,
int32_t *opcode)
{
int i;
struct rx_cache_entry *rxent;
uint32_t clip;
uint32_t sip;
UNALIGNED_MEMCPY(&clip, &ip->ip_dst, sizeof(uint32_t));
UNALIGNED_MEMCPY(&sip, &ip->ip_src, sizeof(uint32_t));
/* Start the search where we last left off */
i = rx_cache_hint;
do {
rxent = &rx_cache[i];
if (rxent->callnum == EXTRACT_32BITS(&rxh->callNumber) &&
rxent->client.s_addr == clip &&
rxent->server.s_addr == sip &&
rxent->serviceId == EXTRACT_16BITS(&rxh->serviceId) &&
rxent->dport == sport) {
/* We got a match! */
rx_cache_hint = i;
*opcode = rxent->opcode;
return(1);
}
if (++i >= RX_CACHE_SIZE)
i = 0;
} while (i != rx_cache_hint);
/* Our search failed */
return(0);
}
| 169,845 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Core(const OAuthProviderInfo& info,
net::URLRequestContextGetter* request_context_getter)
: provider_info_(info),
request_context_getter_(request_context_getter),
delegate_(NULL) {
}
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 | Core(const OAuthProviderInfo& info,
net::URLRequestContextGetter* request_context_getter)
: provider_info_(info),
request_context_getter_(request_context_getter),
delegate_(NULL),
url_fetcher_type_(URL_FETCHER_NONE) {
}
| 170,805 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FindBarController::EndFindSession(SelectionAction action) {
find_bar_->Hide(true);
if (tab_contents_) {
FindManager* find_manager = tab_contents_->GetFindManager();
find_manager->StopFinding(action);
if (action != kKeepSelection)
find_bar_->ClearResults(find_manager->find_result());
find_bar_->RestoreSavedFocus();
}
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void FindBarController::EndFindSession(SelectionAction action) {
find_bar_->Hide(true);
if (tab_contents_) {
FindTabHelper* find_tab_helper = tab_contents_->find_tab_helper();
find_tab_helper->StopFinding(action);
if (action != kKeepSelection)
find_bar_->ClearResults(find_tab_helper->find_result());
find_bar_->RestoreSavedFocus();
}
}
| 170,658 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int sgi_clock_get(clockid_t clockid, struct timespec *tp)
{
u64 nsec;
nsec = rtc_time() * sgi_clock_period
+ sgi_clock_offset.tv_nsec;
tp->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &tp->tv_nsec)
+ sgi_clock_offset.tv_sec;
return 0;
};
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static int sgi_clock_get(clockid_t clockid, struct timespec *tp)
{
u64 nsec;
nsec = rtc_time() * sgi_clock_period
+ sgi_clock_offset.tv_nsec;
*tp = ns_to_timespec(nsec);
tp->tv_sec += sgi_clock_offset.tv_sec;
return 0;
};
| 165,749 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Start() {
DVLOG(2) << "Starting SafeBrowsing download check for: "
<< item_->DebugString(true);
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DownloadCheckResultReason reason = REASON_MAX;
if (!IsSupportedDownload(
*item_, item_->GetTargetFilePath(), &reason, &type_)) {
switch (reason) {
case REASON_EMPTY_URL_CHAIN:
case REASON_INVALID_URL:
case REASON_UNSUPPORTED_URL_SCHEME:
PostFinishTask(UNKNOWN, reason);
return;
case REASON_NOT_BINARY_FILE:
RecordFileExtensionType(item_->GetTargetFilePath());
PostFinishTask(UNKNOWN, reason);
return;
default:
NOTREACHED();
}
}
RecordFileExtensionType(item_->GetTargetFilePath());
if (item_->GetTargetFilePath().MatchesExtension(
FILE_PATH_LITERAL(".zip"))) {
StartExtractZipFeatures();
} else {
DCHECK(!download_protection_util::IsArchiveFile(
item_->GetTargetFilePath()));
StartExtractFileFeatures();
}
}
Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService.
BUG=496898,464083
[email protected], [email protected], [email protected], [email protected]
Review URL: https://codereview.chromium.org/1299223006 .
Cr-Commit-Position: refs/heads/master@{#344876}
CWE ID: | void Start() {
DVLOG(2) << "Starting SafeBrowsing download check for: "
<< item_->DebugString(true);
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DownloadCheckResultReason reason = REASON_MAX;
if (!IsSupportedDownload(
*item_, item_->GetTargetFilePath(), &reason, &type_)) {
switch (reason) {
case REASON_EMPTY_URL_CHAIN:
case REASON_INVALID_URL:
case REASON_UNSUPPORTED_URL_SCHEME:
PostFinishTask(UNKNOWN, reason);
return;
case REASON_NOT_BINARY_FILE:
RecordFileExtensionType(item_->GetTargetFilePath());
PostFinishTask(UNKNOWN, reason);
return;
default:
NOTREACHED();
}
}
RecordFileExtensionType(item_->GetTargetFilePath());
if (item_->GetTargetFilePath().MatchesExtension(
FILE_PATH_LITERAL(".zip"))) {
StartExtractZipFeatures();
#if defined(OS_MACOSX)
} else if (item_->GetTargetFilePath().MatchesExtension(
FILE_PATH_LITERAL(".dmg"))) {
StartExtractDmgFeatures();
#endif
} else {
DCHECK(!download_protection_util::IsArchiveFile(
item_->GetTargetFilePath()));
StartExtractFileFeatures();
}
}
| 171,715 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cc::FrameSinkId RenderWidgetHostViewAura::GetFrameSinkId() {
return delegated_frame_host_ ? delegated_frame_host_->GetFrameSinkId()
: cc::FrameSinkId();
}
Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash
RenderWidgetHostViewChildFrame expects its parent to have a valid
FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even
if DelegatedFrameHost is not used (in mus+ash).
BUG=706553
[email protected]
Review-Url: https://codereview.chromium.org/2847253003
Cr-Commit-Position: refs/heads/master@{#468179}
CWE ID: CWE-254 | cc::FrameSinkId RenderWidgetHostViewAura::GetFrameSinkId() {
return frame_sink_id_;
}
| 172,234 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestSerializedScriptValueInterface::s_info))
return throwVMTypeError(exec);
JSTestSerializedScriptValueInterface* castedThis = jsCast<JSTestSerializedScriptValueInterface*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestSerializedScriptValueInterface::s_info);
TestSerializedScriptValueInterface* impl = static_cast<TestSerializedScriptValueInterface*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
RefPtr<SerializedScriptValue> data(SerializedScriptValue::create(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
size_t argsCount = exec->argumentCount();
if (argsCount <= 1) {
impl->acceptTransferList(data);
return JSValue::encode(jsUndefined());
}
Array* transferList(toArray(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->acceptTransferList(data, transferList);
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestSerializedScriptValueInterface::s_info))
return throwVMTypeError(exec);
JSTestSerializedScriptValueInterface* castedThis = jsCast<JSTestSerializedScriptValueInterface*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestSerializedScriptValueInterface::s_info);
TestSerializedScriptValueInterface* impl = static_cast<TestSerializedScriptValueInterface*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
RefPtr<SerializedScriptValue> data(SerializedScriptValue::create(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
size_t argsCount = exec->argumentCount();
if (argsCount <= 1) {
impl->acceptTransferList(data);
return JSValue::encode(jsUndefined());
}
Array* transferList(toArray(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->acceptTransferList(data, transferList);
return JSValue::encode(jsUndefined());
}
| 170,612 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WARN_UNUSED_RESULT bool VerifyRecordedSamplesForHistogram(
const size_t num_samples,
const std::string& histogram_name) const {
return num_samples ==
histogram_tester_.GetAllSamples(histogram_name).size();
}
Commit Message: Revert "Add explicit flag for compositor scrollbar injected gestures"
This reverts commit d9a56afcbdf9850bc39bb3edb56d07d11a1eb2b2.
Reason for revert:
Findit (https://goo.gl/kROfz5) identified CL at revision 669086 as the
culprit for flakes in the build cycles as shown on:
https://analysis.chromium.org/p/chromium/flake-portal/analysis/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyQwsSDEZsYWtlQ3VscHJpdCIxY2hyb21pdW0vZDlhNTZhZmNiZGY5ODUwYmMzOWJiM2VkYjU2ZDA3ZDExYTFlYjJiMgw
Sample Failed Build: https://ci.chromium.org/buildbot/chromium.chromiumos/linux-chromeos-rel/25818
Sample Failed Step: content_browsertests on Ubuntu-16.04
Sample Flaky Test: ScrollLatencyScrollbarBrowserTest.ScrollbarThumbDragLatency
Original change's description:
> Add explicit flag for compositor scrollbar injected gestures
>
> The original change to enable scrollbar latency for the composited
> scrollbars incorrectly used an existing member to try and determine
> whether a GestureScrollUpdate was the first one in an injected sequence
> or not. is_first_gesture_scroll_update_ was incorrect because it is only
> updated when input is actually dispatched to InputHandlerProxy, and the
> flag is cleared for all GSUs before the location where it was being
> read.
>
> This bug was missed because of incorrect tests. The
> VerifyRecordedSamplesForHistogram method doesn't actually assert or
> expect anything - the return value must be inspected.
>
> As part of fixing up the tests, I made a few other changes to get them
> passing consistently across all platforms:
> - turn on main thread scrollbar injection feature (in case it's ever
> turned off we don't want the tests to start failing)
> - enable mock scrollbars
> - disable smooth scrolling
> - don't run scrollbar tests on Android
>
> The composited scrollbar button test is disabled due to a bug in how
> the mock theme reports its button sizes, which throws off the region
> detection in ScrollbarLayerImplBase::IdentifyScrollbarPart (filed
> crbug.com/974063 for this issue).
>
> Change-Id: Ie1a762a5f6ecc264d22f0256db68f141fc76b950
>
> Bug: 954007
> Change-Id: Ib258e08e083e79da90ba2e4e4216e4879cf00cf7
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1652741
> Commit-Queue: Daniel Libby <[email protected]>
> Reviewed-by: David Bokan <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#669086}
Change-Id: Icc743e48fa740fe27f0cb0cfa21b209a696f518c
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 954007
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1660114
Cr-Commit-Position: refs/heads/master@{#669150}
CWE ID: CWE-281 | WARN_UNUSED_RESULT bool VerifyRecordedSamplesForHistogram(
bool VerifyRecordedSamplesForHistogram(
const size_t num_samples,
const std::string& histogram_name) const {
return num_samples ==
histogram_tester_.GetAllSamples(histogram_name).size();
}
| 172,430 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SSH_PACKET_CALLBACK(ssh_packet_newkeys){
ssh_string sig_blob = NULL;
int rc;
(void)packet;
(void)user;
(void)type;
SSH_LOG(SSH_LOG_PROTOCOL, "Received SSH_MSG_NEWKEYS");
if(session->session_state!= SSH_SESSION_STATE_DH &&
session->dh_handshake_state != DH_STATE_NEWKEYS_SENT){
ssh_set_error(session,SSH_FATAL,"ssh_packet_newkeys called in wrong state : %d:%d",
session->session_state,session->dh_handshake_state);
goto error;
}
if(session->server){
/* server things are done in server.c */
session->dh_handshake_state=DH_STATE_FINISHED;
if (rc != SSH_OK) {
goto error;
}
/*
* Set the cryptographic functions for the next crypto
* (it is needed for generate_session_keys for key lengths)
*/
if (crypt_set_algorithms(session, SSH_3DES) /* knows nothing about DES*/ ) {
goto error;
}
if (generate_session_keys(session) < 0) {
goto error;
}
/* Verify the host's signature. FIXME do it sooner */
sig_blob = session->next_crypto->dh_server_signature;
session->next_crypto->dh_server_signature = NULL;
/* get the server public key */
rc = ssh_pki_import_pubkey_blob(session->next_crypto->server_pubkey, &key);
if (rc < 0) {
return SSH_ERROR;
}
/* check if public key from server matches user preferences */
if (session->opts.wanted_methods[SSH_HOSTKEYS]) {
if(!ssh_match_group(session->opts.wanted_methods[SSH_HOSTKEYS],
key->type_c)) {
ssh_set_error(session,
SSH_FATAL,
"Public key from server (%s) doesn't match user "
"preference (%s)",
key->type_c,
session->opts.wanted_methods[SSH_HOSTKEYS]);
ssh_key_free(key);
return -1;
}
}
rc = ssh_pki_signature_verify_blob(session,
sig_blob,
key,
session->next_crypto->secret_hash,
session->next_crypto->digest_len);
/* Set the server public key type for known host checking */
session->next_crypto->server_pubkey_type = key->type_c;
ssh_key_free(key);
ssh_string_burn(sig_blob);
ssh_string_free(sig_blob);
sig_blob = NULL;
if (rc == SSH_ERROR) {
goto error;
}
SSH_LOG(SSH_LOG_PROTOCOL,"Signature verified and valid");
/*
* Once we got SSH2_MSG_NEWKEYS we can switch next_crypto and
* current_crypto
*/
if (session->current_crypto) {
crypto_free(session->current_crypto);
session->current_crypto=NULL;
}
/* FIXME later, include a function to change keys */
session->current_crypto = session->next_crypto;
session->next_crypto = crypto_new();
if (session->next_crypto == NULL) {
ssh_set_error_oom(session);
goto error;
}
session->next_crypto->session_id = malloc(session->current_crypto->digest_len);
if (session->next_crypto->session_id == NULL) {
ssh_set_error_oom(session);
goto error;
}
memcpy(session->next_crypto->session_id, session->current_crypto->session_id,
session->current_crypto->digest_len);
}
session->dh_handshake_state = DH_STATE_FINISHED;
session->ssh_connection_callback(session);
return SSH_PACKET_USED;
error:
session->session_state=SSH_SESSION_STATE_ERROR;
return SSH_PACKET_USED;
}
Commit Message:
CWE ID: | SSH_PACKET_CALLBACK(ssh_packet_newkeys){
ssh_string sig_blob = NULL;
int rc;
(void)packet;
(void)user;
(void)type;
SSH_LOG(SSH_LOG_PROTOCOL, "Received SSH_MSG_NEWKEYS");
if (session->session_state != SSH_SESSION_STATE_DH ||
session->dh_handshake_state != DH_STATE_NEWKEYS_SENT) {
ssh_set_error(session,
SSH_FATAL,
"ssh_packet_newkeys called in wrong state : %d:%d",
session->session_state,session->dh_handshake_state);
goto error;
}
if(session->server){
/* server things are done in server.c */
session->dh_handshake_state=DH_STATE_FINISHED;
if (rc != SSH_OK) {
goto error;
}
/*
* Set the cryptographic functions for the next crypto
* (it is needed for generate_session_keys for key lengths)
*/
if (crypt_set_algorithms(session, SSH_3DES) /* knows nothing about DES*/ ) {
goto error;
}
if (generate_session_keys(session) < 0) {
goto error;
}
/* Verify the host's signature. FIXME do it sooner */
sig_blob = session->next_crypto->dh_server_signature;
session->next_crypto->dh_server_signature = NULL;
/* get the server public key */
rc = ssh_pki_import_pubkey_blob(session->next_crypto->server_pubkey, &key);
if (rc < 0) {
return SSH_ERROR;
}
/* check if public key from server matches user preferences */
if (session->opts.wanted_methods[SSH_HOSTKEYS]) {
if(!ssh_match_group(session->opts.wanted_methods[SSH_HOSTKEYS],
key->type_c)) {
ssh_set_error(session,
SSH_FATAL,
"Public key from server (%s) doesn't match user "
"preference (%s)",
key->type_c,
session->opts.wanted_methods[SSH_HOSTKEYS]);
ssh_key_free(key);
return -1;
}
}
rc = ssh_pki_signature_verify_blob(session,
sig_blob,
key,
session->next_crypto->secret_hash,
session->next_crypto->digest_len);
/* Set the server public key type for known host checking */
session->next_crypto->server_pubkey_type = key->type_c;
ssh_key_free(key);
ssh_string_burn(sig_blob);
ssh_string_free(sig_blob);
sig_blob = NULL;
if (rc == SSH_ERROR) {
goto error;
}
SSH_LOG(SSH_LOG_PROTOCOL,"Signature verified and valid");
/*
* Once we got SSH2_MSG_NEWKEYS we can switch next_crypto and
* current_crypto
*/
if (session->current_crypto) {
crypto_free(session->current_crypto);
session->current_crypto=NULL;
}
/* FIXME later, include a function to change keys */
session->current_crypto = session->next_crypto;
session->next_crypto = crypto_new();
if (session->next_crypto == NULL) {
ssh_set_error_oom(session);
goto error;
}
session->next_crypto->session_id = malloc(session->current_crypto->digest_len);
if (session->next_crypto->session_id == NULL) {
ssh_set_error_oom(session);
goto error;
}
memcpy(session->next_crypto->session_id, session->current_crypto->session_id,
session->current_crypto->digest_len);
}
session->dh_handshake_state = DH_STATE_FINISHED;
session->ssh_connection_callback(session);
return SSH_PACKET_USED;
error:
session->session_state=SSH_SESSION_STATE_ERROR;
return SSH_PACKET_USED;
}
| 165,324 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseCDSect(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int r, rl;
int s, sl;
int cur, l;
int count = 0;
/* Check 2.6.0 was NXT(0) not RAW */
if (CMP9(CUR_PTR, '<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[')) {
SKIP(9);
} else
return;
ctxt->instate = XML_PARSER_CDATA_SECTION;
r = CUR_CHAR(rl);
if (!IS_CHAR(r)) {
xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL);
ctxt->instate = XML_PARSER_CONTENT;
return;
}
NEXTL(rl);
s = CUR_CHAR(sl);
if (!IS_CHAR(s)) {
xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL);
ctxt->instate = XML_PARSER_CONTENT;
return;
}
NEXTL(sl);
cur = CUR_CHAR(l);
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return;
}
while (IS_CHAR(cur) &&
((r != ']') || (s != ']') || (cur != '>'))) {
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlFree(buf);
xmlErrMemory(ctxt, NULL);
return;
}
buf = tmp;
}
COPY_BUF(rl,buf,len,r);
r = s;
rl = sl;
s = cur;
sl = l;
count++;
if (count > 50) {
GROW;
count = 0;
}
NEXTL(l);
cur = CUR_CHAR(l);
}
buf[len] = 0;
ctxt->instate = XML_PARSER_CONTENT;
if (cur != '>') {
xmlFatalErrMsgStr(ctxt, XML_ERR_CDATA_NOT_FINISHED,
"CData section not finished\n%.50s\n", buf);
xmlFree(buf);
return;
}
NEXTL(l);
/*
* OK the buffer is to be consumed as cdata.
*/
if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
if (ctxt->sax->cdataBlock != NULL)
ctxt->sax->cdataBlock(ctxt->userData, buf, len);
else if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData, buf, len);
}
xmlFree(buf);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseCDSect(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int r, rl;
int s, sl;
int cur, l;
int count = 0;
/* Check 2.6.0 was NXT(0) not RAW */
if (CMP9(CUR_PTR, '<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[')) {
SKIP(9);
} else
return;
ctxt->instate = XML_PARSER_CDATA_SECTION;
r = CUR_CHAR(rl);
if (!IS_CHAR(r)) {
xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL);
ctxt->instate = XML_PARSER_CONTENT;
return;
}
NEXTL(rl);
s = CUR_CHAR(sl);
if (!IS_CHAR(s)) {
xmlFatalErr(ctxt, XML_ERR_CDATA_NOT_FINISHED, NULL);
ctxt->instate = XML_PARSER_CONTENT;
return;
}
NEXTL(sl);
cur = CUR_CHAR(l);
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return;
}
while (IS_CHAR(cur) &&
((r != ']') || (s != ']') || (cur != '>'))) {
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlFree(buf);
xmlErrMemory(ctxt, NULL);
return;
}
buf = tmp;
}
COPY_BUF(rl,buf,len,r);
r = s;
rl = sl;
s = cur;
sl = l;
count++;
if (count > 50) {
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buf);
return;
}
count = 0;
}
NEXTL(l);
cur = CUR_CHAR(l);
}
buf[len] = 0;
ctxt->instate = XML_PARSER_CONTENT;
if (cur != '>') {
xmlFatalErrMsgStr(ctxt, XML_ERR_CDATA_NOT_FINISHED,
"CData section not finished\n%.50s\n", buf);
xmlFree(buf);
return;
}
NEXTL(l);
/*
* OK the buffer is to be consumed as cdata.
*/
if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
if (ctxt->sax->cdataBlock != NULL)
ctxt->sax->cdataBlock(ctxt->userData, buf, len);
else if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData, buf, len);
}
xmlFree(buf);
}
| 171,273 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_inquire_context(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_name_t *src_name,
gss_name_t *targ_name,
OM_uint32 *lifetime_rec,
gss_OID *mech_type,
OM_uint32 *ctx_flags,
int *locally_initiated,
int *opened)
{
OM_uint32 ret = GSS_S_COMPLETE;
ret = gss_inquire_context(minor_status,
context_handle,
src_name,
targ_name,
lifetime_rec,
mech_type,
ctx_flags,
locally_initiated,
opened);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_inquire_context(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_name_t *src_name,
gss_name_t *targ_name,
OM_uint32 *lifetime_rec,
gss_OID *mech_type,
OM_uint32 *ctx_flags,
int *locally_initiated,
int *opened)
{
OM_uint32 ret = GSS_S_COMPLETE;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (src_name != NULL)
*src_name = GSS_C_NO_NAME;
if (targ_name != NULL)
*targ_name = GSS_C_NO_NAME;
if (lifetime_rec != NULL)
*lifetime_rec = 0;
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_spnego;
if (ctx_flags != NULL)
*ctx_flags = 0;
if (locally_initiated != NULL)
*locally_initiated = sc->initiate;
if (opened != NULL)
*opened = sc->opened;
if (sc->ctx_handle != GSS_C_NO_CONTEXT) {
ret = gss_inquire_context(minor_status, sc->ctx_handle,
src_name, targ_name, lifetime_rec,
mech_type, ctx_flags, NULL, NULL);
}
if (!sc->opened) {
/*
* We are still doing SPNEGO negotiation, so report SPNEGO as
* the OID. After negotiation is complete we will report the
* underlying mechanism OID.
*/
if (mech_type != NULL)
*mech_type = (gss_OID)gss_mech_spnego;
/*
* Remove flags we don't support with partially-established
* contexts. (Change this to keep GSS_C_TRANS_FLAG if we add
* support for exporting partial SPNEGO contexts.)
*/
if (ctx_flags != NULL) {
*ctx_flags &= ~GSS_C_PROT_READY_FLAG;
*ctx_flags &= ~GSS_C_TRANS_FLAG;
}
}
return (ret);
}
| 166,661 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cid_parse_font_matrix( CID_Face face,
CID_Parser* parser )
{
CID_FaceDict dict;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts )
{
FT_Matrix* matrix;
FT_Vector* offset;
dict = face->cid.font_dicts + parser->num_dict;
matrix = &dict->font_matrix;
offset = &dict->font_offset;
(void)cid_parser_to_fixed_array( parser, 6, temp, 3 );
temp_scale = FT_ABS( temp[3] );
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
Commit Message:
CWE ID: CWE-20 | cid_parse_font_matrix( CID_Face face,
CID_Parser* parser )
{
CID_FaceDict dict;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts )
{
FT_Matrix* matrix;
FT_Vector* offset;
FT_Int result;
dict = face->cid.font_dicts + parser->num_dict;
matrix = &dict->font_matrix;
offset = &dict->font_offset;
result = cid_parser_to_fixed_array( parser, 6, temp, 3 );
if ( result < 6 )
return FT_THROW( Invalid_File_Format );
temp_scale = FT_ABS( temp[3] );
if ( temp_scale == 0 )
{
FT_ERROR(( "cid_parse_font_matrix: invalid font matrix\n" ));
return FT_THROW( Invalid_File_Format );
}
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
}
| 165,341 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(locale_get_primary_language )
{
get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | PHP_FUNCTION(locale_get_primary_language )
PHP_FUNCTION(locale_get_primary_language )
{
get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,184 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int read_filesystem_tables_4()
{
long long directory_table_end, table_start;
if(read_xattrs_from_disk(fd, &sBlk.s, no_xattrs, &table_start) == 0)
return FALSE;
if(read_uids_guids(&table_start) == FALSE)
return FALSE;
if(parse_exports_table(&table_start) == FALSE)
return FALSE;
if(read_fragment_table(&directory_table_end) == FALSE)
return FALSE;
if(read_inode_table(sBlk.s.inode_table_start,
sBlk.s.directory_table_start) == FALSE)
return FALSE;
if(read_directory_table(sBlk.s.directory_table_start,
directory_table_end) == FALSE)
return FALSE;
if(no_xattrs)
sBlk.s.xattr_id_table_start = SQUASHFS_INVALID_BLK;
return TRUE;
}
Commit Message: unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6
Add more filesystem table sanity checks to Unsquashfs-4 and
also properly fix CVE-2015-4645 and CVE-2015-4646.
The CVEs were raised due to Unsquashfs having variable
oveflow and stack overflow in a number of vulnerable
functions.
The suggested patch only "fixed" one such function and fixed
it badly, and so it was buggy and introduced extra bugs!
The suggested patch was not only buggy, but, it used the
essentially wrong approach too. It was "fixing" the
symptom but not the cause. The symptom is wrong values
causing overflow, the cause is filesystem corruption.
This corruption should be detected and the filesystem
rejected *before* trying to allocate memory.
This patch applies the following fixes:
1. The filesystem super-block tables are checked, and the values
must match across the filesystem.
This will trap corrupted filesystems created by Mksquashfs.
2. The maximum (theorectical) size the filesystem tables could grow
to, were analysed, and some variables were increased from int to
long long.
This analysis has been added as comments.
3. Stack allocation was removed, and a shared buffer (which is
checked and increased as necessary) is used to read the
table indexes.
Signed-off-by: Phillip Lougher <[email protected]>
CWE ID: CWE-190 | int read_filesystem_tables_4()
{
long long table_start;
/* Read xattrs */
if(sBlk.s.xattr_id_table_start != SQUASHFS_INVALID_BLK) {
/* sanity check super block contents */
if(sBlk.s.xattr_id_table_start >= sBlk.s.bytes_used) {
ERROR("read_filesystem_tables: xattr id table start too large in super block\n");
goto corrupted;
}
if(read_xattrs_from_disk(fd, &sBlk.s, no_xattrs, &table_start) == 0)
goto corrupted;
} else
table_start = sBlk.s.bytes_used;
/* Read id lookup table */
/* Sanity check super block contents */
if(sBlk.s.id_table_start >= table_start) {
ERROR("read_filesystem_tables: id table start too large in super block\n");
goto corrupted;
}
/* there should always be at least one id */
if(sBlk.s.no_ids == 0) {
ERROR("read_filesystem_tables: Bad id count in super block\n");
goto corrupted;
}
/*
* the number of ids can never be more than double the number of inodes
* (the maximum is a unique uid and gid for each inode).
*/
if(sBlk.s.no_ids > (sBlk.s.inodes * 2L)) {
ERROR("read_filesystem_tables: Bad id count in super block\n");
goto corrupted;
}
if(read_id_table(&table_start) == FALSE)
goto corrupted;
/* Read exports table */
if(sBlk.s.lookup_table_start != SQUASHFS_INVALID_BLK) {
/* sanity check super block contents */
if(sBlk.s.lookup_table_start >= table_start) {
ERROR("read_filesystem_tables: lookup table start too large in super block\n");
goto corrupted;
}
if(parse_exports_table(&table_start) == FALSE)
goto corrupted;
}
/* Read fragment table */
if(sBlk.s.fragments != 0) {
/* Sanity check super block contents */
if(sBlk.s.fragment_table_start >= table_start) {
ERROR("read_filesystem_tables: fragment table start too large in super block\n");
goto corrupted;
}
/* The number of fragments should not exceed the number of inodes */
if(sBlk.s.fragments > sBlk.s.inodes) {
ERROR("read_filesystem_tables: Bad fragment count in super block\n");
goto corrupted;
}
if(read_fragment_table(&table_start) == FALSE)
goto corrupted;
} else {
/*
* Sanity check super block contents - with 0 fragments,
* the fragment table should be empty
*/
if(sBlk.s.fragment_table_start != table_start) {
ERROR("read_filesystem_tables: fragment table start invalid in super block\n");
goto corrupted;
}
}
/* Read directory table */
/* Sanity check super block contents */
if(sBlk.s.directory_table_start >= table_start) {
ERROR("read_filesystem_tables: directory table start too large in super block\n");
goto corrupted;
}
if(read_directory_table(sBlk.s.directory_table_start,
table_start) == FALSE)
goto corrupted;
/* Read inode table */
/* Sanity check super block contents */
if(sBlk.s.inode_table_start >= sBlk.s.directory_table_start) {
ERROR("read_filesystem_tables: inode table start too large in super block\n");
goto corrupted;
}
if(read_inode_table(sBlk.s.inode_table_start,
sBlk.s.directory_table_start) == FALSE)
goto corrupted;
if(no_xattrs)
sBlk.s.xattr_id_table_start = SQUASHFS_INVALID_BLK;
return TRUE;
corrupted:
ERROR("File system corruption detected\n");
return FALSE;
}
| 168,880 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: FileReaderLoader::~FileReaderLoader()
{
terminate();
if (!m_urlForReading.isEmpty())
ThreadableBlobRegistry::unregisterBlobURL(m_urlForReading);
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | FileReaderLoader::~FileReaderLoader()
{
terminate();
if (!m_urlForReading.isEmpty())
BlobRegistry::unregisterBlobURL(m_urlForReading);
}
| 170,693 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int ip6_ufo_append_data(struct sock *sk,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int hh_len, int fragheaderlen,
int transhdrlen, int mtu,unsigned int flags,
struct rt6_info *rt)
{
struct sk_buff *skb;
int err;
/* There is support for UDP large send offload by network
* device, so create one single skb packet containing complete
* udp datagram
*/
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) {
struct frag_hdr fhdr;
skb = sock_alloc_send_skb(sk,
hh_len + fragheaderlen + transhdrlen + 20,
(flags & MSG_DONTWAIT), &err);
if (skb == NULL)
return err;
/* reserve space for Hardware header */
skb_reserve(skb, hh_len);
/* create space for UDP/IP header */
skb_put(skb,fragheaderlen + transhdrlen);
/* initialize network header pointer */
skb_reset_network_header(skb);
/* initialize protocol header pointer */
skb->transport_header = skb->network_header + fragheaderlen;
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = CHECKSUM_PARTIAL;
skb->csum = 0;
/* Specify the length of each IPv6 datagram fragment.
* It has to be a multiple of 8.
*/
skb_shinfo(skb)->gso_size = (mtu - fragheaderlen -
sizeof(struct frag_hdr)) & ~7;
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
ipv6_select_ident(&fhdr, rt);
skb_shinfo(skb)->ip6_frag_id = fhdr.identification;
__skb_queue_tail(&sk->sk_write_queue, skb);
}
return skb_append_datato_frags(sk, skb, getfrag, from,
(length - transhdrlen));
}
Commit Message: ip6_output: do skb ufo init for peeked non ufo skb as well
Now, if user application does:
sendto len<mtu flag MSG_MORE
sendto len>mtu flag 0
The skb is not treated as fragmented one because it is not initialized
that way. So move the initialization to fix this.
introduced by:
commit e89e9cf539a28df7d0eb1d0a545368e9920b34ac "[IPv4/IPv6]: UFO Scatter-gather approach"
Signed-off-by: Jiri Pirko <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | static inline int ip6_ufo_append_data(struct sock *sk,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int hh_len, int fragheaderlen,
int transhdrlen, int mtu,unsigned int flags,
struct rt6_info *rt)
{
struct sk_buff *skb;
struct frag_hdr fhdr;
int err;
/* There is support for UDP large send offload by network
* device, so create one single skb packet containing complete
* udp datagram
*/
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) {
skb = sock_alloc_send_skb(sk,
hh_len + fragheaderlen + transhdrlen + 20,
(flags & MSG_DONTWAIT), &err);
if (skb == NULL)
return err;
/* reserve space for Hardware header */
skb_reserve(skb, hh_len);
/* create space for UDP/IP header */
skb_put(skb,fragheaderlen + transhdrlen);
/* initialize network header pointer */
skb_reset_network_header(skb);
/* initialize protocol header pointer */
skb->transport_header = skb->network_header + fragheaderlen;
skb->protocol = htons(ETH_P_IPV6);
skb->csum = 0;
__skb_queue_tail(&sk->sk_write_queue, skb);
} else if (skb_is_gso(skb)) {
goto append;
}
skb->ip_summed = CHECKSUM_PARTIAL;
/* Specify the length of each IPv6 datagram fragment.
* It has to be a multiple of 8.
*/
skb_shinfo(skb)->gso_size = (mtu - fragheaderlen -
sizeof(struct frag_hdr)) & ~7;
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
ipv6_select_ident(&fhdr, rt);
skb_shinfo(skb)->ip6_frag_id = fhdr.identification;
append:
return skb_append_datato_frags(sk, skb, getfrag, from,
(length - transhdrlen));
}
| 169,893 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ChromeContentRendererClient::RenderViewCreated(RenderView* render_view) {
ContentSettingsObserver* content_settings =
new ContentSettingsObserver(render_view);
new DevToolsAgent(render_view);
new ExtensionHelper(render_view, extension_dispatcher_.get());
new PageLoadHistograms(render_view, histogram_snapshots_.get());
new PrintWebViewHelper(render_view);
new SearchBox(render_view);
new SpellCheckProvider(render_view, spellcheck_.get());
#if defined(ENABLE_SAFE_BROWSING)
safe_browsing::MalwareDOMDetails::Create(render_view);
#endif
#if defined(OS_MACOSX)
new TextInputClientObserver(render_view);
#endif // defined(OS_MACOSX)
PasswordAutofillManager* password_autofill_manager =
new PasswordAutofillManager(render_view);
AutofillAgent* autofill_agent = new AutofillAgent(render_view,
password_autofill_manager);
PageClickTracker* page_click_tracker = new PageClickTracker(render_view);
page_click_tracker->AddListener(password_autofill_manager);
page_click_tracker->AddListener(autofill_agent);
TranslateHelper* translate = new TranslateHelper(render_view, autofill_agent);
new ChromeRenderViewObserver(
render_view, content_settings, extension_dispatcher_.get(), translate);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDomAutomationController)) {
new AutomationRendererHelper(render_view);
}
}
Commit Message: DevTools: move DevToolsAgent/Client into content.
BUG=84078
TEST=
Review URL: http://codereview.chromium.org/7461019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void ChromeContentRendererClient::RenderViewCreated(RenderView* render_view) {
ContentSettingsObserver* content_settings =
new ContentSettingsObserver(render_view);
new ExtensionHelper(render_view, extension_dispatcher_.get());
new PageLoadHistograms(render_view, histogram_snapshots_.get());
new PrintWebViewHelper(render_view);
new SearchBox(render_view);
new SpellCheckProvider(render_view, spellcheck_.get());
#if defined(ENABLE_SAFE_BROWSING)
safe_browsing::MalwareDOMDetails::Create(render_view);
#endif
#if defined(OS_MACOSX)
new TextInputClientObserver(render_view);
#endif // defined(OS_MACOSX)
PasswordAutofillManager* password_autofill_manager =
new PasswordAutofillManager(render_view);
AutofillAgent* autofill_agent = new AutofillAgent(render_view,
password_autofill_manager);
PageClickTracker* page_click_tracker = new PageClickTracker(render_view);
page_click_tracker->AddListener(password_autofill_manager);
page_click_tracker->AddListener(autofill_agent);
TranslateHelper* translate = new TranslateHelper(render_view, autofill_agent);
new ChromeRenderViewObserver(
render_view, content_settings, extension_dispatcher_.get(), translate);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDomAutomationController)) {
new AutomationRendererHelper(render_view);
}
}
| 170,324 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
if (cid <= 0)
continue;
dctx->remaining = avpriv_dnxhd_get_frame_size(cid);
if (dctx->remaining <= 0) {
dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (dctx->remaining <= 0)
return dctx->remaining;
}
if (buf_size - i + 47 >= dctx->remaining) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
return END_NOT_FOUND;
}
Commit Message: avcodec/dnxhd_parser: Do not return invalid value from dnxhd_find_frame_end() on error
Fixes: Null pointer dereference
Fixes: CVE-2017-9608
Found-by: Yihan Lian
Signed-off-by: Michael Niedermayer <[email protected]>
(cherry picked from commit 611b35627488a8d0763e75c25ee0875c5b7987dd)
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476 | static int dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
int remaining;
if (cid <= 0)
continue;
remaining = avpriv_dnxhd_get_frame_size(cid);
if (remaining <= 0) {
remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (remaining <= 0)
continue;
}
dctx->remaining = remaining;
if (buf_size - i + 47 >= dctx->remaining) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
return END_NOT_FOUND;
}
| 170,046 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TestPlaybackRate(double playback_rate,
int buffer_size_in_frames,
int total_frames_requested) {
int initial_bytes_enqueued = bytes_enqueued_;
int initial_bytes_buffered = algorithm_.bytes_buffered();
algorithm_.SetPlaybackRate(static_cast<float>(playback_rate));
scoped_array<uint8> buffer(
new uint8[buffer_size_in_frames * algorithm_.bytes_per_frame()]);
if (playback_rate == 0.0) {
int frames_written =
algorithm_.FillBuffer(buffer.get(), buffer_size_in_frames);
EXPECT_EQ(0, frames_written);
return;
}
int frames_remaining = total_frames_requested;
while (frames_remaining > 0) {
int frames_requested = std::min(buffer_size_in_frames, frames_remaining);
int frames_written =
algorithm_.FillBuffer(buffer.get(), frames_requested);
CHECK_GT(frames_written, 0);
CheckFakeData(buffer.get(), frames_written, playback_rate);
frames_remaining -= frames_written;
}
int bytes_requested = total_frames_requested * algorithm_.bytes_per_frame();
int bytes_consumed = ComputeConsumedBytes(initial_bytes_enqueued,
initial_bytes_buffered);
if (playback_rate == 1.0) {
EXPECT_EQ(bytes_requested, bytes_consumed);
return;
}
static const double kMaxAcceptableDelta = 0.01;
double actual_playback_rate = 1.0 * bytes_consumed / bytes_requested;
double delta = std::abs(1.0 - (actual_playback_rate / playback_rate));
EXPECT_LE(delta, kMaxAcceptableDelta);
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void TestPlaybackRate(double playback_rate,
int buffer_size_in_frames,
int total_frames_requested) {
int initial_bytes_enqueued = bytes_enqueued_;
int initial_bytes_buffered = algorithm_.bytes_buffered();
algorithm_.SetPlaybackRate(static_cast<float>(playback_rate));
scoped_array<uint8> buffer(
new uint8[buffer_size_in_frames * algorithm_.bytes_per_frame()]);
if (playback_rate == 0.0) {
int frames_written =
algorithm_.FillBuffer(buffer.get(), buffer_size_in_frames);
EXPECT_EQ(0, frames_written);
return;
}
int frames_remaining = total_frames_requested;
while (frames_remaining > 0) {
int frames_requested = std::min(buffer_size_in_frames, frames_remaining);
int frames_written =
algorithm_.FillBuffer(buffer.get(), frames_requested);
ASSERT_GT(frames_written, 0);
CheckFakeData(buffer.get(), frames_written);
frames_remaining -= frames_written;
}
int bytes_requested = total_frames_requested * algorithm_.bytes_per_frame();
int bytes_consumed = ComputeConsumedBytes(initial_bytes_enqueued,
initial_bytes_buffered);
if (playback_rate == 1.0) {
EXPECT_EQ(bytes_requested, bytes_consumed);
return;
}
static const double kMaxAcceptableDelta = 0.01;
double actual_playback_rate = 1.0 * bytes_consumed / bytes_requested;
double delta = std::abs(1.0 - (actual_playback_rate / playback_rate));
EXPECT_LE(delta, kMaxAcceptableDelta);
}
| 171,536 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: scoped_refptr<PermissionSet> UnpackPermissionSet(
const Permissions& permissions, std::string* error) {
APIPermissionSet apis;
std::vector<std::string>* permissions_list = permissions.permissions.get();
if (permissions_list) {
PermissionsInfo* info = PermissionsInfo::GetInstance();
for (std::vector<std::string>::iterator it = permissions_list->begin();
it != permissions_list->end(); ++it) {
if (it->find(kDelimiter) != std::string::npos) {
size_t delimiter = it->find(kDelimiter);
std::string permission_name = it->substr(0, delimiter);
std::string permission_arg = it->substr(delimiter + 1);
scoped_ptr<base::Value> permission_json(
base::JSONReader::Read(permission_arg));
if (!permission_json.get()) {
*error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it);
return NULL;
}
APIPermission* permission = NULL;
const APIPermissionInfo* bluetooth_device_permission_info =
info->GetByID(APIPermission::kBluetoothDevice);
const APIPermissionInfo* usb_device_permission_info =
info->GetByID(APIPermission::kUsbDevice);
if (permission_name == bluetooth_device_permission_info->name()) {
permission = new BluetoothDevicePermission(
bluetooth_device_permission_info);
} else if (permission_name == usb_device_permission_info->name()) {
permission = new UsbDevicePermission(usb_device_permission_info);
} else {
*error = kUnsupportedPermissionId;
return NULL;
}
CHECK(permission);
if (!permission->FromValue(permission_json.get())) {
*error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it);
return NULL;
}
apis.insert(permission);
} else {
const APIPermissionInfo* permission_info = info->GetByName(*it);
if (!permission_info) {
*error = ErrorUtils::FormatErrorMessage(
kUnknownPermissionError, *it);
return NULL;
}
apis.insert(permission_info->id());
}
}
}
URLPatternSet origins;
if (permissions.origins.get()) {
for (std::vector<std::string>::iterator it = permissions.origins->begin();
it != permissions.origins->end(); ++it) {
URLPattern origin(Extension::kValidHostPermissionSchemes);
URLPattern::ParseResult parse_result = origin.Parse(*it);
if (URLPattern::PARSE_SUCCESS != parse_result) {
*error = ErrorUtils::FormatErrorMessage(
kInvalidOrigin,
*it,
URLPattern::GetParseResultString(parse_result));
return NULL;
}
origins.AddPattern(origin);
}
}
return scoped_refptr<PermissionSet>(
new PermissionSet(apis, origins, URLPatternSet()));
}
Commit Message: Check prefs before allowing extension file access in the permissions API.
[email protected]
BUG=169632
Review URL: https://chromiumcodereview.appspot.com/11884008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | scoped_refptr<PermissionSet> UnpackPermissionSet(
const Permissions& permissions,
bool allow_file_access,
std::string* error) {
APIPermissionSet apis;
std::vector<std::string>* permissions_list = permissions.permissions.get();
if (permissions_list) {
PermissionsInfo* info = PermissionsInfo::GetInstance();
for (std::vector<std::string>::iterator it = permissions_list->begin();
it != permissions_list->end(); ++it) {
if (it->find(kDelimiter) != std::string::npos) {
size_t delimiter = it->find(kDelimiter);
std::string permission_name = it->substr(0, delimiter);
std::string permission_arg = it->substr(delimiter + 1);
scoped_ptr<base::Value> permission_json(
base::JSONReader::Read(permission_arg));
if (!permission_json.get()) {
*error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it);
return NULL;
}
APIPermission* permission = NULL;
const APIPermissionInfo* bluetooth_device_permission_info =
info->GetByID(APIPermission::kBluetoothDevice);
const APIPermissionInfo* usb_device_permission_info =
info->GetByID(APIPermission::kUsbDevice);
if (permission_name == bluetooth_device_permission_info->name()) {
permission = new BluetoothDevicePermission(
bluetooth_device_permission_info);
} else if (permission_name == usb_device_permission_info->name()) {
permission = new UsbDevicePermission(usb_device_permission_info);
} else {
*error = kUnsupportedPermissionId;
return NULL;
}
CHECK(permission);
if (!permission->FromValue(permission_json.get())) {
*error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it);
return NULL;
}
apis.insert(permission);
} else {
const APIPermissionInfo* permission_info = info->GetByName(*it);
if (!permission_info) {
*error = ErrorUtils::FormatErrorMessage(
kUnknownPermissionError, *it);
return NULL;
}
apis.insert(permission_info->id());
}
}
}
URLPatternSet origins;
if (permissions.origins.get()) {
for (std::vector<std::string>::iterator it = permissions.origins->begin();
it != permissions.origins->end(); ++it) {
int allowed_schemes = Extension::kValidHostPermissionSchemes;
if (!allow_file_access)
allowed_schemes &= ~URLPattern::SCHEME_FILE;
URLPattern origin(allowed_schemes);
URLPattern::ParseResult parse_result = origin.Parse(*it);
if (URLPattern::PARSE_SUCCESS != parse_result) {
*error = ErrorUtils::FormatErrorMessage(
kInvalidOrigin,
*it,
URLPattern::GetParseResultString(parse_result));
return NULL;
}
origins.AddPattern(origin);
}
}
return scoped_refptr<PermissionSet>(
new PermissionSet(apis, origins, URLPatternSet()));
}
| 171,445 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void mpeg4_encode_gop_header(MpegEncContext *s)
{
int hours, minutes, seconds;
int64_t time;
put_bits(&s->pb, 16, 0);
put_bits(&s->pb, 16, GOP_STARTCODE);
time = s->current_picture_ptr->f->pts;
if (s->reordered_input_picture[1])
time = FFMIN(time, s->reordered_input_picture[1]->f->pts);
time = time * s->avctx->time_base.num;
s->last_time_base = FFUDIV(time, s->avctx->time_base.den);
seconds = FFUDIV(time, s->avctx->time_base.den);
minutes = FFUDIV(seconds, 60); seconds = FFUMOD(seconds, 60);
hours = FFUDIV(minutes, 60); minutes = FFUMOD(minutes, 60);
hours = FFUMOD(hours , 24);
put_bits(&s->pb, 5, hours);
put_bits(&s->pb, 6, minutes);
put_bits(&s->pb, 1, 1);
put_bits(&s->pb, 6, seconds);
put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP));
put_bits(&s->pb, 1, 0); // broken link == NO
ff_mpeg4_stuffing(&s->pb);
}
Commit Message: avcodec/mpeg4videoenc: Use 64 bit for times in mpeg4_encode_gop_header()
Fixes truncation
Fixes Assertion n <= 31 && value < (1U << n) failed at libavcodec/put_bits.h:169
Fixes: ffmpeg_crash_2.avi
Found-by: Thuan Pham <[email protected]>, Marcel Böhme, Andrew Santosa and Alexandru RazvanCaciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-20 | static void mpeg4_encode_gop_header(MpegEncContext *s)
{
int64_t hours, minutes, seconds;
int64_t time;
put_bits(&s->pb, 16, 0);
put_bits(&s->pb, 16, GOP_STARTCODE);
time = s->current_picture_ptr->f->pts;
if (s->reordered_input_picture[1])
time = FFMIN(time, s->reordered_input_picture[1]->f->pts);
time = time * s->avctx->time_base.num;
s->last_time_base = FFUDIV(time, s->avctx->time_base.den);
seconds = FFUDIV(time, s->avctx->time_base.den);
minutes = FFUDIV(seconds, 60); seconds = FFUMOD(seconds, 60);
hours = FFUDIV(minutes, 60); minutes = FFUMOD(minutes, 60);
hours = FFUMOD(hours , 24);
put_bits(&s->pb, 5, hours);
put_bits(&s->pb, 6, minutes);
put_bits(&s->pb, 1, 1);
put_bits(&s->pb, 6, seconds);
put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP));
put_bits(&s->pb, 1, 0); // broken link == NO
ff_mpeg4_stuffing(&s->pb);
}
| 169,192 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
explicit_vr[MaxTextExtent],
implicit_vr[MaxTextExtent],
magick[MaxTextExtent],
photometric[MaxTextExtent];
DCMStreamInfo
*stream_info;
Image
*image;
int
*bluemap,
datum,
*greenmap,
*graymap,
index,
*redmap;
MagickBooleanType
explicit_file,
explicit_retry,
polarity,
sequence,
use_explicit;
MagickOffsetType
offset;
Quantum
*scale;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
size_t
bits_allocated,
bytes_per_pixel,
colors,
depth,
height,
length,
mask,
max_value,
number_scenes,
quantum,
samples_per_pixel,
signed_data,
significant_bits,
status,
width,
window_width;
ssize_t
count,
scene,
window_center,
y;
unsigned char
*data;
unsigned short
group,
element;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=8UL;
image->endian=LSBEndian;
/*
Read DCM preamble.
*/
stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
if (stream_info == (DCMStreamInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(stream_info,0,sizeof(*stream_info));
count=ReadBlob(image,128,(unsigned char *) magick);
if (count != 128)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,4,(unsigned char *) magick);
if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
{
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Read DCM Medical image.
*/
(void) CopyMagickString(photometric,"MONOCHROME1 ",MaxTextExtent);
bits_allocated=8;
bytes_per_pixel=1;
polarity=MagickFalse;
data=(unsigned char *) NULL;
depth=8;
element=0;
explicit_vr[2]='\0';
explicit_file=MagickFalse;
colors=0;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
graymap=(int *) NULL;
height=0;
max_value=255UL;
mask=0xffff;
number_scenes=1;
samples_per_pixel=1;
scale=(Quantum *) NULL;
sequence=MagickFalse;
signed_data=(~0UL);
significant_bits=0;
use_explicit=MagickFalse;
explicit_retry = MagickFalse;
width=0;
window_center=0;
window_width=0;
for (group=0; (group != 0x7FE0) || (element != 0x0010) ||
(sequence != MagickFalse); )
{
/*
Read a group.
*/
image->offset=(ssize_t) TellBlob(image);
group=ReadBlobLSBShort(image);
element=ReadBlobLSBShort(image);
if ((group != 0x0002) && (image->endian == MSBEndian))
{
group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
}
quantum=0;
/*
Find corresponding VR for this group and element.
*/
for (i=0; dicom_info[i].group < 0xffff; i++)
if ((group == dicom_info[i].group) && (element == dicom_info[i].element))
break;
(void) CopyMagickString(implicit_vr,dicom_info[i].vr,MaxTextExtent);
count=ReadBlob(image,2,(unsigned char *) explicit_vr);
if (count != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Check for "explicitness", but meta-file headers always explicit.
*/
if ((explicit_file == MagickFalse) && (group != 0x0002))
explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
(isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
MagickTrue : MagickFalse;
use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
(explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
if ((use_explicit != MagickFalse) && (strcmp(implicit_vr,"xs") == 0))
(void) CopyMagickString(implicit_vr,explicit_vr,MaxTextExtent);
if ((use_explicit == MagickFalse) || (strcmp(implicit_vr,"!!") == 0))
{
offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
quantum=4;
}
else
{
/*
Assume explicit type.
*/
quantum=2;
if ((strcmp(explicit_vr,"OB") == 0) ||
(strcmp(explicit_vr,"UN") == 0) ||
(strcmp(explicit_vr,"OW") == 0) || (strcmp(explicit_vr,"SQ") == 0))
{
(void) ReadBlobLSBShort(image);
quantum=4;
}
}
datum=0;
if (quantum == 4)
{
if (group == 0x0002)
datum=(int) ReadBlobLSBLong(image);
else
datum=(int) ReadBlobLong(image);
}
else
if (quantum == 2)
{
if (group == 0x0002)
datum=(int) ReadBlobLSBShort(image);
else
datum=(int) ReadBlobShort(image);
}
quantum=0;
length=1;
if (datum != 0)
{
if ((strcmp(implicit_vr,"SS") == 0) ||
(strcmp(implicit_vr,"US") == 0))
quantum=2;
else
if ((strcmp(implicit_vr,"UL") == 0) ||
(strcmp(implicit_vr,"SL") == 0) ||
(strcmp(implicit_vr,"FL") == 0))
quantum=4;
else
if (strcmp(implicit_vr,"FD") != 0)
quantum=1;
else
quantum=8;
if (datum != ~0)
length=(size_t) datum/quantum;
else
{
/*
Sequence and item of undefined length.
*/
quantum=0;
length=0;
}
}
if (image_info->verbose != MagickFalse)
{
/*
Display Dicom info.
*/
if (use_explicit == MagickFalse)
explicit_vr[0]='\0';
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
(unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
(unsigned long) group,(unsigned long) element);
if (dicom_info[i].description != (char *) NULL)
(void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
(void) FormatLocaleFile(stdout,": ");
}
if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"\n");
break;
}
/*
Allocate space and read an array.
*/
data=(unsigned char *) NULL;
if ((length == 1) && (quantum == 1))
datum=(int) ReadBlobByte(image);
else
if ((length == 1) && (quantum == 2))
{
if (group == 0x0002)
datum=(int) ReadBlobLSBShort(image);
else
datum=(int) ReadBlobShort(image);
}
else
if ((length == 1) && (quantum == 4))
{
if (group == 0x0002)
datum=(int) ReadBlobLSBLong(image);
else
datum=(int) ReadBlobLong(image);
}
else
if ((quantum != 0) && (length != 0))
{
if (~length >= 1)
data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) quantum*length,data);
if (count != (ssize_t) (quantum*length))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"count=%d quantum=%d "
"length=%d group=%d\n",(int) count,(int) quantum,(int)
length,(int) group);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
data[length*quantum]='\0';
}
else
if ((unsigned int) datum == 0xFFFFFFFFU)
{
sequence=MagickTrue;
continue;
}
if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
sequence=MagickFalse;
continue;
}
if (sequence != MagickFalse)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
continue;
}
switch (group)
{
case 0x0002:
{
switch (element)
{
case 0x0010:
{
char
transfer_syntax[MaxTextExtent];
/*
Transfer Syntax.
*/
if ((datum == 0) && (explicit_retry == MagickFalse))
{
explicit_retry=MagickTrue;
(void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
group=0;
element=0;
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,
"Corrupted image - trying explicit format\n");
break;
}
*transfer_syntax='\0';
if (data != (unsigned char *) NULL)
(void) CopyMagickString(transfer_syntax,(char *) data,
MaxTextExtent);
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
(const char *) transfer_syntax);
if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
{
int
subtype,
type;
type=0;
subtype=0;
(void) sscanf(transfer_syntax+17,".%d.%d",&type,&subtype);
switch (type)
{
case 1:
{
image->endian=LSBEndian;
break;
}
case 2:
{
image->endian=MSBEndian;
break;
}
case 4:
{
if ((subtype >= 80) && (subtype <= 81))
image->compression=JPEGCompression;
else
if ((subtype >= 90) && (subtype <= 93))
image->compression=JPEG2000Compression;
else
image->compression=JPEGCompression;
break;
}
case 5:
{
image->compression=RLECompression;
break;
}
}
}
break;
}
default:
break;
}
break;
}
case 0x0028:
{
switch (element)
{
case 0x0002:
{
/*
Samples per pixel.
*/
samples_per_pixel=(size_t) datum;
break;
}
case 0x0004:
{
/*
Photometric interpretation.
*/
for (i=0; i < (ssize_t) MagickMin(length,MaxTextExtent-1); i++)
photometric[i]=(char) data[i];
photometric[i]='\0';
polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
MagickTrue : MagickFalse;
break;
}
case 0x0006:
{
/*
Planar configuration.
*/
if (datum == 1)
image->interlace=PlaneInterlace;
break;
}
case 0x0008:
{
/*
Number of frames.
*/
number_scenes=StringToUnsignedLong((char *) data);
break;
}
case 0x0010:
{
/*
Image rows.
*/
height=(size_t) datum;
break;
}
case 0x0011:
{
/*
Image columns.
*/
width=(size_t) datum;
break;
}
case 0x0100:
{
/*
Bits allocated.
*/
bits_allocated=(size_t) datum;
bytes_per_pixel=1;
if (datum > 8)
bytes_per_pixel=2;
depth=bits_allocated;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << bits_allocated)-1;
break;
}
case 0x0101:
{
/*
Bits stored.
*/
significant_bits=(size_t) datum;
bytes_per_pixel=1;
if (significant_bits > 8)
bytes_per_pixel=2;
depth=significant_bits;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << significant_bits)-1;
mask=(size_t) GetQuantumRange(significant_bits);
break;
}
case 0x0102:
{
/*
High bit.
*/
break;
}
case 0x0103:
{
/*
Pixel representation.
*/
signed_data=(size_t) datum;
break;
}
case 0x1050:
{
/*
Visible pixel range: center.
*/
if (data != (unsigned char *) NULL)
window_center=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1051:
{
/*
Visible pixel range: width.
*/
if (data != (unsigned char *) NULL)
window_width=StringToUnsignedLong((char *) data);
break;
}
case 0x1200:
case 0x3006:
{
/*
Populate graymap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/bytes_per_pixel);
datum=(int) colors;
graymap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*graymap));
if (graymap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) colors; i++)
if (bytes_per_pixel == 1)
graymap[i]=(int) data[i];
else
graymap[i]=(int) ((short *) data)[i];
break;
}
case 0x1201:
{
unsigned short
index;
/*
Populate redmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
redmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*redmap));
if (redmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
redmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1202:
{
unsigned short
index;
/*
Populate greenmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
greenmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*greenmap));
if (greenmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
greenmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1203:
{
unsigned short
index;
/*
Populate bluemap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
bluemap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*bluemap));
if (bluemap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
bluemap[i]=(int) index;
p+=2;
}
break;
}
default:
break;
}
break;
}
case 0x2050:
{
switch (element)
{
case 0x0020:
{
if ((data != (unsigned char *) NULL) &&
(strncmp((char*) data,"INVERSE", 7) == 0))
polarity=MagickTrue;
break;
}
default:
break;
}
break;
}
default:
break;
}
if (data != (unsigned char *) NULL)
{
char
*attribute;
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
if (dicom_info[i].description != (char *) NULL)
{
attribute=AcquireString("dcm:");
(void) ConcatenateString(&attribute,dicom_info[i].description);
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i == (ssize_t) length) || (length > 4))
{
(void) SubstituteString(&attribute," ","");
(void) SetImageProperty(image,attribute,(char *) data);
}
attribute=DestroyString(attribute);
}
}
if (image_info->verbose != MagickFalse)
{
if (data == (unsigned char *) NULL)
(void) FormatLocaleFile(stdout,"%d\n",datum);
else
{
/*
Display group data.
*/
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i != (ssize_t) length) && (length <= 4))
{
ssize_t
j;
datum=0;
for (j=(ssize_t) length-1; j >= 0; j--)
datum=(256*datum+data[j]);
(void) FormatLocaleFile(stdout,"%d",datum);
}
else
for (i=0; i < (ssize_t) length; i++)
if (isprint((int) data[i]) != MagickFalse)
(void) FormatLocaleFile(stdout,"%c",data[i]);
else
(void) FormatLocaleFile(stdout,"%c",'.');
(void) FormatLocaleFile(stdout,"\n");
}
}
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
if ((width == 0) || (height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) width;
image->rows=(size_t) height;
if (signed_data == 0xffff)
signed_data=(size_t) (significant_bits == 16 ? 1 : 0);
if ((image->compression == JPEGCompression) ||
(image->compression == JPEG2000Compression))
{
Image
*images;
ImageInfo
*read_info;
int
c;
size_t
length;
unsigned int
tag;
/*
Read offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ((int) ReadBlobLSBLong(image));
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
/*
Handle non-native image formats.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
images=NewImageList();
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
char
filename[MaxTextExtent];
const char
*property;
FILE
*file;
Image
*jpeg_image;
int
unique_file;
unsigned int
tag;
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
length=(size_t) ReadBlobLSBLong(image);
if (tag == 0xFFFEE0DD)
break; /* sequence delimiter tag */
if (tag != 0xFFFEE000)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if (file == (FILE *) NULL)
{
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
break;
}
for ( ; length != 0; length--)
{
c=ReadBlobByte(image);
if (c == EOF)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
(void) fputc(c,file);
}
(void) fclose(file);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
filename);
if (image->compression == JPEG2000Compression)
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"j2k:%s",
filename);
jpeg_image=ReadImage(read_info,exception);
if (jpeg_image != (Image *) NULL)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) SetImageProperty(jpeg_image,property,
GetImageProperty(image,property));
property=GetNextImageProperty(image);
}
AppendImageToList(&images,jpeg_image);
}
(void) RelinquishUniqueFileResource(filename);
}
read_info=DestroyImageInfo(read_info);
image=DestroyImage(image);
return(GetFirstImageInList(images));
}
if (depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
{
QuantumAny
range;
size_t
length;
/*
Compute pixel scaling table.
*/
length=(size_t) (GetQuantumRange(depth)+1);
scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*scale));
if (scale == (Quantum *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
range=GetQuantumRange(depth);
for (i=0; i < (ssize_t) (GetQuantumRange(depth)+1); i++)
scale[i]=ScaleAnyToQuantum((size_t) i,range);
}
if (image->compression == RLECompression)
{
size_t
length;
unsigned int
tag;
/*
Read RLE offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ((int) ReadBlobLSBLong(image));
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
}
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
if (image_info->ping != MagickFalse)
break;
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=depth;
image->colorspace=RGBColorspace;
if ((image->colormap == (PixelPacket *) NULL) && (samples_per_pixel == 1))
{
size_t
one;
one=1;
if (colors == 0)
colors=one << depth;
if (AcquireImageColormap(image,one << depth) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (redmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=redmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(Quantum) index;
}
if (greenmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=greenmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].green=(Quantum) index;
}
if (bluemap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=bluemap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].blue=(Quantum) index;
}
if (graymap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=graymap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(Quantum) index;
image->colormap[i].green=(Quantum) index;
image->colormap[i].blue=(Quantum) index;
}
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE segment table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
stream_info->remaining=(size_t) ReadBlobLSBLong(image);
if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
(EOFBlob(image) != MagickFalse))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
stream_info->count=0;
stream_info->segment_count=ReadBlobLSBLong(image);
if (stream_info->segment_count > 1)
{
bytes_per_pixel=1;
depth=8;
}
for (i=0; i < 15; i++)
stream_info->segments[i]=(ssize_t) ((int) ReadBlobLSBLong(image));
stream_info->remaining-=64;
}
if ((samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
{
/*
Convert Planar RGB DCM Medical image to pixel packets.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch ((int) i)
{
case 0:
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 1:
{
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 2:
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 3:
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
default:
break;
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
}
else
{
const char
*option;
int
byte;
LongPixelPacket
pixel;
/*
Convert DCM Medical image to pixel packets.
*/
byte=0;
i=0;
if ((window_center != 0) && (window_width == 0))
window_width=(size_t) window_center;
option=GetImageOption(image_info,"dcm:display-range");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"reset") == 0)
window_width=0;
}
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ? ((int) max_value-
ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
pixel_value=(int) (polarity != MagickFalse ? (max_value-
ReadDCMShort(stream_info,image)) :
ReadDCMShort(stream_info,image));
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=(int) ReadDCMShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=pixel_value;
if (window_width == 0)
{
if (signed_data == 1)
index=pixel_value-32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t) pixel_value <= window_min)
index=0;
else
if ((ssize_t) pixel_value > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((pixel_value-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index);
SetPixelIndex(indexes+x,index);
pixel.red=1U*image->colormap[index].red;
pixel.green=1U*image->colormap[index].green;
pixel.blue=1U*image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
pixel.red=scale[pixel.red];
pixel.green=scale[pixel.green];
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (stream_info->segment_count > 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ? ((int) max_value-
ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
{
pixel_value=(int) (polarity != MagickFalse ? (max_value-
ReadDCMShort(stream_info,image)) :
ReadDCMShort(stream_info,image));
if (signed_data == 1)
pixel_value=((signed short) pixel_value);
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=(int) ReadDCMShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=pixel_value;
if (window_width == 0)
{
if (signed_data == 1)
index=pixel_value-32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t) pixel_value <= window_min)
index=0;
else
if ((ssize_t) pixel_value > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((pixel_value-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index);
SetPixelIndex(indexes+x,(((size_t) GetPixelIndex(indexes+x)) |
(((size_t) index) << 8)));
pixel.red=1U*image->colormap[index].red;
pixel.green=1U*image->colormap[index].green;
pixel.blue=1U*image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
pixel.red=scale[pixel.red];
pixel.green=scale[pixel.green];
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(q,(((size_t) GetPixelRed(q)) |
(((size_t) pixel.red) << 8)));
SetPixelGreen(q,(((size_t) GetPixelGreen(q)) |
(((size_t) pixel.green) << 8)));
SetPixelBlue(q,(((size_t) GetPixelBlue(q)) |
(((size_t) pixel.blue) << 8)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (IsGrayImage(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (number_scenes-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
/*
Free resources.
*/
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (scale != (Quantum *) NULL)
scale=(Quantum *) RelinquishMagickMemory(scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
explicit_vr[MaxTextExtent],
implicit_vr[MaxTextExtent],
magick[MaxTextExtent],
photometric[MaxTextExtent];
DCMStreamInfo
*stream_info;
Image
*image;
int
*bluemap,
datum,
*greenmap,
*graymap,
index,
*redmap;
MagickBooleanType
explicit_file,
explicit_retry,
polarity,
sequence,
use_explicit;
MagickOffsetType
offset;
Quantum
*scale;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
size_t
bits_allocated,
bytes_per_pixel,
colors,
depth,
height,
length,
mask,
max_value,
number_scenes,
quantum,
samples_per_pixel,
signed_data,
significant_bits,
status,
width,
window_width;
ssize_t
count,
scene,
window_center,
y;
unsigned char
*data;
unsigned short
group,
element;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=8UL;
image->endian=LSBEndian;
/*
Read DCM preamble.
*/
stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
if (stream_info == (DCMStreamInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(stream_info,0,sizeof(*stream_info));
count=ReadBlob(image,128,(unsigned char *) magick);
if (count != 128)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,4,(unsigned char *) magick);
if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
{
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Read DCM Medical image.
*/
(void) CopyMagickString(photometric,"MONOCHROME1 ",MaxTextExtent);
bits_allocated=8;
bytes_per_pixel=1;
polarity=MagickFalse;
data=(unsigned char *) NULL;
depth=8;
element=0;
explicit_vr[2]='\0';
explicit_file=MagickFalse;
colors=0;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
graymap=(int *) NULL;
height=0;
max_value=255UL;
mask=0xffff;
number_scenes=1;
samples_per_pixel=1;
scale=(Quantum *) NULL;
sequence=MagickFalse;
signed_data=(~0UL);
significant_bits=0;
use_explicit=MagickFalse;
explicit_retry = MagickFalse;
width=0;
window_center=0;
window_width=0;
for (group=0; (group != 0x7FE0) || (element != 0x0010) ||
(sequence != MagickFalse); )
{
/*
Read a group.
*/
image->offset=(ssize_t) TellBlob(image);
group=ReadBlobLSBShort(image);
element=ReadBlobLSBShort(image);
if ((group != 0x0002) && (image->endian == MSBEndian))
{
group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
}
quantum=0;
/*
Find corresponding VR for this group and element.
*/
for (i=0; dicom_info[i].group < 0xffff; i++)
if ((group == dicom_info[i].group) && (element == dicom_info[i].element))
break;
(void) CopyMagickString(implicit_vr,dicom_info[i].vr,MaxTextExtent);
count=ReadBlob(image,2,(unsigned char *) explicit_vr);
if (count != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Check for "explicitness", but meta-file headers always explicit.
*/
if ((explicit_file == MagickFalse) && (group != 0x0002))
explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
(isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
MagickTrue : MagickFalse;
use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
(explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
if ((use_explicit != MagickFalse) && (strcmp(implicit_vr,"xs") == 0))
(void) CopyMagickString(implicit_vr,explicit_vr,MaxTextExtent);
if ((use_explicit == MagickFalse) || (strcmp(implicit_vr,"!!") == 0))
{
offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
quantum=4;
}
else
{
/*
Assume explicit type.
*/
quantum=2;
if ((strcmp(explicit_vr,"OB") == 0) ||
(strcmp(explicit_vr,"UN") == 0) ||
(strcmp(explicit_vr,"OW") == 0) || (strcmp(explicit_vr,"SQ") == 0))
{
(void) ReadBlobLSBShort(image);
quantum=4;
}
}
datum=0;
if (quantum == 4)
{
if (group == 0x0002)
datum=(int) ReadBlobLSBLong(image);
else
datum=(int) ReadBlobLong(image);
}
else
if (quantum == 2)
{
if (group == 0x0002)
datum=(int) ReadBlobLSBShort(image);
else
datum=(int) ReadBlobShort(image);
}
quantum=0;
length=1;
if (datum != 0)
{
if ((strcmp(implicit_vr,"SS") == 0) ||
(strcmp(implicit_vr,"US") == 0))
quantum=2;
else
if ((strcmp(implicit_vr,"UL") == 0) ||
(strcmp(implicit_vr,"SL") == 0) ||
(strcmp(implicit_vr,"FL") == 0))
quantum=4;
else
if (strcmp(implicit_vr,"FD") != 0)
quantum=1;
else
quantum=8;
if (datum != ~0)
length=(size_t) datum/quantum;
else
{
/*
Sequence and item of undefined length.
*/
quantum=0;
length=0;
}
}
if (image_info->verbose != MagickFalse)
{
/*
Display Dicom info.
*/
if (use_explicit == MagickFalse)
explicit_vr[0]='\0';
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
(unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
(unsigned long) group,(unsigned long) element);
if (dicom_info[i].description != (char *) NULL)
(void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
(void) FormatLocaleFile(stdout,": ");
}
if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"\n");
break;
}
/*
Allocate space and read an array.
*/
data=(unsigned char *) NULL;
if ((length == 1) && (quantum == 1))
datum=(int) ReadBlobByte(image);
else
if ((length == 1) && (quantum == 2))
{
if (group == 0x0002)
datum=(int) ReadBlobLSBShort(image);
else
datum=(int) ReadBlobShort(image);
}
else
if ((length == 1) && (quantum == 4))
{
if (group == 0x0002)
datum=(int) ReadBlobLSBLong(image);
else
datum=(int) ReadBlobLong(image);
}
else
if ((quantum != 0) && (length != 0))
{
if (~length >= 1)
data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) quantum*length,data);
if (count != (ssize_t) (quantum*length))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"count=%d quantum=%d "
"length=%d group=%d\n",(int) count,(int) quantum,(int)
length,(int) group);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
data[length*quantum]='\0';
}
else
if ((unsigned int) datum == 0xFFFFFFFFU)
{
sequence=MagickTrue;
continue;
}
if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
sequence=MagickFalse;
continue;
}
if (sequence != MagickFalse)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
continue;
}
switch (group)
{
case 0x0002:
{
switch (element)
{
case 0x0010:
{
char
transfer_syntax[MaxTextExtent];
/*
Transfer Syntax.
*/
if ((datum == 0) && (explicit_retry == MagickFalse))
{
explicit_retry=MagickTrue;
(void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
group=0;
element=0;
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,
"Corrupted image - trying explicit format\n");
break;
}
*transfer_syntax='\0';
if (data != (unsigned char *) NULL)
(void) CopyMagickString(transfer_syntax,(char *) data,
MaxTextExtent);
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
(const char *) transfer_syntax);
if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
{
int
subtype,
type;
type=0;
subtype=0;
(void) sscanf(transfer_syntax+17,".%d.%d",&type,&subtype);
switch (type)
{
case 1:
{
image->endian=LSBEndian;
break;
}
case 2:
{
image->endian=MSBEndian;
break;
}
case 4:
{
if ((subtype >= 80) && (subtype <= 81))
image->compression=JPEGCompression;
else
if ((subtype >= 90) && (subtype <= 93))
image->compression=JPEG2000Compression;
else
image->compression=JPEGCompression;
break;
}
case 5:
{
image->compression=RLECompression;
break;
}
}
}
break;
}
default:
break;
}
break;
}
case 0x0028:
{
switch (element)
{
case 0x0002:
{
/*
Samples per pixel.
*/
samples_per_pixel=(size_t) datum;
break;
}
case 0x0004:
{
/*
Photometric interpretation.
*/
for (i=0; i < (ssize_t) MagickMin(length,MaxTextExtent-1); i++)
photometric[i]=(char) data[i];
photometric[i]='\0';
polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
MagickTrue : MagickFalse;
break;
}
case 0x0006:
{
/*
Planar configuration.
*/
if (datum == 1)
image->interlace=PlaneInterlace;
break;
}
case 0x0008:
{
/*
Number of frames.
*/
number_scenes=StringToUnsignedLong((char *) data);
break;
}
case 0x0010:
{
/*
Image rows.
*/
height=(size_t) datum;
break;
}
case 0x0011:
{
/*
Image columns.
*/
width=(size_t) datum;
break;
}
case 0x0100:
{
/*
Bits allocated.
*/
bits_allocated=(size_t) datum;
bytes_per_pixel=1;
if (datum > 8)
bytes_per_pixel=2;
depth=bits_allocated;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << bits_allocated)-1;
break;
}
case 0x0101:
{
/*
Bits stored.
*/
significant_bits=(size_t) datum;
bytes_per_pixel=1;
if (significant_bits > 8)
bytes_per_pixel=2;
depth=significant_bits;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << significant_bits)-1;
mask=(size_t) GetQuantumRange(significant_bits);
break;
}
case 0x0102:
{
/*
High bit.
*/
break;
}
case 0x0103:
{
/*
Pixel representation.
*/
signed_data=(size_t) datum;
break;
}
case 0x1050:
{
/*
Visible pixel range: center.
*/
if (data != (unsigned char *) NULL)
window_center=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1051:
{
/*
Visible pixel range: width.
*/
if (data != (unsigned char *) NULL)
window_width=StringToUnsignedLong((char *) data);
break;
}
case 0x1200:
case 0x3006:
{
/*
Populate graymap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/bytes_per_pixel);
datum=(int) colors;
graymap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*graymap));
if (graymap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) colors; i++)
if (bytes_per_pixel == 1)
graymap[i]=(int) data[i];
else
graymap[i]=(int) ((short *) data)[i];
break;
}
case 0x1201:
{
unsigned short
index;
/*
Populate redmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
redmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*redmap));
if (redmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
redmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1202:
{
unsigned short
index;
/*
Populate greenmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
greenmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*greenmap));
if (greenmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
greenmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1203:
{
unsigned short
index;
/*
Populate bluemap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
bluemap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*bluemap));
if (bluemap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
bluemap[i]=(int) index;
p+=2;
}
break;
}
default:
break;
}
break;
}
case 0x2050:
{
switch (element)
{
case 0x0020:
{
if ((data != (unsigned char *) NULL) &&
(strncmp((char*) data,"INVERSE", 7) == 0))
polarity=MagickTrue;
break;
}
default:
break;
}
break;
}
default:
break;
}
if (data != (unsigned char *) NULL)
{
char
*attribute;
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
if (dicom_info[i].description != (char *) NULL)
{
attribute=AcquireString("dcm:");
(void) ConcatenateString(&attribute,dicom_info[i].description);
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i == (ssize_t) length) || (length > 4))
{
(void) SubstituteString(&attribute," ","");
(void) SetImageProperty(image,attribute,(char *) data);
}
attribute=DestroyString(attribute);
}
}
if (image_info->verbose != MagickFalse)
{
if (data == (unsigned char *) NULL)
(void) FormatLocaleFile(stdout,"%d\n",datum);
else
{
/*
Display group data.
*/
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i != (ssize_t) length) && (length <= 4))
{
ssize_t
j;
datum=0;
for (j=(ssize_t) length-1; j >= 0; j--)
datum=(256*datum+data[j]);
(void) FormatLocaleFile(stdout,"%d",datum);
}
else
for (i=0; i < (ssize_t) length; i++)
if (isprint((int) data[i]) != MagickFalse)
(void) FormatLocaleFile(stdout,"%c",data[i]);
else
(void) FormatLocaleFile(stdout,"%c",'.');
(void) FormatLocaleFile(stdout,"\n");
}
}
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
if ((width == 0) || (height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) width;
image->rows=(size_t) height;
if (signed_data == 0xffff)
signed_data=(size_t) (significant_bits == 16 ? 1 : 0);
if ((image->compression == JPEGCompression) ||
(image->compression == JPEG2000Compression))
{
Image
*images;
ImageInfo
*read_info;
int
c;
size_t
length;
unsigned int
tag;
/*
Read offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ((int) ReadBlobLSBLong(image));
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
/*
Handle non-native image formats.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
images=NewImageList();
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
char
filename[MaxTextExtent];
const char
*property;
FILE
*file;
Image
*jpeg_image;
int
unique_file;
unsigned int
tag;
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
length=(size_t) ReadBlobLSBLong(image);
if (tag == 0xFFFEE0DD)
break; /* sequence delimiter tag */
if (tag != 0xFFFEE000)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if (file == (FILE *) NULL)
{
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
break;
}
for ( ; length != 0; length--)
{
c=ReadBlobByte(image);
if (c == EOF)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
(void) fputc(c,file);
}
(void) fclose(file);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
filename);
if (image->compression == JPEG2000Compression)
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"j2k:%s",
filename);
jpeg_image=ReadImage(read_info,exception);
if (jpeg_image != (Image *) NULL)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) SetImageProperty(jpeg_image,property,
GetImageProperty(image,property));
property=GetNextImageProperty(image);
}
AppendImageToList(&images,jpeg_image);
}
(void) RelinquishUniqueFileResource(filename);
}
read_info=DestroyImageInfo(read_info);
image=DestroyImage(image);
return(GetFirstImageInList(images));
}
if (depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
{
QuantumAny
range;
size_t
length;
/*
Compute pixel scaling table.
*/
length=(size_t) (GetQuantumRange(depth)+1);
scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*scale));
if (scale == (Quantum *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
range=GetQuantumRange(depth);
for (i=0; i < (ssize_t) (GetQuantumRange(depth)+1); i++)
scale[i]=ScaleAnyToQuantum((size_t) i,range);
}
if (image->compression == RLECompression)
{
size_t
length;
unsigned int
tag;
/*
Read RLE offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ((int) ReadBlobLSBLong(image));
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
}
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
if (image_info->ping != MagickFalse)
break;
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
break;
}
image->colorspace=RGBColorspace;
if ((image->colormap == (PixelPacket *) NULL) && (samples_per_pixel == 1))
{
size_t
one;
one=1;
if (colors == 0)
colors=one << depth;
if (AcquireImageColormap(image,one << depth) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (redmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=redmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(Quantum) index;
}
if (greenmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=greenmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].green=(Quantum) index;
}
if (bluemap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=bluemap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].blue=(Quantum) index;
}
if (graymap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=graymap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(Quantum) index;
image->colormap[i].green=(Quantum) index;
image->colormap[i].blue=(Quantum) index;
}
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE segment table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
stream_info->remaining=(size_t) ReadBlobLSBLong(image);
if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
(EOFBlob(image) != MagickFalse))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
stream_info->count=0;
stream_info->segment_count=ReadBlobLSBLong(image);
if (stream_info->segment_count > 1)
{
bytes_per_pixel=1;
depth=8;
}
for (i=0; i < 15; i++)
stream_info->segments[i]=(ssize_t) ((int) ReadBlobLSBLong(image));
stream_info->remaining-=64;
}
if ((samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
{
/*
Convert Planar RGB DCM Medical image to pixel packets.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch ((int) i)
{
case 0:
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 1:
{
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 2:
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
case 3:
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)));
break;
}
default:
break;
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
}
else
{
const char
*option;
int
byte;
LongPixelPacket
pixel;
/*
Convert DCM Medical image to pixel packets.
*/
byte=0;
i=0;
if ((window_center != 0) && (window_width == 0))
window_width=(size_t) window_center;
option=GetImageOption(image_info,"dcm:display-range");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"reset") == 0)
window_width=0;
}
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ? ((int) max_value-
ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
pixel_value=(int) (polarity != MagickFalse ? (max_value-
ReadDCMShort(stream_info,image)) :
ReadDCMShort(stream_info,image));
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=(int) ReadDCMShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=pixel_value;
if (window_width == 0)
{
if (signed_data == 1)
index=pixel_value-32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t) pixel_value <= window_min)
index=0;
else
if ((ssize_t) pixel_value > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((pixel_value-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index);
SetPixelIndex(indexes+x,index);
pixel.red=1U*image->colormap[index].red;
pixel.green=1U*image->colormap[index].green;
pixel.blue=1U*image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
pixel.red=scale[pixel.red];
pixel.green=scale[pixel.green];
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (stream_info->segment_count > 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ? ((int) max_value-
ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
{
pixel_value=(int) (polarity != MagickFalse ? (max_value-
ReadDCMShort(stream_info,image)) :
ReadDCMShort(stream_info,image));
if (signed_data == 1)
pixel_value=((signed short) pixel_value);
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=(int) ReadDCMShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=pixel_value;
if (window_width == 0)
{
if (signed_data == 1)
index=pixel_value-32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t) pixel_value <= window_min)
index=0;
else
if ((ssize_t) pixel_value > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((pixel_value-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index);
SetPixelIndex(indexes+x,(((size_t) GetPixelIndex(indexes+x)) |
(((size_t) index) << 8)));
pixel.red=1U*image->colormap[index].red;
pixel.green=1U*image->colormap[index].green;
pixel.blue=1U*image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
pixel.red=scale[pixel.red];
pixel.green=scale[pixel.green];
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(q,(((size_t) GetPixelRed(q)) |
(((size_t) pixel.red) << 8)));
SetPixelGreen(q,(((size_t) GetPixelGreen(q)) |
(((size_t) pixel.green) << 8)));
SetPixelBlue(q,(((size_t) GetPixelBlue(q)) |
(((size_t) pixel.blue) << 8)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (IsGrayImage(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (number_scenes-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
/*
Free resources.
*/
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (scale != (Quantum *) NULL)
scale=(Quantum *) RelinquishMagickMemory(scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,555 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void array_cleanup( char* arr[] , int arr_size)
{
int i=0;
for( i=0; i< arr_size; i++ ){
if( arr[i*2] ){
efree( arr[i*2]);
}
}
efree(arr);
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | static void array_cleanup( char* arr[] , int arr_size)
{
int i=0;
for( i=0; i< arr_size; i++ ){
if( arr[i*2] ){
efree( arr[i*2]);
}
}
efree(arr);
}
| 167,200 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int DefragMfIpv6Test(void)
{
int retval = 0;
int ip_id = 9;
Packet *p = NULL;
DefragInit();
Packet *p1 = IPV6BuildTestPacket(ip_id, 2, 1, 'C', 8);
Packet *p2 = IPV6BuildTestPacket(ip_id, 0, 1, 'A', 8);
Packet *p3 = IPV6BuildTestPacket(ip_id, 1, 0, 'B', 8);
if (p1 == NULL || p2 == NULL || p3 == NULL) {
goto end;
}
p = Defrag(NULL, NULL, p1, NULL);
if (p != NULL) {
goto end;
}
p = Defrag(NULL, NULL, p2, NULL);
if (p != NULL) {
goto end;
}
/* This should return a packet as MF=0. */
p = Defrag(NULL, NULL, p3, NULL);
if (p == NULL) {
goto end;
}
/* For IPv6 the expected length is just the length of the payload
* of 2 fragments, so 16. */
if (IPV6_GET_PLEN(p) != 16) {
goto end;
}
retval = 1;
end:
if (p1 != NULL) {
SCFree(p1);
}
if (p2 != NULL) {
SCFree(p2);
}
if (p3 != NULL) {
SCFree(p3);
}
if (p != NULL) {
SCFree(p);
}
DefragDestroy();
return retval;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | static int DefragMfIpv6Test(void)
{
int retval = 0;
int ip_id = 9;
Packet *p = NULL;
DefragInit();
Packet *p1 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 2, 1, 'C', 8);
Packet *p2 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 0, 1, 'A', 8);
Packet *p3 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 1, 0, 'B', 8);
if (p1 == NULL || p2 == NULL || p3 == NULL) {
goto end;
}
p = Defrag(NULL, NULL, p1, NULL);
if (p != NULL) {
goto end;
}
p = Defrag(NULL, NULL, p2, NULL);
if (p != NULL) {
goto end;
}
/* This should return a packet as MF=0. */
p = Defrag(NULL, NULL, p3, NULL);
if (p == NULL) {
goto end;
}
/* For IPv6 the expected length is just the length of the payload
* of 2 fragments, so 16. */
if (IPV6_GET_PLEN(p) != 16) {
goto end;
}
retval = 1;
end:
if (p1 != NULL) {
SCFree(p1);
}
if (p2 != NULL) {
SCFree(p2);
}
if (p3 != NULL) {
SCFree(p3);
}
if (p != NULL) {
SCFree(p);
}
DefragDestroy();
return retval;
}
| 168,300 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.