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: ExtensionsGuestViewMessageFilter::ExtensionsGuestViewMessageFilter(
int render_process_id,
BrowserContext* context)
: GuestViewMessageFilter(kFilteredMessageClasses,
base::size(kFilteredMessageClasses),
render_process_id,
context),
content::BrowserAssociatedInterface<mojom::GuestView>(this, this) {
GetProcessIdToFilterMap()->insert_or_assign(render_process_id_, this);
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362 | ExtensionsGuestViewMessageFilter::ExtensionsGuestViewMessageFilter(
int render_process_id,
BrowserContext* context)
: GuestViewMessageFilter(kFilteredMessageClasses,
base::size(kFilteredMessageClasses),
render_process_id,
context),
content::BrowserAssociatedInterface<mojom::GuestView>(this, this) {
}
| 173,039 |
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 SoftVPXEncoder::initEncoder() {
vpx_codec_err_t codec_return;
mCodecContext = new vpx_codec_ctx_t;
mCodecConfiguration = new vpx_codec_enc_cfg_t;
mCodecInterface = vpx_codec_vp8_cx();
if (mCodecInterface == NULL) {
return UNKNOWN_ERROR;
}
ALOGD("VP8: initEncoder. BRMode: %u. TSLayers: %zu. KF: %u. QP: %u - %u",
(uint32_t)mBitrateControlMode, mTemporalLayers, mKeyFrameInterval,
mMinQuantizer, mMaxQuantizer);
codec_return = vpx_codec_enc_config_default(mCodecInterface,
mCodecConfiguration,
0); // Codec specific flags
if (codec_return != VPX_CODEC_OK) {
ALOGE("Error populating default configuration for vpx encoder.");
return UNKNOWN_ERROR;
}
mCodecConfiguration->g_w = mWidth;
mCodecConfiguration->g_h = mHeight;
mCodecConfiguration->g_threads = GetCPUCoreCount();
mCodecConfiguration->g_error_resilient = mErrorResilience;
switch (mLevel) {
case OMX_VIDEO_VP8Level_Version0:
mCodecConfiguration->g_profile = 0;
break;
case OMX_VIDEO_VP8Level_Version1:
mCodecConfiguration->g_profile = 1;
break;
case OMX_VIDEO_VP8Level_Version2:
mCodecConfiguration->g_profile = 2;
break;
case OMX_VIDEO_VP8Level_Version3:
mCodecConfiguration->g_profile = 3;
break;
default:
mCodecConfiguration->g_profile = 0;
}
mCodecConfiguration->g_timebase.num = 1;
mCodecConfiguration->g_timebase.den = 1000000;
mCodecConfiguration->rc_target_bitrate = (mBitrate + 500) / 1000;
mCodecConfiguration->rc_end_usage = mBitrateControlMode;
mCodecConfiguration->rc_dropframe_thresh = 0;
if (mBitrateControlMode == VPX_CBR) {
mCodecConfiguration->rc_resize_allowed = 0;
mCodecConfiguration->g_pass = VPX_RC_ONE_PASS;
mCodecConfiguration->rc_undershoot_pct = 100;
mCodecConfiguration->rc_overshoot_pct = 15;
mCodecConfiguration->rc_buf_initial_sz = 500;
mCodecConfiguration->rc_buf_optimal_sz = 600;
mCodecConfiguration->rc_buf_sz = 1000;
mCodecConfiguration->g_error_resilient = 1;
mCodecConfiguration->g_lag_in_frames = 0;
mCodecConfiguration->kf_max_dist = 3000;
mCodecConfiguration->kf_mode = VPX_KF_AUTO;
}
switch (mTemporalLayers) {
case 0:
{
mTemporalPatternLength = 0;
break;
}
case 1:
{
mCodecConfiguration->ts_number_layers = 1;
mCodecConfiguration->ts_rate_decimator[0] = 1;
mCodecConfiguration->ts_periodicity = 1;
mCodecConfiguration->ts_layer_id[0] = 0;
mTemporalPattern[0] = kTemporalUpdateLastRefAll;
mTemporalPatternLength = 1;
break;
}
case 2:
{
mCodecConfiguration->ts_number_layers = 2;
mCodecConfiguration->ts_rate_decimator[0] = 2;
mCodecConfiguration->ts_rate_decimator[1] = 1;
mCodecConfiguration->ts_periodicity = 2;
mCodecConfiguration->ts_layer_id[0] = 0;
mCodecConfiguration->ts_layer_id[1] = 1;
mTemporalPattern[0] = kTemporalUpdateLastAndGoldenRefAltRef;
mTemporalPattern[1] = kTemporalUpdateGoldenWithoutDependencyRefAltRef;
mTemporalPattern[2] = kTemporalUpdateLastRefAltRef;
mTemporalPattern[3] = kTemporalUpdateGoldenRefAltRef;
mTemporalPattern[4] = kTemporalUpdateLastRefAltRef;
mTemporalPattern[5] = kTemporalUpdateGoldenRefAltRef;
mTemporalPattern[6] = kTemporalUpdateLastRefAltRef;
mTemporalPattern[7] = kTemporalUpdateNone;
mTemporalPatternLength = 8;
break;
}
case 3:
{
mCodecConfiguration->ts_number_layers = 3;
mCodecConfiguration->ts_rate_decimator[0] = 4;
mCodecConfiguration->ts_rate_decimator[1] = 2;
mCodecConfiguration->ts_rate_decimator[2] = 1;
mCodecConfiguration->ts_periodicity = 4;
mCodecConfiguration->ts_layer_id[0] = 0;
mCodecConfiguration->ts_layer_id[1] = 2;
mCodecConfiguration->ts_layer_id[2] = 1;
mCodecConfiguration->ts_layer_id[3] = 2;
mTemporalPattern[0] = kTemporalUpdateLastAndGoldenRefAltRef;
mTemporalPattern[1] = kTemporalUpdateNoneNoRefGoldenRefAltRef;
mTemporalPattern[2] = kTemporalUpdateGoldenWithoutDependencyRefAltRef;
mTemporalPattern[3] = kTemporalUpdateNone;
mTemporalPattern[4] = kTemporalUpdateLastRefAltRef;
mTemporalPattern[5] = kTemporalUpdateNone;
mTemporalPattern[6] = kTemporalUpdateGoldenRefAltRef;
mTemporalPattern[7] = kTemporalUpdateNone;
mTemporalPatternLength = 8;
break;
}
default:
{
ALOGE("Wrong number of temporal layers %zu", mTemporalLayers);
return UNKNOWN_ERROR;
}
}
for (size_t i = 0; i < mCodecConfiguration->ts_number_layers; i++) {
mCodecConfiguration->ts_target_bitrate[i] =
mCodecConfiguration->rc_target_bitrate *
mTemporalLayerBitrateRatio[i] / 100;
}
if (mKeyFrameInterval > 0) {
mCodecConfiguration->kf_max_dist = mKeyFrameInterval;
mCodecConfiguration->kf_min_dist = mKeyFrameInterval;
mCodecConfiguration->kf_mode = VPX_KF_AUTO;
}
if (mMinQuantizer > 0) {
mCodecConfiguration->rc_min_quantizer = mMinQuantizer;
}
if (mMaxQuantizer > 0) {
mCodecConfiguration->rc_max_quantizer = mMaxQuantizer;
}
codec_return = vpx_codec_enc_init(mCodecContext,
mCodecInterface,
mCodecConfiguration,
0); // flags
if (codec_return != VPX_CODEC_OK) {
ALOGE("Error initializing vpx encoder");
return UNKNOWN_ERROR;
}
codec_return = vpx_codec_control(mCodecContext,
VP8E_SET_TOKEN_PARTITIONS,
mDCTPartitions);
if (codec_return != VPX_CODEC_OK) {
ALOGE("Error setting dct partitions for vpx encoder.");
return UNKNOWN_ERROR;
}
if (mBitrateControlMode == VPX_CBR) {
codec_return = vpx_codec_control(mCodecContext,
VP8E_SET_STATIC_THRESHOLD,
1);
if (codec_return == VPX_CODEC_OK) {
uint32_t rc_max_intra_target =
mCodecConfiguration->rc_buf_optimal_sz * (mFramerate >> 17) / 10;
if (rc_max_intra_target < 300) {
rc_max_intra_target = 300;
}
codec_return = vpx_codec_control(mCodecContext,
VP8E_SET_MAX_INTRA_BITRATE_PCT,
rc_max_intra_target);
}
if (codec_return == VPX_CODEC_OK) {
codec_return = vpx_codec_control(mCodecContext,
VP8E_SET_CPUUSED,
-8);
}
if (codec_return != VPX_CODEC_OK) {
ALOGE("Error setting cbr parameters for vpx encoder.");
return UNKNOWN_ERROR;
}
}
if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) {
free(mConversionBuffer);
mConversionBuffer = (uint8_t *)malloc(mWidth * mHeight * 3 / 2);
if (mConversionBuffer == NULL) {
ALOGE("Allocating conversion buffer failed.");
return UNKNOWN_ERROR;
}
}
return OK;
}
Commit Message: DO NOT MERGE - libstagefright: check requested memory size before allocation for SoftMPEG4Encoder and SoftVPXEncoder.
Bug: 25812794
Change-Id: I96dc74734380d462583f6efa33d09946f9532809
(cherry picked from commit 87f8cbb223ee516803dbb99699320c2484cbf3ba)
(cherry picked from commit 0462975291796e414891e04bcec9da993914e458)
CWE ID: CWE-119 | status_t SoftVPXEncoder::initEncoder() {
vpx_codec_err_t codec_return;
mCodecContext = new vpx_codec_ctx_t;
mCodecConfiguration = new vpx_codec_enc_cfg_t;
mCodecInterface = vpx_codec_vp8_cx();
if (mCodecInterface == NULL) {
return UNKNOWN_ERROR;
}
ALOGD("VP8: initEncoder. BRMode: %u. TSLayers: %zu. KF: %u. QP: %u - %u",
(uint32_t)mBitrateControlMode, mTemporalLayers, mKeyFrameInterval,
mMinQuantizer, mMaxQuantizer);
codec_return = vpx_codec_enc_config_default(mCodecInterface,
mCodecConfiguration,
0); // Codec specific flags
if (codec_return != VPX_CODEC_OK) {
ALOGE("Error populating default configuration for vpx encoder.");
return UNKNOWN_ERROR;
}
mCodecConfiguration->g_w = mWidth;
mCodecConfiguration->g_h = mHeight;
mCodecConfiguration->g_threads = GetCPUCoreCount();
mCodecConfiguration->g_error_resilient = mErrorResilience;
switch (mLevel) {
case OMX_VIDEO_VP8Level_Version0:
mCodecConfiguration->g_profile = 0;
break;
case OMX_VIDEO_VP8Level_Version1:
mCodecConfiguration->g_profile = 1;
break;
case OMX_VIDEO_VP8Level_Version2:
mCodecConfiguration->g_profile = 2;
break;
case OMX_VIDEO_VP8Level_Version3:
mCodecConfiguration->g_profile = 3;
break;
default:
mCodecConfiguration->g_profile = 0;
}
mCodecConfiguration->g_timebase.num = 1;
mCodecConfiguration->g_timebase.den = 1000000;
mCodecConfiguration->rc_target_bitrate = (mBitrate + 500) / 1000;
mCodecConfiguration->rc_end_usage = mBitrateControlMode;
mCodecConfiguration->rc_dropframe_thresh = 0;
if (mBitrateControlMode == VPX_CBR) {
mCodecConfiguration->rc_resize_allowed = 0;
mCodecConfiguration->g_pass = VPX_RC_ONE_PASS;
mCodecConfiguration->rc_undershoot_pct = 100;
mCodecConfiguration->rc_overshoot_pct = 15;
mCodecConfiguration->rc_buf_initial_sz = 500;
mCodecConfiguration->rc_buf_optimal_sz = 600;
mCodecConfiguration->rc_buf_sz = 1000;
mCodecConfiguration->g_error_resilient = 1;
mCodecConfiguration->g_lag_in_frames = 0;
mCodecConfiguration->kf_max_dist = 3000;
mCodecConfiguration->kf_mode = VPX_KF_AUTO;
}
switch (mTemporalLayers) {
case 0:
{
mTemporalPatternLength = 0;
break;
}
case 1:
{
mCodecConfiguration->ts_number_layers = 1;
mCodecConfiguration->ts_rate_decimator[0] = 1;
mCodecConfiguration->ts_periodicity = 1;
mCodecConfiguration->ts_layer_id[0] = 0;
mTemporalPattern[0] = kTemporalUpdateLastRefAll;
mTemporalPatternLength = 1;
break;
}
case 2:
{
mCodecConfiguration->ts_number_layers = 2;
mCodecConfiguration->ts_rate_decimator[0] = 2;
mCodecConfiguration->ts_rate_decimator[1] = 1;
mCodecConfiguration->ts_periodicity = 2;
mCodecConfiguration->ts_layer_id[0] = 0;
mCodecConfiguration->ts_layer_id[1] = 1;
mTemporalPattern[0] = kTemporalUpdateLastAndGoldenRefAltRef;
mTemporalPattern[1] = kTemporalUpdateGoldenWithoutDependencyRefAltRef;
mTemporalPattern[2] = kTemporalUpdateLastRefAltRef;
mTemporalPattern[3] = kTemporalUpdateGoldenRefAltRef;
mTemporalPattern[4] = kTemporalUpdateLastRefAltRef;
mTemporalPattern[5] = kTemporalUpdateGoldenRefAltRef;
mTemporalPattern[6] = kTemporalUpdateLastRefAltRef;
mTemporalPattern[7] = kTemporalUpdateNone;
mTemporalPatternLength = 8;
break;
}
case 3:
{
mCodecConfiguration->ts_number_layers = 3;
mCodecConfiguration->ts_rate_decimator[0] = 4;
mCodecConfiguration->ts_rate_decimator[1] = 2;
mCodecConfiguration->ts_rate_decimator[2] = 1;
mCodecConfiguration->ts_periodicity = 4;
mCodecConfiguration->ts_layer_id[0] = 0;
mCodecConfiguration->ts_layer_id[1] = 2;
mCodecConfiguration->ts_layer_id[2] = 1;
mCodecConfiguration->ts_layer_id[3] = 2;
mTemporalPattern[0] = kTemporalUpdateLastAndGoldenRefAltRef;
mTemporalPattern[1] = kTemporalUpdateNoneNoRefGoldenRefAltRef;
mTemporalPattern[2] = kTemporalUpdateGoldenWithoutDependencyRefAltRef;
mTemporalPattern[3] = kTemporalUpdateNone;
mTemporalPattern[4] = kTemporalUpdateLastRefAltRef;
mTemporalPattern[5] = kTemporalUpdateNone;
mTemporalPattern[6] = kTemporalUpdateGoldenRefAltRef;
mTemporalPattern[7] = kTemporalUpdateNone;
mTemporalPatternLength = 8;
break;
}
default:
{
ALOGE("Wrong number of temporal layers %zu", mTemporalLayers);
return UNKNOWN_ERROR;
}
}
for (size_t i = 0; i < mCodecConfiguration->ts_number_layers; i++) {
mCodecConfiguration->ts_target_bitrate[i] =
mCodecConfiguration->rc_target_bitrate *
mTemporalLayerBitrateRatio[i] / 100;
}
if (mKeyFrameInterval > 0) {
mCodecConfiguration->kf_max_dist = mKeyFrameInterval;
mCodecConfiguration->kf_min_dist = mKeyFrameInterval;
mCodecConfiguration->kf_mode = VPX_KF_AUTO;
}
if (mMinQuantizer > 0) {
mCodecConfiguration->rc_min_quantizer = mMinQuantizer;
}
if (mMaxQuantizer > 0) {
mCodecConfiguration->rc_max_quantizer = mMaxQuantizer;
}
codec_return = vpx_codec_enc_init(mCodecContext,
mCodecInterface,
mCodecConfiguration,
0); // flags
if (codec_return != VPX_CODEC_OK) {
ALOGE("Error initializing vpx encoder");
return UNKNOWN_ERROR;
}
codec_return = vpx_codec_control(mCodecContext,
VP8E_SET_TOKEN_PARTITIONS,
mDCTPartitions);
if (codec_return != VPX_CODEC_OK) {
ALOGE("Error setting dct partitions for vpx encoder.");
return UNKNOWN_ERROR;
}
if (mBitrateControlMode == VPX_CBR) {
codec_return = vpx_codec_control(mCodecContext,
VP8E_SET_STATIC_THRESHOLD,
1);
if (codec_return == VPX_CODEC_OK) {
uint32_t rc_max_intra_target =
mCodecConfiguration->rc_buf_optimal_sz * (mFramerate >> 17) / 10;
if (rc_max_intra_target < 300) {
rc_max_intra_target = 300;
}
codec_return = vpx_codec_control(mCodecContext,
VP8E_SET_MAX_INTRA_BITRATE_PCT,
rc_max_intra_target);
}
if (codec_return == VPX_CODEC_OK) {
codec_return = vpx_codec_control(mCodecContext,
VP8E_SET_CPUUSED,
-8);
}
if (codec_return != VPX_CODEC_OK) {
ALOGE("Error setting cbr parameters for vpx encoder.");
return UNKNOWN_ERROR;
}
}
if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) {
free(mConversionBuffer);
mConversionBuffer = NULL;
if (((uint64_t)mWidth * mHeight) > ((uint64_t)INT32_MAX / 3)) {
ALOGE("b/25812794, Buffer size is too big.");
return UNKNOWN_ERROR;
}
mConversionBuffer = (uint8_t *)malloc(mWidth * mHeight * 3 / 2);
if (mConversionBuffer == NULL) {
ALOGE("Allocating conversion buffer failed.");
return UNKNOWN_ERROR;
}
}
return OK;
}
| 173,971 |
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: psf_close (SF_PRIVATE *psf)
{ uint32_t k ;
int error = 0 ;
if (psf->codec_close)
{ error = psf->codec_close (psf) ;
/* To prevent it being called in psf->container_close(). */
psf->codec_close = NULL ;
} ;
if (psf->container_close)
error = psf->container_close (psf) ;
error = psf_fclose (psf) ;
psf_close_rsrc (psf) ;
/* For an ISO C compliant implementation it is ok to free a NULL pointer. */
free (psf->container_data) ;
free (psf->codec_data) ;
free (psf->interleave) ;
free (psf->dither) ;
free (psf->peak_info) ;
free (psf->broadcast_16k) ;
free (psf->loop_info) ;
free (psf->instrument) ;
free (psf->cues) ;
free (psf->channel_map) ;
free (psf->format_desc) ;
free (psf->strings.storage) ;
if (psf->wchunks.chunks)
for (k = 0 ; k < psf->wchunks.used ; k++)
free (psf->wchunks.chunks [k].data) ;
free (psf->rchunks.chunks) ;
free (psf->wchunks.chunks) ;
free (psf->iterator) ;
free (psf->cart_16k) ;
memset (psf, 0, sizeof (SF_PRIVATE)) ;
free (psf) ;
return error ;
} /* psf_close */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | psf_close (SF_PRIVATE *psf)
{ uint32_t k ;
int error = 0 ;
if (psf->codec_close)
{ error = psf->codec_close (psf) ;
/* To prevent it being called in psf->container_close(). */
psf->codec_close = NULL ;
} ;
if (psf->container_close)
error = psf->container_close (psf) ;
error = psf_fclose (psf) ;
psf_close_rsrc (psf) ;
/* For an ISO C compliant implementation it is ok to free a NULL pointer. */
free (psf->header.ptr) ;
free (psf->container_data) ;
free (psf->codec_data) ;
free (psf->interleave) ;
free (psf->dither) ;
free (psf->peak_info) ;
free (psf->broadcast_16k) ;
free (psf->loop_info) ;
free (psf->instrument) ;
free (psf->cues) ;
free (psf->channel_map) ;
free (psf->format_desc) ;
free (psf->strings.storage) ;
if (psf->wchunks.chunks)
for (k = 0 ; k < psf->wchunks.used ; k++)
free (psf->wchunks.chunks [k].data) ;
free (psf->rchunks.chunks) ;
free (psf->wchunks.chunks) ;
free (psf->iterator) ;
free (psf->cart_16k) ;
memset (psf, 0, sizeof (SF_PRIVATE)) ;
free (psf) ;
return error ;
} /* psf_close */
| 170,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: nfs4_callback_svc(void *vrqstp)
{
int err;
struct svc_rqst *rqstp = vrqstp;
set_freezable();
while (!kthread_should_stop()) {
/*
* Listen for a request on the socket
*/
err = svc_recv(rqstp, MAX_SCHEDULE_TIMEOUT);
if (err == -EAGAIN || err == -EINTR)
continue;
svc_process(rqstp);
}
return 0;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | nfs4_callback_svc(void *vrqstp)
{
int err;
struct svc_rqst *rqstp = vrqstp;
set_freezable();
while (!kthread_freezable_should_stop(NULL)) {
if (signal_pending(current))
flush_signals(current);
/*
* Listen for a request on the socket
*/
err = svc_recv(rqstp, MAX_SCHEDULE_TIMEOUT);
if (err == -EAGAIN || err == -EINTR)
continue;
svc_process(rqstp);
}
svc_exit_thread(rqstp);
module_put_and_exit(0);
return 0;
}
| 168,138 |
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(Phar, getSupportedSignatures)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_next_index_stringl(return_value, "MD5", 3, 1);
add_next_index_stringl(return_value, "SHA-1", 5, 1);
#ifdef PHAR_HASH_OK
add_next_index_stringl(return_value, "SHA-256", 7, 1);
add_next_index_stringl(return_value, "SHA-512", 7, 1);
#endif
#if PHAR_HAVE_OPENSSL
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
#else
if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) {
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
}
#endif
}
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, getSupportedSignatures)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_next_index_stringl(return_value, "MD5", 3, 1);
add_next_index_stringl(return_value, "SHA-1", 5, 1);
#ifdef PHAR_HASH_OK
add_next_index_stringl(return_value, "SHA-256", 7, 1);
add_next_index_stringl(return_value, "SHA-512", 7, 1);
#endif
#if PHAR_HAVE_OPENSSL
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
#else
if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) {
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
}
#endif
}
| 165,292 |
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 FragmentPaintPropertyTreeBuilder::UpdateFragmentClip() {
DCHECK(properties_);
if (NeedsPaintPropertyUpdate()) {
if (context_.fragment_clip) {
OnUpdateClip(properties_->UpdateFragmentClip(
context_.current.clip,
ClipPaintPropertyNode::State{context_.current.transform,
ToClipRect(*context_.fragment_clip)}));
} else {
OnClearClip(properties_->ClearFragmentClip());
}
}
if (properties_->FragmentClip())
context_.current.clip = properties_->FragmentClip();
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | void FragmentPaintPropertyTreeBuilder::UpdateFragmentClip() {
DCHECK(properties_);
if (NeedsPaintPropertyUpdate()) {
if (context_.fragment_clip) {
OnUpdateClip(properties_->UpdateFragmentClip(
*context_.current.clip,
ClipPaintPropertyNode::State{context_.current.transform,
ToClipRect(*context_.fragment_clip)}));
} else {
OnClearClip(properties_->ClearFragmentClip());
}
}
if (properties_->FragmentClip())
context_.current.clip = properties_->FragmentClip();
}
| 171,797 |
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 ip6_frag_queue(struct frag_queue *fq, struct sk_buff *skb,
struct frag_hdr *fhdr, int nhoff)
{
struct sk_buff *prev, *next;
struct net_device *dev;
int offset, end;
struct net *net = dev_net(skb_dst(skb)->dev);
if (fq->q.last_in & INET_FRAG_COMPLETE)
goto err;
offset = ntohs(fhdr->frag_off) & ~0x7;
end = offset + (ntohs(ipv6_hdr(skb)->payload_len) -
((u8 *)(fhdr + 1) - (u8 *)(ipv6_hdr(skb) + 1)));
if ((unsigned int)end > IPV6_MAXPLEN) {
IP6_INC_STATS_BH(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_INHDRERRORS);
icmpv6_param_prob(skb, ICMPV6_HDR_FIELD,
((u8 *)&fhdr->frag_off -
skb_network_header(skb)));
return -1;
}
if (skb->ip_summed == CHECKSUM_COMPLETE) {
const unsigned char *nh = skb_network_header(skb);
skb->csum = csum_sub(skb->csum,
csum_partial(nh, (u8 *)(fhdr + 1) - nh,
0));
}
/* Is this the final fragment? */
if (!(fhdr->frag_off & htons(IP6_MF))) {
/* If we already have some bits beyond end
* or have different end, the segment is corrupted.
*/
if (end < fq->q.len ||
((fq->q.last_in & INET_FRAG_LAST_IN) && end != fq->q.len))
goto err;
fq->q.last_in |= INET_FRAG_LAST_IN;
fq->q.len = end;
} else {
/* Check if the fragment is rounded to 8 bytes.
* Required by the RFC.
*/
if (end & 0x7) {
/* RFC2460 says always send parameter problem in
* this case. -DaveM
*/
IP6_INC_STATS_BH(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_INHDRERRORS);
icmpv6_param_prob(skb, ICMPV6_HDR_FIELD,
offsetof(struct ipv6hdr, payload_len));
return -1;
}
if (end > fq->q.len) {
/* Some bits beyond end -> corruption. */
if (fq->q.last_in & INET_FRAG_LAST_IN)
goto err;
fq->q.len = end;
}
}
if (end == offset)
goto err;
/* Point into the IP datagram 'data' part. */
if (!pskb_pull(skb, (u8 *) (fhdr + 1) - skb->data))
goto err;
if (pskb_trim_rcsum(skb, end - offset))
goto err;
/* Find out which fragments are in front and at the back of us
* in the chain of fragments so far. We must know where to put
* this fragment, right?
*/
prev = fq->q.fragments_tail;
if (!prev || FRAG6_CB(prev)->offset < offset) {
next = NULL;
goto found;
}
prev = NULL;
for(next = fq->q.fragments; next != NULL; next = next->next) {
if (FRAG6_CB(next)->offset >= offset)
break; /* bingo! */
prev = next;
}
found:
/* We found where to put this one. Check for overlap with
* preceding fragment, and, if needed, align things so that
* any overlaps are eliminated.
*/
if (prev) {
int i = (FRAG6_CB(prev)->offset + prev->len) - offset;
if (i > 0) {
offset += i;
if (end <= offset)
goto err;
if (!pskb_pull(skb, i))
goto err;
if (skb->ip_summed != CHECKSUM_UNNECESSARY)
skb->ip_summed = CHECKSUM_NONE;
}
}
/* Look for overlap with succeeding segments.
* If we can merge fragments, do it.
*/
while (next && FRAG6_CB(next)->offset < end) {
int i = end - FRAG6_CB(next)->offset; /* overlap is 'i' bytes */
if (i < next->len) {
/* Eat head of the next overlapped fragment
* and leave the loop. The next ones cannot overlap.
*/
if (!pskb_pull(next, i))
goto err;
FRAG6_CB(next)->offset += i; /* next fragment */
fq->q.meat -= i;
if (next->ip_summed != CHECKSUM_UNNECESSARY)
next->ip_summed = CHECKSUM_NONE;
break;
} else {
struct sk_buff *free_it = next;
/* Old fragment is completely overridden with
* new one drop it.
*/
next = next->next;
if (prev)
prev->next = next;
else
fq->q.fragments = next;
fq->q.meat -= free_it->len;
frag_kfree_skb(fq->q.net, free_it);
}
}
FRAG6_CB(skb)->offset = offset;
/* Insert this fragment in the chain of fragments. */
skb->next = next;
if (!next)
fq->q.fragments_tail = skb;
if (prev)
prev->next = skb;
else
fq->q.fragments = skb;
dev = skb->dev;
if (dev) {
fq->iif = dev->ifindex;
skb->dev = NULL;
}
fq->q.stamp = skb->tstamp;
fq->q.meat += skb->len;
atomic_add(skb->truesize, &fq->q.net->mem);
/* The first fragment.
* nhoffset is obtained from the first fragment, of course.
*/
if (offset == 0) {
fq->nhoffset = nhoff;
fq->q.last_in |= INET_FRAG_FIRST_IN;
}
if (fq->q.last_in == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) &&
fq->q.meat == fq->q.len)
return ip6_frag_reasm(fq, prev, dev);
write_lock(&ip6_frags.lock);
list_move_tail(&fq->q.lru_list, &fq->q.net->lru_list);
write_unlock(&ip6_frags.lock);
return -1;
err:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_REASMFAILS);
kfree_skb(skb);
return -1;
}
Commit Message: ipv6: discard overlapping fragment
RFC5722 prohibits reassembling fragments when some data overlaps.
Bug spotted by Zhang Zuotao <[email protected]>.
Signed-off-by: Nicolas Dichtel <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static int ip6_frag_queue(struct frag_queue *fq, struct sk_buff *skb,
struct frag_hdr *fhdr, int nhoff)
{
struct sk_buff *prev, *next;
struct net_device *dev;
int offset, end;
struct net *net = dev_net(skb_dst(skb)->dev);
if (fq->q.last_in & INET_FRAG_COMPLETE)
goto err;
offset = ntohs(fhdr->frag_off) & ~0x7;
end = offset + (ntohs(ipv6_hdr(skb)->payload_len) -
((u8 *)(fhdr + 1) - (u8 *)(ipv6_hdr(skb) + 1)));
if ((unsigned int)end > IPV6_MAXPLEN) {
IP6_INC_STATS_BH(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_INHDRERRORS);
icmpv6_param_prob(skb, ICMPV6_HDR_FIELD,
((u8 *)&fhdr->frag_off -
skb_network_header(skb)));
return -1;
}
if (skb->ip_summed == CHECKSUM_COMPLETE) {
const unsigned char *nh = skb_network_header(skb);
skb->csum = csum_sub(skb->csum,
csum_partial(nh, (u8 *)(fhdr + 1) - nh,
0));
}
/* Is this the final fragment? */
if (!(fhdr->frag_off & htons(IP6_MF))) {
/* If we already have some bits beyond end
* or have different end, the segment is corrupted.
*/
if (end < fq->q.len ||
((fq->q.last_in & INET_FRAG_LAST_IN) && end != fq->q.len))
goto err;
fq->q.last_in |= INET_FRAG_LAST_IN;
fq->q.len = end;
} else {
/* Check if the fragment is rounded to 8 bytes.
* Required by the RFC.
*/
if (end & 0x7) {
/* RFC2460 says always send parameter problem in
* this case. -DaveM
*/
IP6_INC_STATS_BH(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_INHDRERRORS);
icmpv6_param_prob(skb, ICMPV6_HDR_FIELD,
offsetof(struct ipv6hdr, payload_len));
return -1;
}
if (end > fq->q.len) {
/* Some bits beyond end -> corruption. */
if (fq->q.last_in & INET_FRAG_LAST_IN)
goto err;
fq->q.len = end;
}
}
if (end == offset)
goto err;
/* Point into the IP datagram 'data' part. */
if (!pskb_pull(skb, (u8 *) (fhdr + 1) - skb->data))
goto err;
if (pskb_trim_rcsum(skb, end - offset))
goto err;
/* Find out which fragments are in front and at the back of us
* in the chain of fragments so far. We must know where to put
* this fragment, right?
*/
prev = fq->q.fragments_tail;
if (!prev || FRAG6_CB(prev)->offset < offset) {
next = NULL;
goto found;
}
prev = NULL;
for(next = fq->q.fragments; next != NULL; next = next->next) {
if (FRAG6_CB(next)->offset >= offset)
break; /* bingo! */
prev = next;
}
found:
/* RFC5722, Section 4:
* When reassembling an IPv6 datagram, if
* one or more its constituent fragments is determined to be an
* overlapping fragment, the entire datagram (and any constituent
* fragments, including those not yet received) MUST be silently
* discarded.
*/
/* Check for overlap with preceding fragment. */
if (prev &&
(FRAG6_CB(prev)->offset + prev->len) - offset > 0)
goto discard_fq;
/* Look for overlap with succeeding segment. */
if (next && FRAG6_CB(next)->offset < end)
goto discard_fq;
FRAG6_CB(skb)->offset = offset;
/* Insert this fragment in the chain of fragments. */
skb->next = next;
if (!next)
fq->q.fragments_tail = skb;
if (prev)
prev->next = skb;
else
fq->q.fragments = skb;
dev = skb->dev;
if (dev) {
fq->iif = dev->ifindex;
skb->dev = NULL;
}
fq->q.stamp = skb->tstamp;
fq->q.meat += skb->len;
atomic_add(skb->truesize, &fq->q.net->mem);
/* The first fragment.
* nhoffset is obtained from the first fragment, of course.
*/
if (offset == 0) {
fq->nhoffset = nhoff;
fq->q.last_in |= INET_FRAG_FIRST_IN;
}
if (fq->q.last_in == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) &&
fq->q.meat == fq->q.len)
return ip6_frag_reasm(fq, prev, dev);
write_lock(&ip6_frags.lock);
list_move_tail(&fq->q.lru_list, &fq->q.net->lru_list);
write_unlock(&ip6_frags.lock);
return -1;
discard_fq:
fq_kill(fq);
err:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_REASMFAILS);
kfree_skb(skb);
return -1;
}
| 165,539 |
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 perf_swevent_add(struct perf_event *event, int flags)
{
struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
struct hw_perf_event *hwc = &event->hw;
struct hlist_head *head;
if (is_sampling_event(event)) {
hwc->last_period = hwc->sample_period;
perf_swevent_set_period(event);
}
hwc->state = !(flags & PERF_EF_START);
head = find_swevent_head(swhash, event);
if (!head) {
/*
* We can race with cpu hotplug code. Do not
* WARN if the cpu just got unplugged.
*/
WARN_ON_ONCE(swhash->online);
return -EINVAL;
}
hlist_add_head_rcu(&event->hlist_entry, head);
perf_event_update_userpage(event);
return 0;
}
Commit Message: perf: Fix race in swevent hash
There's a race on CPU unplug where we free the swevent hash array
while it can still have events on. This will result in a
use-after-free which is BAD.
Simply do not free the hash array on unplug. This leaves the thing
around and no use-after-free takes place.
When the last swevent dies, we do a for_each_possible_cpu() iteration
anyway to clean these up, at which time we'll free it, so no leakage
will occur.
Reported-by: Sasha Levin <[email protected]>
Tested-by: Sasha Levin <[email protected]>
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Stephane Eranian <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Vince Weaver <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-416 | static int perf_swevent_add(struct perf_event *event, int flags)
{
struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
struct hw_perf_event *hwc = &event->hw;
struct hlist_head *head;
if (is_sampling_event(event)) {
hwc->last_period = hwc->sample_period;
perf_swevent_set_period(event);
}
hwc->state = !(flags & PERF_EF_START);
head = find_swevent_head(swhash, event);
if (WARN_ON_ONCE(!head))
return -EINVAL;
hlist_add_head_rcu(&event->hlist_entry, head);
perf_event_update_userpage(event);
return 0;
}
| 167,462 |
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 GpuProcessHostUIShim::OnAcceleratedSurfaceNew(
const GpuHostMsg_AcceleratedSurfaceNew_Params& params) {
RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(
params.surface_id);
if (!view)
return;
view->AcceleratedSurfaceNew(
params.width, params.height, params.surface_handle);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuProcessHostUIShim::OnAcceleratedSurfaceNew(
const GpuHostMsg_AcceleratedSurfaceNew_Params& params) {
RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(
params.surface_id);
if (!view)
return;
if (params.mailbox_name.length() &&
params.mailbox_name.length() != GL_MAILBOX_SIZE_CHROMIUM)
return;
view->AcceleratedSurfaceNew(
params.width, params.height, params.surface_handle,
params.mailbox_name);
}
| 171,358 |
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 dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, int MI, int MA, int paddr, int ins_size,
int insns_size, char *class_name, int regsz,
int debug_info_off) {
struct r_bin_t *rbin = binfile->rbin;
const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL);
const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off;
ut64 line_start;
ut64 parameters_size;
ut64 param_type_idx;
ut16 argReg = regsz - ins_size;
ut64 source_file_idx = c->source_file;
RList *params, *debug_positions, *emitted_debug_locals = NULL;
bool keep = true;
if (argReg >= regsz) {
}
p4 = r_uleb128 (p4, p4_end - p4, &line_start);
p4 = r_uleb128 (p4, p4_end - p4, ¶meters_size);
ut32 address = 0;
ut32 line = line_start;
if (!(debug_positions = r_list_newf ((RListFree)free))) {
return;
}
if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) {
r_list_free (debug_positions);
return;
}
struct dex_debug_local_t debug_locals[regsz];
memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz);
if (!(MA & 0x0008)) {
debug_locals[argReg].name = "this";
debug_locals[argReg].descriptor = r_str_newf("%s;", class_name);
debug_locals[argReg].startAddress = 0;
debug_locals[argReg].signature = NULL;
debug_locals[argReg].live = true;
argReg++;
}
if (!(params = dex_method_signature2 (bin, MI))) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
return;
}
RListIter *iter = r_list_iterator (params);
char *name;
char *type;
int reg;
r_list_foreach (params, iter, type) {
if ((argReg >= regsz) || !type || parameters_size <= 0) {
r_list_free (debug_positions);
r_list_free (params);
r_list_free (emitted_debug_locals);
return;
}
p4 = r_uleb128 (p4, p4_end - p4, ¶m_type_idx); // read uleb128p1
param_type_idx -= 1;
name = getstr (bin, param_type_idx);
reg = argReg;
switch (type[0]) {
case 'D':
case 'J':
argReg += 2;
break;
default:
argReg += 1;
break;
}
if (name) {
debug_locals[reg].name = name;
debug_locals[reg].descriptor = type;
debug_locals[reg].signature = NULL;
debug_locals[reg].startAddress = address;
debug_locals[reg].live = true;
}
--parameters_size;
}
ut8 opcode = *(p4++) & 0xff;
while (keep) {
switch (opcode) {
case 0x0: // DBG_END_SEQUENCE
keep = false;
break;
case 0x1: // DBG_ADVANCE_PC
{
ut64 addr_diff;
p4 = r_uleb128 (p4, p4_end - p4, &addr_diff);
address += addr_diff;
}
break;
case 0x2: // DBG_ADVANCE_LINE
{
st64 line_diff = r_sleb128 (&p4, p4_end);
line += line_diff;
}
break;
case 0x3: // DBG_START_LOCAL
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = NULL;
debug_locals[register_num].live = true;
}
break;
case 0x4: //DBG_START_LOCAL_EXTENDED
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
ut64 sig_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &sig_idx);
sig_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = getstr (bin, sig_idx);
debug_locals[register_num].live = true;
}
break;
case 0x5: // DBG_END_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].live = false;
}
break;
case 0x6: // DBG_RESTART_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (!debug_locals[register_num].live) {
debug_locals[register_num].startAddress = address;
debug_locals[register_num].live = true;
}
}
break;
case 0x7: //DBG_SET_PROLOGUE_END
break;
case 0x8: //DBG_SET_PROLOGUE_BEGIN
break;
case 0x9:
{
p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx);
source_file_idx--;
}
break;
default:
{
int adjusted_opcode = opcode - 0x0a;
address += (adjusted_opcode / 15);
line += -4 + (adjusted_opcode % 15);
struct dex_debug_position_t *position =
malloc (sizeof (struct dex_debug_position_t));
if (!position) {
keep = false;
break;
}
position->source_file_idx = source_file_idx;
position->address = address;
position->line = line;
r_list_append (debug_positions, position);
}
break;
}
opcode = *(p4++) & 0xff;
}
if (!binfile->sdb_addrinfo) {
binfile->sdb_addrinfo = sdb_new0 ();
}
char *fileline;
char offset[64];
char *offset_ptr;
RListIter *iter1;
struct dex_debug_position_t *pos;
r_list_foreach (debug_positions, iter1, pos) {
fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line);
offset_ptr = sdb_itoa (pos->address + paddr, offset, 16);
sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0);
sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0);
}
if (!dexdump) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
return;
}
RListIter *iter2;
struct dex_debug_position_t *position;
rbin->cb_printf (" positions :\n");
r_list_foreach (debug_positions, iter2, position) {
rbin->cb_printf (" 0x%04llx line=%llu\n",
position->address, position->line);
}
rbin->cb_printf (" locals :\n");
RListIter *iter3;
struct dex_debug_local_t *local;
r_list_foreach (emitted_debug_locals, iter3, local) {
if (local->signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor,
local->signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor);
}
}
for (reg = 0; reg < regsz; reg++) {
if (debug_locals[reg].live) {
if (debug_locals[reg].signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s "
"%s\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor,
debug_locals[reg].signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s"
"\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor);
}
}
}
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
}
Commit Message: Fix #6836 - oob write in dex
CWE ID: CWE-119 | static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, int MI, int MA, int paddr, int ins_size,
int insns_size, char *class_name, int regsz,
int debug_info_off) {
struct r_bin_t *rbin = binfile->rbin;
const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL);
const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off;
ut64 line_start;
ut64 parameters_size;
ut64 param_type_idx;
ut16 argReg = regsz - ins_size;
ut64 source_file_idx = c->source_file;
RList *params, *debug_positions, *emitted_debug_locals = NULL;
bool keep = true;
if (argReg > regsz) {
return; // this return breaks tests
}
p4 = r_uleb128 (p4, p4_end - p4, &line_start);
p4 = r_uleb128 (p4, p4_end - p4, ¶meters_size);
ut32 address = 0;
ut32 line = line_start;
if (!(debug_positions = r_list_newf ((RListFree)free))) {
return;
}
if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) {
r_list_free (debug_positions);
return;
}
struct dex_debug_local_t debug_locals[regsz];
memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz);
if (!(MA & 0x0008)) {
debug_locals[argReg].name = "this";
debug_locals[argReg].descriptor = r_str_newf("%s;", class_name);
debug_locals[argReg].startAddress = 0;
debug_locals[argReg].signature = NULL;
debug_locals[argReg].live = true;
argReg++;
}
if (!(params = dex_method_signature2 (bin, MI))) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
return;
}
RListIter *iter = r_list_iterator (params);
char *name;
char *type;
int reg;
r_list_foreach (params, iter, type) {
if ((argReg >= regsz) || !type || parameters_size <= 0) {
r_list_free (debug_positions);
r_list_free (params);
r_list_free (emitted_debug_locals);
return;
}
p4 = r_uleb128 (p4, p4_end - p4, ¶m_type_idx); // read uleb128p1
param_type_idx -= 1;
name = getstr (bin, param_type_idx);
reg = argReg;
switch (type[0]) {
case 'D':
case 'J':
argReg += 2;
break;
default:
argReg += 1;
break;
}
if (name) {
debug_locals[reg].name = name;
debug_locals[reg].descriptor = type;
debug_locals[reg].signature = NULL;
debug_locals[reg].startAddress = address;
debug_locals[reg].live = true;
}
--parameters_size;
}
ut8 opcode = *(p4++) & 0xff;
while (keep) {
switch (opcode) {
case 0x0: // DBG_END_SEQUENCE
keep = false;
break;
case 0x1: // DBG_ADVANCE_PC
{
ut64 addr_diff;
p4 = r_uleb128 (p4, p4_end - p4, &addr_diff);
address += addr_diff;
}
break;
case 0x2: // DBG_ADVANCE_LINE
{
st64 line_diff = r_sleb128 (&p4, p4_end);
line += line_diff;
}
break;
case 0x3: // DBG_START_LOCAL
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = NULL;
debug_locals[register_num].live = true;
}
break;
case 0x4: //DBG_START_LOCAL_EXTENDED
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
ut64 sig_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &sig_idx);
sig_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = getstr (bin, sig_idx);
debug_locals[register_num].live = true;
}
break;
case 0x5: // DBG_END_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].live = false;
}
break;
case 0x6: // DBG_RESTART_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (!debug_locals[register_num].live) {
debug_locals[register_num].startAddress = address;
debug_locals[register_num].live = true;
}
}
break;
case 0x7: //DBG_SET_PROLOGUE_END
break;
case 0x8: //DBG_SET_PROLOGUE_BEGIN
break;
case 0x9:
{
p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx);
source_file_idx--;
}
break;
default:
{
int adjusted_opcode = opcode - 0x0a;
address += (adjusted_opcode / 15);
line += -4 + (adjusted_opcode % 15);
struct dex_debug_position_t *position =
malloc (sizeof (struct dex_debug_position_t));
if (!position) {
keep = false;
break;
}
position->source_file_idx = source_file_idx;
position->address = address;
position->line = line;
r_list_append (debug_positions, position);
}
break;
}
opcode = *(p4++) & 0xff;
}
if (!binfile->sdb_addrinfo) {
binfile->sdb_addrinfo = sdb_new0 ();
}
char *fileline;
char offset[64];
char *offset_ptr;
RListIter *iter1;
struct dex_debug_position_t *pos;
r_list_foreach (debug_positions, iter1, pos) {
fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line);
offset_ptr = sdb_itoa (pos->address + paddr, offset, 16);
sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0);
sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0);
}
if (!dexdump) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
return;
}
RListIter *iter2;
struct dex_debug_position_t *position;
rbin->cb_printf (" positions :\n");
r_list_foreach (debug_positions, iter2, position) {
rbin->cb_printf (" 0x%04llx line=%llu\n",
position->address, position->line);
}
rbin->cb_printf (" locals :\n");
RListIter *iter3;
struct dex_debug_local_t *local;
r_list_foreach (emitted_debug_locals, iter3, local) {
if (local->signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor,
local->signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor);
}
}
for (reg = 0; reg < regsz; reg++) {
if (debug_locals[reg].live) {
if (debug_locals[reg].signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s "
"%s\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor,
debug_locals[reg].signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s"
"\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor);
}
}
}
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
}
| 168,350 |
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 start_decoder(vorb *f)
{
uint8 header[6], x,y;
int len,i,j,k, max_submaps = 0;
int longest_floorlist=0;
if (!start_page(f)) return FALSE;
if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
if (f->segments[0] != 30) return error(f, VORBIS_invalid_first_page);
if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
get32(f); // bitrate_maximum
get32(f); // bitrate_nominal
get32(f); // bitrate_minimum
x = get8(f);
{
int log0,log1;
log0 = x & 15;
log1 = x >> 4;
f->blocksize_0 = 1 << log0;
f->blocksize_1 = 1 << log1;
if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
if (log0 > log1) return error(f, VORBIS_invalid_setup);
}
x = get8(f);
if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
if (!start_page(f)) return FALSE;
if (!start_packet(f)) return FALSE;
do {
len = next_segment(f);
skip(f, len);
f->bytes_in_seg = 0;
} while (len);
if (!start_packet(f)) return FALSE;
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (IS_PUSH_MODE(f)) {
if (!is_whole_packet_present(f, TRUE)) {
if (f->error == VORBIS_invalid_stream)
f->error = VORBIS_invalid_setup;
return FALSE;
}
}
#endif
crc32_init(); // always init it, to avoid multithread race conditions
if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
for (i=0; i < 6; ++i) header[i] = get8_packet(f);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
f->codebook_count = get_bits(f,8) + 1;
f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
for (i=0; i < f->codebook_count; ++i) {
uint32 *values;
int ordered, sorted_count;
int total=0;
uint8 *lengths;
Codebook *c = f->codebooks+i;
CHECK(f);
x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8);
c->dimensions = (get_bits(f, 8)<<8) + x;
x = get_bits(f, 8);
y = get_bits(f, 8);
c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
ordered = get_bits(f,1);
c->sparse = ordered ? 0 : get_bits(f,1);
if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup);
if (c->sparse)
lengths = (uint8 *) setup_temp_malloc(f, c->entries);
else
lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (!lengths) return error(f, VORBIS_outofmem);
if (ordered) {
int current_entry = 0;
int current_length = get_bits(f,5) + 1;
while (current_entry < c->entries) {
int limit = c->entries - current_entry;
int n = get_bits(f, ilog(limit));
if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
memset(lengths + current_entry, current_length, n);
current_entry += n;
++current_length;
}
} else {
for (j=0; j < c->entries; ++j) {
int present = c->sparse ? get_bits(f,1) : 1;
if (present) {
lengths[j] = get_bits(f, 5) + 1;
++total;
if (lengths[j] == 32)
return error(f, VORBIS_invalid_setup);
} else {
lengths[j] = NO_CODE;
}
}
}
if (c->sparse && total >= c->entries >> 2) {
if (c->entries > (int) f->setup_temp_memory_required)
f->setup_temp_memory_required = c->entries;
c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);
memcpy(c->codeword_lengths, lengths, c->entries);
setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
lengths = c->codeword_lengths;
c->sparse = 0;
}
if (c->sparse) {
sorted_count = total;
} else {
sorted_count = 0;
#ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
for (j=0; j < c->entries; ++j)
if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
++sorted_count;
#endif
}
c->sorted_entries = sorted_count;
values = NULL;
CHECK(f);
if (!c->sparse) {
c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
} else {
unsigned int size;
if (c->sorted_entries) {
c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
if (!values) return error(f, VORBIS_outofmem);
}
size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
if (size > f->setup_temp_memory_required)
f->setup_temp_memory_required = size;
}
if (!compute_codewords(c, lengths, c->entries, values)) {
if (c->sparse) setup_temp_free(f, values, 0);
return error(f, VORBIS_invalid_setup);
}
if (c->sorted_entries) {
c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);
c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);
++c->sorted_values;
c->sorted_values[-1] = -1;
compute_sorted_huffman(c, lengths, values);
}
if (c->sparse) {
setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
setup_temp_free(f, lengths, c->entries);
c->codewords = NULL;
}
compute_accelerated_huffman(c);
CHECK(f);
c->lookup_type = get_bits(f, 4);
if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
if (c->lookup_type > 0) {
uint16 *mults;
c->minimum_value = float32_unpack(get_bits(f, 32));
c->delta_value = float32_unpack(get_bits(f, 32));
c->value_bits = get_bits(f, 4)+1;
c->sequence_p = get_bits(f,1);
if (c->lookup_type == 1) {
c->lookup_values = lookup1_values(c->entries, c->dimensions);
} else {
c->lookup_values = c->entries * c->dimensions;
}
if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);
mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
if (mults == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < (int) c->lookup_values; ++j) {
int q = get_bits(f, c->value_bits);
if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
mults[j] = q;
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int len, sparse = c->sparse;
float last=0;
if (sparse) {
if (c->sorted_entries == 0) goto skip;
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
} else
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
len = sparse ? c->sorted_entries : c->entries;
for (j=0; j < len; ++j) {
unsigned int z = sparse ? c->sorted_values[j] : j;
unsigned int div=1;
for (k=0; k < c->dimensions; ++k) {
int off = (z / div) % c->lookup_values;
float val = mults[off];
val = mults[off]*c->delta_value + c->minimum_value + last;
c->multiplicands[j*c->dimensions + k] = val;
if (c->sequence_p)
last = val;
if (k+1 < c->dimensions) {
if (div > UINT_MAX / (unsigned int) c->lookup_values) {
setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
return error(f, VORBIS_invalid_setup);
}
div *= c->lookup_values;
}
}
}
c->lookup_type = 2;
}
else
#endif
{
float last=0;
CHECK(f);
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
for (j=0; j < (int) c->lookup_values; ++j) {
float val = mults[j] * c->delta_value + c->minimum_value + last;
c->multiplicands[j] = val;
if (c->sequence_p)
last = val;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
skip:;
#endif
setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);
CHECK(f);
}
CHECK(f);
}
x = get_bits(f, 6) + 1;
for (i=0; i < x; ++i) {
uint32 z = get_bits(f, 16);
if (z != 0) return error(f, VORBIS_invalid_setup);
}
f->floor_count = get_bits(f, 6)+1;
f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
if (f->floor_config == NULL) return error(f, VORBIS_outofmem);
for (i=0; i < f->floor_count; ++i) {
f->floor_types[i] = get_bits(f, 16);
if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
if (f->floor_types[i] == 0) {
Floor0 *g = &f->floor_config[i].floor0;
g->order = get_bits(f,8);
g->rate = get_bits(f,16);
g->bark_map_size = get_bits(f,16);
g->amplitude_bits = get_bits(f,6);
g->amplitude_offset = get_bits(f,8);
g->number_of_books = get_bits(f,4) + 1;
for (j=0; j < g->number_of_books; ++j)
g->book_list[j] = get_bits(f,8);
return error(f, VORBIS_feature_not_supported);
} else {
stbv__floor_ordering p[31*8+2];
Floor1 *g = &f->floor_config[i].floor1;
int max_class = -1;
g->partitions = get_bits(f, 5);
for (j=0; j < g->partitions; ++j) {
g->partition_class_list[j] = get_bits(f, 4);
if (g->partition_class_list[j] > max_class)
max_class = g->partition_class_list[j];
}
for (j=0; j <= max_class; ++j) {
g->class_dimensions[j] = get_bits(f, 3)+1;
g->class_subclasses[j] = get_bits(f, 2);
if (g->class_subclasses[j]) {
g->class_masterbooks[j] = get_bits(f, 8);
if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
g->subclass_books[j][k] = get_bits(f,8)-1;
if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
}
g->floor1_multiplier = get_bits(f,2)+1;
g->rangebits = get_bits(f,4);
g->Xlist[0] = 0;
g->Xlist[1] = 1 << g->rangebits;
g->values = 2;
for (j=0; j < g->partitions; ++j) {
int c = g->partition_class_list[j];
for (k=0; k < g->class_dimensions[c]; ++k) {
g->Xlist[g->values] = get_bits(f, g->rangebits);
++g->values;
}
}
for (j=0; j < g->values; ++j) {
p[j].x = g->Xlist[j];
p[j].id = j;
}
qsort(p, g->values, sizeof(p[0]), point_compare);
for (j=0; j < g->values; ++j)
g->sorted_order[j] = (uint8) p[j].id;
for (j=2; j < g->values; ++j) {
int low,hi;
neighbors(g->Xlist, j, &low,&hi);
g->neighbors[j][0] = low;
g->neighbors[j][1] = hi;
}
if (g->values > longest_floorlist)
longest_floorlist = g->values;
}
}
f->residue_count = get_bits(f, 6)+1;
f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));
if (f->residue_config == NULL) return error(f, VORBIS_outofmem);
memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
for (i=0; i < f->residue_count; ++i) {
uint8 residue_cascade[64];
Residue *r = f->residue_config+i;
f->residue_types[i] = get_bits(f, 16);
if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
r->begin = get_bits(f, 24);
r->end = get_bits(f, 24);
if (r->end < r->begin) return error(f, VORBIS_invalid_setup);
r->part_size = get_bits(f,24)+1;
r->classifications = get_bits(f,6)+1;
r->classbook = get_bits(f,8);
if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup);
for (j=0; j < r->classifications; ++j) {
uint8 high_bits=0;
uint8 low_bits=get_bits(f,3);
if (get_bits(f,1))
high_bits = get_bits(f,5);
residue_cascade[j] = high_bits*8 + low_bits;
}
r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
if (r->residue_books == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < r->classifications; ++j) {
for (k=0; k < 8; ++k) {
if (residue_cascade[j] & (1 << k)) {
r->residue_books[j][k] = get_bits(f, 8);
if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
} else {
r->residue_books[j][k] = -1;
}
}
}
r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
if (!r->classdata) return error(f, VORBIS_outofmem);
memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
int classwords = f->codebooks[r->classbook].dimensions;
int temp = j;
r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);
for (k=classwords-1; k >= 0; --k) {
r->classdata[j][k] = temp % r->classifications;
temp /= r->classifications;
}
}
}
f->mapping_count = get_bits(f,6)+1;
f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
if (f->mapping == NULL) return error(f, VORBIS_outofmem);
memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
for (i=0; i < f->mapping_count; ++i) {
Mapping *m = f->mapping + i;
int mapping_type = get_bits(f,16);
if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
if (m->chan == NULL) return error(f, VORBIS_outofmem);
if (get_bits(f,1))
m->submaps = get_bits(f,4)+1;
else
m->submaps = 1;
if (m->submaps > max_submaps)
max_submaps = m->submaps;
if (get_bits(f,1)) {
m->coupling_steps = get_bits(f,8)+1;
for (k=0; k < m->coupling_steps; ++k) {
m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));
m->chan[k].angle = get_bits(f, ilog(f->channels-1));
if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
}
} else
m->coupling_steps = 0;
if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
if (m->submaps > 1) {
for (j=0; j < f->channels; ++j) {
m->chan[j].mux = get_bits(f, 4);
if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
}
} else
for (j=0; j < f->channels; ++j)
m->chan[j].mux = 0;
for (j=0; j < m->submaps; ++j) {
get_bits(f,8); // discard
m->submap_floor[j] = get_bits(f,8);
m->submap_residue[j] = get_bits(f,8);
if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
}
}
f->mode_count = get_bits(f, 6)+1;
for (i=0; i < f->mode_count; ++i) {
Mode *m = f->mode_config+i;
m->blockflag = get_bits(f,1);
m->windowtype = get_bits(f,16);
m->transformtype = get_bits(f,16);
m->mapping = get_bits(f,8);
if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
}
flush_packet(f);
f->previous_length = 0;
for (i=0; i < f->channels; ++i) {
f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);
#endif
}
if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
f->blocksize[0] = f->blocksize_0;
f->blocksize[1] = f->blocksize_1;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (integer_divide_table[1][1]==0)
for (i=0; i < DIVTAB_NUMER; ++i)
for (j=1; j < DIVTAB_DENOM; ++j)
integer_divide_table[i][j] = i / j;
#endif
{
uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
uint32 classify_mem;
int i,max_part_read=0;
for (i=0; i < f->residue_count; ++i) {
Residue *r = f->residue_config + i;
int n_read = r->end - r->begin;
int part_read = n_read / r->part_size;
if (part_read > max_part_read)
max_part_read = part_read;
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
#else
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
#endif
f->temp_memory_required = classify_mem;
if (imdct_mem > f->temp_memory_required)
f->temp_memory_required = imdct_mem;
}
f->first_decode = TRUE;
if (f->alloc.alloc_buffer) {
assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
return error(f, VORBIS_outofmem);
}
f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
return TRUE;
}
Commit Message: fix unchecked length in stb_vorbis that could crash on corrupt/invalid files
CWE ID: CWE-119 | static int start_decoder(vorb *f)
{
uint8 header[6], x,y;
int len,i,j,k, max_submaps = 0;
int longest_floorlist=0;
if (!start_page(f)) return FALSE;
if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
if (f->segments[0] != 30) return error(f, VORBIS_invalid_first_page);
if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
get32(f); // bitrate_maximum
get32(f); // bitrate_nominal
get32(f); // bitrate_minimum
x = get8(f);
{
int log0,log1;
log0 = x & 15;
log1 = x >> 4;
f->blocksize_0 = 1 << log0;
f->blocksize_1 = 1 << log1;
if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
if (log0 > log1) return error(f, VORBIS_invalid_setup);
}
x = get8(f);
if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
if (!start_page(f)) return FALSE;
if (!start_packet(f)) return FALSE;
do {
len = next_segment(f);
skip(f, len);
f->bytes_in_seg = 0;
} while (len);
if (!start_packet(f)) return FALSE;
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (IS_PUSH_MODE(f)) {
if (!is_whole_packet_present(f, TRUE)) {
if (f->error == VORBIS_invalid_stream)
f->error = VORBIS_invalid_setup;
return FALSE;
}
}
#endif
crc32_init(); // always init it, to avoid multithread race conditions
if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
for (i=0; i < 6; ++i) header[i] = get8_packet(f);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
f->codebook_count = get_bits(f,8) + 1;
f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
for (i=0; i < f->codebook_count; ++i) {
uint32 *values;
int ordered, sorted_count;
int total=0;
uint8 *lengths;
Codebook *c = f->codebooks+i;
CHECK(f);
x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8);
c->dimensions = (get_bits(f, 8)<<8) + x;
x = get_bits(f, 8);
y = get_bits(f, 8);
c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
ordered = get_bits(f,1);
c->sparse = ordered ? 0 : get_bits(f,1);
if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup);
if (c->sparse)
lengths = (uint8 *) setup_temp_malloc(f, c->entries);
else
lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (!lengths) return error(f, VORBIS_outofmem);
if (ordered) {
int current_entry = 0;
int current_length = get_bits(f,5) + 1;
while (current_entry < c->entries) {
int limit = c->entries - current_entry;
int n = get_bits(f, ilog(limit));
if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
memset(lengths + current_entry, current_length, n);
current_entry += n;
++current_length;
}
} else {
for (j=0; j < c->entries; ++j) {
int present = c->sparse ? get_bits(f,1) : 1;
if (present) {
lengths[j] = get_bits(f, 5) + 1;
++total;
if (lengths[j] == 32)
return error(f, VORBIS_invalid_setup);
} else {
lengths[j] = NO_CODE;
}
}
}
if (c->sparse && total >= c->entries >> 2) {
if (c->entries > (int) f->setup_temp_memory_required)
f->setup_temp_memory_required = c->entries;
c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);
memcpy(c->codeword_lengths, lengths, c->entries);
setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
lengths = c->codeword_lengths;
c->sparse = 0;
}
if (c->sparse) {
sorted_count = total;
} else {
sorted_count = 0;
#ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
for (j=0; j < c->entries; ++j)
if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
++sorted_count;
#endif
}
c->sorted_entries = sorted_count;
values = NULL;
CHECK(f);
if (!c->sparse) {
c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
} else {
unsigned int size;
if (c->sorted_entries) {
c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
if (!values) return error(f, VORBIS_outofmem);
}
size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
if (size > f->setup_temp_memory_required)
f->setup_temp_memory_required = size;
}
if (!compute_codewords(c, lengths, c->entries, values)) {
if (c->sparse) setup_temp_free(f, values, 0);
return error(f, VORBIS_invalid_setup);
}
if (c->sorted_entries) {
c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);
c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);
++c->sorted_values;
c->sorted_values[-1] = -1;
compute_sorted_huffman(c, lengths, values);
}
if (c->sparse) {
setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
setup_temp_free(f, lengths, c->entries);
c->codewords = NULL;
}
compute_accelerated_huffman(c);
CHECK(f);
c->lookup_type = get_bits(f, 4);
if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
if (c->lookup_type > 0) {
uint16 *mults;
c->minimum_value = float32_unpack(get_bits(f, 32));
c->delta_value = float32_unpack(get_bits(f, 32));
c->value_bits = get_bits(f, 4)+1;
c->sequence_p = get_bits(f,1);
if (c->lookup_type == 1) {
c->lookup_values = lookup1_values(c->entries, c->dimensions);
} else {
c->lookup_values = c->entries * c->dimensions;
}
if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);
mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
if (mults == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < (int) c->lookup_values; ++j) {
int q = get_bits(f, c->value_bits);
if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
mults[j] = q;
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int len, sparse = c->sparse;
float last=0;
if (sparse) {
if (c->sorted_entries == 0) goto skip;
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
} else
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
len = sparse ? c->sorted_entries : c->entries;
for (j=0; j < len; ++j) {
unsigned int z = sparse ? c->sorted_values[j] : j;
unsigned int div=1;
for (k=0; k < c->dimensions; ++k) {
int off = (z / div) % c->lookup_values;
float val = mults[off];
val = mults[off]*c->delta_value + c->minimum_value + last;
c->multiplicands[j*c->dimensions + k] = val;
if (c->sequence_p)
last = val;
if (k+1 < c->dimensions) {
if (div > UINT_MAX / (unsigned int) c->lookup_values) {
setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
return error(f, VORBIS_invalid_setup);
}
div *= c->lookup_values;
}
}
}
c->lookup_type = 2;
}
else
#endif
{
float last=0;
CHECK(f);
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
for (j=0; j < (int) c->lookup_values; ++j) {
float val = mults[j] * c->delta_value + c->minimum_value + last;
c->multiplicands[j] = val;
if (c->sequence_p)
last = val;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
skip:;
#endif
setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);
CHECK(f);
}
CHECK(f);
}
x = get_bits(f, 6) + 1;
for (i=0; i < x; ++i) {
uint32 z = get_bits(f, 16);
if (z != 0) return error(f, VORBIS_invalid_setup);
}
f->floor_count = get_bits(f, 6)+1;
f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
if (f->floor_config == NULL) return error(f, VORBIS_outofmem);
for (i=0; i < f->floor_count; ++i) {
f->floor_types[i] = get_bits(f, 16);
if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
if (f->floor_types[i] == 0) {
Floor0 *g = &f->floor_config[i].floor0;
g->order = get_bits(f,8);
g->rate = get_bits(f,16);
g->bark_map_size = get_bits(f,16);
g->amplitude_bits = get_bits(f,6);
g->amplitude_offset = get_bits(f,8);
g->number_of_books = get_bits(f,4) + 1;
for (j=0; j < g->number_of_books; ++j)
g->book_list[j] = get_bits(f,8);
return error(f, VORBIS_feature_not_supported);
} else {
stbv__floor_ordering p[31*8+2];
Floor1 *g = &f->floor_config[i].floor1;
int max_class = -1;
g->partitions = get_bits(f, 5);
for (j=0; j < g->partitions; ++j) {
g->partition_class_list[j] = get_bits(f, 4);
if (g->partition_class_list[j] > max_class)
max_class = g->partition_class_list[j];
}
for (j=0; j <= max_class; ++j) {
g->class_dimensions[j] = get_bits(f, 3)+1;
g->class_subclasses[j] = get_bits(f, 2);
if (g->class_subclasses[j]) {
g->class_masterbooks[j] = get_bits(f, 8);
if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
g->subclass_books[j][k] = get_bits(f,8)-1;
if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
}
g->floor1_multiplier = get_bits(f,2)+1;
g->rangebits = get_bits(f,4);
g->Xlist[0] = 0;
g->Xlist[1] = 1 << g->rangebits;
g->values = 2;
for (j=0; j < g->partitions; ++j) {
int c = g->partition_class_list[j];
for (k=0; k < g->class_dimensions[c]; ++k) {
g->Xlist[g->values] = get_bits(f, g->rangebits);
++g->values;
}
}
for (j=0; j < g->values; ++j) {
p[j].x = g->Xlist[j];
p[j].id = j;
}
qsort(p, g->values, sizeof(p[0]), point_compare);
for (j=0; j < g->values; ++j)
g->sorted_order[j] = (uint8) p[j].id;
for (j=2; j < g->values; ++j) {
int low,hi;
neighbors(g->Xlist, j, &low,&hi);
g->neighbors[j][0] = low;
g->neighbors[j][1] = hi;
}
if (g->values > longest_floorlist)
longest_floorlist = g->values;
}
}
f->residue_count = get_bits(f, 6)+1;
f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));
if (f->residue_config == NULL) return error(f, VORBIS_outofmem);
memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
for (i=0; i < f->residue_count; ++i) {
uint8 residue_cascade[64];
Residue *r = f->residue_config+i;
f->residue_types[i] = get_bits(f, 16);
if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
r->begin = get_bits(f, 24);
r->end = get_bits(f, 24);
if (r->end < r->begin) return error(f, VORBIS_invalid_setup);
r->part_size = get_bits(f,24)+1;
r->classifications = get_bits(f,6)+1;
r->classbook = get_bits(f,8);
if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup);
for (j=0; j < r->classifications; ++j) {
uint8 high_bits=0;
uint8 low_bits=get_bits(f,3);
if (get_bits(f,1))
high_bits = get_bits(f,5);
residue_cascade[j] = high_bits*8 + low_bits;
}
r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
if (r->residue_books == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < r->classifications; ++j) {
for (k=0; k < 8; ++k) {
if (residue_cascade[j] & (1 << k)) {
r->residue_books[j][k] = get_bits(f, 8);
if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
} else {
r->residue_books[j][k] = -1;
}
}
}
r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
if (!r->classdata) return error(f, VORBIS_outofmem);
memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
int classwords = f->codebooks[r->classbook].dimensions;
int temp = j;
r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);
for (k=classwords-1; k >= 0; --k) {
r->classdata[j][k] = temp % r->classifications;
temp /= r->classifications;
}
}
}
f->mapping_count = get_bits(f,6)+1;
f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
if (f->mapping == NULL) return error(f, VORBIS_outofmem);
memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
for (i=0; i < f->mapping_count; ++i) {
Mapping *m = f->mapping + i;
int mapping_type = get_bits(f,16);
if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
if (m->chan == NULL) return error(f, VORBIS_outofmem);
if (get_bits(f,1))
m->submaps = get_bits(f,4)+1;
else
m->submaps = 1;
if (m->submaps > max_submaps)
max_submaps = m->submaps;
if (get_bits(f,1)) {
m->coupling_steps = get_bits(f,8)+1;
for (k=0; k < m->coupling_steps; ++k) {
m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));
m->chan[k].angle = get_bits(f, ilog(f->channels-1));
if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
}
} else
m->coupling_steps = 0;
if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
if (m->submaps > 1) {
for (j=0; j < f->channels; ++j) {
m->chan[j].mux = get_bits(f, 4);
if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
}
} else
for (j=0; j < f->channels; ++j)
m->chan[j].mux = 0;
for (j=0; j < m->submaps; ++j) {
get_bits(f,8); // discard
m->submap_floor[j] = get_bits(f,8);
m->submap_residue[j] = get_bits(f,8);
if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
}
}
f->mode_count = get_bits(f, 6)+1;
for (i=0; i < f->mode_count; ++i) {
Mode *m = f->mode_config+i;
m->blockflag = get_bits(f,1);
m->windowtype = get_bits(f,16);
m->transformtype = get_bits(f,16);
m->mapping = get_bits(f,8);
if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
}
flush_packet(f);
f->previous_length = 0;
for (i=0; i < f->channels; ++i) {
f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);
#endif
}
if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
f->blocksize[0] = f->blocksize_0;
f->blocksize[1] = f->blocksize_1;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (integer_divide_table[1][1]==0)
for (i=0; i < DIVTAB_NUMER; ++i)
for (j=1; j < DIVTAB_DENOM; ++j)
integer_divide_table[i][j] = i / j;
#endif
{
uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
uint32 classify_mem;
int i,max_part_read=0;
for (i=0; i < f->residue_count; ++i) {
Residue *r = f->residue_config + i;
unsigned int actual_size = f->blocksize_1 / 2;
unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size;
unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size;
int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
if (part_read > max_part_read)
max_part_read = part_read;
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
#else
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
#endif
// maximum reasonable partition size is f->blocksize_1
f->temp_memory_required = classify_mem;
if (imdct_mem > f->temp_memory_required)
f->temp_memory_required = imdct_mem;
}
f->first_decode = TRUE;
if (f->alloc.alloc_buffer) {
assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
return error(f, VORBIS_outofmem);
}
f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
return TRUE;
}
| 168,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: IndexedDBTransaction* IndexedDBConnection::CreateTransaction(
int64_t id,
const std::set<int64_t>& scope,
blink::WebIDBTransactionMode mode,
IndexedDBBackingStore::Transaction* backing_store_transaction) {
DCHECK_EQ(GetTransaction(id), nullptr) << "Duplicate transaction id." << id;
std::unique_ptr<IndexedDBTransaction> transaction =
IndexedDBClassFactory::Get()->CreateIndexedDBTransaction(
id, this, scope, mode, backing_store_transaction);
IndexedDBTransaction* transaction_ptr = transaction.get();
transactions_[id] = std::move(transaction);
return transaction_ptr;
}
Commit Message: [IndexedDB] Fixed transaction use-after-free vuln
Bug: 725032
Change-Id: I689ded6c74d5563403587b149c3f3e02e807e4aa
Reviewed-on: https://chromium-review.googlesource.com/518483
Reviewed-by: Joshua Bell <[email protected]>
Commit-Queue: Daniel Murphy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#475952}
CWE ID: CWE-416 | IndexedDBTransaction* IndexedDBConnection::CreateTransaction(
int64_t id,
const std::set<int64_t>& scope,
blink::WebIDBTransactionMode mode,
IndexedDBBackingStore::Transaction* backing_store_transaction) {
CHECK_EQ(GetTransaction(id), nullptr) << "Duplicate transaction id." << id;
std::unique_ptr<IndexedDBTransaction> transaction =
IndexedDBClassFactory::Get()->CreateIndexedDBTransaction(
id, this, scope, mode, backing_store_transaction);
IndexedDBTransaction* transaction_ptr = transaction.get();
transactions_[id] = std::move(transaction);
return transaction_ptr;
}
| 172,352 |
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_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
{
zend_hash_destroy(&pglobals->ht_rc);
}
Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free
CWE ID: CWE-415 | static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
{
zend_hash_destroy(&pglobals->ht_rc);
}
| 167,119 |
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 InstallablePaymentAppCrawler::OnPaymentMethodManifestParsed(
const GURL& method_manifest_url,
const std::vector<GURL>& default_applications,
const std::vector<url::Origin>& supported_origins,
bool all_origins_supported) {
number_of_payment_method_manifest_to_parse_--;
if (web_contents() == nullptr)
return;
content::PermissionManager* permission_manager =
web_contents()->GetBrowserContext()->GetPermissionManager();
if (permission_manager == nullptr)
return;
for (const auto& url : default_applications) {
if (downloaded_web_app_manifests_.find(url) !=
downloaded_web_app_manifests_.end()) {
continue;
}
if (permission_manager->GetPermissionStatus(
content::PermissionType::PAYMENT_HANDLER, url.GetOrigin(),
url.GetOrigin()) != blink::mojom::PermissionStatus::GRANTED) {
continue;
}
number_of_web_app_manifest_to_download_++;
downloaded_web_app_manifests_.insert(url);
downloader_->DownloadWebAppManifest(
url,
base::BindOnce(
&InstallablePaymentAppCrawler::OnPaymentWebAppManifestDownloaded,
weak_ptr_factory_.GetWeakPtr(), method_manifest_url, url));
}
FinishCrawlingPaymentAppsIfReady();
}
Commit Message: [Payments] Restrict just-in-time payment handler to payment method domain and its subdomains
Bug: 853937
Change-Id: I148b3d96950a9d90fa362e580e9593caa6b92a36
Reviewed-on: https://chromium-review.googlesource.com/1132116
Reviewed-by: Mathieu Perreault <[email protected]>
Commit-Queue: Ganggui Tang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#573911}
CWE ID: | void InstallablePaymentAppCrawler::OnPaymentMethodManifestParsed(
const GURL& method_manifest_url,
const std::vector<GURL>& default_applications,
const std::vector<url::Origin>& supported_origins,
bool all_origins_supported) {
number_of_payment_method_manifest_to_parse_--;
if (web_contents() == nullptr)
return;
content::PermissionManager* permission_manager =
web_contents()->GetBrowserContext()->GetPermissionManager();
if (permission_manager == nullptr)
return;
for (const auto& url : default_applications) {
if (downloaded_web_app_manifests_.find(url) !=
downloaded_web_app_manifests_.end()) {
continue;
}
if (!net::registry_controlled_domains::SameDomainOrHost(
method_manifest_url, url,
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) {
WarnIfPossible("Installable payment app from " + url.spec() +
" is not allowed for the method " +
method_manifest_url.spec());
continue;
}
if (permission_manager->GetPermissionStatus(
content::PermissionType::PAYMENT_HANDLER, url.GetOrigin(),
url.GetOrigin()) != blink::mojom::PermissionStatus::GRANTED) {
continue;
}
number_of_web_app_manifest_to_download_++;
downloaded_web_app_manifests_.insert(url);
downloader_->DownloadWebAppManifest(
url,
base::BindOnce(
&InstallablePaymentAppCrawler::OnPaymentWebAppManifestDownloaded,
weak_ptr_factory_.GetWeakPtr(), method_manifest_url, url));
}
FinishCrawlingPaymentAppsIfReady();
}
| 172,652 |
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 BlockPainter::PaintScrollHitTestDisplayItem(const PaintInfo& paint_info) {
DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
if (paint_info.GetGlobalPaintFlags() & kGlobalPaintFlattenCompositingLayers)
return;
const auto* fragment = paint_info.FragmentToPaint(layout_block_);
const auto* properties = fragment ? fragment->PaintProperties() : nullptr;
if (properties && properties->Scroll()) {
DCHECK(properties->ScrollTranslation());
ScopedPaintChunkProperties scroll_hit_test_properties(
paint_info.context.GetPaintController(),
fragment->LocalBorderBoxProperties(), layout_block_,
DisplayItem::kScrollHitTest);
ScrollHitTestDisplayItem::Record(paint_info.context, layout_block_,
DisplayItem::kScrollHitTest,
properties->ScrollTranslation());
}
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | void BlockPainter::PaintScrollHitTestDisplayItem(const PaintInfo& paint_info) {
DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
if (paint_info.GetGlobalPaintFlags() & kGlobalPaintFlattenCompositingLayers)
return;
const auto* fragment = paint_info.FragmentToPaint(layout_block_);
const auto* properties = fragment ? fragment->PaintProperties() : nullptr;
if (properties && properties->Scroll()) {
DCHECK(properties->ScrollTranslation());
ScopedPaintChunkProperties scroll_hit_test_properties(
paint_info.context.GetPaintController(),
fragment->LocalBorderBoxProperties(), layout_block_,
DisplayItem::kScrollHitTest);
ScrollHitTestDisplayItem::Record(paint_info.context, layout_block_,
DisplayItem::kScrollHitTest,
*properties->ScrollTranslation());
}
}
| 171,790 |
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 NetworkHandler::DeleteCookies(
const std::string& name,
Maybe<std::string> url,
Maybe<std::string> domain,
Maybe<std::string> path,
std::unique_ptr<DeleteCookiesCallback> callback) {
if (!process_) {
callback->sendFailure(Response::InternalError());
return;
}
if (!url.isJust() && !domain.isJust()) {
callback->sendFailure(Response::InvalidParams(
"At least one of the url and domain needs to be specified"));
}
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&DeleteCookiesOnIO,
base::Unretained(
process_->GetStoragePartition()->GetURLRequestContext()),
name, url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""),
base::BindOnce(&DeleteCookiesCallback::sendSuccess,
std::move(callback))));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void NetworkHandler::DeleteCookies(
const std::string& name,
Maybe<std::string> url,
Maybe<std::string> domain,
Maybe<std::string> path,
std::unique_ptr<DeleteCookiesCallback> callback) {
if (!storage_partition_) {
callback->sendFailure(Response::InternalError());
return;
}
if (!url.isJust() && !domain.isJust()) {
callback->sendFailure(Response::InvalidParams(
"At least one of the url and domain needs to be specified"));
}
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&DeleteCookiesOnIO,
base::Unretained(storage_partition_->GetURLRequestContext()), name,
url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""),
base::BindOnce(&DeleteCookiesCallback::sendSuccess,
std::move(callback))));
}
| 172,755 |
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 ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
{
MOVMuxContext *mov = s->priv_data;
AVIOContext *pb = s->pb;
MOVTrack *trk = &mov->tracks[pkt->stream_index];
AVCodecParameters *par = trk->par;
unsigned int samples_in_chunk = 0;
int size = pkt->size, ret = 0;
uint8_t *reformatted_data = NULL;
ret = check_pkt(s, pkt);
if (ret < 0)
return ret;
if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
int ret;
if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
if (mov->frag_interleave && mov->fragments > 0) {
if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
return ret;
}
}
if (!trk->mdat_buf) {
if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
return ret;
}
pb = trk->mdat_buf;
} else {
if (!mov->mdat_buf) {
if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
return ret;
}
pb = mov->mdat_buf;
}
}
if (par->codec_id == AV_CODEC_ID_AMR_NB) {
/* We must find out how many AMR blocks there are in one packet */
static const uint16_t packed_size[16] =
{13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
int len = 0;
while (len < size && samples_in_chunk < 100) {
len += packed_size[(pkt->data[len] >> 3) & 0x0F];
samples_in_chunk++;
}
if (samples_in_chunk > 1) {
av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
return -1;
}
} else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
samples_in_chunk = trk->par->frame_size;
} else if (trk->sample_size)
samples_in_chunk = size / trk->sample_size;
else
samples_in_chunk = 1;
/* copy extradata if it exists */
if (trk->vos_len == 0 && par->extradata_size > 0 &&
!TAG_IS_AVCI(trk->tag) &&
(par->codec_id != AV_CODEC_ID_DNXHD)) {
trk->vos_len = par->extradata_size;
trk->vos_data = av_malloc(trk->vos_len);
if (!trk->vos_data) {
ret = AVERROR(ENOMEM);
goto err;
}
memcpy(trk->vos_data, par->extradata, trk->vos_len);
}
if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
(AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
if (!s->streams[pkt->stream_index]->nb_frames) {
av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
"use the audio bitstream filter 'aac_adtstoasc' to fix it "
"('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
return -1;
}
av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
}
if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
/* from x264 or from bytestream H.264 */
/* NAL reformatting needed */
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
&size);
avio_write(pb, reformatted_data, size);
} else {
if (trk->cenc.aes_ctr) {
size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
if (size < 0) {
ret = size;
goto err;
}
} else {
size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
}
}
} else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
(AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
/* extradata is Annex B, assume the bitstream is too and convert it */
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
avio_write(pb, reformatted_data, size);
} else {
size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
}
#if CONFIG_AC3_PARSER
} else if (par->codec_id == AV_CODEC_ID_EAC3) {
size = handle_eac3(mov, pkt, trk);
if (size < 0)
return size;
else if (!size)
goto end;
avio_write(pb, pkt->data, size);
#endif
} else {
if (trk->cenc.aes_ctr) {
if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
int nal_size_length = (par->extradata[4] & 0x3) + 1;
ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
} else {
ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
}
if (ret) {
goto err;
}
} else {
avio_write(pb, pkt->data, size);
}
}
if ((par->codec_id == AV_CODEC_ID_DNXHD ||
par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
/* copy frame to create needed atoms */
trk->vos_len = size;
trk->vos_data = av_malloc(size);
if (!trk->vos_data) {
ret = AVERROR(ENOMEM);
goto err;
}
memcpy(trk->vos_data, pkt->data, size);
}
if (trk->entry >= trk->cluster_capacity) {
unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
if (av_reallocp_array(&trk->cluster, new_capacity,
sizeof(*trk->cluster))) {
ret = AVERROR(ENOMEM);
goto err;
}
trk->cluster_capacity = new_capacity;
}
trk->cluster[trk->entry].pos = avio_tell(pb) - size;
trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
trk->cluster[trk->entry].chunkNum = 0;
trk->cluster[trk->entry].size = size;
trk->cluster[trk->entry].entries = samples_in_chunk;
trk->cluster[trk->entry].dts = pkt->dts;
trk->cluster[trk->entry].pts = pkt->pts;
if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
if (!trk->frag_discont) {
/* First packet of a new fragment. We already wrote the duration
* of the last packet of the previous fragment based on track_duration,
* which might not exactly match our dts. Therefore adjust the dts
* of this packet to be what the previous packets duration implies. */
trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
/* We also may have written the pts and the corresponding duration
* in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
* the next fragment. This means the cts of the first sample must
* be the same in all fragments, unless end_pts was updated by
* the packet causing the fragment to be written. */
if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
mov->mode == MODE_ISM)
pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
} else {
/* New fragment, but discontinuous from previous fragments.
* Pretend the duration sum of the earlier fragments is
* pkt->dts - trk->start_dts. */
trk->frag_start = pkt->dts - trk->start_dts;
trk->end_pts = AV_NOPTS_VALUE;
trk->frag_discont = 0;
}
}
if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
/* Not using edit lists and shifting the first track to start from zero.
* If the other streams start from a later timestamp, we won't be able
* to signal the difference in starting time without an edit list.
* Thus move the timestamp for this first sample to 0, increasing
* its duration instead. */
trk->cluster[trk->entry].dts = trk->start_dts = 0;
}
if (trk->start_dts == AV_NOPTS_VALUE) {
trk->start_dts = pkt->dts;
if (trk->frag_discont) {
if (mov->use_editlist) {
/* Pretend the whole stream started at pts=0, with earlier fragments
* already written. If the stream started at pts=0, the duration sum
* of earlier fragments would have been pkt->pts. */
trk->frag_start = pkt->pts;
trk->start_dts = pkt->dts - pkt->pts;
} else {
/* Pretend the whole stream started at dts=0, with earlier fragments
* already written, with a duration summing up to pkt->dts. */
trk->frag_start = pkt->dts;
trk->start_dts = 0;
}
trk->frag_discont = 0;
} else if (pkt->dts && mov->moov_written)
av_log(s, AV_LOG_WARNING,
"Track %d starts with a nonzero dts %"PRId64", while the moov "
"already has been written. Set the delay_moov flag to handle "
"this case.\n",
pkt->stream_index, pkt->dts);
}
trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
trk->last_sample_is_subtitle_end = 0;
if (pkt->pts == AV_NOPTS_VALUE) {
av_log(s, AV_LOG_WARNING, "pts has no value\n");
pkt->pts = pkt->dts;
}
if (pkt->dts != pkt->pts)
trk->flags |= MOV_TRACK_CTTS;
trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
trk->cluster[trk->entry].flags = 0;
if (trk->start_cts == AV_NOPTS_VALUE)
trk->start_cts = pkt->pts - pkt->dts;
if (trk->end_pts == AV_NOPTS_VALUE)
trk->end_pts = trk->cluster[trk->entry].dts +
trk->cluster[trk->entry].cts + pkt->duration;
else
trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
trk->cluster[trk->entry].cts +
pkt->duration);
if (par->codec_id == AV_CODEC_ID_VC1) {
mov_parse_vc1_frame(pkt, trk);
} else if (pkt->flags & AV_PKT_FLAG_KEY) {
if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
trk->entry > 0) { // force sync sample for the first key frame
mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
trk->flags |= MOV_TRACK_STPS;
} else {
trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
}
if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
trk->has_keyframes++;
}
if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
trk->has_disposable++;
}
trk->entry++;
trk->sample_count += samples_in_chunk;
mov->mdat_size += size;
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
reformatted_data, size);
end:
err:
av_free(reformatted_data);
return ret;
}
Commit Message: avformat/movenc: Check input sample count
Fixes: division by 0
Fixes: fpe_movenc.c_199_1.wav
Fixes: fpe_movenc.c_199_2.wav
Fixes: fpe_movenc.c_199_3.wav
Fixes: fpe_movenc.c_199_4.wav
Fixes: fpe_movenc.c_199_5.wav
Fixes: fpe_movenc.c_199_6.wav
Fixes: fpe_movenc.c_199_7.wav
Found-by: #CHEN HONGXU# <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-369 | int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
{
MOVMuxContext *mov = s->priv_data;
AVIOContext *pb = s->pb;
MOVTrack *trk = &mov->tracks[pkt->stream_index];
AVCodecParameters *par = trk->par;
unsigned int samples_in_chunk = 0;
int size = pkt->size, ret = 0;
uint8_t *reformatted_data = NULL;
ret = check_pkt(s, pkt);
if (ret < 0)
return ret;
if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
int ret;
if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
if (mov->frag_interleave && mov->fragments > 0) {
if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
return ret;
}
}
if (!trk->mdat_buf) {
if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
return ret;
}
pb = trk->mdat_buf;
} else {
if (!mov->mdat_buf) {
if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
return ret;
}
pb = mov->mdat_buf;
}
}
if (par->codec_id == AV_CODEC_ID_AMR_NB) {
/* We must find out how many AMR blocks there are in one packet */
static const uint16_t packed_size[16] =
{13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
int len = 0;
while (len < size && samples_in_chunk < 100) {
len += packed_size[(pkt->data[len] >> 3) & 0x0F];
samples_in_chunk++;
}
if (samples_in_chunk > 1) {
av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
return -1;
}
} else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
samples_in_chunk = trk->par->frame_size;
} else if (trk->sample_size)
samples_in_chunk = size / trk->sample_size;
else
samples_in_chunk = 1;
if (samples_in_chunk < 1) {
av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
return AVERROR_PATCHWELCOME;
}
/* copy extradata if it exists */
if (trk->vos_len == 0 && par->extradata_size > 0 &&
!TAG_IS_AVCI(trk->tag) &&
(par->codec_id != AV_CODEC_ID_DNXHD)) {
trk->vos_len = par->extradata_size;
trk->vos_data = av_malloc(trk->vos_len);
if (!trk->vos_data) {
ret = AVERROR(ENOMEM);
goto err;
}
memcpy(trk->vos_data, par->extradata, trk->vos_len);
}
if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
(AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
if (!s->streams[pkt->stream_index]->nb_frames) {
av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
"use the audio bitstream filter 'aac_adtstoasc' to fix it "
"('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
return -1;
}
av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
}
if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
/* from x264 or from bytestream H.264 */
/* NAL reformatting needed */
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
&size);
avio_write(pb, reformatted_data, size);
} else {
if (trk->cenc.aes_ctr) {
size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
if (size < 0) {
ret = size;
goto err;
}
} else {
size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
}
}
} else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
(AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
/* extradata is Annex B, assume the bitstream is too and convert it */
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
avio_write(pb, reformatted_data, size);
} else {
size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
}
#if CONFIG_AC3_PARSER
} else if (par->codec_id == AV_CODEC_ID_EAC3) {
size = handle_eac3(mov, pkt, trk);
if (size < 0)
return size;
else if (!size)
goto end;
avio_write(pb, pkt->data, size);
#endif
} else {
if (trk->cenc.aes_ctr) {
if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
int nal_size_length = (par->extradata[4] & 0x3) + 1;
ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
} else {
ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
}
if (ret) {
goto err;
}
} else {
avio_write(pb, pkt->data, size);
}
}
if ((par->codec_id == AV_CODEC_ID_DNXHD ||
par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
/* copy frame to create needed atoms */
trk->vos_len = size;
trk->vos_data = av_malloc(size);
if (!trk->vos_data) {
ret = AVERROR(ENOMEM);
goto err;
}
memcpy(trk->vos_data, pkt->data, size);
}
if (trk->entry >= trk->cluster_capacity) {
unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
if (av_reallocp_array(&trk->cluster, new_capacity,
sizeof(*trk->cluster))) {
ret = AVERROR(ENOMEM);
goto err;
}
trk->cluster_capacity = new_capacity;
}
trk->cluster[trk->entry].pos = avio_tell(pb) - size;
trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
trk->cluster[trk->entry].chunkNum = 0;
trk->cluster[trk->entry].size = size;
trk->cluster[trk->entry].entries = samples_in_chunk;
trk->cluster[trk->entry].dts = pkt->dts;
trk->cluster[trk->entry].pts = pkt->pts;
if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
if (!trk->frag_discont) {
/* First packet of a new fragment. We already wrote the duration
* of the last packet of the previous fragment based on track_duration,
* which might not exactly match our dts. Therefore adjust the dts
* of this packet to be what the previous packets duration implies. */
trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
/* We also may have written the pts and the corresponding duration
* in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
* the next fragment. This means the cts of the first sample must
* be the same in all fragments, unless end_pts was updated by
* the packet causing the fragment to be written. */
if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
mov->mode == MODE_ISM)
pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
} else {
/* New fragment, but discontinuous from previous fragments.
* Pretend the duration sum of the earlier fragments is
* pkt->dts - trk->start_dts. */
trk->frag_start = pkt->dts - trk->start_dts;
trk->end_pts = AV_NOPTS_VALUE;
trk->frag_discont = 0;
}
}
if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
/* Not using edit lists and shifting the first track to start from zero.
* If the other streams start from a later timestamp, we won't be able
* to signal the difference in starting time without an edit list.
* Thus move the timestamp for this first sample to 0, increasing
* its duration instead. */
trk->cluster[trk->entry].dts = trk->start_dts = 0;
}
if (trk->start_dts == AV_NOPTS_VALUE) {
trk->start_dts = pkt->dts;
if (trk->frag_discont) {
if (mov->use_editlist) {
/* Pretend the whole stream started at pts=0, with earlier fragments
* already written. If the stream started at pts=0, the duration sum
* of earlier fragments would have been pkt->pts. */
trk->frag_start = pkt->pts;
trk->start_dts = pkt->dts - pkt->pts;
} else {
/* Pretend the whole stream started at dts=0, with earlier fragments
* already written, with a duration summing up to pkt->dts. */
trk->frag_start = pkt->dts;
trk->start_dts = 0;
}
trk->frag_discont = 0;
} else if (pkt->dts && mov->moov_written)
av_log(s, AV_LOG_WARNING,
"Track %d starts with a nonzero dts %"PRId64", while the moov "
"already has been written. Set the delay_moov flag to handle "
"this case.\n",
pkt->stream_index, pkt->dts);
}
trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
trk->last_sample_is_subtitle_end = 0;
if (pkt->pts == AV_NOPTS_VALUE) {
av_log(s, AV_LOG_WARNING, "pts has no value\n");
pkt->pts = pkt->dts;
}
if (pkt->dts != pkt->pts)
trk->flags |= MOV_TRACK_CTTS;
trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
trk->cluster[trk->entry].flags = 0;
if (trk->start_cts == AV_NOPTS_VALUE)
trk->start_cts = pkt->pts - pkt->dts;
if (trk->end_pts == AV_NOPTS_VALUE)
trk->end_pts = trk->cluster[trk->entry].dts +
trk->cluster[trk->entry].cts + pkt->duration;
else
trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
trk->cluster[trk->entry].cts +
pkt->duration);
if (par->codec_id == AV_CODEC_ID_VC1) {
mov_parse_vc1_frame(pkt, trk);
} else if (pkt->flags & AV_PKT_FLAG_KEY) {
if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
trk->entry > 0) { // force sync sample for the first key frame
mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
trk->flags |= MOV_TRACK_STPS;
} else {
trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
}
if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
trk->has_keyframes++;
}
if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
trk->has_disposable++;
}
trk->entry++;
trk->sample_count += samples_in_chunk;
mov->mdat_size += size;
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
reformatted_data, size);
end:
err:
av_free(reformatted_data);
return ret;
}
| 169,118 |
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 jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
int nonOpt(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
size_t argsCount = exec->argumentCount();
if (argsCount <= 1) {
impl->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt);
return JSValue::encode(jsUndefined());
}
int opt1(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
if (argsCount <= 2) {
impl->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1);
return JSValue::encode(jsUndefined());
}
int opt2(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1, opt2);
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 jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
int nonOpt(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
size_t argsCount = exec->argumentCount();
if (argsCount <= 1) {
impl->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt);
return JSValue::encode(jsUndefined());
}
int opt1(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
if (argsCount <= 2) {
impl->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1);
return JSValue::encode(jsUndefined());
}
int opt2(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1, opt2);
return JSValue::encode(jsUndefined());
}
| 170,595 |
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 region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect)
{
REGION16_DATA* newItems;
const RECTANGLE_16* srcPtr, *endPtr, *srcExtents;
RECTANGLE_16* dstPtr;
UINT32 nbRects, usedRects;
RECTANGLE_16 common, newExtents;
assert(src);
assert(src->data);
srcPtr = region16_rects(src, &nbRects);
if (!nbRects)
{
region16_clear(dst);
return TRUE;
}
srcExtents = region16_extents(src);
if (nbRects == 1)
{
BOOL intersects = rectangles_intersection(srcExtents, rect, &common);
region16_clear(dst);
if (intersects)
return region16_union_rect(dst, dst, &common);
return TRUE;
}
newItems = allocateRegion(nbRects);
if (!newItems)
return FALSE;
dstPtr = (RECTANGLE_16*)(&newItems[1]);
usedRects = 0;
ZeroMemory(&newExtents, sizeof(newExtents));
/* accumulate intersecting rectangles, the final region16_simplify_bands() will
* do all the bad job to recreate correct rectangles
*/
for (endPtr = srcPtr + nbRects; (srcPtr < endPtr) && (rect->bottom > srcPtr->top); srcPtr++)
{
if (rectangles_intersection(srcPtr, rect, &common))
{
*dstPtr = common;
usedRects++;
dstPtr++;
if (rectangle_is_empty(&newExtents))
{
/* Check if the existing newExtents is empty. If it is empty, use
* new common directly. We do not need to check common rectangle
* because the rectangles_intersection() ensures that it is not empty.
*/
newExtents = common;
}
else
{
newExtents.top = MIN(common.top, newExtents.top);
newExtents.left = MIN(common.left, newExtents.left);
newExtents.bottom = MAX(common.bottom, newExtents.bottom);
newExtents.right = MAX(common.right, newExtents.right);
}
}
}
newItems->nbRects = usedRects;
newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16));
if ((dst->data->size > 0) && (dst->data != &empty_region))
free(dst->data);
dst->data = realloc(newItems, newItems->size);
if (!dst->data)
{
free(newItems);
return FALSE;
}
dst->extents = newExtents;
return region16_simplify_bands(dst);
}
Commit Message: Fixed #5645: realloc return handling
CWE ID: CWE-772 | BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect)
{
REGION16_DATA* data;
REGION16_DATA* newItems;
const RECTANGLE_16* srcPtr, *endPtr, *srcExtents;
RECTANGLE_16* dstPtr;
UINT32 nbRects, usedRects;
RECTANGLE_16 common, newExtents;
assert(src);
assert(src->data);
srcPtr = region16_rects(src, &nbRects);
if (!nbRects)
{
region16_clear(dst);
return TRUE;
}
srcExtents = region16_extents(src);
if (nbRects == 1)
{
BOOL intersects = rectangles_intersection(srcExtents, rect, &common);
region16_clear(dst);
if (intersects)
return region16_union_rect(dst, dst, &common);
return TRUE;
}
newItems = allocateRegion(nbRects);
if (!newItems)
return FALSE;
dstPtr = (RECTANGLE_16*)(&newItems[1]);
usedRects = 0;
ZeroMemory(&newExtents, sizeof(newExtents));
/* accumulate intersecting rectangles, the final region16_simplify_bands() will
* do all the bad job to recreate correct rectangles
*/
for (endPtr = srcPtr + nbRects; (srcPtr < endPtr) && (rect->bottom > srcPtr->top); srcPtr++)
{
if (rectangles_intersection(srcPtr, rect, &common))
{
*dstPtr = common;
usedRects++;
dstPtr++;
if (rectangle_is_empty(&newExtents))
{
/* Check if the existing newExtents is empty. If it is empty, use
* new common directly. We do not need to check common rectangle
* because the rectangles_intersection() ensures that it is not empty.
*/
newExtents = common;
}
else
{
newExtents.top = MIN(common.top, newExtents.top);
newExtents.left = MIN(common.left, newExtents.left);
newExtents.bottom = MAX(common.bottom, newExtents.bottom);
newExtents.right = MAX(common.right, newExtents.right);
}
}
}
newItems->nbRects = usedRects;
newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16));
if ((dst->data->size > 0) && (dst->data != &empty_region))
free(dst->data);
data = realloc(newItems, newItems->size);
if (!data)
free(dst->data);
dst->data = data;
if (!dst->data)
{
free(newItems);
return FALSE;
}
dst->extents = newExtents;
return region16_simplify_bands(dst);
}
| 169,496 |
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 WebGL2RenderingContextBase::framebufferTextureLayer(GLenum target,
GLenum attachment,
WebGLTexture* texture,
GLint level,
GLint layer) {
if (isContextLost() || !ValidateFramebufferFuncParameters(
"framebufferTextureLayer", target, attachment))
return;
if (texture && !texture->Validate(ContextGroup(), this)) {
SynthesizeGLError(GL_INVALID_VALUE, "framebufferTextureLayer",
"no texture or texture not from this context");
return;
}
GLenum textarget = texture ? texture->GetTarget() : 0;
if (texture) {
if (textarget != GL_TEXTURE_3D && textarget != GL_TEXTURE_2D_ARRAY) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"invalid texture type");
return;
}
if (!ValidateTexFuncLayer("framebufferTextureLayer", textarget, layer))
return;
if (!ValidateTexFuncLevel("framebufferTextureLayer", textarget, level))
return;
}
WebGLFramebuffer* framebuffer_binding = GetFramebufferBinding(target);
if (!framebuffer_binding || !framebuffer_binding->Object()) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"no framebuffer bound");
return;
}
if (framebuffer_binding && framebuffer_binding->Opaque()) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"opaque framebuffer bound");
return;
}
framebuffer_binding->SetAttachmentForBoundFramebuffer(
target, attachment, textarget, texture, level, layer);
ApplyStencilTest();
}
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 | void WebGL2RenderingContextBase::framebufferTextureLayer(GLenum target,
GLenum attachment,
WebGLTexture* texture,
GLint level,
GLint layer) {
if (isContextLost() || !ValidateFramebufferFuncParameters(
"framebufferTextureLayer", target, attachment))
return;
if (texture && !texture->Validate(ContextGroup(), this)) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"texture does not belong to this context");
return;
}
GLenum textarget = texture ? texture->GetTarget() : 0;
if (texture) {
if (textarget != GL_TEXTURE_3D && textarget != GL_TEXTURE_2D_ARRAY) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"invalid texture type");
return;
}
if (!ValidateTexFuncLayer("framebufferTextureLayer", textarget, layer))
return;
if (!ValidateTexFuncLevel("framebufferTextureLayer", textarget, level))
return;
}
WebGLFramebuffer* framebuffer_binding = GetFramebufferBinding(target);
if (!framebuffer_binding || !framebuffer_binding->Object()) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"no framebuffer bound");
return;
}
if (framebuffer_binding && framebuffer_binding->Opaque()) {
SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer",
"opaque framebuffer bound");
return;
}
framebuffer_binding->SetAttachmentForBoundFramebuffer(
target, attachment, textarget, texture, level, layer);
ApplyStencilTest();
}
| 173,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: ikev2_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
const struct ikev2_n *p;
struct ikev2_n n;
const u_char *cp;
u_char showspi, showdata, showsomedata;
const char *notify_name;
uint32_t type;
p = (const struct ikev2_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical);
showspi = 1;
showdata = 0;
showsomedata=0;
notify_name=NULL;
ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id)));
type = ntohs(n.type);
/* notify space is annoying sparse */
switch(type) {
case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD:
notify_name = "unsupported_critical_payload";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_IKE_SPI:
notify_name = "invalid_ike_spi";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MAJOR_VERSION:
notify_name = "invalid_major_version";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SYNTAX:
notify_name = "invalid_syntax";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MESSAGE_ID:
notify_name = "invalid_message_id";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_SPI:
notify_name = "invalid_spi";
showspi = 1;
break;
case IV2_NOTIFY_NO_PROPOSAL_CHOSEN:
notify_name = "no_protocol_chosen";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_KE_PAYLOAD:
notify_name = "invalid_ke_payload";
showspi = 1;
break;
case IV2_NOTIFY_AUTHENTICATION_FAILED:
notify_name = "authentication_failed";
showspi = 1;
break;
case IV2_NOTIFY_SINGLE_PAIR_REQUIRED:
notify_name = "single_pair_required";
showspi = 1;
break;
case IV2_NOTIFY_NO_ADDITIONAL_SAS:
notify_name = "no_additional_sas";
showspi = 0;
break;
case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE:
notify_name = "internal_address_failure";
showspi = 0;
break;
case IV2_NOTIFY_FAILED_CP_REQUIRED:
notify_name = "failed:cp_required";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SELECTORS:
notify_name = "invalid_selectors";
showspi = 0;
break;
case IV2_NOTIFY_INITIAL_CONTACT:
notify_name = "initial_contact";
showspi = 0;
break;
case IV2_NOTIFY_SET_WINDOW_SIZE:
notify_name = "set_window_size";
showspi = 0;
break;
case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE:
notify_name = "additional_ts_possible";
showspi = 0;
break;
case IV2_NOTIFY_IPCOMP_SUPPORTED:
notify_name = "ipcomp_supported";
showspi = 0;
break;
case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP:
notify_name = "nat_detection_source_ip";
showspi = 1;
break;
case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP:
notify_name = "nat_detection_destination_ip";
showspi = 1;
break;
case IV2_NOTIFY_COOKIE:
notify_name = "cookie";
showspi = 1;
showsomedata= 1;
showdata= 0;
break;
case IV2_NOTIFY_USE_TRANSPORT_MODE:
notify_name = "use_transport_mode";
showspi = 0;
break;
case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED:
notify_name = "http_cert_lookup_supported";
showspi = 0;
break;
case IV2_NOTIFY_REKEY_SA:
notify_name = "rekey_sa";
showspi = 1;
break;
case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED:
notify_name = "tfc_padding_not_supported";
showspi = 0;
break;
case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO:
notify_name = "non_first_fragment_also";
showspi = 0;
break;
default:
if (type < 8192) {
notify_name="error";
} else if(type < 16384) {
notify_name="private-error";
} else if(type < 40960) {
notify_name="status";
} else {
notify_name="private-status";
}
}
if(notify_name) {
ND_PRINT((ndo," type=%u(%s)", type, notify_name));
}
if (showspi && n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
if(3 < ndo->ndo_vflag) {
showdata = 1;
}
if ((showdata || (showsomedata && ep-cp < 30)) && cp < ep) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else if(showsomedata && cp < ep) {
if(!ike_show_somedata(ndo, cp, ep)) goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
Commit Message: CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data.
The closest thing to a specification for the contents of the payload
data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it
is ever a complete ISAKMP message, so don't dissect types we don't have
specific code for as a complete ISAKMP message.
While we're at it, fix a comment, and clean up printing of V1 Nonce,
V2 Authentication payloads, and v2 Notice payloads.
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-835 | ikev2_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
const struct ikev2_n *p;
struct ikev2_n n;
const u_char *cp;
u_char showspi, showsomedata;
const char *notify_name;
uint32_t type;
p = (const struct ikev2_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical);
showspi = 1;
showsomedata=0;
notify_name=NULL;
ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id)));
type = ntohs(n.type);
/* notify space is annoying sparse */
switch(type) {
case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD:
notify_name = "unsupported_critical_payload";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_IKE_SPI:
notify_name = "invalid_ike_spi";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MAJOR_VERSION:
notify_name = "invalid_major_version";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SYNTAX:
notify_name = "invalid_syntax";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MESSAGE_ID:
notify_name = "invalid_message_id";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_SPI:
notify_name = "invalid_spi";
showspi = 1;
break;
case IV2_NOTIFY_NO_PROPOSAL_CHOSEN:
notify_name = "no_protocol_chosen";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_KE_PAYLOAD:
notify_name = "invalid_ke_payload";
showspi = 1;
break;
case IV2_NOTIFY_AUTHENTICATION_FAILED:
notify_name = "authentication_failed";
showspi = 1;
break;
case IV2_NOTIFY_SINGLE_PAIR_REQUIRED:
notify_name = "single_pair_required";
showspi = 1;
break;
case IV2_NOTIFY_NO_ADDITIONAL_SAS:
notify_name = "no_additional_sas";
showspi = 0;
break;
case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE:
notify_name = "internal_address_failure";
showspi = 0;
break;
case IV2_NOTIFY_FAILED_CP_REQUIRED:
notify_name = "failed:cp_required";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SELECTORS:
notify_name = "invalid_selectors";
showspi = 0;
break;
case IV2_NOTIFY_INITIAL_CONTACT:
notify_name = "initial_contact";
showspi = 0;
break;
case IV2_NOTIFY_SET_WINDOW_SIZE:
notify_name = "set_window_size";
showspi = 0;
break;
case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE:
notify_name = "additional_ts_possible";
showspi = 0;
break;
case IV2_NOTIFY_IPCOMP_SUPPORTED:
notify_name = "ipcomp_supported";
showspi = 0;
break;
case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP:
notify_name = "nat_detection_source_ip";
showspi = 1;
break;
case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP:
notify_name = "nat_detection_destination_ip";
showspi = 1;
break;
case IV2_NOTIFY_COOKIE:
notify_name = "cookie";
showspi = 1;
showsomedata= 1;
break;
case IV2_NOTIFY_USE_TRANSPORT_MODE:
notify_name = "use_transport_mode";
showspi = 0;
break;
case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED:
notify_name = "http_cert_lookup_supported";
showspi = 0;
break;
case IV2_NOTIFY_REKEY_SA:
notify_name = "rekey_sa";
showspi = 1;
break;
case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED:
notify_name = "tfc_padding_not_supported";
showspi = 0;
break;
case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO:
notify_name = "non_first_fragment_also";
showspi = 0;
break;
default:
if (type < 8192) {
notify_name="error";
} else if(type < 16384) {
notify_name="private-error";
} else if(type < 40960) {
notify_name="status";
} else {
notify_name="private-status";
}
}
if(notify_name) {
ND_PRINT((ndo," type=%u(%s)", type, notify_name));
}
if (showspi && n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
if (cp < ep) {
if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else if (showsomedata) {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
| 167,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: static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
struct btrfs_fs_info *fs_info,
struct btrfs_pending_snapshot *pending)
{
struct btrfs_key key;
struct btrfs_root_item *new_root_item;
struct btrfs_root *tree_root = fs_info->tree_root;
struct btrfs_root *root = pending->root;
struct btrfs_root *parent_root;
struct btrfs_block_rsv *rsv;
struct inode *parent_inode;
struct btrfs_path *path;
struct btrfs_dir_item *dir_item;
struct dentry *parent;
struct dentry *dentry;
struct extent_buffer *tmp;
struct extent_buffer *old;
struct timespec cur_time = CURRENT_TIME;
int ret;
u64 to_reserve = 0;
u64 index = 0;
u64 objectid;
u64 root_flags;
uuid_le new_uuid;
path = btrfs_alloc_path();
if (!path) {
ret = pending->error = -ENOMEM;
goto path_alloc_fail;
}
new_root_item = kmalloc(sizeof(*new_root_item), GFP_NOFS);
if (!new_root_item) {
ret = pending->error = -ENOMEM;
goto root_item_alloc_fail;
}
ret = btrfs_find_free_objectid(tree_root, &objectid);
if (ret) {
pending->error = ret;
goto no_free_objectid;
}
btrfs_reloc_pre_snapshot(trans, pending, &to_reserve);
if (to_reserve > 0) {
ret = btrfs_block_rsv_add(root, &pending->block_rsv,
to_reserve,
BTRFS_RESERVE_NO_FLUSH);
if (ret) {
pending->error = ret;
goto no_free_objectid;
}
}
ret = btrfs_qgroup_inherit(trans, fs_info, root->root_key.objectid,
objectid, pending->inherit);
if (ret) {
pending->error = ret;
goto no_free_objectid;
}
key.objectid = objectid;
key.offset = (u64)-1;
key.type = BTRFS_ROOT_ITEM_KEY;
rsv = trans->block_rsv;
trans->block_rsv = &pending->block_rsv;
dentry = pending->dentry;
parent = dget_parent(dentry);
parent_inode = parent->d_inode;
parent_root = BTRFS_I(parent_inode)->root;
record_root_in_trans(trans, parent_root);
/*
* insert the directory item
*/
ret = btrfs_set_inode_index(parent_inode, &index);
BUG_ON(ret); /* -ENOMEM */
/* check if there is a file/dir which has the same name. */
dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
btrfs_ino(parent_inode),
dentry->d_name.name,
dentry->d_name.len, 0);
if (dir_item != NULL && !IS_ERR(dir_item)) {
pending->error = -EEXIST;
goto fail;
} else if (IS_ERR(dir_item)) {
ret = PTR_ERR(dir_item);
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
btrfs_release_path(path);
/*
* pull in the delayed directory update
* and the delayed inode item
* otherwise we corrupt the FS during
* snapshot
*/
ret = btrfs_run_delayed_items(trans, root);
if (ret) { /* Transaction aborted */
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
record_root_in_trans(trans, root);
btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
btrfs_check_and_init_root_item(new_root_item);
root_flags = btrfs_root_flags(new_root_item);
if (pending->readonly)
root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
else
root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
btrfs_set_root_flags(new_root_item, root_flags);
btrfs_set_root_generation_v2(new_root_item,
trans->transid);
uuid_le_gen(&new_uuid);
memcpy(new_root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
memcpy(new_root_item->parent_uuid, root->root_item.uuid,
BTRFS_UUID_SIZE);
new_root_item->otime.sec = cpu_to_le64(cur_time.tv_sec);
new_root_item->otime.nsec = cpu_to_le32(cur_time.tv_nsec);
btrfs_set_root_otransid(new_root_item, trans->transid);
memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
btrfs_set_root_stransid(new_root_item, 0);
btrfs_set_root_rtransid(new_root_item, 0);
old = btrfs_lock_root_node(root);
ret = btrfs_cow_block(trans, root, old, NULL, 0, &old);
if (ret) {
btrfs_tree_unlock(old);
free_extent_buffer(old);
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
btrfs_set_lock_blocking(old);
ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
/* clean up in any case */
btrfs_tree_unlock(old);
free_extent_buffer(old);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
/* see comments in should_cow_block() */
root->force_cow = 1;
smp_wmb();
btrfs_set_root_node(new_root_item, tmp);
/* record when the snapshot was created in key.offset */
key.offset = trans->transid;
ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
btrfs_tree_unlock(tmp);
free_extent_buffer(tmp);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
/*
* insert root back/forward references
*/
ret = btrfs_add_root_ref(trans, tree_root, objectid,
parent_root->root_key.objectid,
btrfs_ino(parent_inode), index,
dentry->d_name.name, dentry->d_name.len);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
key.offset = (u64)-1;
pending->snap = btrfs_read_fs_root_no_name(root->fs_info, &key);
if (IS_ERR(pending->snap)) {
ret = PTR_ERR(pending->snap);
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
ret = btrfs_reloc_post_snapshot(trans, pending);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
ret = btrfs_insert_dir_item(trans, parent_root,
dentry->d_name.name, dentry->d_name.len,
parent_inode, &key,
BTRFS_FT_DIR, index);
/* We have check then name at the beginning, so it is impossible. */
BUG_ON(ret == -EEXIST);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
btrfs_i_size_write(parent_inode, parent_inode->i_size +
dentry->d_name.len * 2);
parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode);
if (ret)
btrfs_abort_transaction(trans, root, ret);
fail:
dput(parent);
trans->block_rsv = rsv;
no_free_objectid:
kfree(new_root_item);
root_item_alloc_fail:
btrfs_free_path(path);
path_alloc_fail:
btrfs_block_rsv_release(root, &pending->block_rsv, (u64)-1);
return ret;
}
Commit Message: Btrfs: fix hash overflow handling
The handling for directory crc hash overflows was fairly obscure,
split_leaf returns EOVERFLOW when we try to extend the item and that is
supposed to bubble up to userland. For a while it did so, but along the
way we added better handling of errors and forced the FS readonly if we
hit IO errors during the directory insertion.
Along the way, we started testing only for EEXIST and the EOVERFLOW case
was dropped. The end result is that we may force the FS readonly if we
catch a directory hash bucket overflow.
This fixes a few problem spots. First I add tests for EOVERFLOW in the
places where we can safely just return the error up the chain.
btrfs_rename is harder though, because it tries to insert the new
directory item only after it has already unlinked anything the rename
was going to overwrite. Rather than adding very complex logic, I added
a helper to test for the hash overflow case early while it is still safe
to bail out.
Snapshot and subvolume creation had a similar problem, so they are using
the new helper now too.
Signed-off-by: Chris Mason <[email protected]>
Reported-by: Pascal Junod <[email protected]>
CWE ID: CWE-310 | static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
struct btrfs_fs_info *fs_info,
struct btrfs_pending_snapshot *pending)
{
struct btrfs_key key;
struct btrfs_root_item *new_root_item;
struct btrfs_root *tree_root = fs_info->tree_root;
struct btrfs_root *root = pending->root;
struct btrfs_root *parent_root;
struct btrfs_block_rsv *rsv;
struct inode *parent_inode;
struct btrfs_path *path;
struct btrfs_dir_item *dir_item;
struct dentry *parent;
struct dentry *dentry;
struct extent_buffer *tmp;
struct extent_buffer *old;
struct timespec cur_time = CURRENT_TIME;
int ret;
u64 to_reserve = 0;
u64 index = 0;
u64 objectid;
u64 root_flags;
uuid_le new_uuid;
path = btrfs_alloc_path();
if (!path) {
ret = pending->error = -ENOMEM;
goto path_alloc_fail;
}
new_root_item = kmalloc(sizeof(*new_root_item), GFP_NOFS);
if (!new_root_item) {
ret = pending->error = -ENOMEM;
goto root_item_alloc_fail;
}
ret = btrfs_find_free_objectid(tree_root, &objectid);
if (ret) {
pending->error = ret;
goto no_free_objectid;
}
btrfs_reloc_pre_snapshot(trans, pending, &to_reserve);
if (to_reserve > 0) {
ret = btrfs_block_rsv_add(root, &pending->block_rsv,
to_reserve,
BTRFS_RESERVE_NO_FLUSH);
if (ret) {
pending->error = ret;
goto no_free_objectid;
}
}
ret = btrfs_qgroup_inherit(trans, fs_info, root->root_key.objectid,
objectid, pending->inherit);
if (ret) {
pending->error = ret;
goto no_free_objectid;
}
key.objectid = objectid;
key.offset = (u64)-1;
key.type = BTRFS_ROOT_ITEM_KEY;
rsv = trans->block_rsv;
trans->block_rsv = &pending->block_rsv;
dentry = pending->dentry;
parent = dget_parent(dentry);
parent_inode = parent->d_inode;
parent_root = BTRFS_I(parent_inode)->root;
record_root_in_trans(trans, parent_root);
/*
* insert the directory item
*/
ret = btrfs_set_inode_index(parent_inode, &index);
BUG_ON(ret); /* -ENOMEM */
/* check if there is a file/dir which has the same name. */
dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
btrfs_ino(parent_inode),
dentry->d_name.name,
dentry->d_name.len, 0);
if (dir_item != NULL && !IS_ERR(dir_item)) {
pending->error = -EEXIST;
goto fail;
} else if (IS_ERR(dir_item)) {
ret = PTR_ERR(dir_item);
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
btrfs_release_path(path);
/*
* pull in the delayed directory update
* and the delayed inode item
* otherwise we corrupt the FS during
* snapshot
*/
ret = btrfs_run_delayed_items(trans, root);
if (ret) { /* Transaction aborted */
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
record_root_in_trans(trans, root);
btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
btrfs_check_and_init_root_item(new_root_item);
root_flags = btrfs_root_flags(new_root_item);
if (pending->readonly)
root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
else
root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
btrfs_set_root_flags(new_root_item, root_flags);
btrfs_set_root_generation_v2(new_root_item,
trans->transid);
uuid_le_gen(&new_uuid);
memcpy(new_root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
memcpy(new_root_item->parent_uuid, root->root_item.uuid,
BTRFS_UUID_SIZE);
new_root_item->otime.sec = cpu_to_le64(cur_time.tv_sec);
new_root_item->otime.nsec = cpu_to_le32(cur_time.tv_nsec);
btrfs_set_root_otransid(new_root_item, trans->transid);
memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
btrfs_set_root_stransid(new_root_item, 0);
btrfs_set_root_rtransid(new_root_item, 0);
old = btrfs_lock_root_node(root);
ret = btrfs_cow_block(trans, root, old, NULL, 0, &old);
if (ret) {
btrfs_tree_unlock(old);
free_extent_buffer(old);
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
btrfs_set_lock_blocking(old);
ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
/* clean up in any case */
btrfs_tree_unlock(old);
free_extent_buffer(old);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
/* see comments in should_cow_block() */
root->force_cow = 1;
smp_wmb();
btrfs_set_root_node(new_root_item, tmp);
/* record when the snapshot was created in key.offset */
key.offset = trans->transid;
ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
btrfs_tree_unlock(tmp);
free_extent_buffer(tmp);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
/*
* insert root back/forward references
*/
ret = btrfs_add_root_ref(trans, tree_root, objectid,
parent_root->root_key.objectid,
btrfs_ino(parent_inode), index,
dentry->d_name.name, dentry->d_name.len);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
key.offset = (u64)-1;
pending->snap = btrfs_read_fs_root_no_name(root->fs_info, &key);
if (IS_ERR(pending->snap)) {
ret = PTR_ERR(pending->snap);
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
ret = btrfs_reloc_post_snapshot(trans, pending);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
ret = btrfs_insert_dir_item(trans, parent_root,
dentry->d_name.name, dentry->d_name.len,
parent_inode, &key,
BTRFS_FT_DIR, index);
/* We have check then name at the beginning, so it is impossible. */
BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto fail;
}
btrfs_i_size_write(parent_inode, parent_inode->i_size +
dentry->d_name.len * 2);
parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode);
if (ret)
btrfs_abort_transaction(trans, root, ret);
fail:
dput(parent);
trans->block_rsv = rsv;
no_free_objectid:
kfree(new_root_item);
root_item_alloc_fail:
btrfs_free_path(path);
path_alloc_fail:
btrfs_block_rsv_release(root, &pending->block_rsv, (u64)-1);
return ret;
}
| 166,196 |
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 ext4_ext_convert_to_initialized(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path *path)
{
struct ext4_extent *ex, newex, orig_ex;
struct ext4_extent *ex1 = NULL;
struct ext4_extent *ex2 = NULL;
struct ext4_extent *ex3 = NULL;
struct ext4_extent_header *eh;
ext4_lblk_t ee_block, eof_block;
unsigned int allocated, ee_len, depth;
ext4_fsblk_t newblock;
int err = 0;
int ret = 0;
int may_zeroout;
ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)map->m_lblk, map->m_len);
eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map->m_len)
eof_block = map->m_lblk + map->m_len;
depth = ext_depth(inode);
eh = path[depth].p_hdr;
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
allocated = ee_len - (map->m_lblk - ee_block);
newblock = map->m_lblk - ee_block + ext4_ext_pblock(ex);
ex2 = ex;
orig_ex.ee_block = ex->ee_block;
orig_ex.ee_len = cpu_to_le16(ee_len);
ext4_ext_store_pblock(&orig_ex, ext4_ext_pblock(ex));
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully insde i_size or new_size.
*/
may_zeroout = ee_block + ee_len <= eof_block;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
/* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
if (ee_len <= 2*EXT4_EXT_ZERO_LEN && may_zeroout) {
err = ext4_ext_zeroout(inode, &orig_ex);
if (err)
goto fix_extent_len;
/* update the extent length and mark as initialized */
ex->ee_block = orig_ex.ee_block;
ex->ee_len = orig_ex.ee_len;
ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
ext4_ext_dirty(handle, inode, path + depth);
/* zeroed the full extent */
return allocated;
}
/* ex1: ee_block to map->m_lblk - 1 : uninitialized */
if (map->m_lblk > ee_block) {
ex1 = ex;
ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block);
ext4_ext_mark_uninitialized(ex1);
ex2 = &newex;
}
/*
* for sanity, update the length of the ex2 extent before
* we insert ex3, if ex1 is NULL. This is to avoid temporary
* overlap of blocks.
*/
if (!ex1 && allocated > map->m_len)
ex2->ee_len = cpu_to_le16(map->m_len);
/* ex3: to ee_block + ee_len : uninitialised */
if (allocated > map->m_len) {
unsigned int newdepth;
/* If extent has less than EXT4_EXT_ZERO_LEN zerout directly */
if (allocated <= EXT4_EXT_ZERO_LEN && may_zeroout) {
/*
* map->m_lblk == ee_block is handled by the zerouout
* at the beginning.
* Mark first half uninitialized.
* Mark second half initialized and zero out the
* initialized extent
*/
ex->ee_block = orig_ex.ee_block;
ex->ee_len = cpu_to_le16(ee_len - allocated);
ext4_ext_mark_uninitialized(ex);
ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
ext4_ext_dirty(handle, inode, path + depth);
ex3 = &newex;
ex3->ee_block = cpu_to_le32(map->m_lblk);
ext4_ext_store_pblock(ex3, newblock);
ex3->ee_len = cpu_to_le16(allocated);
err = ext4_ext_insert_extent(handle, inode, path,
ex3, 0);
if (err == -ENOSPC) {
err = ext4_ext_zeroout(inode, &orig_ex);
if (err)
goto fix_extent_len;
ex->ee_block = orig_ex.ee_block;
ex->ee_len = orig_ex.ee_len;
ext4_ext_store_pblock(ex,
ext4_ext_pblock(&orig_ex));
ext4_ext_dirty(handle, inode, path + depth);
/* blocks available from map->m_lblk */
return allocated;
} else if (err)
goto fix_extent_len;
/*
* We need to zero out the second half because
* an fallocate request can update file size and
* converting the second half to initialized extent
* implies that we can leak some junk data to user
* space.
*/
err = ext4_ext_zeroout(inode, ex3);
if (err) {
/*
* We should actually mark the
* second half as uninit and return error
* Insert would have changed the extent
*/
depth = ext_depth(inode);
ext4_ext_drop_refs(path);
path = ext4_ext_find_extent(inode, map->m_lblk,
path);
if (IS_ERR(path)) {
err = PTR_ERR(path);
return err;
}
/* get the second half extent details */
ex = path[depth].p_ext;
err = ext4_ext_get_access(handle, inode,
path + depth);
if (err)
return err;
ext4_ext_mark_uninitialized(ex);
ext4_ext_dirty(handle, inode, path + depth);
return err;
}
/* zeroed the second half */
return allocated;
}
ex3 = &newex;
ex3->ee_block = cpu_to_le32(map->m_lblk + map->m_len);
ext4_ext_store_pblock(ex3, newblock + map->m_len);
ex3->ee_len = cpu_to_le16(allocated - map->m_len);
ext4_ext_mark_uninitialized(ex3);
err = ext4_ext_insert_extent(handle, inode, path, ex3, 0);
if (err == -ENOSPC && may_zeroout) {
err = ext4_ext_zeroout(inode, &orig_ex);
if (err)
goto fix_extent_len;
/* update the extent length and mark as initialized */
ex->ee_block = orig_ex.ee_block;
ex->ee_len = orig_ex.ee_len;
ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
ext4_ext_dirty(handle, inode, path + depth);
/* zeroed the full extent */
/* blocks available from map->m_lblk */
return allocated;
} else if (err)
goto fix_extent_len;
/*
* The depth, and hence eh & ex might change
* as part of the insert above.
*/
newdepth = ext_depth(inode);
/*
* update the extent length after successful insert of the
* split extent
*/
ee_len -= ext4_ext_get_actual_len(ex3);
orig_ex.ee_len = cpu_to_le16(ee_len);
may_zeroout = ee_block + ee_len <= eof_block;
depth = newdepth;
ext4_ext_drop_refs(path);
path = ext4_ext_find_extent(inode, map->m_lblk, path);
if (IS_ERR(path)) {
err = PTR_ERR(path);
goto out;
}
eh = path[depth].p_hdr;
ex = path[depth].p_ext;
if (ex2 != &newex)
ex2 = ex;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
allocated = map->m_len;
/* If extent has less than EXT4_EXT_ZERO_LEN and we are trying
* to insert a extent in the middle zerout directly
* otherwise give the extent a chance to merge to left
*/
if (le16_to_cpu(orig_ex.ee_len) <= EXT4_EXT_ZERO_LEN &&
map->m_lblk != ee_block && may_zeroout) {
err = ext4_ext_zeroout(inode, &orig_ex);
if (err)
goto fix_extent_len;
/* update the extent length and mark as initialized */
ex->ee_block = orig_ex.ee_block;
ex->ee_len = orig_ex.ee_len;
ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
ext4_ext_dirty(handle, inode, path + depth);
/* zero out the first half */
/* blocks available from map->m_lblk */
return allocated;
}
}
/*
* If there was a change of depth as part of the
* insertion of ex3 above, we need to update the length
* of the ex1 extent again here
*/
if (ex1 && ex1 != ex) {
ex1 = ex;
ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block);
ext4_ext_mark_uninitialized(ex1);
ex2 = &newex;
}
/* ex2: map->m_lblk to map->m_lblk + maxblocks-1 : initialised */
ex2->ee_block = cpu_to_le32(map->m_lblk);
ext4_ext_store_pblock(ex2, newblock);
ex2->ee_len = cpu_to_le16(allocated);
if (ex2 != ex)
goto insert;
/*
* New (initialized) extent starts from the first block
* in the current extent. i.e., ex2 == ex
* We have to see if it can be merged with the extent
* on the left.
*/
if (ex2 > EXT_FIRST_EXTENT(eh)) {
/*
* To merge left, pass "ex2 - 1" to try_to_merge(),
* since it merges towards right _only_.
*/
ret = ext4_ext_try_to_merge(inode, path, ex2 - 1);
if (ret) {
err = ext4_ext_correct_indexes(handle, inode, path);
if (err)
goto out;
depth = ext_depth(inode);
ex2--;
}
}
/*
* Try to Merge towards right. This might be required
* only when the whole extent is being written to.
* i.e. ex2 == ex and ex3 == NULL.
*/
if (!ex3) {
ret = ext4_ext_try_to_merge(inode, path, ex2);
if (ret) {
err = ext4_ext_correct_indexes(handle, inode, path);
if (err)
goto out;
}
}
/* Mark modified extent as dirty */
err = ext4_ext_dirty(handle, inode, path + depth);
goto out;
insert:
err = ext4_ext_insert_extent(handle, inode, path, &newex, 0);
if (err == -ENOSPC && may_zeroout) {
err = ext4_ext_zeroout(inode, &orig_ex);
if (err)
goto fix_extent_len;
/* update the extent length and mark as initialized */
ex->ee_block = orig_ex.ee_block;
ex->ee_len = orig_ex.ee_len;
ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
ext4_ext_dirty(handle, inode, path + depth);
/* zero out the first half */
return allocated;
} else if (err)
goto fix_extent_len;
out:
ext4_ext_show_leaf(inode, path);
return err ? err : allocated;
fix_extent_len:
ex->ee_block = orig_ex.ee_block;
ex->ee_len = orig_ex.ee_len;
ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex));
ext4_ext_mark_uninitialized(ex);
ext4_ext_dirty(handle, inode, path + depth);
return err;
}
Commit Message: ext4: reimplement convert and split_unwritten
Reimplement ext4_ext_convert_to_initialized() and
ext4_split_unwritten_extents() using ext4_split_extent()
Signed-off-by: Yongqiang Yang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Tested-by: Allison Henderson <[email protected]>
CWE ID: | static int ext4_ext_convert_to_initialized(handle_t *handle,
struct inode *inode,
struct ext4_map_blocks *map,
struct ext4_ext_path *path)
{
struct ext4_map_blocks split_map;
struct ext4_extent zero_ex;
struct ext4_extent *ex;
ext4_lblk_t ee_block, eof_block;
unsigned int allocated, ee_len, depth;
int err = 0;
int split_flag = 0;
ext_debug("ext4_ext_convert_to_initialized: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)map->m_lblk, map->m_len);
eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>
inode->i_sb->s_blocksize_bits;
if (eof_block < map->m_lblk + map->m_len)
eof_block = map->m_lblk + map->m_len;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
allocated = ee_len - (map->m_lblk - ee_block);
WARN_ON(map->m_lblk < ee_block);
/*
* It is safe to convert extent to initialized via explicit
* zeroout only if extent is fully insde i_size or new_size.
*/
split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;
/* If extent has less than 2*EXT4_EXT_ZERO_LEN zerout directly */
if (ee_len <= 2*EXT4_EXT_ZERO_LEN &&
(EXT4_EXT_MAY_ZEROOUT & split_flag)) {
err = ext4_ext_zeroout(inode, ex);
if (err)
goto out;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
ext4_ext_mark_initialized(ex);
ext4_ext_try_to_merge(inode, path, ex);
err = ext4_ext_dirty(handle, inode, path + depth);
goto out;
}
/*
* four cases:
* 1. split the extent into three extents.
* 2. split the extent into two extents, zeroout the first half.
* 3. split the extent into two extents, zeroout the second half.
* 4. split the extent into two extents with out zeroout.
*/
split_map.m_lblk = map->m_lblk;
split_map.m_len = map->m_len;
if (allocated > map->m_len) {
if (allocated <= EXT4_EXT_ZERO_LEN &&
(EXT4_EXT_MAY_ZEROOUT & split_flag)) {
/* case 3 */
zero_ex.ee_block =
cpu_to_le32(map->m_lblk + map->m_len);
zero_ex.ee_len = cpu_to_le16(allocated - map->m_len);
ext4_ext_store_pblock(&zero_ex,
ext4_ext_pblock(ex) + map->m_lblk - ee_block);
err = ext4_ext_zeroout(inode, &zero_ex);
if (err)
goto out;
split_map.m_lblk = map->m_lblk;
split_map.m_len = allocated;
} else if ((map->m_lblk - ee_block + map->m_len <
EXT4_EXT_ZERO_LEN) &&
(EXT4_EXT_MAY_ZEROOUT & split_flag)) {
/* case 2 */
if (map->m_lblk != ee_block) {
zero_ex.ee_block = ex->ee_block;
zero_ex.ee_len = cpu_to_le16(map->m_lblk -
ee_block);
ext4_ext_store_pblock(&zero_ex,
ext4_ext_pblock(ex));
err = ext4_ext_zeroout(inode, &zero_ex);
if (err)
goto out;
}
allocated = map->m_lblk - ee_block + map->m_len;
split_map.m_lblk = ee_block;
split_map.m_len = allocated;
}
}
allocated = ext4_split_extent(handle, inode, path,
&split_map, split_flag, 0);
if (allocated < 0)
err = allocated;
out:
return err ? err : allocated;
}
| 166,217 |
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 WebGL2RenderingContextBase::texImage3D(GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLsizei depth,
GLint border,
GLenum format,
GLenum type,
GLintptr offset) {
if (isContextLost())
return;
if (!ValidateTexture3DBinding("texImage3D", target))
return;
if (!bound_pixel_unpack_buffer_) {
SynthesizeGLError(GL_INVALID_OPERATION, "texImage3D",
"no bound PIXEL_UNPACK_BUFFER");
return;
}
if (!ValidateTexFunc("texImage3D", kTexImage, kSourceUnpackBuffer, target,
level, internalformat, width, height, depth, border,
format, type, 0, 0, 0))
return;
if (!ValidateValueFitNonNegInt32("texImage3D", "offset", offset))
return;
ContextGL()->TexImage3D(target, level,
ConvertTexInternalFormat(internalformat, type), width,
height, depth, border, format, type,
reinterpret_cast<const void*>(offset));
}
Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA.
BUG=774174
TEST=https://github.com/KhronosGroup/WebGL/pull/2555
[email protected]
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I4f4e7636314502451104730501a5048a5d7b9f3f
Reviewed-on: https://chromium-review.googlesource.com/808665
Commit-Queue: Zhenyao Mo <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522003}
CWE ID: CWE-125 | void WebGL2RenderingContextBase::texImage3D(GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLsizei depth,
GLint border,
GLenum format,
GLenum type,
GLintptr offset) {
if (isContextLost())
return;
if (!ValidateTexture3DBinding("texImage3D", target))
return;
if (!bound_pixel_unpack_buffer_) {
SynthesizeGLError(GL_INVALID_OPERATION, "texImage3D",
"no bound PIXEL_UNPACK_BUFFER");
return;
}
if (unpack_flip_y_ || unpack_premultiply_alpha_) {
SynthesizeGLError(
GL_INVALID_OPERATION, "texImage3D",
"FLIP_Y or PREMULTIPLY_ALPHA isn't allowed for uploading 3D textures");
return;
}
if (!ValidateTexFunc("texImage3D", kTexImage, kSourceUnpackBuffer, target,
level, internalformat, width, height, depth, border,
format, type, 0, 0, 0))
return;
if (!ValidateValueFitNonNegInt32("texImage3D", "offset", offset))
return;
ContextGL()->TexImage3D(target, level,
ConvertTexInternalFormat(internalformat, type), width,
height, depth, border, format, type,
reinterpret_cast<const void*>(offset));
}
| 172,677 |
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 jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps)
{
int i;
int j;
int thresh;
jpc_fix_t val;
jpc_fix_t mag;
bool warn;
uint_fast32_t mask;
if (roishift == 0 && bgshift == 0) {
return;
}
thresh = 1 << roishift;
warn = false;
for (i = 0; i < jas_matrix_numrows(x); ++i) {
for (j = 0; j < jas_matrix_numcols(x); ++j) {
val = jas_matrix_get(x, i, j);
mag = JAS_ABS(val);
if (mag >= thresh) {
/* We are dealing with ROI data. */
mag >>= roishift;
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
} else {
/* We are dealing with non-ROI (i.e., background) data. */
mag <<= bgshift;
mask = (1 << numbps) - 1;
/* Perform a basic sanity check on the sample value. */
/* Some implementations write garbage in the unused
most-significant bit planes introduced by ROI shifting.
Here we ensure that any such bits are masked off. */
if (mag & (~mask)) {
if (!warn) {
jas_eprintf("warning: possibly corrupt code stream\n");
warn = true;
}
mag &= mask;
}
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
}
}
}
}
Commit Message: Fixed an integral type promotion problem by adding a JAS_CAST.
Modified the jpc_tsfb_synthesize function so that it will be a noop for
an empty sequence (in order to avoid dereferencing a null pointer).
CWE ID: CWE-476 | static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps)
{
int i;
int j;
int thresh;
jpc_fix_t val;
jpc_fix_t mag;
bool warn;
uint_fast32_t mask;
if (roishift < 0) {
/* We could instead return an error here. */
/* I do not think it matters much. */
jas_eprintf("warning: forcing negative ROI shift to zero "
"(bitstream is probably corrupt)\n");
roishift = 0;
}
if (roishift == 0 && bgshift == 0) {
return;
}
thresh = 1 << roishift;
warn = false;
for (i = 0; i < jas_matrix_numrows(x); ++i) {
for (j = 0; j < jas_matrix_numcols(x); ++j) {
val = jas_matrix_get(x, i, j);
mag = JAS_ABS(val);
if (mag >= thresh) {
/* We are dealing with ROI data. */
mag >>= roishift;
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
} else {
/* We are dealing with non-ROI (i.e., background) data. */
mag <<= bgshift;
mask = (JAS_CAST(uint_fast32_t, 1) << numbps) - 1;
/* Perform a basic sanity check on the sample value. */
/* Some implementations write garbage in the unused
most-significant bit planes introduced by ROI shifting.
Here we ensure that any such bits are masked off. */
if (mag & (~mask)) {
if (!warn) {
jas_eprintf("warning: possibly corrupt code stream\n");
warn = true;
}
mag &= mask;
}
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
}
}
}
}
| 168,477 |
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 shmem_remount_fs(struct super_block *sb, int *flags, char *data)
{
struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
struct shmem_sb_info config = *sbinfo;
unsigned long inodes;
int error = -EINVAL;
if (shmem_parse_options(data, &config, true))
return error;
spin_lock(&sbinfo->stat_lock);
inodes = sbinfo->max_inodes - sbinfo->free_inodes;
if (percpu_counter_compare(&sbinfo->used_blocks, config.max_blocks) > 0)
goto out;
if (config.max_inodes < inodes)
goto out;
/*
* Those tests disallow limited->unlimited while any are in use;
* but we must separately disallow unlimited->limited, because
* in that case we have no record of how much is already in use.
*/
if (config.max_blocks && !sbinfo->max_blocks)
goto out;
if (config.max_inodes && !sbinfo->max_inodes)
goto out;
error = 0;
sbinfo->max_blocks = config.max_blocks;
sbinfo->max_inodes = config.max_inodes;
sbinfo->free_inodes = config.max_inodes - inodes;
mpol_put(sbinfo->mpol);
sbinfo->mpol = config.mpol; /* transfers initial ref */
out:
spin_unlock(&sbinfo->stat_lock);
return error;
}
Commit Message: tmpfs: fix use-after-free of mempolicy object
The tmpfs remount logic preserves filesystem mempolicy if the mpol=M
option is not specified in the remount request. A new policy can be
specified if mpol=M is given.
Before this patch remounting an mpol bound tmpfs without specifying
mpol= mount option in the remount request would set the filesystem's
mempolicy object to a freed mempolicy object.
To reproduce the problem boot a DEBUG_PAGEALLOC kernel and run:
# mkdir /tmp/x
# mount -t tmpfs -o size=100M,mpol=interleave nodev /tmp/x
# grep /tmp/x /proc/mounts
nodev /tmp/x tmpfs rw,relatime,size=102400k,mpol=interleave:0-3 0 0
# mount -o remount,size=200M nodev /tmp/x
# grep /tmp/x /proc/mounts
nodev /tmp/x tmpfs rw,relatime,size=204800k,mpol=??? 0 0
# note ? garbage in mpol=... output above
# dd if=/dev/zero of=/tmp/x/f count=1
# panic here
Panic:
BUG: unable to handle kernel NULL pointer dereference at (null)
IP: [< (null)>] (null)
[...]
Oops: 0010 [#1] SMP DEBUG_PAGEALLOC
Call Trace:
mpol_shared_policy_init+0xa5/0x160
shmem_get_inode+0x209/0x270
shmem_mknod+0x3e/0xf0
shmem_create+0x18/0x20
vfs_create+0xb5/0x130
do_last+0x9a1/0xea0
path_openat+0xb3/0x4d0
do_filp_open+0x42/0xa0
do_sys_open+0xfe/0x1e0
compat_sys_open+0x1b/0x20
cstar_dispatch+0x7/0x1f
Non-debug kernels will not crash immediately because referencing the
dangling mpol will not cause a fault. Instead the filesystem will
reference a freed mempolicy object, which will cause unpredictable
behavior.
The problem boils down to a dropped mpol reference below if
shmem_parse_options() does not allocate a new mpol:
config = *sbinfo
shmem_parse_options(data, &config, true)
mpol_put(sbinfo->mpol)
sbinfo->mpol = config.mpol /* BUG: saves unreferenced mpol */
This patch avoids the crash by not releasing the mempolicy if
shmem_parse_options() doesn't create a new mpol.
How far back does this issue go? I see it in both 2.6.36 and 3.3. I did
not look back further.
Signed-off-by: Greg Thelen <[email protected]>
Acked-by: Hugh Dickins <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399 | static int shmem_remount_fs(struct super_block *sb, int *flags, char *data)
{
struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
struct shmem_sb_info config = *sbinfo;
unsigned long inodes;
int error = -EINVAL;
config.mpol = NULL;
if (shmem_parse_options(data, &config, true))
return error;
spin_lock(&sbinfo->stat_lock);
inodes = sbinfo->max_inodes - sbinfo->free_inodes;
if (percpu_counter_compare(&sbinfo->used_blocks, config.max_blocks) > 0)
goto out;
if (config.max_inodes < inodes)
goto out;
/*
* Those tests disallow limited->unlimited while any are in use;
* but we must separately disallow unlimited->limited, because
* in that case we have no record of how much is already in use.
*/
if (config.max_blocks && !sbinfo->max_blocks)
goto out;
if (config.max_inodes && !sbinfo->max_inodes)
goto out;
error = 0;
sbinfo->max_blocks = config.max_blocks;
sbinfo->max_inodes = config.max_inodes;
sbinfo->free_inodes = config.max_inodes - inodes;
/*
* Preserve previous mempolicy unless mpol remount option was specified.
*/
if (config.mpol) {
mpol_put(sbinfo->mpol);
sbinfo->mpol = config.mpol; /* transfers initial ref */
}
out:
spin_unlock(&sbinfo->stat_lock);
return error;
}
| 166,127 |
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 _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor)
{
const gdFixed f_127 = gd_itofx(127);
register int c = src->tpixels[y][x];
c = c | (( (int) (gd_fxtof(gd_mulfx(coverage, f_127)) + 50.5f)) << 24);
return _color_blend(bgColor, c);
}
Commit Message: Fixed bug #72227: imagescale out-of-bounds read
Ported from https://github.com/libgd/libgd/commit/4f65a3e4eedaffa1efcf9ee1eb08f0b504fbc31a
CWE ID: CWE-125 | static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor)
static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor)
{
const gdFixed f_127 = gd_itofx(127);
register int c = src->tpixels[y][x];
c = c | (( (int) (gd_fxtof(gd_mulfx(coverage, f_127)) + 50.5f)) << 24);
return _color_blend(bgColor, c);
}
| 170,005 |
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 wdm_read
(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
{
int rv, cntr;
int i = 0;
struct wdm_device *desc = file->private_data;
rv = mutex_lock_interruptible(&desc->rlock); /*concurrent reads */
if (rv < 0)
return -ERESTARTSYS;
cntr = ACCESS_ONCE(desc->length);
if (cntr == 0) {
desc->read = 0;
retry:
if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
rv = -ENODEV;
goto err;
}
i++;
if (file->f_flags & O_NONBLOCK) {
if (!test_bit(WDM_READ, &desc->flags)) {
rv = cntr ? cntr : -EAGAIN;
goto err;
}
rv = 0;
} else {
rv = wait_event_interruptible(desc->wait,
test_bit(WDM_READ, &desc->flags));
}
/* may have happened while we slept */
if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
rv = -ENODEV;
goto err;
}
if (test_bit(WDM_RESETTING, &desc->flags)) {
rv = -EIO;
goto err;
}
usb_mark_last_busy(interface_to_usbdev(desc->intf));
if (rv < 0) {
rv = -ERESTARTSYS;
goto err;
}
spin_lock_irq(&desc->iuspin);
if (desc->rerr) { /* read completed, error happened */
desc->rerr = 0;
spin_unlock_irq(&desc->iuspin);
rv = -EIO;
goto err;
}
/*
* recheck whether we've lost the race
* against the completion handler
*/
if (!test_bit(WDM_READ, &desc->flags)) { /* lost race */
spin_unlock_irq(&desc->iuspin);
goto retry;
}
if (!desc->reslength) { /* zero length read */
dev_dbg(&desc->intf->dev, "%s: zero length - clearing WDM_READ\n", __func__);
clear_bit(WDM_READ, &desc->flags);
spin_unlock_irq(&desc->iuspin);
goto retry;
}
cntr = desc->length;
spin_unlock_irq(&desc->iuspin);
}
if (cntr > count)
cntr = count;
rv = copy_to_user(buffer, desc->ubuf, cntr);
if (rv > 0) {
rv = -EFAULT;
goto err;
}
spin_lock_irq(&desc->iuspin);
for (i = 0; i < desc->length - cntr; i++)
desc->ubuf[i] = desc->ubuf[i + cntr];
desc->length -= cntr;
/* in case we had outstanding data */
if (!desc->length)
clear_bit(WDM_READ, &desc->flags);
spin_unlock_irq(&desc->iuspin);
rv = cntr;
err:
mutex_unlock(&desc->rlock);
return rv;
}
Commit Message: USB: cdc-wdm: fix buffer overflow
The buffer for responses must not overflow.
If this would happen, set a flag, drop the data and return
an error after user space has read all remaining data.
Signed-off-by: Oliver Neukum <[email protected]>
CC: [email protected]
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-119 | static ssize_t wdm_read
(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
{
int rv, cntr;
int i = 0;
struct wdm_device *desc = file->private_data;
rv = mutex_lock_interruptible(&desc->rlock); /*concurrent reads */
if (rv < 0)
return -ERESTARTSYS;
cntr = ACCESS_ONCE(desc->length);
if (cntr == 0) {
desc->read = 0;
retry:
if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
rv = -ENODEV;
goto err;
}
if (test_bit(WDM_OVERFLOW, &desc->flags)) {
clear_bit(WDM_OVERFLOW, &desc->flags);
rv = -ENOBUFS;
goto err;
}
i++;
if (file->f_flags & O_NONBLOCK) {
if (!test_bit(WDM_READ, &desc->flags)) {
rv = cntr ? cntr : -EAGAIN;
goto err;
}
rv = 0;
} else {
rv = wait_event_interruptible(desc->wait,
test_bit(WDM_READ, &desc->flags));
}
/* may have happened while we slept */
if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
rv = -ENODEV;
goto err;
}
if (test_bit(WDM_RESETTING, &desc->flags)) {
rv = -EIO;
goto err;
}
usb_mark_last_busy(interface_to_usbdev(desc->intf));
if (rv < 0) {
rv = -ERESTARTSYS;
goto err;
}
spin_lock_irq(&desc->iuspin);
if (desc->rerr) { /* read completed, error happened */
desc->rerr = 0;
spin_unlock_irq(&desc->iuspin);
rv = -EIO;
goto err;
}
/*
* recheck whether we've lost the race
* against the completion handler
*/
if (!test_bit(WDM_READ, &desc->flags)) { /* lost race */
spin_unlock_irq(&desc->iuspin);
goto retry;
}
if (!desc->reslength) { /* zero length read */
dev_dbg(&desc->intf->dev, "%s: zero length - clearing WDM_READ\n", __func__);
clear_bit(WDM_READ, &desc->flags);
spin_unlock_irq(&desc->iuspin);
goto retry;
}
cntr = desc->length;
spin_unlock_irq(&desc->iuspin);
}
if (cntr > count)
cntr = count;
rv = copy_to_user(buffer, desc->ubuf, cntr);
if (rv > 0) {
rv = -EFAULT;
goto err;
}
spin_lock_irq(&desc->iuspin);
for (i = 0; i < desc->length - cntr; i++)
desc->ubuf[i] = desc->ubuf[i + cntr];
desc->length -= cntr;
/* in case we had outstanding data */
if (!desc->length)
clear_bit(WDM_READ, &desc->flags);
spin_unlock_irq(&desc->iuspin);
rv = cntr;
err:
mutex_unlock(&desc->rlock);
return rv;
}
| 166,105 |
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: PP_Bool StartPpapiProxy(PP_Instance instance) {
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClIPCProxy)) {
ChannelHandleMap& map = g_channel_handle_map.Get();
ChannelHandleMap::iterator it = map.find(instance);
if (it == map.end())
return PP_FALSE;
IPC::ChannelHandle channel_handle = it->second;
map.erase(it);
webkit::ppapi::PluginInstance* plugin_instance =
content::GetHostGlobals()->GetInstance(instance);
if (!plugin_instance)
return PP_FALSE;
WebView* web_view =
plugin_instance->container()->element().document().frame()->view();
RenderView* render_view = content::RenderView::FromWebView(web_view);
webkit::ppapi::PluginModule* plugin_module = plugin_instance->module();
scoped_refptr<SyncMessageStatusReceiver>
status_receiver(new SyncMessageStatusReceiver());
scoped_ptr<OutOfProcessProxy> out_of_process_proxy(new OutOfProcessProxy);
if (out_of_process_proxy->Init(
channel_handle,
plugin_module->pp_module(),
webkit::ppapi::PluginModule::GetLocalGetInterfaceFunc(),
ppapi::Preferences(render_view->GetWebkitPreferences()),
status_receiver.get())) {
plugin_module->InitAsProxiedNaCl(
out_of_process_proxy.PassAs<PluginDelegate::OutOfProcessProxy>(),
instance);
return PP_TRUE;
}
}
return PP_FALSE;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | PP_Bool StartPpapiProxy(PP_Instance instance) {
return PP_FALSE;
}
| 170,739 |
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 ip_options_get_from_user(struct net *net, struct ip_options **optp,
unsigned char __user *data, int optlen)
{
struct ip_options *opt = ip_options_get_alloc(optlen);
if (!opt)
return -ENOMEM;
if (optlen && copy_from_user(opt->__data, data, optlen)) {
kfree(opt);
return -EFAULT;
}
return ip_options_get_finish(net, optp, opt, optlen);
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | int ip_options_get_from_user(struct net *net, struct ip_options **optp,
int ip_options_get_from_user(struct net *net, struct ip_options_rcu **optp,
unsigned char __user *data, int optlen)
{
struct ip_options_rcu *opt = ip_options_get_alloc(optlen);
if (!opt)
return -ENOMEM;
if (optlen && copy_from_user(opt->opt.__data, data, optlen)) {
kfree(opt);
return -EFAULT;
}
return ip_options_get_finish(net, optp, opt, optlen);
}
| 165,561 |
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 propagate_mnt(struct mount *dest_mnt, struct dentry *dest_dentry,
struct mount *source_mnt, struct list_head *tree_list)
{
struct mount *m, *child;
int ret = 0;
struct mount *prev_dest_mnt = dest_mnt;
struct mount *prev_src_mnt = source_mnt;
LIST_HEAD(tmp_list);
LIST_HEAD(umount_list);
for (m = propagation_next(dest_mnt, dest_mnt); m;
m = propagation_next(m, dest_mnt)) {
int type;
struct mount *source;
if (IS_MNT_NEW(m))
continue;
source = get_source(m, prev_dest_mnt, prev_src_mnt, &type);
child = copy_tree(source, source->mnt.mnt_root, type);
if (IS_ERR(child)) {
ret = PTR_ERR(child);
list_splice(tree_list, tmp_list.prev);
goto out;
}
if (is_subdir(dest_dentry, m->mnt.mnt_root)) {
mnt_set_mountpoint(m, dest_dentry, child);
list_add_tail(&child->mnt_hash, tree_list);
} else {
/*
* This can happen if the parent mount was bind mounted
* on some subdirectory of a shared/slave mount.
*/
list_add_tail(&child->mnt_hash, &tmp_list);
}
prev_dest_mnt = m;
prev_src_mnt = child;
}
out:
br_write_lock(&vfsmount_lock);
while (!list_empty(&tmp_list)) {
child = list_first_entry(&tmp_list, struct mount, mnt_hash);
umount_tree(child, 0, &umount_list);
}
br_write_unlock(&vfsmount_lock);
release_mounts(&umount_list);
return ret;
}
Commit Message: vfs: Carefully propogate mounts across user namespaces
As a matter of policy MNT_READONLY should not be changable if the
original mounter had more privileges than creator of the mount
namespace.
Add the flag CL_UNPRIVILEGED to note when we are copying a mount from
a mount namespace that requires more privileges to a mount namespace
that requires fewer privileges.
When the CL_UNPRIVILEGED flag is set cause clone_mnt to set MNT_NO_REMOUNT
if any of the mnt flags that should never be changed are set.
This protects both mount propagation and the initial creation of a less
privileged mount namespace.
Cc: [email protected]
Acked-by: Serge Hallyn <[email protected]>
Reported-by: Andy Lutomirski <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-264 | int propagate_mnt(struct mount *dest_mnt, struct dentry *dest_dentry,
struct mount *source_mnt, struct list_head *tree_list)
{
struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns;
struct mount *m, *child;
int ret = 0;
struct mount *prev_dest_mnt = dest_mnt;
struct mount *prev_src_mnt = source_mnt;
LIST_HEAD(tmp_list);
LIST_HEAD(umount_list);
for (m = propagation_next(dest_mnt, dest_mnt); m;
m = propagation_next(m, dest_mnt)) {
int type;
struct mount *source;
if (IS_MNT_NEW(m))
continue;
source = get_source(m, prev_dest_mnt, prev_src_mnt, &type);
/* Notice when we are propagating across user namespaces */
if (m->mnt_ns->user_ns != user_ns)
type |= CL_UNPRIVILEGED;
child = copy_tree(source, source->mnt.mnt_root, type);
if (IS_ERR(child)) {
ret = PTR_ERR(child);
list_splice(tree_list, tmp_list.prev);
goto out;
}
if (is_subdir(dest_dentry, m->mnt.mnt_root)) {
mnt_set_mountpoint(m, dest_dentry, child);
list_add_tail(&child->mnt_hash, tree_list);
} else {
/*
* This can happen if the parent mount was bind mounted
* on some subdirectory of a shared/slave mount.
*/
list_add_tail(&child->mnt_hash, &tmp_list);
}
prev_dest_mnt = m;
prev_src_mnt = child;
}
out:
br_write_lock(&vfsmount_lock);
while (!list_empty(&tmp_list)) {
child = list_first_entry(&tmp_list, struct mount, mnt_hash);
umount_tree(child, 0, &umount_list);
}
br_write_unlock(&vfsmount_lock);
release_mounts(&umount_list);
return ret;
}
| 166,096 |
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 *ReadPALMImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
totalOffset,
seekNextDepth;
MagickPixelPacket
transpix;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
size_t
bytes_per_row,
flags,
bits_per_pixel,
version,
nextDepthOffset,
transparentIndex,
compressionType,
byte,
mask,
redbits,
greenbits,
bluebits,
one,
pad,
size,
bit;
ssize_t
count,
y;
unsigned char
*lastrow,
*one_row,
*ptr;
unsigned short
color16;
/*
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)
{
(void) DestroyImageList(image);
return((Image *) NULL);
}
totalOffset=0;
do
{
image->columns=ReadBlobMSBShort(image);
image->rows=ReadBlobMSBShort(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
bytes_per_row=ReadBlobMSBShort(image);
flags=ReadBlobMSBShort(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
if ((bits_per_pixel != 1) && (bits_per_pixel != 2) &&
(bits_per_pixel != 4) && (bits_per_pixel != 8) &&
(bits_per_pixel != 16))
ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
version=(size_t) ReadBlobByte(image);
if ((version != 0) && (version != 1) && (version != 2))
ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch");
nextDepthOffset=(size_t) ReadBlobMSBShort(image);
transparentIndex=(size_t) ReadBlobByte(image);
compressionType=(size_t) ReadBlobByte(image);
if ((compressionType != PALM_COMPRESSION_NONE) &&
(compressionType != PALM_COMPRESSION_SCANLINE ) &&
(compressionType != PALM_COMPRESSION_RLE))
ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
pad=ReadBlobMSBShort(image);
(void) pad;
/*
Initialize image colormap.
*/
one=1;
if ((bits_per_pixel < 16) &&
(AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetMagickPixelPacket(image,&transpix);
if (bits_per_pixel == 16) /* Direct Color */
{
redbits=(size_t) ReadBlobByte(image); /* # of bits of red */
(void) redbits;
greenbits=(size_t) ReadBlobByte(image); /* # of bits of green */
(void) greenbits;
bluebits=(size_t) ReadBlobByte(image); /* # of bits of blue */
(void) bluebits;
ReadBlobByte(image); /* reserved by Palm */
ReadBlobByte(image); /* reserved by Palm */
transpix.red=(MagickRealType) (QuantumRange*ReadBlobByte(image)/31);
transpix.green=(MagickRealType) (QuantumRange*ReadBlobByte(image)/63);
transpix.blue=(MagickRealType) (QuantumRange*ReadBlobByte(image)/31);
}
if (bits_per_pixel == 8)
{
IndexPacket
index;
if (flags & PALM_HAS_COLORMAP_FLAG)
{
count=(ssize_t) ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) count; i++)
{
ReadBlobByte(image);
index=ConstrainColormapIndex(image,(size_t) (255-i));
image->colormap[(int) index].red=ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image));
image->colormap[(int) index].green=ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image));
image->colormap[(int) index].blue=ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image));
}
}
else
for (i=0; i < (ssize_t) (1L << bits_per_pixel); i++)
{
index=ConstrainColormapIndex(image,(size_t) (255-i));
image->colormap[(int) index].red=ScaleCharToQuantum(
PalmPalette[i][0]);
image->colormap[(int) index].green=ScaleCharToQuantum(
PalmPalette[i][1]);
image->colormap[(int) index].blue=ScaleCharToQuantum(
PalmPalette[i][2]);
}
}
if (flags & PALM_IS_COMPRESSED_FLAG)
size=ReadBlobMSBShort(image);
(void) size;
image->storage_class=DirectClass;
if (bits_per_pixel < 16)
{
image->storage_class=PseudoClass;
image->depth=8;
}
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
one_row=(unsigned char *) AcquireQuantumMemory(MagickMax(bytes_per_row,
2*image->columns),sizeof(*one_row));
if (one_row == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
lastrow=(unsigned char *) NULL;
if (compressionType == PALM_COMPRESSION_SCANLINE)
{
lastrow=(unsigned char *) AcquireQuantumMemory(MagickMax(bytes_per_row,
2*image->columns),sizeof(*lastrow));
if (lastrow == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
mask=(size_t) (1U << bits_per_pixel)-1;
for (y=0; y < (ssize_t) image->rows; y++)
{
if ((flags & PALM_IS_COMPRESSED_FLAG) == 0)
{
/* TODO move out of loop! */
image->compression=NoCompression;
count=ReadBlob(image,bytes_per_row,one_row);
if (count != (ssize_t) bytes_per_row)
break;
}
else
{
if (compressionType == PALM_COMPRESSION_RLE)
{
/* TODO move out of loop! */
image->compression=RLECompression;
for (i=0; i < (ssize_t) bytes_per_row; )
{
count=(ssize_t) ReadBlobByte(image);
if (count < 0)
break;
count=MagickMin(count,(ssize_t) bytes_per_row-i);
byte=(size_t) ReadBlobByte(image);
(void) ResetMagickMemory(one_row+i,(int) byte,(size_t) count);
i+=count;
}
}
else
if (compressionType == PALM_COMPRESSION_SCANLINE)
{
size_t
one;
/* TODO move out of loop! */
one=1;
image->compression=FaxCompression;
for (i=0; i < (ssize_t) bytes_per_row; i+=8)
{
count=(ssize_t) ReadBlobByte(image);
if (count < 0)
break;
byte=(size_t) MagickMin((ssize_t) bytes_per_row-i,8);
for (bit=0; bit < byte; bit++)
{
if ((y == 0) || (count & (one << (7 - bit))))
one_row[i+bit]=(unsigned char) ReadBlobByte(image);
else
one_row[i+bit]=lastrow[i+bit];
}
}
(void) CopyMagickMemory(lastrow, one_row, bytes_per_row);
}
}
ptr=one_row;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if (bits_per_pixel == 16)
{
if (image->columns > (2*bytes_per_row))
{
one_row=(unsigned char *) RelinquishMagickMemory(one_row);
if (compressionType == PALM_COMPRESSION_SCANLINE)
lastrow=(unsigned char *) RelinquishMagickMemory(lastrow);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
for (x=0; x < (ssize_t) image->columns; x++)
{
color16=(*ptr++ << 8);
color16|=(*ptr++);
SetPixelRed(q,(QuantumRange*((color16 >> 11) & 0x1f))/0x1f);
SetPixelGreen(q,(QuantumRange*((color16 >> 5) & 0x3f))/0x3f);
SetPixelBlue(q,(QuantumRange*((color16 >> 0) & 0x1f))/0x1f);
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
}
else
{
bit=8-bits_per_pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((size_t) (ptr-one_row) >= bytes_per_row)
{
one_row=(unsigned char *) RelinquishMagickMemory(one_row);
if (compressionType == PALM_COMPRESSION_SCANLINE)
lastrow=(unsigned char *) RelinquishMagickMemory(lastrow);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
index=(IndexPacket) (mask-(((*ptr) & (mask << bit)) >> bit));
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
if (bit)
bit-=bits_per_pixel;
else
{
ptr++;
bit=8-bits_per_pixel;
}
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 (flags & PALM_HAS_TRANSPARENCY_FLAG)
{
IndexPacket index=ConstrainColormapIndex(image,(mask-transparentIndex));
if (bits_per_pixel != 16)
SetMagickPixelPacket(image,image->colormap+(ssize_t) index,
(const IndexPacket *) NULL,&transpix);
(void) TransparentPaintImage(image,&transpix,(Quantum)
TransparentOpacity,MagickFalse);
}
one_row=(unsigned char *) RelinquishMagickMemory(one_row);
if (compressionType == PALM_COMPRESSION_SCANLINE)
lastrow=(unsigned char *) RelinquishMagickMemory(lastrow);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image. Copied from coders/pnm.c
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (nextDepthOffset != 0)
{
/*
Skip to next image.
*/
totalOffset+=(MagickOffsetType) (nextDepthOffset*4);
if (totalOffset >= (MagickOffsetType) GetBlobSize(image))
ThrowReaderException(CorruptImageError,"ImproperImageHeader")
else
seekNextDepth=SeekBlob(image,totalOffset,SEEK_SET);
if (seekNextDepth != totalOffset)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Allocate next image structure. Copied from coders/pnm.c
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
(void) DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (nextDepthOffset != 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/574
CWE ID: CWE-772 | static Image *ReadPALMImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
totalOffset,
seekNextDepth;
MagickPixelPacket
transpix;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
size_t
bytes_per_row,
flags,
bits_per_pixel,
version,
nextDepthOffset,
transparentIndex,
compressionType,
byte,
mask,
redbits,
greenbits,
bluebits,
one,
pad,
size,
bit;
ssize_t
count,
y;
unsigned char
*last_row,
*one_row,
*ptr;
unsigned short
color16;
/*
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)
{
(void) DestroyImageList(image);
return((Image *) NULL);
}
totalOffset=0;
do
{
image->columns=ReadBlobMSBShort(image);
image->rows=ReadBlobMSBShort(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
bytes_per_row=ReadBlobMSBShort(image);
flags=ReadBlobMSBShort(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
if ((bits_per_pixel != 1) && (bits_per_pixel != 2) &&
(bits_per_pixel != 4) && (bits_per_pixel != 8) &&
(bits_per_pixel != 16))
ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
version=(size_t) ReadBlobByte(image);
if ((version != 0) && (version != 1) && (version != 2))
ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch");
nextDepthOffset=(size_t) ReadBlobMSBShort(image);
transparentIndex=(size_t) ReadBlobByte(image);
compressionType=(size_t) ReadBlobByte(image);
if ((compressionType != PALM_COMPRESSION_NONE) &&
(compressionType != PALM_COMPRESSION_SCANLINE ) &&
(compressionType != PALM_COMPRESSION_RLE))
ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
pad=ReadBlobMSBShort(image);
(void) pad;
/*
Initialize image colormap.
*/
one=1;
if ((bits_per_pixel < 16) &&
(AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetMagickPixelPacket(image,&transpix);
if (bits_per_pixel == 16) /* Direct Color */
{
redbits=(size_t) ReadBlobByte(image); /* # of bits of red */
(void) redbits;
greenbits=(size_t) ReadBlobByte(image); /* # of bits of green */
(void) greenbits;
bluebits=(size_t) ReadBlobByte(image); /* # of bits of blue */
(void) bluebits;
ReadBlobByte(image); /* reserved by Palm */
ReadBlobByte(image); /* reserved by Palm */
transpix.red=(MagickRealType) (QuantumRange*ReadBlobByte(image)/31);
transpix.green=(MagickRealType) (QuantumRange*ReadBlobByte(image)/63);
transpix.blue=(MagickRealType) (QuantumRange*ReadBlobByte(image)/31);
}
if (bits_per_pixel == 8)
{
IndexPacket
index;
if (flags & PALM_HAS_COLORMAP_FLAG)
{
count=(ssize_t) ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) count; i++)
{
ReadBlobByte(image);
index=ConstrainColormapIndex(image,(size_t) (255-i));
image->colormap[(int) index].red=ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image));
image->colormap[(int) index].green=ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image));
image->colormap[(int) index].blue=ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image));
}
}
else
for (i=0; i < (ssize_t) (1L << bits_per_pixel); i++)
{
index=ConstrainColormapIndex(image,(size_t) (255-i));
image->colormap[(int) index].red=ScaleCharToQuantum(
PalmPalette[i][0]);
image->colormap[(int) index].green=ScaleCharToQuantum(
PalmPalette[i][1]);
image->colormap[(int) index].blue=ScaleCharToQuantum(
PalmPalette[i][2]);
}
}
if (flags & PALM_IS_COMPRESSED_FLAG)
size=ReadBlobMSBShort(image);
(void) size;
image->storage_class=DirectClass;
if (bits_per_pixel < 16)
{
image->storage_class=PseudoClass;
image->depth=8;
}
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
one_row=(unsigned char *) AcquireQuantumMemory(MagickMax(bytes_per_row,
2*image->columns),sizeof(*one_row));
if (one_row == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
last_row=(unsigned char *) NULL;
if (compressionType == PALM_COMPRESSION_SCANLINE)
{
last_row=(unsigned char *) AcquireQuantumMemory(MagickMax(bytes_per_row,
2*image->columns),sizeof(*last_row));
if (last_row == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
mask=(size_t) (1U << bits_per_pixel)-1;
for (y=0; y < (ssize_t) image->rows; y++)
{
if ((flags & PALM_IS_COMPRESSED_FLAG) == 0)
{
/* TODO move out of loop! */
image->compression=NoCompression;
count=ReadBlob(image,bytes_per_row,one_row);
if (count != (ssize_t) bytes_per_row)
break;
}
else
{
if (compressionType == PALM_COMPRESSION_RLE)
{
/* TODO move out of loop! */
image->compression=RLECompression;
for (i=0; i < (ssize_t) bytes_per_row; )
{
count=(ssize_t) ReadBlobByte(image);
if (count < 0)
break;
count=MagickMin(count,(ssize_t) bytes_per_row-i);
byte=(size_t) ReadBlobByte(image);
(void) ResetMagickMemory(one_row+i,(int) byte,(size_t) count);
i+=count;
}
}
else
if (compressionType == PALM_COMPRESSION_SCANLINE)
{
size_t
one;
/* TODO move out of loop! */
one=1;
image->compression=FaxCompression;
for (i=0; i < (ssize_t) bytes_per_row; i+=8)
{
count=(ssize_t) ReadBlobByte(image);
if (count < 0)
break;
byte=(size_t) MagickMin((ssize_t) bytes_per_row-i,8);
for (bit=0; bit < byte; bit++)
{
if ((y == 0) || (count & (one << (7 - bit))))
one_row[i+bit]=(unsigned char) ReadBlobByte(image);
else
one_row[i+bit]=last_row[i+bit];
}
}
(void) CopyMagickMemory(last_row, one_row, bytes_per_row);
}
}
ptr=one_row;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if (bits_per_pixel == 16)
{
if (image->columns > (2*bytes_per_row))
{
one_row=(unsigned char *) RelinquishMagickMemory(one_row);
if (compressionType == PALM_COMPRESSION_SCANLINE)
last_row=(unsigned char *) RelinquishMagickMemory(last_row);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
for (x=0; x < (ssize_t) image->columns; x++)
{
color16=(*ptr++ << 8);
color16|=(*ptr++);
SetPixelRed(q,(QuantumRange*((color16 >> 11) & 0x1f))/0x1f);
SetPixelGreen(q,(QuantumRange*((color16 >> 5) & 0x3f))/0x3f);
SetPixelBlue(q,(QuantumRange*((color16 >> 0) & 0x1f))/0x1f);
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
}
else
{
bit=8-bits_per_pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((size_t) (ptr-one_row) >= bytes_per_row)
{
one_row=(unsigned char *) RelinquishMagickMemory(one_row);
if (compressionType == PALM_COMPRESSION_SCANLINE)
last_row=(unsigned char *) RelinquishMagickMemory(last_row);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
index=(IndexPacket) (mask-(((*ptr) & (mask << bit)) >> bit));
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
if (bit)
bit-=bits_per_pixel;
else
{
ptr++;
bit=8-bits_per_pixel;
}
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 (flags & PALM_HAS_TRANSPARENCY_FLAG)
{
IndexPacket index=ConstrainColormapIndex(image,(mask-transparentIndex));
if (bits_per_pixel != 16)
SetMagickPixelPacket(image,image->colormap+(ssize_t) index,
(const IndexPacket *) NULL,&transpix);
(void) TransparentPaintImage(image,&transpix,(Quantum)
TransparentOpacity,MagickFalse);
}
one_row=(unsigned char *) RelinquishMagickMemory(one_row);
if (compressionType == PALM_COMPRESSION_SCANLINE)
last_row=(unsigned char *) RelinquishMagickMemory(last_row);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image. Copied from coders/pnm.c
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (nextDepthOffset != 0)
{
/*
Skip to next image.
*/
totalOffset+=(MagickOffsetType) (nextDepthOffset*4);
if (totalOffset >= (MagickOffsetType) GetBlobSize(image))
ThrowReaderException(CorruptImageError,"ImproperImageHeader")
else
seekNextDepth=SeekBlob(image,totalOffset,SEEK_SET);
if (seekNextDepth != totalOffset)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Allocate next image structure. Copied from coders/pnm.c
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
(void) DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (nextDepthOffset != 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 167,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: void snd_pcm_period_elapsed(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime;
unsigned long flags;
if (PCM_RUNTIME_CHECK(substream))
return;
runtime = substream->runtime;
snd_pcm_stream_lock_irqsave(substream, flags);
if (!snd_pcm_running(substream) ||
snd_pcm_update_hw_ptr0(substream, 1) < 0)
goto _end;
#ifdef CONFIG_SND_PCM_TIMER
if (substream->timer_running)
snd_timer_interrupt(substream->timer, 1);
#endif
_end:
snd_pcm_stream_unlock_irqrestore(substream, flags);
kill_fasync(&runtime->fasync, SIGIO, POLL_IN);
}
Commit Message: ALSA: pcm : Call kill_fasync() in stream lock
Currently kill_fasync() is called outside the stream lock in
snd_pcm_period_elapsed(). This is potentially racy, since the stream
may get released even during the irq handler is running. Although
snd_pcm_release_substream() calls snd_pcm_drop(), this doesn't
guarantee that the irq handler finishes, thus the kill_fasync() call
outside the stream spin lock may be invoked after the substream is
detached, as recently reported by KASAN.
As a quick workaround, move kill_fasync() call inside the stream
lock. The fasync is rarely used interface, so this shouldn't have a
big impact from the performance POV.
Ideally, we should implement some sync mechanism for the proper finish
of stream and irq handler. But this oneliner should suffice for most
cases, so far.
Reported-by: Baozeng Ding <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-416 | void snd_pcm_period_elapsed(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime;
unsigned long flags;
if (PCM_RUNTIME_CHECK(substream))
return;
runtime = substream->runtime;
snd_pcm_stream_lock_irqsave(substream, flags);
if (!snd_pcm_running(substream) ||
snd_pcm_update_hw_ptr0(substream, 1) < 0)
goto _end;
#ifdef CONFIG_SND_PCM_TIMER
if (substream->timer_running)
snd_timer_interrupt(substream->timer, 1);
#endif
_end:
kill_fasync(&runtime->fasync, SIGIO, POLL_IN);
snd_pcm_stream_unlock_irqrestore(substream, flags);
}
| 166,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: static int snd_compress_check_input(struct snd_compr_params *params)
{
/* first let's check the buffer parameter's */
if (params->buffer.fragment_size == 0 ||
params->buffer.fragments > SIZE_MAX / params->buffer.fragment_size)
return -EINVAL;
/* now codec parameters */
if (params->codec.id == 0 || params->codec.id > SND_AUDIOCODEC_MAX)
return -EINVAL;
if (params->codec.ch_in == 0 || params->codec.ch_out == 0)
return -EINVAL;
return 0;
}
Commit Message: ALSA: compress: fix an integer overflow check
I previously added an integer overflow check here but looking at it now,
it's still buggy.
The bug happens in snd_compr_allocate_buffer(). We multiply
".fragments" and ".fragment_size" and that doesn't overflow but then we
save it in an unsigned int so it truncates the high bits away and we
allocate a smaller than expected size.
Fixes: b35cc8225845 ('ALSA: compress_core: integer overflow in snd_compr_allocate_buffer()')
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: | static int snd_compress_check_input(struct snd_compr_params *params)
{
/* first let's check the buffer parameter's */
if (params->buffer.fragment_size == 0 ||
params->buffer.fragments > INT_MAX / params->buffer.fragment_size)
return -EINVAL;
/* now codec parameters */
if (params->codec.id == 0 || params->codec.id > SND_AUDIOCODEC_MAX)
return -EINVAL;
if (params->codec.ch_in == 0 || params->codec.ch_out == 0)
return -EINVAL;
return 0;
}
| 167,574 |
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(mcrypt_module_is_block_algorithm)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
if (mcrypt_module_is_block_algorithm(module, dir) == 1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_module_is_block_algorithm)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
if (mcrypt_module_is_block_algorithm(module, dir) == 1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
| 167,097 |
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 JSValueRef touchEndCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
for (unsigned i = 0; i < touches.size(); ++i)
if (touches[i].m_state != BlackBerry::Platform::TouchPoint::TouchReleased) {
sendTouchEvent(BlackBerry::Platform::TouchEvent::TouchMove);
return JSValueMakeUndefined(context);
}
sendTouchEvent(BlackBerry::Platform::TouchEvent::TouchEnd);
touchActive = false;
return JSValueMakeUndefined(context);
}
Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API
https://bugs.webkit.org/show_bug.cgi?id=105143
RIM PR 171941
Reviewed by Rob Buis.
Internally reviewed by George Staikos.
Source/WebCore:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit.
Also adapt to new method names and encapsulation of TouchPoint data
members.
No change in behavior, no new tests.
* platform/blackberry/PlatformTouchPointBlackBerry.cpp:
(WebCore::PlatformTouchPoint::PlatformTouchPoint):
Source/WebKit/blackberry:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit. One exception
is when passing events to a full screen plugin.
Also adapt to new method names and encapsulation of TouchPoint data
members.
* Api/WebPage.cpp:
(BlackBerry::WebKit::WebPage::touchEvent):
(BlackBerry::WebKit::WebPage::touchPointAsMouseEvent):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin):
* WebKitSupport/InputHandler.cpp:
(BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint):
* WebKitSupport/InputHandler.h:
(InputHandler):
* WebKitSupport/TouchEventHandler.cpp:
(BlackBerry::WebKit::TouchEventHandler::doFatFingers):
(BlackBerry::WebKit::TouchEventHandler::handleTouchPoint):
* WebKitSupport/TouchEventHandler.h:
(TouchEventHandler):
Tools:
Adapt to new method names and encapsulation of TouchPoint data members.
* DumpRenderTree/blackberry/EventSender.cpp:
(addTouchPointCallback):
(updateTouchPointCallback):
(touchEndCallback):
(releaseTouchPointCallback):
(sendTouchEvent):
git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static JSValueRef touchEndCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
for (unsigned i = 0; i < touches.size(); ++i)
if (touches[i].state() != BlackBerry::Platform::TouchPoint::TouchReleased) {
sendTouchEvent(BlackBerry::Platform::TouchEvent::TouchMove);
return JSValueMakeUndefined(context);
}
sendTouchEvent(BlackBerry::Platform::TouchEvent::TouchEnd);
touchActive = false;
return JSValueMakeUndefined(context);
}
| 170,774 |
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 IDNSpoofChecker::Check(base::StringPiece16 label) {
UErrorCode status = U_ZERO_ERROR;
int32_t result = uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()),
NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII ||
(result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string)))
return true;
if (non_ascii_latin_letters_.containsSome(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
"[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]"
"[\\u30ce\\u30f3\\u30bd\\u30be]"
"[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]|"
"[^\\p{scx=kana}\\p{scx=hira}]\\u30fc|"
"\\u30fc[^\\p{scx=kana}\\p{scx=hira}]|"
"^[\\p{scx=kana}]+[\\u3078-\\u307a][\\p{scx=kana}]+$|"
"^[\\p{scx=hira}]+[\\u30d8-\\u30da][\\p{scx=hira}]+$|"
"[a-z]\\u30fb|\\u30fb[a-z]|"
"^[\\u0585\\u0581]+[a-z]|[a-z][\\u0585\\u0581]+$|"
"[a-z][\\u0585\\u0581]+[a-z]|"
"^[og]+[\\p{scx=armn}]|[\\p{scx=armn}][og]+$|"
"[\\p{scx=armn}][og]+[\\p{scx=armn}]", -1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
Commit Message: Block domain labels made of Cyrillic letters that look alike Latin
Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф.
BUG=683314
TEST=components_unittests --gtest_filter=U*IDN*
Review-Url: https://codereview.chromium.org/2683793010
Cr-Commit-Position: refs/heads/master@{#459226}
CWE ID: CWE-20 | bool IDNSpoofChecker::Check(base::StringPiece16 label) {
bool IDNSpoofChecker::Check(base::StringPiece16 label, bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result = uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()),
NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
// extra check unless it contains Kana letter exceptions or it's made entirely
// of Cyrillic letters that look like Latin letters. Note that the following
// combinations of scripts are treated as a 'logical' single script.
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII) return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string)) {
// Check Cyrillic confusable only for ASCII TLDs.
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
"[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]"
"[\\u30ce\\u30f3\\u30bd\\u30be]"
"[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]|"
"[^\\p{scx=kana}\\p{scx=hira}]\\u30fc|"
"\\u30fc[^\\p{scx=kana}\\p{scx=hira}]|"
"^[\\p{scx=kana}]+[\\u3078-\\u307a][\\p{scx=kana}]+$|"
"^[\\p{scx=hira}]+[\\u30d8-\\u30da][\\p{scx=hira}]+$|"
"[a-z]\\u30fb|\\u30fb[a-z]|"
"^[\\u0585\\u0581]+[a-z]|[a-z][\\u0585\\u0581]+$|"
"[a-z][\\u0585\\u0581]+[a-z]|"
"^[og]+[\\p{scx=armn}]|[\\p{scx=armn}][og]+$|"
"[\\p{scx=armn}][og]+[\\p{scx=armn}]", -1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
| 172,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 bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
{
u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
u32 exit_reason = vmx->exit_reason;
trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
vmcs_readl(EXIT_QUALIFICATION),
vmx->idt_vectoring_info,
intr_info,
vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
KVM_ISA_VMX);
if (vmx->nested.nested_run_pending)
return 0;
if (unlikely(vmx->fail)) {
pr_info_ratelimited("%s failed vm entry %x\n", __func__,
vmcs_read32(VM_INSTRUCTION_ERROR));
return 1;
}
switch (exit_reason) {
case EXIT_REASON_EXCEPTION_NMI:
if (!is_exception(intr_info))
return 0;
else if (is_page_fault(intr_info))
return enable_ept;
else if (is_no_device(intr_info) &&
!(vmcs12->guest_cr0 & X86_CR0_TS))
return 0;
return vmcs12->exception_bitmap &
(1u << (intr_info & INTR_INFO_VECTOR_MASK));
case EXIT_REASON_EXTERNAL_INTERRUPT:
return 0;
case EXIT_REASON_TRIPLE_FAULT:
return 1;
case EXIT_REASON_PENDING_INTERRUPT:
return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
case EXIT_REASON_NMI_WINDOW:
return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
case EXIT_REASON_TASK_SWITCH:
return 1;
case EXIT_REASON_CPUID:
if (kvm_register_read(vcpu, VCPU_REGS_RAX) == 0xa)
return 0;
return 1;
case EXIT_REASON_HLT:
return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
case EXIT_REASON_INVD:
return 1;
case EXIT_REASON_INVLPG:
return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
case EXIT_REASON_RDPMC:
return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
case EXIT_REASON_RDTSC:
return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
case EXIT_REASON_INVEPT:
/*
* VMX instructions trap unconditionally. This allows L1 to
* emulate them for its L2 guest, i.e., allows 3-level nesting!
*/
return 1;
case EXIT_REASON_CR_ACCESS:
return nested_vmx_exit_handled_cr(vcpu, vmcs12);
case EXIT_REASON_DR_ACCESS:
return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
case EXIT_REASON_IO_INSTRUCTION:
return nested_vmx_exit_handled_io(vcpu, vmcs12);
case EXIT_REASON_MSR_READ:
case EXIT_REASON_MSR_WRITE:
return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
case EXIT_REASON_INVALID_STATE:
return 1;
case EXIT_REASON_MWAIT_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
case EXIT_REASON_MONITOR_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
case EXIT_REASON_PAUSE_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
nested_cpu_has2(vmcs12,
SECONDARY_EXEC_PAUSE_LOOP_EXITING);
case EXIT_REASON_MCE_DURING_VMENTRY:
return 0;
case EXIT_REASON_TPR_BELOW_THRESHOLD:
return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
case EXIT_REASON_APIC_ACCESS:
return nested_cpu_has2(vmcs12,
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
case EXIT_REASON_EPT_VIOLATION:
/*
* L0 always deals with the EPT violation. If nested EPT is
* used, and the nested mmu code discovers that the address is
* missing in the guest EPT table (EPT12), the EPT violation
* will be injected with nested_ept_inject_page_fault()
*/
return 0;
case EXIT_REASON_EPT_MISCONFIG:
/*
* L2 never uses directly L1's EPT, but rather L0's own EPT
* table (shadow on EPT) or a merged EPT table that L0 built
* (EPT on EPT). So any problems with the structure of the
* table is L0's fault.
*/
return 0;
case EXIT_REASON_WBINVD:
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
case EXIT_REASON_XSETBV:
return 1;
default:
return 1;
}
}
Commit Message: kvm: vmx: handle invvpid vm exit gracefully
On systems with invvpid instruction support (corresponding bit in
IA32_VMX_EPT_VPID_CAP MSR is set) guest invocation of invvpid
causes vm exit, which is currently not handled and results in
propagation of unknown exit to userspace.
Fix this by installing an invvpid vm exit handler.
This is CVE-2014-3646.
Cc: [email protected]
Signed-off-by: Petr Matousek <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
{
u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
u32 exit_reason = vmx->exit_reason;
trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
vmcs_readl(EXIT_QUALIFICATION),
vmx->idt_vectoring_info,
intr_info,
vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
KVM_ISA_VMX);
if (vmx->nested.nested_run_pending)
return 0;
if (unlikely(vmx->fail)) {
pr_info_ratelimited("%s failed vm entry %x\n", __func__,
vmcs_read32(VM_INSTRUCTION_ERROR));
return 1;
}
switch (exit_reason) {
case EXIT_REASON_EXCEPTION_NMI:
if (!is_exception(intr_info))
return 0;
else if (is_page_fault(intr_info))
return enable_ept;
else if (is_no_device(intr_info) &&
!(vmcs12->guest_cr0 & X86_CR0_TS))
return 0;
return vmcs12->exception_bitmap &
(1u << (intr_info & INTR_INFO_VECTOR_MASK));
case EXIT_REASON_EXTERNAL_INTERRUPT:
return 0;
case EXIT_REASON_TRIPLE_FAULT:
return 1;
case EXIT_REASON_PENDING_INTERRUPT:
return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
case EXIT_REASON_NMI_WINDOW:
return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
case EXIT_REASON_TASK_SWITCH:
return 1;
case EXIT_REASON_CPUID:
if (kvm_register_read(vcpu, VCPU_REGS_RAX) == 0xa)
return 0;
return 1;
case EXIT_REASON_HLT:
return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
case EXIT_REASON_INVD:
return 1;
case EXIT_REASON_INVLPG:
return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
case EXIT_REASON_RDPMC:
return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
case EXIT_REASON_RDTSC:
return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
/*
* VMX instructions trap unconditionally. This allows L1 to
* emulate them for its L2 guest, i.e., allows 3-level nesting!
*/
return 1;
case EXIT_REASON_CR_ACCESS:
return nested_vmx_exit_handled_cr(vcpu, vmcs12);
case EXIT_REASON_DR_ACCESS:
return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
case EXIT_REASON_IO_INSTRUCTION:
return nested_vmx_exit_handled_io(vcpu, vmcs12);
case EXIT_REASON_MSR_READ:
case EXIT_REASON_MSR_WRITE:
return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
case EXIT_REASON_INVALID_STATE:
return 1;
case EXIT_REASON_MWAIT_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
case EXIT_REASON_MONITOR_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
case EXIT_REASON_PAUSE_INSTRUCTION:
return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
nested_cpu_has2(vmcs12,
SECONDARY_EXEC_PAUSE_LOOP_EXITING);
case EXIT_REASON_MCE_DURING_VMENTRY:
return 0;
case EXIT_REASON_TPR_BELOW_THRESHOLD:
return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
case EXIT_REASON_APIC_ACCESS:
return nested_cpu_has2(vmcs12,
SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
case EXIT_REASON_EPT_VIOLATION:
/*
* L0 always deals with the EPT violation. If nested EPT is
* used, and the nested mmu code discovers that the address is
* missing in the guest EPT table (EPT12), the EPT violation
* will be injected with nested_ept_inject_page_fault()
*/
return 0;
case EXIT_REASON_EPT_MISCONFIG:
/*
* L2 never uses directly L1's EPT, but rather L0's own EPT
* table (shadow on EPT) or a merged EPT table that L0 built
* (EPT on EPT). So any problems with the structure of the
* table is L0's fault.
*/
return 0;
case EXIT_REASON_WBINVD:
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
case EXIT_REASON_XSETBV:
return 1;
default:
return 1;
}
}
| 166,344 |
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 fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
{
static const U32 maxSrcLog = 23;
static const U32 maxSampleLog = 22;
size_t const srcBufferSize = (size_t)1<<maxSrcLog;
size_t const dstBufferSize = (size_t)1<<maxSampleLog;
size_t const cBufferSize = ZSTD_compressBound(dstBufferSize);
BYTE* cNoiseBuffer[5];
BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
ZSTD_CCtx* const ctx = ZSTD_createCCtx();
ZSTD_DCtx* const dctx = ZSTD_createDCtx();
U32 result = 0;
U32 testNb = 0;
U32 coreSeed = seed;
UTIL_time_t const startClock = UTIL_getTime();
U64 const maxClockSpan = maxDurationS * SEC_TO_MICRO;
int const cLevelLimiter = bigTests ? 3 : 2;
/* allocation */
cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
|| !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
"Not enough memory, fuzzer tests cancelled");
/* Create initial samples */
RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
/* catch up testNb */
for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);
/* main test loop */
for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < maxClockSpan); testNb++ ) {
BYTE* srcBuffer; /* jumping pointer */
U32 lseed;
size_t sampleSize, maxTestSize, totalTestSize;
size_t cSize, totalCSize, totalGenSize;
U64 crcOrig;
BYTE* sampleBuffer;
const BYTE* dict;
size_t dictSize;
/* notification */
if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); }
else { DISPLAYUPDATE(2, "\r%6u ", testNb); }
FUZ_rand(&coreSeed);
{ U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }
/* srcBuffer selection [0-4] */
{ U32 buffNb = FUZ_rand(&lseed) & 0x7F;
if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
else {
buffNb >>= 3;
if (buffNb & 7) {
const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
buffNb = tnb[buffNb >> 3];
} else {
const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
buffNb = tnb[buffNb >> 3];
} }
srcBuffer = cNoiseBuffer[buffNb];
}
/* select src segment */
sampleSize = FUZ_randomLength(&lseed, maxSampleLog);
/* create sample buffer (to catch read error with valgrind & sanitizers) */
sampleBuffer = (BYTE*)malloc(sampleSize);
CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
{ size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
crcOrig = XXH64(sampleBuffer, sampleSize, 0);
/* compression tests */
{ int const cLevelPositive =
( FUZ_rand(&lseed) %
(ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
+ 1;
int const cLevel = ((FUZ_rand(&lseed) & 15) == 3) ?
- (int)((FUZ_rand(&lseed) & 7) + 1) : /* test negative cLevel */
cLevelPositive;
DISPLAYLEVEL(5, "fuzzer t%u: Simple compression test (level %i) \n", testNb, cLevel);
cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));
/* compression failure test : too small dest buffer */
if (cSize > 3) {
const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
const size_t tooSmallSize = cSize - missing;
const U32 endMark = 0x4DC2B1A9;
memcpy(dstBuffer+tooSmallSize, &endMark, 4);
{ size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (U32)tooSmallSize, (U32)cSize); }
{ U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4);
CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow"); }
} }
/* frame header decompression test */
{ ZSTD_frameHeader zfh;
CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );
CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect");
}
/* Decompressed size test */
{ unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
CHECK(rSize != sampleSize, "decompressed size incorrect");
}
/* successful decompression test */
DISPLAYLEVEL(5, "fuzzer t%u: simple decompression test \n", testNb);
{ size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize);
{ U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize);
} }
free(sampleBuffer); /* no longer useful after this point */
/* truncated src decompression test */
DISPLAYLEVEL(5, "fuzzer t%u: decompression of truncated source \n", testNb);
{ size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
size_t const tooSmallSize = cSize - missing;
void* cBufferTooSmall = malloc(tooSmallSize); /* valgrind will catch read overflows */
CHECK(cBufferTooSmall == NULL, "not enough memory !");
memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
{ size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
free(cBufferTooSmall);
}
/* too small dst decompression test */
DISPLAYLEVEL(5, "fuzzer t%u: decompress into too small dst buffer \n", testNb);
if (sampleSize > 3) {
size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
size_t const tooSmallSize = sampleSize - missing;
static const BYTE token = 0xA9;
dstBuffer[tooSmallSize] = token;
{ size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (U32)errorCode, (U32)tooSmallSize); }
CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
}
/* noisy src decompression test */
if (cSize > 6) {
/* insert noise into src */
{ U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
size_t pos = 4; /* preserve magic number (too easy to detect) */
for (;;) {
/* keep some original src */
{ U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
size_t const mask = (1<<nbBits) - 1;
size_t const skipLength = FUZ_rand(&lseed) & mask;
pos += skipLength;
}
if (pos >= cSize) break;
/* add noise */
{ U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
size_t const mask = (1<<nbBits) - 1;
size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
pos += noiseLength;
} } }
/* decompress noisy source */
DISPLAYLEVEL(5, "fuzzer t%u: decompress noisy source \n", testNb);
{ U32 const endMark = 0xA9B1C3D6;
memcpy(dstBuffer+sampleSize, &endMark, 4);
{ size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
/* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
"ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (U32)decompressResult, (U32)sampleSize);
}
{ U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
} } } /* noisy src decompression test */
/*===== Bufferless streaming compression test, scattered segments and dictionary =====*/
DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming compression test \n", testNb);
{ U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
int const cLevel = (FUZ_rand(&lseed) %
(ZSTD_maxCLevel() -
(MAX(testLog, dictLog) / cLevelLimiter))) +
1;
maxTestSize = FUZ_rLogLength(&lseed, testLog);
if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;
dictSize = FUZ_rLogLength(&lseed, dictLog); /* needed also for decompression */
dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));
DISPLAYLEVEL(6, "fuzzer t%u: Compressing up to <=%u bytes at level %i with dictionary size %u \n",
testNb, (U32)maxTestSize, cLevel, (U32)dictSize);
if (FUZ_rand(&lseed) & 0xF) {
CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
} else {
ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
!(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
0 /*NodictID*/ }; /* note : since dictionary is fake, dictIDflag has no impact */
ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
}
CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
}
{ U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
U32 n;
XXH64_state_t xxhState;
XXH64_reset(&xxhState, 0);
for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);
if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break; /* avoid invalid dstBufferTooSmall */
if (totalTestSize+segmentSize > maxTestSize) break;
{ size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
cSize += compressResult;
}
XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
totalTestSize += segmentSize;
}
{ size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
cSize += flushResult;
}
crcOrig = XXH64_digest(&xxhState);
}
/* streaming decompression test */
DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming decompression test \n", testNb);
/* ensure memory requirement is good enough (should always be true) */
{ ZSTD_frameHeader zfh;
CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_frameHeaderSize_max),
"ZSTD_getFrameHeader(): error retrieving frame information");
{ size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize);
CHECK_Z(roundBuffSize);
CHECK((roundBuffSize > totalTestSize) && (zfh.frameContentSize!=ZSTD_CONTENTSIZE_UNKNOWN),
"ZSTD_decodingBufferSize_min() requires more memory (%u) than necessary (%u)",
(U32)roundBuffSize, (U32)totalTestSize );
} }
if (dictSize<8) dictSize=0, dict=NULL; /* disable dictionary */
CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
totalCSize = 0;
totalGenSize = 0;
while (totalCSize < cSize) {
size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
totalGenSize += genSize;
totalCSize += inSize;
}
CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
CHECK (totalCSize != cSize, "compressed data should be fully read")
{ U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
CHECK(crcOrig != crcDest, "streaming decompressed data corrupted (pos %u / %u)",
(U32)findDiff(mirrorBuffer, dstBuffer, totalTestSize), (U32)totalTestSize);
}
} /* for ( ; (testNb <= nbTests) */
DISPLAY("\r%u fuzzer tests completed \n", testNb-1);
_cleanup:
ZSTD_freeCCtx(refCtx);
ZSTD_freeCCtx(ctx);
ZSTD_freeDCtx(dctx);
free(cNoiseBuffer[0]);
free(cNoiseBuffer[1]);
free(cNoiseBuffer[2]);
free(cNoiseBuffer[3]);
free(cNoiseBuffer[4]);
free(cBuffer);
free(dstBuffer);
free(mirrorBuffer);
return result;
_output_error:
result = 1;
goto _cleanup;
}
Commit Message: fixed T36302429
CWE ID: CWE-362 | static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
{
static const U32 maxSrcLog = 23;
static const U32 maxSampleLog = 22;
size_t const srcBufferSize = (size_t)1<<maxSrcLog;
size_t const dstBufferSize = (size_t)1<<maxSampleLog;
size_t const cBufferSize = ZSTD_compressBound(dstBufferSize);
BYTE* cNoiseBuffer[5];
BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
ZSTD_CCtx* const ctx = ZSTD_createCCtx();
ZSTD_DCtx* const dctx = ZSTD_createDCtx();
U32 result = 0;
U32 testNb = 0;
U32 coreSeed = seed;
UTIL_time_t const startClock = UTIL_getTime();
U64 const maxClockSpan = maxDurationS * SEC_TO_MICRO;
int const cLevelLimiter = bigTests ? 3 : 2;
/* allocation */
cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
|| !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
"Not enough memory, fuzzer tests cancelled");
/* Create initial samples */
RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
/* catch up testNb */
for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);
/* main test loop */
for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < maxClockSpan); testNb++ ) {
BYTE* srcBuffer; /* jumping pointer */
U32 lseed;
size_t sampleSize, maxTestSize, totalTestSize;
size_t cSize, totalCSize, totalGenSize;
U64 crcOrig;
BYTE* sampleBuffer;
const BYTE* dict;
size_t dictSize;
/* notification */
if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); }
else { DISPLAYUPDATE(2, "\r%6u ", testNb); }
FUZ_rand(&coreSeed);
{ U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }
/* srcBuffer selection [0-4] */
{ U32 buffNb = FUZ_rand(&lseed) & 0x7F;
if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
else {
buffNb >>= 3;
if (buffNb & 7) {
const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
buffNb = tnb[buffNb >> 3];
} else {
const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
buffNb = tnb[buffNb >> 3];
} }
srcBuffer = cNoiseBuffer[buffNb];
}
/* select src segment */
sampleSize = FUZ_randomLength(&lseed, maxSampleLog);
/* create sample buffer (to catch read error with valgrind & sanitizers) */
sampleBuffer = (BYTE*)malloc(sampleSize);
CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
{ size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
crcOrig = XXH64(sampleBuffer, sampleSize, 0);
/* compression tests */
{ int const cLevelPositive =
( FUZ_rand(&lseed) %
(ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
+ 1;
int const cLevel = ((FUZ_rand(&lseed) & 15) == 3) ?
- (int)((FUZ_rand(&lseed) & 7) + 1) : /* test negative cLevel */
cLevelPositive;
DISPLAYLEVEL(5, "fuzzer t%u: Simple compression test (level %i) \n", testNb, cLevel);
cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));
/* compression failure test : too small dest buffer */
assert(cSize > 3);
{ const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1;
const size_t tooSmallSize = cSize - missing;
const U32 endMark = 0x4DC2B1A9;
memcpy(dstBuffer+tooSmallSize, &endMark, 4);
DISPLAYLEVEL(5, "fuzzer t%u: compress into too small buffer of size %u (missing %u bytes) \n",
testNb, (unsigned)tooSmallSize, (unsigned)missing);
{ size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (U32)tooSmallSize, (U32)cSize); }
{ U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4);
CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow (check.%08X != %08X.mark)", endCheck, endMark); }
} }
/* frame header decompression test */
{ ZSTD_frameHeader zfh;
CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );
CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect");
}
/* Decompressed size test */
{ unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
CHECK(rSize != sampleSize, "decompressed size incorrect");
}
/* successful decompression test */
DISPLAYLEVEL(5, "fuzzer t%u: simple decompression test \n", testNb);
{ size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize);
{ U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize);
} }
free(sampleBuffer); /* no longer useful after this point */
/* truncated src decompression test */
DISPLAYLEVEL(5, "fuzzer t%u: decompression of truncated source \n", testNb);
{ size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
size_t const tooSmallSize = cSize - missing;
void* cBufferTooSmall = malloc(tooSmallSize); /* valgrind will catch read overflows */
CHECK(cBufferTooSmall == NULL, "not enough memory !");
memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
{ size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
free(cBufferTooSmall);
}
/* too small dst decompression test */
DISPLAYLEVEL(5, "fuzzer t%u: decompress into too small dst buffer \n", testNb);
if (sampleSize > 3) {
size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
size_t const tooSmallSize = sampleSize - missing;
static const BYTE token = 0xA9;
dstBuffer[tooSmallSize] = token;
{ size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (U32)errorCode, (U32)tooSmallSize); }
CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
}
/* noisy src decompression test */
if (cSize > 6) {
/* insert noise into src */
{ U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
size_t pos = 4; /* preserve magic number (too easy to detect) */
for (;;) {
/* keep some original src */
{ U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
size_t const mask = (1<<nbBits) - 1;
size_t const skipLength = FUZ_rand(&lseed) & mask;
pos += skipLength;
}
if (pos >= cSize) break;
/* add noise */
{ U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
size_t const mask = (1<<nbBits) - 1;
size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
pos += noiseLength;
} } }
/* decompress noisy source */
DISPLAYLEVEL(5, "fuzzer t%u: decompress noisy source \n", testNb);
{ U32 const endMark = 0xA9B1C3D6;
memcpy(dstBuffer+sampleSize, &endMark, 4);
{ size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
/* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
"ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (U32)decompressResult, (U32)sampleSize);
}
{ U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
} } } /* noisy src decompression test */
/*===== Bufferless streaming compression test, scattered segments and dictionary =====*/
DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming compression test \n", testNb);
{ U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
int const cLevel = (FUZ_rand(&lseed) %
(ZSTD_maxCLevel() -
(MAX(testLog, dictLog) / cLevelLimiter))) +
1;
maxTestSize = FUZ_rLogLength(&lseed, testLog);
if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;
dictSize = FUZ_rLogLength(&lseed, dictLog); /* needed also for decompression */
dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));
DISPLAYLEVEL(6, "fuzzer t%u: Compressing up to <=%u bytes at level %i with dictionary size %u \n",
testNb, (U32)maxTestSize, cLevel, (U32)dictSize);
if (FUZ_rand(&lseed) & 0xF) {
CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
} else {
ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
!(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
0 /*NodictID*/ }; /* note : since dictionary is fake, dictIDflag has no impact */
ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
}
CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
}
{ U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
U32 n;
XXH64_state_t xxhState;
XXH64_reset(&xxhState, 0);
for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);
if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break; /* avoid invalid dstBufferTooSmall */
if (totalTestSize+segmentSize > maxTestSize) break;
{ size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
cSize += compressResult;
}
XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
totalTestSize += segmentSize;
}
{ size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
cSize += flushResult;
}
crcOrig = XXH64_digest(&xxhState);
}
/* streaming decompression test */
DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming decompression test \n", testNb);
/* ensure memory requirement is good enough (should always be true) */
{ ZSTD_frameHeader zfh;
CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_frameHeaderSize_max),
"ZSTD_getFrameHeader(): error retrieving frame information");
{ size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize);
CHECK_Z(roundBuffSize);
CHECK((roundBuffSize > totalTestSize) && (zfh.frameContentSize!=ZSTD_CONTENTSIZE_UNKNOWN),
"ZSTD_decodingBufferSize_min() requires more memory (%u) than necessary (%u)",
(U32)roundBuffSize, (U32)totalTestSize );
} }
if (dictSize<8) dictSize=0, dict=NULL; /* disable dictionary */
CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
totalCSize = 0;
totalGenSize = 0;
while (totalCSize < cSize) {
size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
totalGenSize += genSize;
totalCSize += inSize;
}
CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
CHECK (totalCSize != cSize, "compressed data should be fully read")
{ U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
CHECK(crcOrig != crcDest, "streaming decompressed data corrupted (pos %u / %u)",
(U32)findDiff(mirrorBuffer, dstBuffer, totalTestSize), (U32)totalTestSize);
}
} /* for ( ; (testNb <= nbTests) */
DISPLAY("\r%u fuzzer tests completed \n", testNb-1);
_cleanup:
ZSTD_freeCCtx(refCtx);
ZSTD_freeCCtx(ctx);
ZSTD_freeDCtx(dctx);
free(cNoiseBuffer[0]);
free(cNoiseBuffer[1]);
free(cNoiseBuffer[2]);
free(cNoiseBuffer[3]);
free(cNoiseBuffer[4]);
free(cBuffer);
free(dstBuffer);
free(mirrorBuffer);
return result;
_output_error:
result = 1;
goto _cleanup;
}
| 169,675 |
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 rxrpc_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct rxrpc_skb_priv *sp;
struct rxrpc_call *call = NULL, *continue_call = NULL;
struct rxrpc_sock *rx = rxrpc_sk(sock->sk);
struct sk_buff *skb;
long timeo;
int copy, ret, ullen, offset, copied = 0;
u32 abort_code;
DEFINE_WAIT(wait);
_enter(",,,%zu,%d", len, flags);
if (flags & (MSG_OOB | MSG_TRUNC))
return -EOPNOTSUPP;
ullen = msg->msg_flags & MSG_CMSG_COMPAT ? 4 : sizeof(unsigned long);
timeo = sock_rcvtimeo(&rx->sk, flags & MSG_DONTWAIT);
msg->msg_flags |= MSG_MORE;
lock_sock(&rx->sk);
for (;;) {
/* return immediately if a client socket has no outstanding
* calls */
if (RB_EMPTY_ROOT(&rx->calls)) {
if (copied)
goto out;
if (rx->sk.sk_state != RXRPC_SERVER_LISTENING) {
release_sock(&rx->sk);
if (continue_call)
rxrpc_put_call(continue_call);
return -ENODATA;
}
}
/* get the next message on the Rx queue */
skb = skb_peek(&rx->sk.sk_receive_queue);
if (!skb) {
/* nothing remains on the queue */
if (copied &&
(msg->msg_flags & MSG_PEEK || timeo == 0))
goto out;
/* wait for a message to turn up */
release_sock(&rx->sk);
prepare_to_wait_exclusive(sk_sleep(&rx->sk), &wait,
TASK_INTERRUPTIBLE);
ret = sock_error(&rx->sk);
if (ret)
goto wait_error;
if (skb_queue_empty(&rx->sk.sk_receive_queue)) {
if (signal_pending(current))
goto wait_interrupted;
timeo = schedule_timeout(timeo);
}
finish_wait(sk_sleep(&rx->sk), &wait);
lock_sock(&rx->sk);
continue;
}
peek_next_packet:
sp = rxrpc_skb(skb);
call = sp->call;
ASSERT(call != NULL);
_debug("next pkt %s", rxrpc_pkts[sp->hdr.type]);
/* make sure we wait for the state to be updated in this call */
spin_lock_bh(&call->lock);
spin_unlock_bh(&call->lock);
if (test_bit(RXRPC_CALL_RELEASED, &call->flags)) {
_debug("packet from released call");
if (skb_dequeue(&rx->sk.sk_receive_queue) != skb)
BUG();
rxrpc_free_skb(skb);
continue;
}
/* determine whether to continue last data receive */
if (continue_call) {
_debug("maybe cont");
if (call != continue_call ||
skb->mark != RXRPC_SKB_MARK_DATA) {
release_sock(&rx->sk);
rxrpc_put_call(continue_call);
_leave(" = %d [noncont]", copied);
return copied;
}
}
rxrpc_get_call(call);
/* copy the peer address and timestamp */
if (!continue_call) {
if (msg->msg_name && msg->msg_namelen > 0)
memcpy(msg->msg_name,
&call->conn->trans->peer->srx,
sizeof(call->conn->trans->peer->srx));
sock_recv_ts_and_drops(msg, &rx->sk, skb);
}
/* receive the message */
if (skb->mark != RXRPC_SKB_MARK_DATA)
goto receive_non_data_message;
_debug("recvmsg DATA #%u { %d, %d }",
ntohl(sp->hdr.seq), skb->len, sp->offset);
if (!continue_call) {
/* only set the control data once per recvmsg() */
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_USER_CALL_ID,
ullen, &call->user_call_ID);
if (ret < 0)
goto copy_error;
ASSERT(test_bit(RXRPC_CALL_HAS_USERID, &call->flags));
}
ASSERTCMP(ntohl(sp->hdr.seq), >=, call->rx_data_recv);
ASSERTCMP(ntohl(sp->hdr.seq), <=, call->rx_data_recv + 1);
call->rx_data_recv = ntohl(sp->hdr.seq);
ASSERTCMP(ntohl(sp->hdr.seq), >, call->rx_data_eaten);
offset = sp->offset;
copy = skb->len - offset;
if (copy > len - copied)
copy = len - copied;
if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
ret = skb_copy_datagram_iovec(skb, offset,
msg->msg_iov, copy);
} else {
ret = skb_copy_and_csum_datagram_iovec(skb, offset,
msg->msg_iov);
if (ret == -EINVAL)
goto csum_copy_error;
}
if (ret < 0)
goto copy_error;
/* handle piecemeal consumption of data packets */
_debug("copied %d+%d", copy, copied);
offset += copy;
copied += copy;
if (!(flags & MSG_PEEK))
sp->offset = offset;
if (sp->offset < skb->len) {
_debug("buffer full");
ASSERTCMP(copied, ==, len);
break;
}
/* we transferred the whole data packet */
if (sp->hdr.flags & RXRPC_LAST_PACKET) {
_debug("last");
if (call->conn->out_clientflag) {
/* last byte of reply received */
ret = copied;
goto terminal_message;
}
/* last bit of request received */
if (!(flags & MSG_PEEK)) {
_debug("eat packet");
if (skb_dequeue(&rx->sk.sk_receive_queue) !=
skb)
BUG();
rxrpc_free_skb(skb);
}
msg->msg_flags &= ~MSG_MORE;
break;
}
/* move on to the next data message */
_debug("next");
if (!continue_call)
continue_call = sp->call;
else
rxrpc_put_call(call);
call = NULL;
if (flags & MSG_PEEK) {
_debug("peek next");
skb = skb->next;
if (skb == (struct sk_buff *) &rx->sk.sk_receive_queue)
break;
goto peek_next_packet;
}
_debug("eat packet");
if (skb_dequeue(&rx->sk.sk_receive_queue) != skb)
BUG();
rxrpc_free_skb(skb);
}
/* end of non-terminal data packet reception for the moment */
_debug("end rcv data");
out:
release_sock(&rx->sk);
if (call)
rxrpc_put_call(call);
if (continue_call)
rxrpc_put_call(continue_call);
_leave(" = %d [data]", copied);
return copied;
/* handle non-DATA messages such as aborts, incoming connections and
* final ACKs */
receive_non_data_message:
_debug("non-data");
if (skb->mark == RXRPC_SKB_MARK_NEW_CALL) {
_debug("RECV NEW CALL");
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_NEW_CALL, 0, &abort_code);
if (ret < 0)
goto copy_error;
if (!(flags & MSG_PEEK)) {
if (skb_dequeue(&rx->sk.sk_receive_queue) != skb)
BUG();
rxrpc_free_skb(skb);
}
goto out;
}
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_USER_CALL_ID,
ullen, &call->user_call_ID);
if (ret < 0)
goto copy_error;
ASSERT(test_bit(RXRPC_CALL_HAS_USERID, &call->flags));
switch (skb->mark) {
case RXRPC_SKB_MARK_DATA:
BUG();
case RXRPC_SKB_MARK_FINAL_ACK:
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_ACK, 0, &abort_code);
break;
case RXRPC_SKB_MARK_BUSY:
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_BUSY, 0, &abort_code);
break;
case RXRPC_SKB_MARK_REMOTE_ABORT:
abort_code = call->abort_code;
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_ABORT, 4, &abort_code);
break;
case RXRPC_SKB_MARK_NET_ERROR:
_debug("RECV NET ERROR %d", sp->error);
abort_code = sp->error;
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_NET_ERROR, 4, &abort_code);
break;
case RXRPC_SKB_MARK_LOCAL_ERROR:
_debug("RECV LOCAL ERROR %d", sp->error);
abort_code = sp->error;
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_LOCAL_ERROR, 4,
&abort_code);
break;
default:
BUG();
break;
}
if (ret < 0)
goto copy_error;
terminal_message:
_debug("terminal");
msg->msg_flags &= ~MSG_MORE;
msg->msg_flags |= MSG_EOR;
if (!(flags & MSG_PEEK)) {
_net("free terminal skb %p", skb);
if (skb_dequeue(&rx->sk.sk_receive_queue) != skb)
BUG();
rxrpc_free_skb(skb);
rxrpc_remove_user_ID(rx, call);
}
release_sock(&rx->sk);
rxrpc_put_call(call);
if (continue_call)
rxrpc_put_call(continue_call);
_leave(" = %d", ret);
return ret;
copy_error:
_debug("copy error");
release_sock(&rx->sk);
rxrpc_put_call(call);
if (continue_call)
rxrpc_put_call(continue_call);
_leave(" = %d", ret);
return ret;
csum_copy_error:
_debug("csum error");
release_sock(&rx->sk);
if (continue_call)
rxrpc_put_call(continue_call);
rxrpc_kill_skb(skb);
skb_kill_datagram(&rx->sk, skb, flags);
rxrpc_put_call(call);
return -EAGAIN;
wait_interrupted:
ret = sock_intr_errno(timeo);
wait_error:
finish_wait(sk_sleep(&rx->sk), &wait);
if (continue_call)
rxrpc_put_call(continue_call);
if (copied)
copied = ret;
_leave(" = %d [waitfail %d]", copied, ret);
return copied;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | int rxrpc_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct rxrpc_skb_priv *sp;
struct rxrpc_call *call = NULL, *continue_call = NULL;
struct rxrpc_sock *rx = rxrpc_sk(sock->sk);
struct sk_buff *skb;
long timeo;
int copy, ret, ullen, offset, copied = 0;
u32 abort_code;
DEFINE_WAIT(wait);
_enter(",,,%zu,%d", len, flags);
if (flags & (MSG_OOB | MSG_TRUNC))
return -EOPNOTSUPP;
ullen = msg->msg_flags & MSG_CMSG_COMPAT ? 4 : sizeof(unsigned long);
timeo = sock_rcvtimeo(&rx->sk, flags & MSG_DONTWAIT);
msg->msg_flags |= MSG_MORE;
lock_sock(&rx->sk);
for (;;) {
/* return immediately if a client socket has no outstanding
* calls */
if (RB_EMPTY_ROOT(&rx->calls)) {
if (copied)
goto out;
if (rx->sk.sk_state != RXRPC_SERVER_LISTENING) {
release_sock(&rx->sk);
if (continue_call)
rxrpc_put_call(continue_call);
return -ENODATA;
}
}
/* get the next message on the Rx queue */
skb = skb_peek(&rx->sk.sk_receive_queue);
if (!skb) {
/* nothing remains on the queue */
if (copied &&
(msg->msg_flags & MSG_PEEK || timeo == 0))
goto out;
/* wait for a message to turn up */
release_sock(&rx->sk);
prepare_to_wait_exclusive(sk_sleep(&rx->sk), &wait,
TASK_INTERRUPTIBLE);
ret = sock_error(&rx->sk);
if (ret)
goto wait_error;
if (skb_queue_empty(&rx->sk.sk_receive_queue)) {
if (signal_pending(current))
goto wait_interrupted;
timeo = schedule_timeout(timeo);
}
finish_wait(sk_sleep(&rx->sk), &wait);
lock_sock(&rx->sk);
continue;
}
peek_next_packet:
sp = rxrpc_skb(skb);
call = sp->call;
ASSERT(call != NULL);
_debug("next pkt %s", rxrpc_pkts[sp->hdr.type]);
/* make sure we wait for the state to be updated in this call */
spin_lock_bh(&call->lock);
spin_unlock_bh(&call->lock);
if (test_bit(RXRPC_CALL_RELEASED, &call->flags)) {
_debug("packet from released call");
if (skb_dequeue(&rx->sk.sk_receive_queue) != skb)
BUG();
rxrpc_free_skb(skb);
continue;
}
/* determine whether to continue last data receive */
if (continue_call) {
_debug("maybe cont");
if (call != continue_call ||
skb->mark != RXRPC_SKB_MARK_DATA) {
release_sock(&rx->sk);
rxrpc_put_call(continue_call);
_leave(" = %d [noncont]", copied);
return copied;
}
}
rxrpc_get_call(call);
/* copy the peer address and timestamp */
if (!continue_call) {
if (msg->msg_name) {
size_t len =
sizeof(call->conn->trans->peer->srx);
memcpy(msg->msg_name,
&call->conn->trans->peer->srx, len);
msg->msg_namelen = len;
}
sock_recv_ts_and_drops(msg, &rx->sk, skb);
}
/* receive the message */
if (skb->mark != RXRPC_SKB_MARK_DATA)
goto receive_non_data_message;
_debug("recvmsg DATA #%u { %d, %d }",
ntohl(sp->hdr.seq), skb->len, sp->offset);
if (!continue_call) {
/* only set the control data once per recvmsg() */
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_USER_CALL_ID,
ullen, &call->user_call_ID);
if (ret < 0)
goto copy_error;
ASSERT(test_bit(RXRPC_CALL_HAS_USERID, &call->flags));
}
ASSERTCMP(ntohl(sp->hdr.seq), >=, call->rx_data_recv);
ASSERTCMP(ntohl(sp->hdr.seq), <=, call->rx_data_recv + 1);
call->rx_data_recv = ntohl(sp->hdr.seq);
ASSERTCMP(ntohl(sp->hdr.seq), >, call->rx_data_eaten);
offset = sp->offset;
copy = skb->len - offset;
if (copy > len - copied)
copy = len - copied;
if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
ret = skb_copy_datagram_iovec(skb, offset,
msg->msg_iov, copy);
} else {
ret = skb_copy_and_csum_datagram_iovec(skb, offset,
msg->msg_iov);
if (ret == -EINVAL)
goto csum_copy_error;
}
if (ret < 0)
goto copy_error;
/* handle piecemeal consumption of data packets */
_debug("copied %d+%d", copy, copied);
offset += copy;
copied += copy;
if (!(flags & MSG_PEEK))
sp->offset = offset;
if (sp->offset < skb->len) {
_debug("buffer full");
ASSERTCMP(copied, ==, len);
break;
}
/* we transferred the whole data packet */
if (sp->hdr.flags & RXRPC_LAST_PACKET) {
_debug("last");
if (call->conn->out_clientflag) {
/* last byte of reply received */
ret = copied;
goto terminal_message;
}
/* last bit of request received */
if (!(flags & MSG_PEEK)) {
_debug("eat packet");
if (skb_dequeue(&rx->sk.sk_receive_queue) !=
skb)
BUG();
rxrpc_free_skb(skb);
}
msg->msg_flags &= ~MSG_MORE;
break;
}
/* move on to the next data message */
_debug("next");
if (!continue_call)
continue_call = sp->call;
else
rxrpc_put_call(call);
call = NULL;
if (flags & MSG_PEEK) {
_debug("peek next");
skb = skb->next;
if (skb == (struct sk_buff *) &rx->sk.sk_receive_queue)
break;
goto peek_next_packet;
}
_debug("eat packet");
if (skb_dequeue(&rx->sk.sk_receive_queue) != skb)
BUG();
rxrpc_free_skb(skb);
}
/* end of non-terminal data packet reception for the moment */
_debug("end rcv data");
out:
release_sock(&rx->sk);
if (call)
rxrpc_put_call(call);
if (continue_call)
rxrpc_put_call(continue_call);
_leave(" = %d [data]", copied);
return copied;
/* handle non-DATA messages such as aborts, incoming connections and
* final ACKs */
receive_non_data_message:
_debug("non-data");
if (skb->mark == RXRPC_SKB_MARK_NEW_CALL) {
_debug("RECV NEW CALL");
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_NEW_CALL, 0, &abort_code);
if (ret < 0)
goto copy_error;
if (!(flags & MSG_PEEK)) {
if (skb_dequeue(&rx->sk.sk_receive_queue) != skb)
BUG();
rxrpc_free_skb(skb);
}
goto out;
}
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_USER_CALL_ID,
ullen, &call->user_call_ID);
if (ret < 0)
goto copy_error;
ASSERT(test_bit(RXRPC_CALL_HAS_USERID, &call->flags));
switch (skb->mark) {
case RXRPC_SKB_MARK_DATA:
BUG();
case RXRPC_SKB_MARK_FINAL_ACK:
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_ACK, 0, &abort_code);
break;
case RXRPC_SKB_MARK_BUSY:
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_BUSY, 0, &abort_code);
break;
case RXRPC_SKB_MARK_REMOTE_ABORT:
abort_code = call->abort_code;
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_ABORT, 4, &abort_code);
break;
case RXRPC_SKB_MARK_NET_ERROR:
_debug("RECV NET ERROR %d", sp->error);
abort_code = sp->error;
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_NET_ERROR, 4, &abort_code);
break;
case RXRPC_SKB_MARK_LOCAL_ERROR:
_debug("RECV LOCAL ERROR %d", sp->error);
abort_code = sp->error;
ret = put_cmsg(msg, SOL_RXRPC, RXRPC_LOCAL_ERROR, 4,
&abort_code);
break;
default:
BUG();
break;
}
if (ret < 0)
goto copy_error;
terminal_message:
_debug("terminal");
msg->msg_flags &= ~MSG_MORE;
msg->msg_flags |= MSG_EOR;
if (!(flags & MSG_PEEK)) {
_net("free terminal skb %p", skb);
if (skb_dequeue(&rx->sk.sk_receive_queue) != skb)
BUG();
rxrpc_free_skb(skb);
rxrpc_remove_user_ID(rx, call);
}
release_sock(&rx->sk);
rxrpc_put_call(call);
if (continue_call)
rxrpc_put_call(continue_call);
_leave(" = %d", ret);
return ret;
copy_error:
_debug("copy error");
release_sock(&rx->sk);
rxrpc_put_call(call);
if (continue_call)
rxrpc_put_call(continue_call);
_leave(" = %d", ret);
return ret;
csum_copy_error:
_debug("csum error");
release_sock(&rx->sk);
if (continue_call)
rxrpc_put_call(continue_call);
rxrpc_kill_skb(skb);
skb_kill_datagram(&rx->sk, skb, flags);
rxrpc_put_call(call);
return -EAGAIN;
wait_interrupted:
ret = sock_intr_errno(timeo);
wait_error:
finish_wait(sk_sleep(&rx->sk), &wait);
if (continue_call)
rxrpc_put_call(continue_call);
if (copied)
copied = ret;
_leave(" = %d [waitfail %d]", copied, ret);
return copied;
}
| 166,514 |
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: std::unique_ptr<SiteCharacteristicsDataReader> GetReaderForOrigin(
Profile* profile,
const url::Origin& origin) {
SiteCharacteristicsDataStore* data_store =
LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile);
EXPECT_TRUE(data_store);
std::unique_ptr<SiteCharacteristicsDataReader> reader =
data_store->GetReaderForOrigin(origin);
internal::LocalSiteCharacteristicsDataImpl* impl =
static_cast<LocalSiteCharacteristicsDataReader*>(reader.get())
->impl_for_testing()
.get();
while (!impl->site_characteristics_for_testing().IsInitialized())
base::RunLoop().RunUntilIdle();
return reader;
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <[email protected]>
Reviewed-by: François Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID: | std::unique_ptr<SiteCharacteristicsDataReader> GetReaderForOrigin(
Profile* profile,
const url::Origin& origin) {
SiteCharacteristicsDataStore* data_store =
LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile);
EXPECT_TRUE(data_store);
std::unique_ptr<SiteCharacteristicsDataReader> reader =
data_store->GetReaderForOrigin(origin);
const internal::LocalSiteCharacteristicsDataImpl* impl =
static_cast<LocalSiteCharacteristicsDataReader*>(reader.get())
->impl_for_testing();
while (!impl->site_characteristics_for_testing().IsInitialized())
base::RunLoop().RunUntilIdle();
return reader;
}
| 172,215 |
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: BluetoothAdapterChromeOS::BluetoothAdapterChromeOS()
: weak_ptr_factory_(this) {
DBusThreadManager::Get()->GetBluetoothAdapterClient()->AddObserver(this);
DBusThreadManager::Get()->GetBluetoothDeviceClient()->AddObserver(this);
DBusThreadManager::Get()->GetBluetoothInputClient()->AddObserver(this);
std::vector<dbus::ObjectPath> object_paths =
DBusThreadManager::Get()->GetBluetoothAdapterClient()->GetAdapters();
if (!object_paths.empty()) {
VLOG(1) << object_paths.size() << " Bluetooth adapter(s) available.";
SetAdapter(object_paths[0]);
}
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | BluetoothAdapterChromeOS::BluetoothAdapterChromeOS()
: weak_ptr_factory_(this) {
DBusThreadManager::Get()->GetBluetoothAdapterClient()->AddObserver(this);
DBusThreadManager::Get()->GetBluetoothDeviceClient()->AddObserver(this);
DBusThreadManager::Get()->GetBluetoothInputClient()->AddObserver(this);
std::vector<dbus::ObjectPath> object_paths =
DBusThreadManager::Get()->GetBluetoothAdapterClient()->GetAdapters();
if (!object_paths.empty()) {
VLOG(1) << object_paths.size() << " Bluetooth adapter(s) available.";
SetAdapter(object_paths[0]);
}
// Register the pairing agent.
dbus::Bus* system_bus = DBusThreadManager::Get()->GetSystemBus();
agent_.reset(BluetoothAgentServiceProvider::Create(
system_bus, dbus::ObjectPath(kAgentPath), this));
DCHECK(agent_.get());
VLOG(1) << "Registering pairing agent";
DBusThreadManager::Get()->GetBluetoothAgentManagerClient()->
RegisterAgent(
dbus::ObjectPath(kAgentPath),
bluetooth_agent_manager::kKeyboardDisplayCapability,
base::Bind(&BluetoothAdapterChromeOS::OnRegisterAgent,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&BluetoothAdapterChromeOS::OnRegisterAgentError,
weak_ptr_factory_.GetWeakPtr()));
}
| 171,214 |
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_wrap_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 ret;
ret = gss_wrap_iov(minor_status,
context_handle,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count);
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_wrap_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (sc->ctx_handle == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
ret = gss_wrap_iov(minor_status,
sc->ctx_handle,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count);
return (ret);
}
| 166,673 |
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: acc_ctx_hints(OM_uint32 *minor_status,
gss_ctx_id_t *ctx,
spnego_gss_cred_id_t spcred,
gss_buffer_t *mechListMIC,
OM_uint32 *negState,
send_token_flag *return_token)
{
OM_uint32 tmpmin, ret;
gss_OID_set supported_mechSet;
spnego_gss_ctx_id_t sc = NULL;
*mechListMIC = GSS_C_NO_BUFFER;
supported_mechSet = GSS_C_NO_OID_SET;
*return_token = NO_TOKEN_SEND;
*negState = REJECT;
*minor_status = 0;
/* A hint request must be the first token received. */
if (*ctx != GSS_C_NO_CONTEXT)
return GSS_S_DEFECTIVE_TOKEN;
ret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT,
&supported_mechSet);
if (ret != GSS_S_COMPLETE)
goto cleanup;
ret = make_NegHints(minor_status, mechListMIC);
if (ret != GSS_S_COMPLETE)
goto cleanup;
sc = create_spnego_ctx();
if (sc == NULL) {
ret = GSS_S_FAILURE;
goto cleanup;
}
if (put_mech_set(supported_mechSet, &sc->DER_mechTypes) < 0) {
ret = GSS_S_FAILURE;
goto cleanup;
}
sc->internal_mech = GSS_C_NO_OID;
*negState = ACCEPT_INCOMPLETE;
*return_token = INIT_TOKEN_SEND;
sc->firstpass = 1;
*ctx = (gss_ctx_id_t)sc;
sc = NULL;
ret = GSS_S_COMPLETE;
cleanup:
release_spnego_ctx(&sc);
gss_release_oid_set(&tmpmin, &supported_mechSet);
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 | acc_ctx_hints(OM_uint32 *minor_status,
gss_ctx_id_t *ctx,
spnego_gss_cred_id_t spcred,
gss_buffer_t *mechListMIC,
OM_uint32 *negState,
send_token_flag *return_token)
{
OM_uint32 tmpmin, ret;
gss_OID_set supported_mechSet;
spnego_gss_ctx_id_t sc = NULL;
*mechListMIC = GSS_C_NO_BUFFER;
supported_mechSet = GSS_C_NO_OID_SET;
*return_token = NO_TOKEN_SEND;
*negState = REJECT;
*minor_status = 0;
/* A hint request must be the first token received. */
if (*ctx != GSS_C_NO_CONTEXT)
return GSS_S_DEFECTIVE_TOKEN;
ret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT,
&supported_mechSet);
if (ret != GSS_S_COMPLETE)
goto cleanup;
ret = make_NegHints(minor_status, mechListMIC);
if (ret != GSS_S_COMPLETE)
goto cleanup;
sc = create_spnego_ctx(0);
if (sc == NULL) {
ret = GSS_S_FAILURE;
goto cleanup;
}
if (put_mech_set(supported_mechSet, &sc->DER_mechTypes) < 0) {
ret = GSS_S_FAILURE;
goto cleanup;
}
sc->internal_mech = GSS_C_NO_OID;
*negState = ACCEPT_INCOMPLETE;
*return_token = INIT_TOKEN_SEND;
sc->firstpass = 1;
*ctx = (gss_ctx_id_t)sc;
sc = NULL;
ret = GSS_S_COMPLETE;
cleanup:
release_spnego_ctx(&sc);
gss_release_oid_set(&tmpmin, &supported_mechSet);
return ret;
}
| 166,647 |
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_matching_model_microcode(int cpu, unsigned long start,
void *data, size_t size,
struct mc_saved_data *mc_saved_data,
unsigned long *mc_saved_in_initrd,
struct ucode_cpu_info *uci)
{
u8 *ucode_ptr = data;
unsigned int leftover = size;
enum ucode_state state = UCODE_OK;
unsigned int mc_size;
struct microcode_header_intel *mc_header;
struct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT];
unsigned int mc_saved_count = mc_saved_data->mc_saved_count;
int i;
while (leftover) {
mc_header = (struct microcode_header_intel *)ucode_ptr;
mc_size = get_totalsize(mc_header);
if (!mc_size || mc_size > leftover ||
microcode_sanity_check(ucode_ptr, 0) < 0)
break;
leftover -= mc_size;
/*
* Since APs with same family and model as the BSP may boot in
* the platform, we need to find and save microcode patches
* with the same family and model as the BSP.
*/
if (matching_model_microcode(mc_header, uci->cpu_sig.sig) !=
UCODE_OK) {
ucode_ptr += mc_size;
continue;
}
_save_mc(mc_saved_tmp, ucode_ptr, &mc_saved_count);
ucode_ptr += mc_size;
}
if (leftover) {
state = UCODE_ERROR;
goto out;
}
if (mc_saved_count == 0) {
state = UCODE_NFOUND;
goto out;
}
for (i = 0; i < mc_saved_count; i++)
mc_saved_in_initrd[i] = (unsigned long)mc_saved_tmp[i] - start;
mc_saved_data->mc_saved_count = mc_saved_count;
out:
return state;
}
Commit Message: x86/microcode/intel: Guard against stack overflow in the loader
mc_saved_tmp is a static array allocated on the stack, we need to make
sure mc_saved_count stays within its bounds, otherwise we're overflowing
the stack in _save_mc(). A specially crafted microcode header could lead
to a kernel crash or potentially kernel execution.
Signed-off-by: Quentin Casasnovas <[email protected]>
Cc: "H. Peter Anvin" <[email protected]>
Cc: Fenghua Yu <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Borislav Petkov <[email protected]>
CWE ID: CWE-119 | get_matching_model_microcode(int cpu, unsigned long start,
void *data, size_t size,
struct mc_saved_data *mc_saved_data,
unsigned long *mc_saved_in_initrd,
struct ucode_cpu_info *uci)
{
u8 *ucode_ptr = data;
unsigned int leftover = size;
enum ucode_state state = UCODE_OK;
unsigned int mc_size;
struct microcode_header_intel *mc_header;
struct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT];
unsigned int mc_saved_count = mc_saved_data->mc_saved_count;
int i;
while (leftover && mc_saved_count < ARRAY_SIZE(mc_saved_tmp)) {
mc_header = (struct microcode_header_intel *)ucode_ptr;
mc_size = get_totalsize(mc_header);
if (!mc_size || mc_size > leftover ||
microcode_sanity_check(ucode_ptr, 0) < 0)
break;
leftover -= mc_size;
/*
* Since APs with same family and model as the BSP may boot in
* the platform, we need to find and save microcode patches
* with the same family and model as the BSP.
*/
if (matching_model_microcode(mc_header, uci->cpu_sig.sig) !=
UCODE_OK) {
ucode_ptr += mc_size;
continue;
}
_save_mc(mc_saved_tmp, ucode_ptr, &mc_saved_count);
ucode_ptr += mc_size;
}
if (leftover) {
state = UCODE_ERROR;
goto out;
}
if (mc_saved_count == 0) {
state = UCODE_NFOUND;
goto out;
}
for (i = 0; i < mc_saved_count; i++)
mc_saved_in_initrd[i] = (unsigned long)mc_saved_tmp[i] - start;
mc_saved_data->mc_saved_count = mc_saved_count;
out:
return state;
}
| 166,679 |
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: WORD32 ih264d_create(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
ih264d_create_op_t *ps_create_op;
WORD32 ret;
ps_create_op = (ih264d_create_op_t *)pv_api_op;
ps_create_op->s_ivd_create_op_t.u4_error_code = 0;
ret = ih264d_allocate_static_bufs(&dec_hdl, pv_api_ip, pv_api_op);
/* If allocation of some buffer fails, then free buffers allocated till then */
if((IV_FAIL == ret) && (NULL != dec_hdl))
{
ih264d_free_static_bufs(dec_hdl);
ps_create_op->s_ivd_create_op_t.u4_error_code = IVD_MEM_ALLOC_FAILED;
ps_create_op->s_ivd_create_op_t.u4_error_code = 1 << IVD_FATALERROR;
return IV_FAIL;
}
return IV_SUCCESS;
}
Commit Message: Decoder: Handle dec_hdl memory allocation failure gracefully
If memory allocation for dec_hdl fails, return gracefully
with an error code. All other allocation failures are
handled correctly.
Bug: 68300072
Test: ran poc before/after
Change-Id: I118ae71f4aded658441f1932bd4ede3536f5028b
(cherry picked from commit 7720b3fe3de04523da3a9ecec2b42a3748529bbd)
CWE ID: CWE-770 | WORD32 ih264d_create(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
ih264d_create_ip_t *ps_create_ip;
ih264d_create_op_t *ps_create_op;
WORD32 ret;
ps_create_ip = (ih264d_create_ip_t *)pv_api_ip;
ps_create_op = (ih264d_create_op_t *)pv_api_op;
ps_create_op->s_ivd_create_op_t.u4_error_code = 0;
dec_hdl = NULL;
ret = ih264d_allocate_static_bufs(&dec_hdl, pv_api_ip, pv_api_op);
/* If allocation of some buffer fails, then free buffers allocated till then */
if(IV_FAIL == ret)
{
if(dec_hdl)
{
if(dec_hdl->pv_codec_handle)
{
ih264d_free_static_bufs(dec_hdl);
}
else
{
void (*pf_aligned_free)(void *pv_mem_ctxt, void *pv_buf);
void *pv_mem_ctxt;
pf_aligned_free = ps_create_ip->s_ivd_create_ip_t.pf_aligned_free;
pv_mem_ctxt = ps_create_ip->s_ivd_create_ip_t.pv_mem_ctxt;
pf_aligned_free(pv_mem_ctxt, dec_hdl);
}
}
ps_create_op->s_ivd_create_op_t.u4_error_code = IVD_MEM_ALLOC_FAILED;
ps_create_op->s_ivd_create_op_t.u4_error_code = 1 << IVD_FATALERROR;
return IV_FAIL;
}
return IV_SUCCESS;
}
| 174,112 |
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 void CopyPixels(PixelPacket *destination,
const PixelPacket *source,const MagickSizeType number_pixels)
{
#if !defined(MAGICKCORE_OPENMP_SUPPORT) || (MAGICKCORE_QUANTUM_DEPTH <= 8)
(void) memcpy(destination,source,(size_t) number_pixels*sizeof(*source));
#else
{
register MagickOffsetType
i;
if ((number_pixels*sizeof(*source)) < MagickMaxBufferExtent)
{
(void) memcpy(destination,source,(size_t) number_pixels*
sizeof(*source));
return;
}
#pragma omp parallel for
for (i=0; i < (MagickOffsetType) number_pixels; i++)
destination[i]=source[i];
}
#endif
}
Commit Message:
CWE ID: CWE-189 | static inline void CopyPixels(PixelPacket *destination,
| 168,811 |
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* H264SwDecMalloc(u32 size)
{
return malloc(size);
}
Commit Message: h264dec: check for overflows when calculating allocation size.
Bug: 27855419
Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd
CWE ID: CWE-119 | void* H264SwDecMalloc(u32 size)
void* H264SwDecMalloc(u32 size, u32 num)
{
if (size > UINT32_MAX / num) {
return NULL;
}
return malloc(size * num);
}
| 173,872 |
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: long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
{
struct key *key;
key_ref_t key_ref;
long ret;
/* find the key first */
key_ref = lookup_user_key(keyid, 0, 0);
if (IS_ERR(key_ref)) {
ret = -ENOKEY;
goto error;
}
key = key_ref_to_ptr(key_ref);
/* see if we can read it directly */
ret = key_permission(key_ref, KEY_NEED_READ);
if (ret == 0)
goto can_read_key;
if (ret != -EACCES)
goto error2;
/* we can't; see if it's searchable from this process's keyrings
* - we automatically take account of the fact that it may be
* dangling off an instantiation key
*/
if (!is_key_possessed(key_ref)) {
ret = -EACCES;
goto error2;
}
/* the key is probably readable - now try to read it */
can_read_key:
ret = -EOPNOTSUPP;
if (key->type->read) {
/* Read the data with the semaphore held (since we might sleep)
* to protect against the key being updated or revoked.
*/
down_read(&key->sem);
ret = key_validate(key);
if (ret == 0)
ret = key->type->read(key, buffer, buflen);
up_read(&key->sem);
}
error2:
key_put(key);
error:
return ret;
}
Commit Message: KEYS: prevent KEYCTL_READ on negative key
Because keyctl_read_key() looks up the key with no permissions
requested, it may find a negatively instantiated key. If the key is
also possessed, we went ahead and called ->read() on the key. But the
key payload will actually contain the ->reject_error rather than the
normal payload. Thus, the kernel oopses trying to read the
user_key_payload from memory address (int)-ENOKEY = 0x00000000ffffff82.
Fortunately the payload data is stored inline, so it shouldn't be
possible to abuse this as an arbitrary memory read primitive...
Reproducer:
keyctl new_session
keyctl request2 user desc '' @s
keyctl read $(keyctl show | awk '/user: desc/ {print $1}')
It causes a crash like the following:
BUG: unable to handle kernel paging request at 00000000ffffff92
IP: user_read+0x33/0xa0
PGD 36a54067 P4D 36a54067 PUD 0
Oops: 0000 [#1] SMP
CPU: 0 PID: 211 Comm: keyctl Not tainted 4.14.0-rc1 #337
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-20170228_101828-anatol 04/01/2014
task: ffff90aa3b74c3c0 task.stack: ffff9878c0478000
RIP: 0010:user_read+0x33/0xa0
RSP: 0018:ffff9878c047bee8 EFLAGS: 00010246
RAX: 0000000000000001 RBX: ffff90aa3d7da340 RCX: 0000000000000017
RDX: 0000000000000000 RSI: 00000000ffffff82 RDI: ffff90aa3d7da340
RBP: ffff9878c047bf00 R08: 00000024f95da94f R09: 0000000000000000
R10: 0000000000000001 R11: 0000000000000000 R12: 0000000000000000
R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000000
FS: 00007f58ece69740(0000) GS:ffff90aa3e200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00000000ffffff92 CR3: 0000000036adc001 CR4: 00000000003606f0
Call Trace:
keyctl_read_key+0xac/0xe0
SyS_keyctl+0x99/0x120
entry_SYSCALL_64_fastpath+0x1f/0xbe
RIP: 0033:0x7f58ec787bb9
RSP: 002b:00007ffc8d401678 EFLAGS: 00000206 ORIG_RAX: 00000000000000fa
RAX: ffffffffffffffda RBX: 00007ffc8d402800 RCX: 00007f58ec787bb9
RDX: 0000000000000000 RSI: 00000000174a63ac RDI: 000000000000000b
RBP: 0000000000000004 R08: 00007ffc8d402809 R09: 0000000000000020
R10: 0000000000000000 R11: 0000000000000206 R12: 00007ffc8d402800
R13: 00007ffc8d4016e0 R14: 0000000000000000 R15: 0000000000000000
Code: e5 41 55 49 89 f5 41 54 49 89 d4 53 48 89 fb e8 a4 b4 ad ff 85 c0 74 09 80 3d b9 4c 96 00 00 74 43 48 8b b3 20 01 00 00 4d 85 ed <0f> b7 5e 10 74 29 4d 85 e4 74 24 4c 39 e3 4c 89 e2 4c 89 ef 48
RIP: user_read+0x33/0xa0 RSP: ffff9878c047bee8
CR2: 00000000ffffff92
Fixes: 61ea0c0ba904 ("KEYS: Skip key state checks when checking for possession")
Cc: <[email protected]> [v3.13+]
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: CWE-476 | long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
{
struct key *key;
key_ref_t key_ref;
long ret;
/* find the key first */
key_ref = lookup_user_key(keyid, 0, 0);
if (IS_ERR(key_ref)) {
ret = -ENOKEY;
goto error;
}
key = key_ref_to_ptr(key_ref);
if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {
ret = -ENOKEY;
goto error2;
}
/* see if we can read it directly */
ret = key_permission(key_ref, KEY_NEED_READ);
if (ret == 0)
goto can_read_key;
if (ret != -EACCES)
goto error2;
/* we can't; see if it's searchable from this process's keyrings
* - we automatically take account of the fact that it may be
* dangling off an instantiation key
*/
if (!is_key_possessed(key_ref)) {
ret = -EACCES;
goto error2;
}
/* the key is probably readable - now try to read it */
can_read_key:
ret = -EOPNOTSUPP;
if (key->type->read) {
/* Read the data with the semaphore held (since we might sleep)
* to protect against the key being updated or revoked.
*/
down_read(&key->sem);
ret = key_validate(key);
if (ret == 0)
ret = key->type->read(key, buffer, buflen);
up_read(&key->sem);
}
error2:
key_put(key);
error:
return ret;
}
| 167,987 |
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_16_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
/* expand_16 does something unless the bit depth is already 16. */
return bit_depth < 16;
}
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_16_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
/* expand_16 does something unless the bit depth is already 16. */
return bit_depth < 16;
}
| 173,626 |
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 WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode)
{
int do_rf64 = 0, write_junk = 1;
ChunkHeader ds64hdr, datahdr, fmthdr;
RiffChunkHeader riffhdr;
DS64Chunk ds64_chunk;
JunkChunk junkchunk;
WaveHeader wavhdr;
uint32_t bcount;
int64_t total_data_bytes, total_riff_bytes;
int num_channels = WavpackGetNumChannels (wpc);
int32_t channel_mask = WavpackGetChannelMask (wpc);
int32_t sample_rate = WavpackGetSampleRate (wpc);
int bytes_per_sample = WavpackGetBytesPerSample (wpc);
int bits_per_sample = WavpackGetBitsPerSample (wpc);
int format = WavpackGetFloatNormExp (wpc) ? 3 : 1;
int wavhdrsize = 16;
if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) {
error_line ("can't create valid RIFF wav header for non-normalized floating data!");
return FALSE;
}
if (total_samples == -1)
total_samples = 0x7ffff000 / (bytes_per_sample * num_channels);
total_data_bytes = total_samples * bytes_per_sample * num_channels;
if (total_data_bytes > 0xff000000) {
if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so rf64", total_data_bytes);
write_junk = 0;
do_rf64 = 1;
}
else if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so riff", total_data_bytes);
CLEAR (wavhdr);
wavhdr.FormatTag = format;
wavhdr.NumChannels = num_channels;
wavhdr.SampleRate = sample_rate;
wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample;
wavhdr.BlockAlign = bytes_per_sample * num_channels;
wavhdr.BitsPerSample = bits_per_sample;
if (num_channels > 2 || channel_mask != 0x5 - num_channels) {
wavhdrsize = sizeof (wavhdr);
wavhdr.cbSize = 22;
wavhdr.ValidBitsPerSample = bits_per_sample;
wavhdr.SubFormat = format;
wavhdr.ChannelMask = channel_mask;
wavhdr.FormatTag = 0xfffe;
wavhdr.BitsPerSample = bytes_per_sample * 8;
wavhdr.GUID [4] = 0x10;
wavhdr.GUID [6] = 0x80;
wavhdr.GUID [9] = 0xaa;
wavhdr.GUID [11] = 0x38;
wavhdr.GUID [12] = 0x9b;
wavhdr.GUID [13] = 0x71;
}
strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID));
strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType));
total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1);
if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk);
if (write_junk) total_riff_bytes += sizeof (junkchunk);
strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID));
strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID));
fmthdr.ckSize = wavhdrsize;
if (write_junk) {
CLEAR (junkchunk);
strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID));
junkchunk.ckSize = sizeof (junkchunk) - 8;
WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat);
}
if (do_rf64) {
strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID));
ds64hdr.ckSize = sizeof (ds64_chunk);
CLEAR (ds64_chunk);
ds64_chunk.riffSize64 = total_riff_bytes;
ds64_chunk.dataSize64 = total_data_bytes;
ds64_chunk.sampleCount64 = total_samples;
riffhdr.ckSize = (uint32_t) -1;
datahdr.ckSize = (uint32_t) -1;
WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat);
}
else {
riffhdr.ckSize = (uint32_t) total_riff_bytes;
datahdr.ckSize = (uint32_t) total_data_bytes;
}
WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat);
WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat);
if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk))) ||
(write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) ||
!DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) ||
!DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize ||
!DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
return TRUE;
}
Commit Message: issue #27, do not overwrite stack on corrupt RF64 file
CWE ID: CWE-119 | int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode)
{
int do_rf64 = 0, write_junk = 1, table_length = 0;
ChunkHeader ds64hdr, datahdr, fmthdr;
RiffChunkHeader riffhdr;
DS64Chunk ds64_chunk;
CS64Chunk cs64_chunk;
JunkChunk junkchunk;
WaveHeader wavhdr;
uint32_t bcount;
int64_t total_data_bytes, total_riff_bytes;
int num_channels = WavpackGetNumChannels (wpc);
int32_t channel_mask = WavpackGetChannelMask (wpc);
int32_t sample_rate = WavpackGetSampleRate (wpc);
int bytes_per_sample = WavpackGetBytesPerSample (wpc);
int bits_per_sample = WavpackGetBitsPerSample (wpc);
int format = WavpackGetFloatNormExp (wpc) ? 3 : 1;
int wavhdrsize = 16;
if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) {
error_line ("can't create valid RIFF wav header for non-normalized floating data!");
return FALSE;
}
if (total_samples == -1)
total_samples = 0x7ffff000 / (bytes_per_sample * num_channels);
total_data_bytes = total_samples * bytes_per_sample * num_channels;
if (total_data_bytes > 0xff000000) {
if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so rf64", total_data_bytes);
write_junk = 0;
do_rf64 = 1;
}
else if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so riff", total_data_bytes);
CLEAR (wavhdr);
wavhdr.FormatTag = format;
wavhdr.NumChannels = num_channels;
wavhdr.SampleRate = sample_rate;
wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample;
wavhdr.BlockAlign = bytes_per_sample * num_channels;
wavhdr.BitsPerSample = bits_per_sample;
if (num_channels > 2 || channel_mask != 0x5 - num_channels) {
wavhdrsize = sizeof (wavhdr);
wavhdr.cbSize = 22;
wavhdr.ValidBitsPerSample = bits_per_sample;
wavhdr.SubFormat = format;
wavhdr.ChannelMask = channel_mask;
wavhdr.FormatTag = 0xfffe;
wavhdr.BitsPerSample = bytes_per_sample * 8;
wavhdr.GUID [4] = 0x10;
wavhdr.GUID [6] = 0x80;
wavhdr.GUID [9] = 0xaa;
wavhdr.GUID [11] = 0x38;
wavhdr.GUID [12] = 0x9b;
wavhdr.GUID [13] = 0x71;
}
strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID));
strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType));
total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1);
if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk);
total_riff_bytes += table_length * sizeof (CS64Chunk);
if (write_junk) total_riff_bytes += sizeof (junkchunk);
strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID));
strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID));
fmthdr.ckSize = wavhdrsize;
if (write_junk) {
CLEAR (junkchunk);
strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID));
junkchunk.ckSize = sizeof (junkchunk) - 8;
WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat);
}
if (do_rf64) {
strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID));
ds64hdr.ckSize = sizeof (ds64_chunk) + (table_length * sizeof (CS64Chunk));
CLEAR (ds64_chunk);
ds64_chunk.riffSize64 = total_riff_bytes;
ds64_chunk.dataSize64 = total_data_bytes;
ds64_chunk.sampleCount64 = total_samples;
ds64_chunk.tableLength = table_length;
riffhdr.ckSize = (uint32_t) -1;
datahdr.ckSize = (uint32_t) -1;
WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat);
}
else {
riffhdr.ckSize = (uint32_t) total_riff_bytes;
datahdr.ckSize = (uint32_t) total_data_bytes;
}
// this "table" is just a dummy placeholder for testing (normally not written)
if (table_length) {
strncpy (cs64_chunk.ckID, "dmmy", sizeof (cs64_chunk.ckID));
cs64_chunk.chunkSize64 = 12345678;
WavpackNativeToLittleEndian (&cs64_chunk, CS64ChunkFormat);
}
WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat);
WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat);
if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk)))) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
// again, this is normally not written except for testing
while (table_length--)
if (!DoWriteFile (outfile, &cs64_chunk, sizeof (cs64_chunk), &bcount) || bcount != sizeof (cs64_chunk)) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
if ((write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) ||
!DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) ||
!DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize ||
!DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
return TRUE;
}
| 169,335 |
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_readlink_reply(unsigned char *pkt, unsigned len)
{
uint32_t *data;
char *path;
int rlen;
int ret;
ret = rpc_check_reply(pkt, 1);
if (ret)
return ret;
data = (uint32_t *)(pkt + sizeof(struct rpc_reply));
data++;
rlen = ntohl(net_read_uint32(data)); /* new path length */
data++;
path = (char *)data;
} else {
memcpy(nfs_path, path, rlen);
nfs_path[rlen] = 0;
}
Commit Message:
CWE ID: CWE-119 | static int nfs_readlink_reply(unsigned char *pkt, unsigned len)
{
uint32_t *data;
char *path;
unsigned int rlen;
int ret;
ret = rpc_check_reply(pkt, 1);
if (ret)
return ret;
data = (uint32_t *)(pkt + sizeof(struct rpc_reply));
data++;
rlen = ntohl(net_read_uint32(data)); /* new path length */
rlen = max_t(unsigned int, rlen,
len - sizeof(struct rpc_reply) - sizeof(uint32_t));
data++;
path = (char *)data;
} else {
memcpy(nfs_path, path, rlen);
nfs_path[rlen] = 0;
}
| 164,625 |
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: struct symbol_t* MACH0_(get_symbols)(struct MACH0_(obj_t)* bin) {
const char *symstr;
struct symbol_t *symbols;
int from, to, i, j, s, stridx, symbols_size, symbols_count;
SdbHash *hash;
if (!bin || !bin->symtab || !bin->symstr) {
return NULL;
}
/* parse symbol table */
/* parse dynamic symbol table */
symbols_count = (bin->dysymtab.nextdefsym + \
bin->dysymtab.nlocalsym + \
bin->dysymtab.nundefsym );
symbols_count += bin->nsymtab;
symbols_size = (symbols_count + 1) * 2 * sizeof (struct symbol_t);
if (symbols_size < 1) {
return NULL;
}
if (!(symbols = calloc (1, symbols_size))) {
return NULL;
}
hash = sdb_ht_new ();
j = 0; // symbol_idx
for (s = 0; s < 2; s++) {
switch (s) {
case 0:
from = bin->dysymtab.iextdefsym;
to = from + bin->dysymtab.nextdefsym;
break;
case 1:
from = bin->dysymtab.ilocalsym;
to = from + bin->dysymtab.nlocalsym;
break;
#if NOT_USED
case 2:
from = bin->dysymtab.iundefsym;
to = from + bin->dysymtab.nundefsym;
break;
#endif
}
if (from == to) {
continue;
}
#define OLD 1
#if OLD
from = R_MIN (R_MAX (0, from), symbols_size / sizeof (struct symbol_t));
to = R_MIN (to , symbols_size / sizeof (struct symbol_t));
to = R_MIN (to, bin->nsymtab);
#else
from = R_MIN (R_MAX (0, from), symbols_size/sizeof (struct symbol_t));
to = symbols_count; //symbols_size/sizeof(struct symbol_t);
#endif
int maxsymbols = symbols_size / sizeof (struct symbol_t);
if (to > 0x500000) {
bprintf ("WARNING: corrupted mach0 header: symbol table is too big %d\n", to);
free (symbols);
sdb_ht_free (hash);
return NULL;
}
if (symbols_count >= maxsymbols) {
symbols_count = maxsymbols - 1;
}
for (i = from; i < to && j < symbols_count; i++, j++) {
symbols[j].offset = addr_to_offset (bin, bin->symtab[i].n_value);
symbols[j].addr = bin->symtab[i].n_value;
symbols[j].size = 0; /* TODO: Is it anywhere? */
if (bin->symtab[i].n_type & N_EXT) {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_EXT;
} else {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL;
}
stridx = bin->symtab[i].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char*)bin->symstr + stridx;
} else {
symstr = "???";
}
{
int i = 0;
int len = 0;
len = bin->symstrlen - stridx;
if (len > 0) {
for (i = 0; i < len; i++) {
if ((ut8)(symstr[i] & 0xff) == 0xff || !symstr[i]) {
len = i;
break;
}
}
char *symstr_dup = NULL;
if (len > 0) {
symstr_dup = r_str_ndup (symstr, len);
}
if (!symstr_dup) {
symbols[j].name[0] = 0;
} else {
r_str_ncpy (symbols[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH);
r_str_filter (symbols[j].name, -1);
symbols[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0;
}
free (symstr_dup);
} else {
symbols[j].name[0] = 0;
}
symbols[j].last = 0;
}
if (inSymtab (hash, symbols, symbols[j].name, symbols[j].addr)) {
symbols[j].name[0] = 0;
j--;
}
}
}
to = R_MIN (bin->nsymtab, bin->dysymtab.iundefsym + bin->dysymtab.nundefsym);
for (i = bin->dysymtab.iundefsym; i < to; i++) {
if (j > symbols_count) {
bprintf ("mach0-get-symbols: error\n");
break;
}
if (parse_import_stub(bin, &symbols[j], i))
symbols[j++].last = 0;
}
#if 1
for (i = 0; i < bin->nsymtab; i++) {
struct MACH0_(nlist) *st = &bin->symtab[i];
#if 0
bprintf ("stridx %d -> section %d type %d value = %d\n",
st->n_strx, st->n_sect, st->n_type, st->n_value);
#endif
stridx = st->n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char*)bin->symstr + stridx;
} else {
symstr = "???";
}
int section = st->n_sect;
if (section == 1 && j < symbols_count) { // text ??st->n_type == 1)
/* is symbol */
symbols[j].addr = st->n_value; // + text_base;
symbols[j].offset = addr_to_offset (bin, symbols[j].addr);
symbols[j].size = 0; /* find next symbol and crop */
if (st->n_type & N_EXT) {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_EXT;
} else {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL;
}
strncpy (symbols[j].name, symstr, R_BIN_MACH0_STRING_LENGTH);
symbols[j].name[R_BIN_MACH0_STRING_LENGTH - 1] = 0;
symbols[j].last = 0;
if (inSymtab (hash, symbols, symbols[j].name, symbols[j].addr)) {
symbols[j].name[0] = 0;
} else {
j++;
}
}
}
#endif
sdb_ht_free (hash);
symbols[j].last = 1;
return symbols;
}
Commit Message: Fix #9970 - heap oobread in mach0 parser (#10026)
CWE ID: CWE-125 | struct symbol_t* MACH0_(get_symbols)(struct MACH0_(obj_t)* bin) {
const char *symstr;
struct symbol_t *symbols;
int from, to, i, j, s, stridx, symbols_size, symbols_count;
SdbHash *hash;
if (!bin || !bin->symtab || !bin->symstr) {
return NULL;
}
/* parse symbol table */
/* parse dynamic symbol table */
symbols_count = (bin->dysymtab.nextdefsym + \
bin->dysymtab.nlocalsym + \
bin->dysymtab.nundefsym );
symbols_count += bin->nsymtab;
symbols_size = (symbols_count + 1) * 2 * sizeof (struct symbol_t);
if (symbols_size < 1) {
return NULL;
}
if (!(symbols = calloc (1, symbols_size))) {
return NULL;
}
hash = sdb_ht_new ();
j = 0; // symbol_idx
for (s = 0; s < 2; s++) {
switch (s) {
case 0:
from = bin->dysymtab.iextdefsym;
to = from + bin->dysymtab.nextdefsym;
break;
case 1:
from = bin->dysymtab.ilocalsym;
to = from + bin->dysymtab.nlocalsym;
break;
#if NOT_USED
case 2:
from = bin->dysymtab.iundefsym;
to = from + bin->dysymtab.nundefsym;
break;
#endif
}
if (from == to) {
continue;
}
#define OLD 1
#if OLD
from = R_MIN (R_MAX (0, from), symbols_size / sizeof (struct symbol_t));
to = R_MIN (to , symbols_size / sizeof (struct symbol_t));
to = R_MIN (to, bin->nsymtab);
#else
from = R_MIN (R_MAX (0, from), symbols_size/sizeof (struct symbol_t));
to = symbols_count; //symbols_size/sizeof(struct symbol_t);
#endif
int maxsymbols = symbols_size / sizeof (struct symbol_t);
if (to > 0x500000) {
bprintf ("WARNING: corrupted mach0 header: symbol table is too big %d\n", to);
free (symbols);
sdb_ht_free (hash);
return NULL;
}
if (symbols_count >= maxsymbols) {
symbols_count = maxsymbols - 1;
}
for (i = from; i < to && j < symbols_count; i++, j++) {
symbols[j].offset = addr_to_offset (bin, bin->symtab[i].n_value);
symbols[j].addr = bin->symtab[i].n_value;
symbols[j].size = 0; /* TODO: Is it anywhere? */
if (bin->symtab[i].n_type & N_EXT) {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_EXT;
} else {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL;
}
stridx = bin->symtab[i].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char*)bin->symstr + stridx;
} else {
symstr = "???";
}
{
int i = 0;
int len = 0;
len = bin->symstrlen - stridx;
if (len > 0) {
for (i = 0; i < len; i++) {
if ((ut8)(symstr[i] & 0xff) == 0xff || !symstr[i]) {
len = i;
break;
}
}
char *symstr_dup = NULL;
if (len > 0) {
symstr_dup = r_str_ndup (symstr, len);
}
if (!symstr_dup) {
symbols[j].name[0] = 0;
} else {
r_str_ncpy (symbols[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH);
r_str_filter (symbols[j].name, -1);
symbols[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0;
}
free (symstr_dup);
} else {
symbols[j].name[0] = 0;
}
symbols[j].last = 0;
}
if (inSymtab (hash, symbols, symbols[j].name, symbols[j].addr)) {
symbols[j].name[0] = 0;
j--;
}
}
}
to = R_MIN (bin->nsymtab, bin->dysymtab.iundefsym + bin->dysymtab.nundefsym);
for (i = bin->dysymtab.iundefsym; i < to; i++) {
if (j > symbols_count) {
bprintf ("mach0-get-symbols: error\n");
break;
}
if (parse_import_stub(bin, &symbols[j], i)) {
symbols[j++].last = 0;
}
}
#if 1
for (i = 0; i < bin->nsymtab; i++) {
struct MACH0_(nlist) *st = &bin->symtab[i];
#if 0
bprintf ("stridx %d -> section %d type %d value = %d\n",
st->n_strx, st->n_sect, st->n_type, st->n_value);
#endif
stridx = st->n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char*)bin->symstr + stridx;
} else {
symstr = "???";
}
int section = st->n_sect;
if (section == 1 && j < symbols_count) { // text ??st->n_type == 1)
/* is symbol */
symbols[j].addr = st->n_value; // + text_base;
symbols[j].offset = addr_to_offset (bin, symbols[j].addr);
symbols[j].size = 0; /* find next symbol and crop */
if (st->n_type & N_EXT) {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_EXT;
} else {
symbols[j].type = R_BIN_MACH0_SYMBOL_TYPE_LOCAL;
}
strncpy (symbols[j].name, symstr, R_BIN_MACH0_STRING_LENGTH);
symbols[j].name[R_BIN_MACH0_STRING_LENGTH - 1] = 0;
symbols[j].last = 0;
if (inSymtab (hash, symbols, symbols[j].name, symbols[j].addr)) {
symbols[j].name[0] = 0;
} else {
j++;
}
}
}
#endif
sdb_ht_free (hash);
symbols[j].last = 1;
return symbols;
}
| 169,226 |
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: P2PQuicTransportImpl::P2PQuicTransportImpl(
P2PQuicTransportConfig p2p_transport_config,
std::unique_ptr<net::QuicChromiumConnectionHelper> helper,
std::unique_ptr<quic::QuicConnection> connection,
const quic::QuicConfig& quic_config,
quic::QuicClock* clock)
: quic::QuicSession(connection.get(),
nullptr /* visitor */,
quic_config,
quic::CurrentSupportedVersions()),
helper_(std::move(helper)),
connection_(std::move(connection)),
perspective_(p2p_transport_config.is_server
? quic::Perspective::IS_SERVER
: quic::Perspective::IS_CLIENT),
packet_transport_(p2p_transport_config.packet_transport),
delegate_(p2p_transport_config.delegate),
clock_(clock) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(delegate_);
DCHECK(clock_);
DCHECK(packet_transport_);
DCHECK_GT(p2p_transport_config.certificates.size(), 0u);
if (p2p_transport_config.can_respond_to_crypto_handshake) {
InitializeCryptoStream();
}
certificate_ = p2p_transport_config.certificates[0];
packet_transport_->SetReceiveDelegate(this);
}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <[email protected]>
Reviewed-by: Henrik Boström <[email protected]>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284 | P2PQuicTransportImpl::P2PQuicTransportImpl(
P2PQuicTransportConfig p2p_transport_config,
std::unique_ptr<net::QuicChromiumConnectionHelper> helper,
std::unique_ptr<quic::QuicConnection> connection,
const quic::QuicConfig& quic_config,
quic::QuicClock* clock)
: quic::QuicSession(connection.get(),
nullptr /* visitor */,
quic_config,
quic::CurrentSupportedVersions()),
helper_(std::move(helper)),
connection_(std::move(connection)),
perspective_(p2p_transport_config.is_server
? quic::Perspective::IS_SERVER
: quic::Perspective::IS_CLIENT),
packet_transport_(p2p_transport_config.packet_transport),
delegate_(p2p_transport_config.delegate),
clock_(clock),
stream_write_buffer_size_(p2p_transport_config.stream_write_buffer_size) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(delegate_);
DCHECK(clock_);
DCHECK(packet_transport_);
DCHECK_GT(stream_write_buffer_size_, 0u);
DCHECK_GT(p2p_transport_config.certificates.size(), 0u);
if (p2p_transport_config.can_respond_to_crypto_handshake) {
InitializeCryptoStream();
}
certificate_ = p2p_transport_config.certificates[0];
packet_transport_->SetReceiveDelegate(this);
}
| 172,266 |
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 isUserInteractionEventForSlider(Event* event, LayoutObject* layoutObject) {
if (isUserInteractionEvent(event))
return true;
LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject));
if (!slider.isNull() && !slider.inDragMode())
return false;
const AtomicString& type = event->type();
return type == EventTypeNames::mouseover ||
type == EventTypeNames::mouseout || type == EventTypeNames::mousemove;
}
Commit Message: Fixed volume slider element event handling
MediaControlVolumeSliderElement::defaultEventHandler has making
redundant calls to setVolume() & setMuted() on mouse activity. E.g. if
a mouse click changed the slider position, the above calls were made 4
times, once for each of these events: mousedown, input, mouseup,
DOMActive, click. This crack got exposed when PointerEvents are enabled
by default on M55, adding pointermove, pointerdown & pointerup to the
list.
This CL fixes the code to trigger the calls to setVolume() & setMuted()
only when the slider position is changed. Also added pointer events to
certain lists of mouse events in the code.
BUG=677900
Review-Url: https://codereview.chromium.org/2622273003
Cr-Commit-Position: refs/heads/master@{#446032}
CWE ID: CWE-119 | bool isUserInteractionEventForSlider(Event* event, LayoutObject* layoutObject) {
if (isUserInteractionEvent(event))
return true;
LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject));
if (!slider.isNull() && !slider.inDragMode())
return false;
const AtomicString& type = event->type();
return type == EventTypeNames::mouseover ||
type == EventTypeNames::mouseout ||
type == EventTypeNames::mousemove ||
type == EventTypeNames::pointerover ||
type == EventTypeNames::pointerout ||
type == EventTypeNames::pointermove;
}
| 171,900 |
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: DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq)
{
SCEnter();
uint8_t *orig_pkt = pkt;
uint8_t nh = 0; /* careful, 0 is actually a real type */
uint16_t hdrextlen = 0;
uint16_t plen;
char dstopts = 0;
char exthdr_fh_done = 0;
int hh = 0;
int rh = 0;
int eh = 0;
int ah = 0;
nh = IPV6_GET_NH(p);
plen = len;
while(1)
{
/* No upper layer, but we do have data. Suspicious. */
if (nh == IPPROTO_NONE && plen > 0) {
ENGINE_SET_EVENT(p, IPV6_DATA_AFTER_NONE_HEADER);
SCReturn;
}
if (plen < 2) { /* minimal needed in a hdr */
SCReturn;
}
switch(nh)
{
case IPPROTO_TCP:
IPV6_SET_L4PROTO(p,nh);
DecodeTCP(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_UDP:
IPV6_SET_L4PROTO(p,nh);
DecodeUDP(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_ICMPV6:
IPV6_SET_L4PROTO(p,nh);
DecodeICMPV6(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_SCTP:
IPV6_SET_L4PROTO(p,nh);
DecodeSCTP(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_ROUTING:
IPV6_SET_L4PROTO(p,nh);
hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */
SCLogDebug("hdrextlen %"PRIu8, hdrextlen);
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
if (rh) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_RH);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
rh = 1;
IPV6_EXTHDR_SET_RH(p);
uint8_t ip6rh_type = *(pkt + 2);
if (ip6rh_type == 0) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_RH_TYPE_0);
}
p->ip6eh.rh_type = ip6rh_type;
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
case IPPROTO_HOPOPTS:
case IPPROTO_DSTOPTS:
{
IPV6OptHAO hao_s, *hao = &hao_s;
IPV6OptRA ra_s, *ra = &ra_s;
IPV6OptJumbo jumbo_s, *jumbo = &jumbo_s;
uint16_t optslen = 0;
IPV6_SET_L4PROTO(p,nh);
hdrextlen = (*(pkt+1) + 1) << 3;
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
uint8_t *ptr = pkt + 2; /* +2 to go past nxthdr and len */
/* point the pointers to right structures
* in Packet. */
if (nh == IPPROTO_HOPOPTS) {
if (hh) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_HH);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
hh = 1;
optslen = ((*(pkt + 1) + 1 ) << 3) - 2;
}
else if (nh == IPPROTO_DSTOPTS)
{
if (dstopts == 0) {
optslen = ((*(pkt + 1) + 1 ) << 3) - 2;
dstopts = 1;
} else if (dstopts == 1) {
optslen = ((*(pkt + 1) + 1 ) << 3) - 2;
dstopts = 2;
} else {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_DH);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
}
if (optslen > plen) {
/* since the packet is long enough (we checked
* plen against hdrlen, the optlen must be malformed. */
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
/** \todo move into own function to loaded on demand */
uint16_t padn_cnt = 0;
uint16_t other_cnt = 0;
uint16_t offset = 0;
while(offset < optslen)
{
if (*ptr == IPV6OPT_PAD1)
{
padn_cnt++;
offset++;
ptr++;
continue;
}
if (offset + 1 >= optslen) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
/* length field for each opt */
uint8_t ip6_optlen = *(ptr + 1);
/* see if the optlen from the packet fits the total optslen */
if ((offset + 1 + ip6_optlen) > optslen) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
if (*ptr == IPV6OPT_PADN) /* PadN */
{
padn_cnt++;
/* a zero padN len would be weird */
if (ip6_optlen == 0)
ENGINE_SET_EVENT(p, IPV6_EXTHDR_ZERO_LEN_PADN);
}
else if (*ptr == IPV6OPT_RA) /* RA */
{
ra->ip6ra_type = *(ptr);
ra->ip6ra_len = ip6_optlen;
if (ip6_optlen < sizeof(ra->ip6ra_value)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
memcpy(&ra->ip6ra_value, (ptr + 2), sizeof(ra->ip6ra_value));
ra->ip6ra_value = SCNtohs(ra->ip6ra_value);
other_cnt++;
}
else if (*ptr == IPV6OPT_JUMBO) /* Jumbo */
{
jumbo->ip6j_type = *(ptr);
jumbo->ip6j_len = ip6_optlen;
if (ip6_optlen < sizeof(jumbo->ip6j_payload_len)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
memcpy(&jumbo->ip6j_payload_len, (ptr+2), sizeof(jumbo->ip6j_payload_len));
jumbo->ip6j_payload_len = SCNtohl(jumbo->ip6j_payload_len);
}
else if (*ptr == IPV6OPT_HAO) /* HAO */
{
hao->ip6hao_type = *(ptr);
hao->ip6hao_len = ip6_optlen;
if (ip6_optlen < sizeof(hao->ip6hao_hoa)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
memcpy(&hao->ip6hao_hoa, (ptr+2), sizeof(hao->ip6hao_hoa));
other_cnt++;
} else {
if (nh == IPPROTO_HOPOPTS)
ENGINE_SET_EVENT(p, IPV6_HOPOPTS_UNKNOWN_OPT);
else
ENGINE_SET_EVENT(p, IPV6_DSTOPTS_UNKNOWN_OPT);
other_cnt++;
}
uint16_t optlen = (*(ptr + 1) + 2);
ptr += optlen; /* +2 for opt type and opt len fields */
offset += optlen;
}
/* flag packets that have only padding */
if (padn_cnt > 0 && other_cnt == 0) {
if (nh == IPPROTO_HOPOPTS)
ENGINE_SET_EVENT(p, IPV6_HOPOPTS_ONLY_PADDING);
else
ENGINE_SET_EVENT(p, IPV6_DSTOPTS_ONLY_PADDING);
}
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
case IPPROTO_FRAGMENT:
{
IPV6_SET_L4PROTO(p,nh);
/* store the offset of this extension into the packet
* past the ipv6 header. We use it in defrag for creating
* a defragmented packet without the frag header */
if (exthdr_fh_done == 0) {
p->ip6eh.fh_offset = pkt - orig_pkt;
exthdr_fh_done = 1;
}
uint16_t prev_hdrextlen = hdrextlen;
hdrextlen = sizeof(IPV6FragHdr);
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
/* for the frag header, the length field is reserved */
if (*(pkt + 1) != 0) {
ENGINE_SET_EVENT(p, IPV6_FH_NON_ZERO_RES_FIELD);
/* non fatal, lets try to continue */
}
if (IPV6_EXTHDR_ISSET_FH(p)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_FH);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
/* set the header flag first */
IPV6_EXTHDR_SET_FH(p);
/* parse the header and setup the vars */
DecodeIPV6FragHeader(p, pkt, hdrextlen, plen, prev_hdrextlen);
/* if FH has offset 0 and no more fragments are coming, we
* parse this packet further right away, no defrag will be
* needed. It is a useless FH then though, so we do set an
* decoder event. */
if (p->ip6eh.fh_more_frags_set == 0 && p->ip6eh.fh_offset == 0) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_USELESS_FH);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
/* the rest is parsed upon reassembly */
p->flags |= PKT_IS_FRAGMENT;
SCReturn;
}
case IPPROTO_ESP:
{
IPV6_SET_L4PROTO(p,nh);
hdrextlen = sizeof(IPV6EspHdr);
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
if (eh) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_EH);
SCReturn;
}
eh = 1;
nh = IPPROTO_NONE;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
case IPPROTO_AH:
{
IPV6_SET_L4PROTO(p,nh);
/* we need the header as a minimum */
hdrextlen = sizeof(IPV6AuthHdr);
/* the payload len field is the number of extra 4 byte fields,
* IPV6AuthHdr already contains the first */
if (*(pkt+1) > 0)
hdrextlen += ((*(pkt+1) - 1) * 4);
SCLogDebug("hdrextlen %"PRIu8, hdrextlen);
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
IPV6AuthHdr *ahhdr = (IPV6AuthHdr *)pkt;
if (ahhdr->ip6ah_reserved != 0x0000) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_AH_RES_NOT_NULL);
}
if (ah) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_AH);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
ah = 1;
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
case IPPROTO_IPIP:
IPV6_SET_L4PROTO(p,nh);
DecodeIPv4inIPv6(tv, dtv, p, pkt, plen, pq);
SCReturn;
/* none, last header */
case IPPROTO_NONE:
IPV6_SET_L4PROTO(p,nh);
SCReturn;
case IPPROTO_ICMP:
ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4);
SCReturn;
/* no parsing yet, just skip it */
case IPPROTO_MH:
case IPPROTO_HIP:
case IPPROTO_SHIM6:
hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
default:
ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER);
IPV6_SET_L4PROTO(p,nh);
SCReturn;
}
}
SCReturn;
}
Commit Message: teredo: be stricter on what to consider valid teredo
Invalid Teredo can lead to valid DNS traffic (or other UDP traffic)
being misdetected as Teredo. This leads to false negatives in the
UDP payload inspection.
Make the teredo code only consider a packet teredo if the encapsulated
data was decoded without any 'invalid' events being set.
Bug #2736.
CWE ID: CWE-20 | DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq)
{
SCEnter();
uint8_t *orig_pkt = pkt;
uint8_t nh = IPV6_GET_NH(p); /* careful, 0 is actually a real type */
uint16_t hdrextlen = 0;
uint16_t plen = len;
char dstopts = 0;
char exthdr_fh_done = 0;
int hh = 0;
int rh = 0;
int eh = 0;
int ah = 0;
while(1)
{
if (nh == IPPROTO_NONE) {
if (plen > 0) {
/* No upper layer, but we do have data. Suspicious. */
ENGINE_SET_EVENT(p, IPV6_DATA_AFTER_NONE_HEADER);
}
SCReturn;
}
if (plen < 2) { /* minimal needed in a hdr */
ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
switch(nh)
{
case IPPROTO_TCP:
IPV6_SET_L4PROTO(p,nh);
DecodeTCP(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_UDP:
IPV6_SET_L4PROTO(p,nh);
DecodeUDP(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_ICMPV6:
IPV6_SET_L4PROTO(p,nh);
DecodeICMPV6(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_SCTP:
IPV6_SET_L4PROTO(p,nh);
DecodeSCTP(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_ROUTING:
IPV6_SET_L4PROTO(p,nh);
hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */
SCLogDebug("hdrextlen %"PRIu8, hdrextlen);
if (hdrextlen > plen) {
ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
if (rh) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_RH);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
rh = 1;
IPV6_EXTHDR_SET_RH(p);
uint8_t ip6rh_type = *(pkt + 2);
if (ip6rh_type == 0) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_RH_TYPE_0);
}
p->ip6eh.rh_type = ip6rh_type;
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
case IPPROTO_HOPOPTS:
case IPPROTO_DSTOPTS:
{
IPV6OptHAO hao_s, *hao = &hao_s;
IPV6OptRA ra_s, *ra = &ra_s;
IPV6OptJumbo jumbo_s, *jumbo = &jumbo_s;
uint16_t optslen = 0;
IPV6_SET_L4PROTO(p,nh);
hdrextlen = (*(pkt+1) + 1) << 3;
if (hdrextlen > plen) {
ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
uint8_t *ptr = pkt + 2; /* +2 to go past nxthdr and len */
/* point the pointers to right structures
* in Packet. */
if (nh == IPPROTO_HOPOPTS) {
if (hh) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_HH);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
hh = 1;
optslen = ((*(pkt + 1) + 1 ) << 3) - 2;
}
else if (nh == IPPROTO_DSTOPTS)
{
if (dstopts == 0) {
optslen = ((*(pkt + 1) + 1 ) << 3) - 2;
dstopts = 1;
} else if (dstopts == 1) {
optslen = ((*(pkt + 1) + 1 ) << 3) - 2;
dstopts = 2;
} else {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_DH);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
}
if (optslen > plen) {
/* since the packet is long enough (we checked
* plen against hdrlen, the optlen must be malformed. */
ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
/** \todo move into own function to loaded on demand */
uint16_t padn_cnt = 0;
uint16_t other_cnt = 0;
uint16_t offset = 0;
while(offset < optslen)
{
if (*ptr == IPV6OPT_PAD1)
{
padn_cnt++;
offset++;
ptr++;
continue;
}
if (offset + 1 >= optslen) {
ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
/* length field for each opt */
uint8_t ip6_optlen = *(ptr + 1);
/* see if the optlen from the packet fits the total optslen */
if ((offset + 1 + ip6_optlen) > optslen) {
ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
if (*ptr == IPV6OPT_PADN) /* PadN */
{
padn_cnt++;
/* a zero padN len would be weird */
if (ip6_optlen == 0)
ENGINE_SET_EVENT(p, IPV6_EXTHDR_ZERO_LEN_PADN);
}
else if (*ptr == IPV6OPT_RA) /* RA */
{
ra->ip6ra_type = *(ptr);
ra->ip6ra_len = ip6_optlen;
if (ip6_optlen < sizeof(ra->ip6ra_value)) {
ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
memcpy(&ra->ip6ra_value, (ptr + 2), sizeof(ra->ip6ra_value));
ra->ip6ra_value = SCNtohs(ra->ip6ra_value);
other_cnt++;
}
else if (*ptr == IPV6OPT_JUMBO) /* Jumbo */
{
jumbo->ip6j_type = *(ptr);
jumbo->ip6j_len = ip6_optlen;
if (ip6_optlen < sizeof(jumbo->ip6j_payload_len)) {
ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
memcpy(&jumbo->ip6j_payload_len, (ptr+2), sizeof(jumbo->ip6j_payload_len));
jumbo->ip6j_payload_len = SCNtohl(jumbo->ip6j_payload_len);
}
else if (*ptr == IPV6OPT_HAO) /* HAO */
{
hao->ip6hao_type = *(ptr);
hao->ip6hao_len = ip6_optlen;
if (ip6_optlen < sizeof(hao->ip6hao_hoa)) {
ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
memcpy(&hao->ip6hao_hoa, (ptr+2), sizeof(hao->ip6hao_hoa));
other_cnt++;
} else {
if (nh == IPPROTO_HOPOPTS)
ENGINE_SET_EVENT(p, IPV6_HOPOPTS_UNKNOWN_OPT);
else
ENGINE_SET_EVENT(p, IPV6_DSTOPTS_UNKNOWN_OPT);
other_cnt++;
}
uint16_t optlen = (*(ptr + 1) + 2);
ptr += optlen; /* +2 for opt type and opt len fields */
offset += optlen;
}
/* flag packets that have only padding */
if (padn_cnt > 0 && other_cnt == 0) {
if (nh == IPPROTO_HOPOPTS)
ENGINE_SET_EVENT(p, IPV6_HOPOPTS_ONLY_PADDING);
else
ENGINE_SET_EVENT(p, IPV6_DSTOPTS_ONLY_PADDING);
}
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
case IPPROTO_FRAGMENT:
{
IPV6_SET_L4PROTO(p,nh);
/* store the offset of this extension into the packet
* past the ipv6 header. We use it in defrag for creating
* a defragmented packet without the frag header */
if (exthdr_fh_done == 0) {
p->ip6eh.fh_offset = pkt - orig_pkt;
exthdr_fh_done = 1;
}
uint16_t prev_hdrextlen = hdrextlen;
hdrextlen = sizeof(IPV6FragHdr);
if (hdrextlen > plen) {
ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
/* for the frag header, the length field is reserved */
if (*(pkt + 1) != 0) {
ENGINE_SET_EVENT(p, IPV6_FH_NON_ZERO_RES_FIELD);
/* non fatal, lets try to continue */
}
if (IPV6_EXTHDR_ISSET_FH(p)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_FH);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
/* set the header flag first */
IPV6_EXTHDR_SET_FH(p);
/* parse the header and setup the vars */
DecodeIPV6FragHeader(p, pkt, hdrextlen, plen, prev_hdrextlen);
/* if FH has offset 0 and no more fragments are coming, we
* parse this packet further right away, no defrag will be
* needed. It is a useless FH then though, so we do set an
* decoder event. */
if (p->ip6eh.fh_more_frags_set == 0 && p->ip6eh.fh_offset == 0) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_USELESS_FH);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
/* the rest is parsed upon reassembly */
p->flags |= PKT_IS_FRAGMENT;
SCReturn;
}
case IPPROTO_ESP:
{
IPV6_SET_L4PROTO(p,nh);
hdrextlen = sizeof(IPV6EspHdr);
if (hdrextlen > plen) {
ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
if (eh) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_EH);
SCReturn;
}
eh = 1;
nh = IPPROTO_NONE;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
case IPPROTO_AH:
{
IPV6_SET_L4PROTO(p,nh);
/* we need the header as a minimum */
hdrextlen = sizeof(IPV6AuthHdr);
/* the payload len field is the number of extra 4 byte fields,
* IPV6AuthHdr already contains the first */
if (*(pkt+1) > 0)
hdrextlen += ((*(pkt+1) - 1) * 4);
SCLogDebug("hdrextlen %"PRIu8, hdrextlen);
if (hdrextlen > plen) {
ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
IPV6AuthHdr *ahhdr = (IPV6AuthHdr *)pkt;
if (ahhdr->ip6ah_reserved != 0x0000) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_AH_RES_NOT_NULL);
}
if (ah) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_AH);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
ah = 1;
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
case IPPROTO_IPIP:
IPV6_SET_L4PROTO(p,nh);
DecodeIPv4inIPv6(tv, dtv, p, pkt, plen, pq);
SCReturn;
/* none, last header */
case IPPROTO_NONE:
IPV6_SET_L4PROTO(p,nh);
SCReturn;
case IPPROTO_ICMP:
ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4);
SCReturn;
/* no parsing yet, just skip it */
case IPPROTO_MH:
case IPPROTO_HIP:
case IPPROTO_SHIM6:
hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */
if (hdrextlen > plen) {
ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
default:
ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER);
IPV6_SET_L4PROTO(p,nh);
SCReturn;
}
}
SCReturn;
}
| 169,476 |
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 PeopleHandler::HandleSignout(const base::ListValue* args) {
bool delete_profile = false;
args->GetBoolean(0, &delete_profile);
if (!signin_util::IsUserSignoutAllowedForProfile(profile_)) {
DCHECK(delete_profile);
} else {
SigninManager* signin_manager =
SigninManagerFactory::GetForProfile(profile_);
if (signin_manager->IsAuthenticated()) {
if (GetSyncService())
ProfileSyncService::SyncEvent(ProfileSyncService::STOP_FROM_OPTIONS);
signin_metrics::SignoutDelete delete_metric =
delete_profile ? signin_metrics::SignoutDelete::DELETED
: signin_metrics::SignoutDelete::KEEPING;
signin_manager->SignOutAndRemoveAllAccounts(
signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric);
} else {
DCHECK(!delete_profile)
<< "Deleting the profile should only be offered the user is syncing.";
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)
->RevokeAllCredentials();
}
}
if (delete_profile) {
webui::DeleteProfileAtPath(profile_->GetPath(),
ProfileMetrics::DELETE_PROFILE_SETTINGS);
}
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20 | void PeopleHandler::HandleSignout(const base::ListValue* args) {
bool delete_profile = false;
args->GetBoolean(0, &delete_profile);
if (!signin_util::IsUserSignoutAllowedForProfile(profile_)) {
DCHECK(delete_profile);
} else {
SigninManager* signin_manager =
SigninManagerFactory::GetForProfile(profile_);
if (signin_manager->IsAuthenticated()) {
if (GetSyncService())
ProfileSyncService::SyncEvent(ProfileSyncService::STOP_FROM_OPTIONS);
signin_metrics::SignoutDelete delete_metric =
delete_profile ? signin_metrics::SignoutDelete::DELETED
: signin_metrics::SignoutDelete::KEEPING;
signin_manager->SignOutAndRemoveAllAccounts(
signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric);
} else {
DCHECK(!delete_profile)
<< "Deleting the profile should only be offered the user is syncing.";
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)
->RevokeAllCredentials(
signin_metrics::SourceForRefreshTokenOperation::
kSettings_Signout);
}
}
if (delete_profile) {
webui::DeleteProfileAtPath(profile_->GetPath(),
ProfileMetrics::DELETE_PROFILE_SETTINGS);
}
}
| 172,573 |
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 gboolean nbd_negotiate_continue(QIOChannel *ioc,
GIOCondition condition,
void *opaque)
{
qemu_coroutine_enter(opaque);
return TRUE;
}
Commit Message:
CWE ID: CWE-20 | static gboolean nbd_negotiate_continue(QIOChannel *ioc,
| 165,452 |
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: mconvert(struct magic_set *ms, struct magic *m, int flip)
{
union VALUETYPE *p = &ms->ms_value;
uint8_t type;
switch (type = cvt_flip(m->type, flip)) {
case FILE_BYTE:
cvt_8(p, m);
return 1;
case FILE_SHORT:
cvt_16(p, m);
return 1;
case FILE_LONG:
case FILE_DATE:
case FILE_LDATE:
cvt_32(p, m);
return 1;
case FILE_QUAD:
case FILE_QDATE:
case FILE_QLDATE:
case FILE_QWDATE:
cvt_64(p, m);
return 1;
case FILE_STRING:
case FILE_BESTRING16:
case FILE_LESTRING16: {
/* Null terminate and eat *trailing* return */
p->s[sizeof(p->s) - 1] = '\0';
return 1;
}
case FILE_PSTRING: {
char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m);
size_t len = file_pstring_get_length(m, ptr1);
if (len >= sizeof(p->s))
len = sizeof(p->s) - 1;
while (len--)
*ptr1++ = *ptr2++;
*ptr1 = '\0';
return 1;
}
case FILE_BESHORT:
p->h = (short)((p->hs[0]<<8)|(p->hs[1]));
cvt_16(p, m);
return 1;
case FILE_BELONG:
case FILE_BEDATE:
case FILE_BELDATE:
p->l = (int32_t)
((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));
if (type == FILE_BELONG)
cvt_32(p, m);
return 1;
case FILE_BEQUAD:
case FILE_BEQDATE:
case FILE_BEQLDATE:
case FILE_BEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));
if (type == FILE_BEQUAD)
cvt_64(p, m);
return 1;
case FILE_LESHORT:
p->h = (short)((p->hs[1]<<8)|(p->hs[0]));
cvt_16(p, m);
return 1;
case FILE_LELONG:
case FILE_LEDATE:
case FILE_LELDATE:
p->l = (int32_t)
((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));
if (type == FILE_LELONG)
cvt_32(p, m);
return 1;
case FILE_LEQUAD:
case FILE_LEQDATE:
case FILE_LEQLDATE:
case FILE_LEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));
if (type == FILE_LEQUAD)
cvt_64(p, m);
return 1;
case FILE_MELONG:
case FILE_MEDATE:
case FILE_MELDATE:
p->l = (int32_t)
((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));
if (type == FILE_MELONG)
cvt_32(p, m);
return 1;
case FILE_FLOAT:
cvt_float(p, m);
return 1;
case FILE_BEFLOAT:
p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)|
((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]);
cvt_float(p, m);
return 1;
case FILE_LEFLOAT:
p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)|
((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]);
cvt_float(p, m);
return 1;
case FILE_DOUBLE:
cvt_double(p, m);
return 1;
case FILE_BEDOUBLE:
p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]);
cvt_double(p, m);
return 1;
case FILE_LEDOUBLE:
p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]);
cvt_double(p, m);
return 1;
case FILE_REGEX:
case FILE_SEARCH:
case FILE_DEFAULT:
case FILE_CLEAR:
case FILE_NAME:
case FILE_USE:
return 1;
default:
file_magerror(ms, "invalid type %d in mconvert()", m->type);
return 0;
}
}
Commit Message: Correctly compute the truncated pascal string size (Francisco Alonso and
Jan Kaluza at RedHat)
CWE ID: CWE-119 | mconvert(struct magic_set *ms, struct magic *m, int flip)
{
union VALUETYPE *p = &ms->ms_value;
uint8_t type;
switch (type = cvt_flip(m->type, flip)) {
case FILE_BYTE:
cvt_8(p, m);
return 1;
case FILE_SHORT:
cvt_16(p, m);
return 1;
case FILE_LONG:
case FILE_DATE:
case FILE_LDATE:
cvt_32(p, m);
return 1;
case FILE_QUAD:
case FILE_QDATE:
case FILE_QLDATE:
case FILE_QWDATE:
cvt_64(p, m);
return 1;
case FILE_STRING:
case FILE_BESTRING16:
case FILE_LESTRING16: {
/* Null terminate and eat *trailing* return */
p->s[sizeof(p->s) - 1] = '\0';
return 1;
}
case FILE_PSTRING: {
size_t sz = file_pstring_length_size(m);
char *ptr1 = p->s, *ptr2 = ptr1 + sz;
size_t len = file_pstring_get_length(m, ptr1);
if (len >= sizeof(p->s)) {
/*
* The size of the pascal string length (sz)
* is 1, 2, or 4. We need at least 1 byte for NUL
* termination, but we've already truncated the
* string by p->s, so we need to deduct sz.
*/
len = sizeof(p->s) - sz;
}
while (len--)
*ptr1++ = *ptr2++;
*ptr1 = '\0';
return 1;
}
case FILE_BESHORT:
p->h = (short)((p->hs[0]<<8)|(p->hs[1]));
cvt_16(p, m);
return 1;
case FILE_BELONG:
case FILE_BEDATE:
case FILE_BELDATE:
p->l = (int32_t)
((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));
if (type == FILE_BELONG)
cvt_32(p, m);
return 1;
case FILE_BEQUAD:
case FILE_BEQDATE:
case FILE_BEQLDATE:
case FILE_BEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));
if (type == FILE_BEQUAD)
cvt_64(p, m);
return 1;
case FILE_LESHORT:
p->h = (short)((p->hs[1]<<8)|(p->hs[0]));
cvt_16(p, m);
return 1;
case FILE_LELONG:
case FILE_LEDATE:
case FILE_LELDATE:
p->l = (int32_t)
((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));
if (type == FILE_LELONG)
cvt_32(p, m);
return 1;
case FILE_LEQUAD:
case FILE_LEQDATE:
case FILE_LEQLDATE:
case FILE_LEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));
if (type == FILE_LEQUAD)
cvt_64(p, m);
return 1;
case FILE_MELONG:
case FILE_MEDATE:
case FILE_MELDATE:
p->l = (int32_t)
((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));
if (type == FILE_MELONG)
cvt_32(p, m);
return 1;
case FILE_FLOAT:
cvt_float(p, m);
return 1;
case FILE_BEFLOAT:
p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)|
((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]);
cvt_float(p, m);
return 1;
case FILE_LEFLOAT:
p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)|
((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]);
cvt_float(p, m);
return 1;
case FILE_DOUBLE:
cvt_double(p, m);
return 1;
case FILE_BEDOUBLE:
p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]);
cvt_double(p, m);
return 1;
case FILE_LEDOUBLE:
p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]);
cvt_double(p, m);
return 1;
case FILE_REGEX:
case FILE_SEARCH:
case FILE_DEFAULT:
case FILE_CLEAR:
case FILE_NAME:
case FILE_USE:
return 1;
default:
file_magerror(ms, "invalid type %d in mconvert()", m->type);
return 0;
}
}
| 166,367 |
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 realpath_cache_bucket* realpath_cache_find(const char *path, int path_len, time_t t TSRMLS_DC) /* {{{ */
{
#ifdef PHP_WIN32
unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC);
#else
unsigned long key = realpath_cache_key(path, path_len);
#endif
unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0]));
realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n];
while (*bucket != NULL) {
if (CWDG(realpath_cache_ttl) && (*bucket)->expires < t) {
realpath_cache_bucket *r = *bucket;
*bucket = (*bucket)->next;
/* if the pointers match then only subtract the length of the path */
if(r->path == r->realpath) {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1;
} else {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1;
}
free(r);
} else if (key == (*bucket)->key && path_len == (*bucket)->path_len &&
memcmp(path, (*bucket)->path, path_len) == 0) {
return *bucket;
} else {
bucket = &(*bucket)->next;
}
}
return NULL;
}
/* }}} */
Commit Message:
CWE ID: CWE-190 | static inline realpath_cache_bucket* realpath_cache_find(const char *path, int path_len, time_t t TSRMLS_DC) /* {{{ */
{
#ifdef PHP_WIN32
unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC);
#else
unsigned long key = realpath_cache_key(path, path_len);
#endif
unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0]));
realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n];
while (*bucket != NULL) {
if (CWDG(realpath_cache_ttl) && (*bucket)->expires < t) {
realpath_cache_bucket *r = *bucket;
*bucket = (*bucket)->next;
/* if the pointers match then only subtract the length of the path */
if(r->path == r->realpath) {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1;
} else {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1;
}
free(r);
} else if (key == (*bucket)->key && path_len == (*bucket)->path_len &&
memcmp(path, (*bucket)->path, path_len) == 0) {
return *bucket;
} else {
bucket = &(*bucket)->next;
}
}
return NULL;
}
/* }}} */
| 164,983 |
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 TaskManagerView::Init() {
table_model_.reset(new TaskManagerTableModel(model_));
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_TASK_COLUMN,
ui::TableColumn::LEFT, -1, 1));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN,
ui::TableColumn::LEFT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PHYSICAL_MEM_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SHARED_MEM_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_CPU_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_NET_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROCESS_ID_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(
IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(
IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_FPS_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(
ui::TableColumn(IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
tab_table_ = new BackgroundColorGroupTableView(
table_model_.get(), columns_, highlight_background_resources_);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROCESS_ID_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SHARED_MEM_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN,
false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN,
false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN,
false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN,
false);
tab_table_->SetColumnVisibility(
IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_GOATS_TELEPORTED_COLUMN,
false);
UpdateStatsCounters();
tab_table_->SetObserver(this);
tab_table_->set_context_menu_controller(this);
set_context_menu_controller(this);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kPurgeMemoryButton)) {
purge_memory_button_ = new views::NativeTextButton(this,
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_PURGE_MEMORY));
}
kill_button_ = new views::NativeTextButton(
this, l10n_util::GetStringUTF16(IDS_TASK_MANAGER_KILL));
kill_button_->AddAccelerator(ui::Accelerator(ui::VKEY_E, false, false,
false));
kill_button_->SetAccessibleKeyboardShortcut(L"E");
kill_button_->set_prefix_type(views::TextButtonBase::PREFIX_SHOW);
about_memory_link_ = new views::Link(
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_ABOUT_MEMORY_LINK));
about_memory_link_->set_listener(this);
OnSelectionChanged();
}
Commit Message: accelerators: Remove deprecated Accelerator ctor that takes booleans.
BUG=128242
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10399085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137957 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void TaskManagerView::Init() {
table_model_.reset(new TaskManagerTableModel(model_));
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_TASK_COLUMN,
ui::TableColumn::LEFT, -1, 1));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN,
ui::TableColumn::LEFT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PHYSICAL_MEM_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SHARED_MEM_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_CPU_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_NET_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROCESS_ID_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(
IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(
IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_FPS_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(
ui::TableColumn(IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
tab_table_ = new BackgroundColorGroupTableView(
table_model_.get(), columns_, highlight_background_resources_);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROCESS_ID_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SHARED_MEM_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN,
false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN,
false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN,
false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN,
false);
tab_table_->SetColumnVisibility(
IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_GOATS_TELEPORTED_COLUMN,
false);
UpdateStatsCounters();
tab_table_->SetObserver(this);
tab_table_->set_context_menu_controller(this);
set_context_menu_controller(this);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kPurgeMemoryButton)) {
purge_memory_button_ = new views::NativeTextButton(this,
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_PURGE_MEMORY));
}
kill_button_ = new views::NativeTextButton(
this, l10n_util::GetStringUTF16(IDS_TASK_MANAGER_KILL));
kill_button_->AddAccelerator(ui::Accelerator(ui::VKEY_E, ui::EF_NONE));
kill_button_->SetAccessibleKeyboardShortcut(L"E");
kill_button_->set_prefix_type(views::TextButtonBase::PREFIX_SHOW);
about_memory_link_ = new views::Link(
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_ABOUT_MEMORY_LINK));
about_memory_link_->set_listener(this);
OnSelectionChanged();
}
| 170,906 |
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: ImageBitmapFactories::ImageBitmapLoader::ImageBitmapLoader(
ImageBitmapFactories& factory,
base::Optional<IntRect> crop_rect,
ScriptState* script_state,
const ImageBitmapOptions* options)
: loader_(
FileReaderLoader::Create(FileReaderLoader::kReadAsArrayBuffer, this)),
factory_(&factory),
resolver_(ScriptPromiseResolver::Create(script_state)),
crop_rect_(crop_rect),
options_(options) {}
Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader
FileReaderLoader stores its client as a raw pointer, so in cases like
ImageBitmapLoader where the FileReaderLoaderClient really is garbage
collected we have to make sure to destroy the FileReaderLoader when
the ExecutionContext that owns it is destroyed.
Bug: 913970
Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861
Reviewed-on: https://chromium-review.googlesource.com/c/1374511
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Marijn Kruisselbrink <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616342}
CWE ID: CWE-416 | ImageBitmapFactories::ImageBitmapLoader::ImageBitmapLoader(
ImageBitmapFactories& factory,
base::Optional<IntRect> crop_rect,
ScriptState* script_state,
const ImageBitmapOptions* options)
: ContextLifecycleObserver(ExecutionContext::From(script_state)),
loader_(
FileReaderLoader::Create(FileReaderLoader::kReadAsArrayBuffer, this)),
factory_(&factory),
resolver_(ScriptPromiseResolver::Create(script_state)),
crop_rect_(crop_rect),
options_(options) {}
| 173,067 |
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: SProcXFixesChangeSaveSet(ClientPtr client)
{
REQUEST(xXFixesChangeSaveSetReq);
swaps(&stuff->length);
swapl(&stuff->window);
}
Commit Message:
CWE ID: CWE-20 | SProcXFixesChangeSaveSet(ClientPtr client)
{
REQUEST(xXFixesChangeSaveSetReq);
REQUEST_SIZE_MATCH(xXFixesChangeSaveSetReq);
swaps(&stuff->length);
swapl(&stuff->window);
}
| 165,443 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 TaskService::RunTask(InstanceId instance_id,
RunnerId runner_id,
base::OnceClosure task) {
base::subtle::AutoReadLock task_lock(task_lock_);
{
base::AutoLock lock(lock_);
if (instance_id != bound_instance_id_)
return;
}
std::move(task).Run();
}
Commit Message: Change ReadWriteLock to Lock+ConditionVariable in TaskService
There are non-trivial performance implications of using shared
SRWLocking on Windows as more state has to be checked.
Since there are only two uses of the ReadWriteLock in Chromium after
over 1 year, the decision is to remove it.
BUG=758721
Change-Id: I84d1987d7b624a89e896eb37184ee50845c39d80
Reviewed-on: https://chromium-review.googlesource.com/634423
Commit-Queue: Robert Liao <[email protected]>
Reviewed-by: Takashi Toyoshima <[email protected]>
Reviewed-by: Francois Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#497632}
CWE ID: CWE-20 | void TaskService::RunTask(InstanceId instance_id,
RunnerId runner_id,
base::OnceClosure task) {
{
base::AutoLock tasks_in_flight_auto_lock(tasks_in_flight_lock_);
++tasks_in_flight_;
}
if (IsInstanceIdStillBound(instance_id))
std::move(task).Run();
{
base::AutoLock tasks_in_flight_auto_lock(tasks_in_flight_lock_);
--tasks_in_flight_;
DCHECK_GE(tasks_in_flight_, 0);
if (tasks_in_flight_ == 0)
no_tasks_in_flight_cv_.Signal();
}
}
bool TaskService::IsInstanceIdStillBound(InstanceId instance_id) {
base::AutoLock lock(lock_);
return instance_id == bound_instance_id_;
}
| 172,212 |
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 jpc_qmfb_split_col(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];
jpc_fix_t *buf = splitbuf;
register jpc_fix_t *srcptr;
register jpc_fix_t *dstptr;
register int n;
register int m;
int hstartcol;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numrows >= 2) {
hstartcol = (numrows + 1 - parity) >> 1;
m = numrows - hstartcol;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[(1 - parity) * stride];
while (n-- > 0) {
*dstptr = *srcptr;
++dstptr;
srcptr += stride << 1;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[(1 - parity) * stride];
srcptr = &a[(2 - parity) * stride];
n = numrows - m - (!parity);
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += stride;
++srcptr;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec
that was caused by a buffer being allocated with a size that was too small
in some cases.
Added a new regression test case.
CWE ID: CWE-119 | void jpc_qmfb_split_col(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];
jpc_fix_t *buf = splitbuf;
register jpc_fix_t *srcptr;
register jpc_fix_t *dstptr;
register int n;
register int m;
int hstartrow;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numrows >= 2) {
hstartrow = (numrows + 1 - parity) >> 1;
// ORIGINAL (WRONG): m = (parity) ? hstartrow : (numrows - hstartrow);
m = numrows - hstartrow;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[(1 - parity) * stride];
while (n-- > 0) {
*dstptr = *srcptr;
++dstptr;
srcptr += stride << 1;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[(1 - parity) * stride];
srcptr = &a[(2 - parity) * stride];
n = numrows - m - (!parity);
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartrow * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += stride;
++srcptr;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
| 169,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 int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,
const uint8_t *buf, int buf_size,
int first_field)
{
int i, cid, ret;
int old_bit_depth = ctx->bit_depth, bitdepth;
uint64_t header_prefix;
if (buf_size < 0x280) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < 640).\n", buf_size);
return AVERROR_INVALIDDATA;
}
header_prefix = ff_dnxhd_parse_header_prefix(buf);
if (header_prefix == 0) {
av_log(ctx->avctx, AV_LOG_ERROR,
"unknown header 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n",
buf[0], buf[1], buf[2], buf[3], buf[4]);
return AVERROR_INVALIDDATA;
}
if (buf[5] & 2) { /* interlaced */
ctx->cur_field = buf[5] & 1;
frame->interlaced_frame = 1;
frame->top_field_first = first_field ^ ctx->cur_field;
av_log(ctx->avctx, AV_LOG_DEBUG,
"interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field);
} else {
ctx->cur_field = 0;
}
ctx->mbaff = (buf[0x6] >> 5) & 1;
ctx->height = AV_RB16(buf + 0x18);
ctx->width = AV_RB16(buf + 0x1a);
switch(buf[0x21] >> 5) {
case 1: bitdepth = 8; break;
case 2: bitdepth = 10; break;
case 3: bitdepth = 12; break;
default:
av_log(ctx->avctx, AV_LOG_ERROR,
"Unknown bitdepth indicator (%d)\n", buf[0x21] >> 5);
return AVERROR_INVALIDDATA;
}
cid = AV_RB32(buf + 0x28);
ctx->avctx->profile = dnxhd_get_profile(cid);
if ((ret = dnxhd_init_vlc(ctx, cid, bitdepth)) < 0)
return ret;
if (ctx->mbaff && ctx->cid_table->cid != 1260)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive MB interlace flag in an unsupported profile.\n");
ctx->act = buf[0x2C] & 7;
if (ctx->act && ctx->cid_table->cid != 1256 && ctx->cid_table->cid != 1270)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive color transform in an unsupported profile.\n");
ctx->is_444 = (buf[0x2C] >> 6) & 1;
if (ctx->is_444) {
if (bitdepth == 8) {
avpriv_request_sample(ctx->avctx, "4:4:4 8 bits");
return AVERROR_INVALIDDATA;
} else if (bitdepth == 10) {
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P10
: AV_PIX_FMT_GBRP10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_12_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P12
: AV_PIX_FMT_GBRP12;
}
} else if (bitdepth == 12) {
ctx->decode_dct_block = dnxhd_decode_dct_block_12;
ctx->pix_fmt = AV_PIX_FMT_YUV422P12;
} else if (bitdepth == 10) {
if (ctx->avctx->profile == FF_PROFILE_DNXHR_HQX)
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
else
ctx->decode_dct_block = dnxhd_decode_dct_block_10;
ctx->pix_fmt = AV_PIX_FMT_YUV422P10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_8;
ctx->pix_fmt = AV_PIX_FMT_YUV422P;
}
ctx->avctx->bits_per_raw_sample = ctx->bit_depth = bitdepth;
if (ctx->bit_depth != old_bit_depth) {
ff_blockdsp_init(&ctx->bdsp, ctx->avctx);
ff_idctdsp_init(&ctx->idsp, ctx->avctx);
ff_init_scantable(ctx->idsp.idct_permutation, &ctx->scantable,
ff_zigzag_direct);
}
if (ctx->width != ctx->cid_table->width &&
ctx->cid_table->width != DNXHD_VARIABLE) {
av_reduce(&ctx->avctx->sample_aspect_ratio.num,
&ctx->avctx->sample_aspect_ratio.den,
ctx->width, ctx->cid_table->width, 255);
ctx->width = ctx->cid_table->width;
}
if (buf_size < ctx->cid_table->coding_unit_size) {
av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size (%d < %u).\n",
buf_size, ctx->cid_table->coding_unit_size);
return AVERROR_INVALIDDATA;
}
ctx->mb_width = (ctx->width + 15)>> 4;
ctx->mb_height = AV_RB16(buf + 0x16c);
if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame)
ctx->height <<= 1;
av_log(ctx->avctx, AV_LOG_VERBOSE, "%dx%d, 4:%s %d bits, MBAFF=%d ACT=%d\n",
ctx->width, ctx->height, ctx->is_444 ? "4:4" : "2:2",
ctx->bit_depth, ctx->mbaff, ctx->act);
if (ctx->mb_height > 68 && ff_dnxhd_check_header_prefix_hr(header_prefix)) {
ctx->data_offset = 0x170 + (ctx->mb_height << 2);
} else {
if (ctx->mb_height > 68 ||
(ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb height too big: %d\n", ctx->mb_height);
return AVERROR_INVALIDDATA;
}
ctx->data_offset = 0x280;
}
if (buf_size < ctx->data_offset) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < %d).\n", buf_size, ctx->data_offset);
return AVERROR_INVALIDDATA;
}
if (ctx->mb_height > FF_ARRAY_ELEMS(ctx->mb_scan_index)) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb_height too big (%d > %"SIZE_SPECIFIER").\n", ctx->mb_height, FF_ARRAY_ELEMS(ctx->mb_scan_index));
return AVERROR_INVALIDDATA;
}
for (i = 0; i < ctx->mb_height; i++) {
ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2));
ff_dlog(ctx->avctx, "mb scan index %d, pos %d: %"PRIu32"\n",
i, 0x170 + (i << 2), ctx->mb_scan_index[i]);
if (buf_size - ctx->data_offset < ctx->mb_scan_index[i]) {
av_log(ctx->avctx, AV_LOG_ERROR,
"invalid mb scan index (%"PRIu32" vs %u).\n",
ctx->mb_scan_index[i], buf_size - ctx->data_offset);
return AVERROR_INVALIDDATA;
}
}
return 0;
}
Commit Message: avcodec/dnxhddec: Move mb height check out of non hr branch
Fixes: out of array access
Fixes: poc.dnxhd
Found-by: Bingchang, Liu@VARAS of IIE
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-125 | static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,
const uint8_t *buf, int buf_size,
int first_field)
{
int i, cid, ret;
int old_bit_depth = ctx->bit_depth, bitdepth;
uint64_t header_prefix;
if (buf_size < 0x280) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < 640).\n", buf_size);
return AVERROR_INVALIDDATA;
}
header_prefix = ff_dnxhd_parse_header_prefix(buf);
if (header_prefix == 0) {
av_log(ctx->avctx, AV_LOG_ERROR,
"unknown header 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n",
buf[0], buf[1], buf[2], buf[3], buf[4]);
return AVERROR_INVALIDDATA;
}
if (buf[5] & 2) { /* interlaced */
ctx->cur_field = buf[5] & 1;
frame->interlaced_frame = 1;
frame->top_field_first = first_field ^ ctx->cur_field;
av_log(ctx->avctx, AV_LOG_DEBUG,
"interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field);
} else {
ctx->cur_field = 0;
}
ctx->mbaff = (buf[0x6] >> 5) & 1;
ctx->height = AV_RB16(buf + 0x18);
ctx->width = AV_RB16(buf + 0x1a);
switch(buf[0x21] >> 5) {
case 1: bitdepth = 8; break;
case 2: bitdepth = 10; break;
case 3: bitdepth = 12; break;
default:
av_log(ctx->avctx, AV_LOG_ERROR,
"Unknown bitdepth indicator (%d)\n", buf[0x21] >> 5);
return AVERROR_INVALIDDATA;
}
cid = AV_RB32(buf + 0x28);
ctx->avctx->profile = dnxhd_get_profile(cid);
if ((ret = dnxhd_init_vlc(ctx, cid, bitdepth)) < 0)
return ret;
if (ctx->mbaff && ctx->cid_table->cid != 1260)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive MB interlace flag in an unsupported profile.\n");
ctx->act = buf[0x2C] & 7;
if (ctx->act && ctx->cid_table->cid != 1256 && ctx->cid_table->cid != 1270)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive color transform in an unsupported profile.\n");
ctx->is_444 = (buf[0x2C] >> 6) & 1;
if (ctx->is_444) {
if (bitdepth == 8) {
avpriv_request_sample(ctx->avctx, "4:4:4 8 bits");
return AVERROR_INVALIDDATA;
} else if (bitdepth == 10) {
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P10
: AV_PIX_FMT_GBRP10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_12_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P12
: AV_PIX_FMT_GBRP12;
}
} else if (bitdepth == 12) {
ctx->decode_dct_block = dnxhd_decode_dct_block_12;
ctx->pix_fmt = AV_PIX_FMT_YUV422P12;
} else if (bitdepth == 10) {
if (ctx->avctx->profile == FF_PROFILE_DNXHR_HQX)
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
else
ctx->decode_dct_block = dnxhd_decode_dct_block_10;
ctx->pix_fmt = AV_PIX_FMT_YUV422P10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_8;
ctx->pix_fmt = AV_PIX_FMT_YUV422P;
}
ctx->avctx->bits_per_raw_sample = ctx->bit_depth = bitdepth;
if (ctx->bit_depth != old_bit_depth) {
ff_blockdsp_init(&ctx->bdsp, ctx->avctx);
ff_idctdsp_init(&ctx->idsp, ctx->avctx);
ff_init_scantable(ctx->idsp.idct_permutation, &ctx->scantable,
ff_zigzag_direct);
}
if (ctx->width != ctx->cid_table->width &&
ctx->cid_table->width != DNXHD_VARIABLE) {
av_reduce(&ctx->avctx->sample_aspect_ratio.num,
&ctx->avctx->sample_aspect_ratio.den,
ctx->width, ctx->cid_table->width, 255);
ctx->width = ctx->cid_table->width;
}
if (buf_size < ctx->cid_table->coding_unit_size) {
av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size (%d < %u).\n",
buf_size, ctx->cid_table->coding_unit_size);
return AVERROR_INVALIDDATA;
}
ctx->mb_width = (ctx->width + 15)>> 4;
ctx->mb_height = AV_RB16(buf + 0x16c);
if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame)
ctx->height <<= 1;
av_log(ctx->avctx, AV_LOG_VERBOSE, "%dx%d, 4:%s %d bits, MBAFF=%d ACT=%d\n",
ctx->width, ctx->height, ctx->is_444 ? "4:4" : "2:2",
ctx->bit_depth, ctx->mbaff, ctx->act);
if (ctx->mb_height > 68 && ff_dnxhd_check_header_prefix_hr(header_prefix)) {
ctx->data_offset = 0x170 + (ctx->mb_height << 2);
} else {
if (ctx->mb_height > 68) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb height too big: %d\n", ctx->mb_height);
return AVERROR_INVALIDDATA;
}
ctx->data_offset = 0x280;
}
if ((ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb height too big: %d\n", ctx->mb_height);
return AVERROR_INVALIDDATA;
}
if (buf_size < ctx->data_offset) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < %d).\n", buf_size, ctx->data_offset);
return AVERROR_INVALIDDATA;
}
if (ctx->mb_height > FF_ARRAY_ELEMS(ctx->mb_scan_index)) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb_height too big (%d > %"SIZE_SPECIFIER").\n", ctx->mb_height, FF_ARRAY_ELEMS(ctx->mb_scan_index));
return AVERROR_INVALIDDATA;
}
for (i = 0; i < ctx->mb_height; i++) {
ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2));
ff_dlog(ctx->avctx, "mb scan index %d, pos %d: %"PRIu32"\n",
i, 0x170 + (i << 2), ctx->mb_scan_index[i]);
if (buf_size - ctx->data_offset < ctx->mb_scan_index[i]) {
av_log(ctx->avctx, AV_LOG_ERROR,
"invalid mb scan index (%"PRIu32" vs %u).\n",
ctx->mb_scan_index[i], buf_size - ctx->data_offset);
return AVERROR_INVALIDDATA;
}
}
return 0;
}
| 168,000 |
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: xsltCopyTextString(xsltTransformContextPtr ctxt, xmlNodePtr target,
const xmlChar *string, int noescape)
{
xmlNodePtr copy;
int len;
if (string == NULL)
return(NULL);
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_COPY_TEXT,xsltGenericDebug(xsltGenericDebugContext,
"xsltCopyTextString: copy text %s\n",
string));
#endif
/*
* Play safe and reset the merging mechanism for every new
* target node.
*/
if ((target == NULL) || (target->children == NULL)) {
ctxt->lasttext = NULL;
}
/* handle coalescing of text nodes here */
len = xmlStrlen(string);
if ((ctxt->type == XSLT_OUTPUT_XML) &&
(ctxt->style->cdataSection != NULL) &&
(target != NULL) &&
(target->type == XML_ELEMENT_NODE) &&
(((target->ns == NULL) &&
(xmlHashLookup2(ctxt->style->cdataSection,
target->name, NULL) != NULL)) ||
((target->ns != NULL) &&
(xmlHashLookup2(ctxt->style->cdataSection,
target->name, target->ns->href) != NULL))))
{
/*
* Process "cdata-section-elements".
*/
if ((target->last != NULL) &&
(target->last->type == XML_CDATA_SECTION_NODE))
{
return(xsltAddTextString(ctxt, target->last, string, len));
}
copy = xmlNewCDataBlock(ctxt->output, string, len);
} else if (noescape) {
/*
* Process "disable-output-escaping".
*/
if ((target != NULL) && (target->last != NULL) &&
(target->last->type == XML_TEXT_NODE) &&
(target->last->name == xmlStringTextNoenc))
{
return(xsltAddTextString(ctxt, target->last, string, len));
}
copy = xmlNewTextLen(string, len);
if (copy != NULL)
copy->name = xmlStringTextNoenc;
} else {
/*
* Default processing.
*/
if ((target != NULL) && (target->last != NULL) &&
(target->last->type == XML_TEXT_NODE) &&
(target->last->name == xmlStringText)) {
return(xsltAddTextString(ctxt, target->last, string, len));
}
copy = xmlNewTextLen(string, len);
}
if (copy != NULL) {
if (target != NULL)
copy = xsltAddChild(target, copy);
ctxt->lasttext = copy->content;
ctxt->lasttsize = len;
ctxt->lasttuse = len;
} else {
xsltTransformError(ctxt, NULL, target,
"xsltCopyTextString: text copy failed\n");
ctxt->lasttext = NULL;
}
return(copy);
}
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 | xsltCopyTextString(xsltTransformContextPtr ctxt, xmlNodePtr target,
const xmlChar *string, int noescape)
{
xmlNodePtr copy;
int len;
if (string == NULL)
return(NULL);
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_COPY_TEXT,xsltGenericDebug(xsltGenericDebugContext,
"xsltCopyTextString: copy text %s\n",
string));
#endif
/*
* Play safe and reset the merging mechanism for every new
* target node.
*/
if ((target == NULL) || (target->children == NULL)) {
ctxt->lasttext = NULL;
}
/* handle coalescing of text nodes here */
len = xmlStrlen(string);
if ((ctxt->type == XSLT_OUTPUT_XML) &&
(ctxt->style->cdataSection != NULL) &&
(target != NULL) &&
(target->type == XML_ELEMENT_NODE) &&
(((target->ns == NULL) &&
(xmlHashLookup2(ctxt->style->cdataSection,
target->name, NULL) != NULL)) ||
((target->ns != NULL) &&
(xmlHashLookup2(ctxt->style->cdataSection,
target->name, target->ns->href) != NULL))))
{
/*
* Process "cdata-section-elements".
*/
if ((target->last != NULL) &&
(target->last->type == XML_CDATA_SECTION_NODE))
{
return(xsltAddTextString(ctxt, target->last, string, len));
}
copy = xmlNewCDataBlock(ctxt->output, string, len);
} else if (noescape) {
/*
* Process "disable-output-escaping".
*/
if ((target != NULL) && (target->last != NULL) &&
(target->last->type == XML_TEXT_NODE) &&
(target->last->name == xmlStringTextNoenc))
{
return(xsltAddTextString(ctxt, target->last, string, len));
}
copy = xmlNewTextLen(string, len);
if (copy != NULL)
copy->name = xmlStringTextNoenc;
} else {
/*
* Default processing.
*/
if ((target != NULL) && (target->last != NULL) &&
(target->last->type == XML_TEXT_NODE) &&
(target->last->name == xmlStringText)) {
return(xsltAddTextString(ctxt, target->last, string, len));
}
copy = xmlNewTextLen(string, len);
}
if (copy != NULL && target != NULL)
copy = xsltAddChild(target, copy);
if (copy != NULL) {
ctxt->lasttext = copy->content;
ctxt->lasttsize = len;
ctxt->lasttuse = len;
} else {
xsltTransformError(ctxt, NULL, target,
"xsltCopyTextString: text copy failed\n");
ctxt->lasttext = NULL;
}
return(copy);
}
| 173,323 |
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: Chapters::Atom::Atom()
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | Chapters::Atom::Atom()
long long SegmentInfo::GetDuration() const {
if (m_duration < 0)
return -1;
assert(m_timecodeScale >= 1);
const double dd = double(m_duration) * double(m_timecodeScale);
const long long d = static_cast<long long>(dd);
return d;
}
| 174,238 |
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: rdp_in_unistr(STREAM s, int in_len, char **string, uint32 * str_size)
{
static iconv_t icv_utf16_to_local;
size_t ibl, obl;
char *pin, *pout;
if (!icv_utf16_to_local)
{
icv_utf16_to_local = iconv_open(g_codepage, WINDOWS_CODEPAGE);
if (icv_utf16_to_local == (iconv_t) - 1)
{
logger(Protocol, Error, "rdp_in_unistr(), iconv_open[%s -> %s] fail %p",
WINDOWS_CODEPAGE, g_codepage, icv_utf16_to_local);
abort();
}
}
/* Dynamic allocate of destination string if not provided */
if (*string == NULL)
{
*string = xmalloc(in_len * 2);
*str_size = in_len * 2;
}
ibl = in_len;
obl = *str_size - 1;
pin = (char *) s->p;
pout = *string;
if (iconv(icv_utf16_to_local, (char **) &pin, &ibl, &pout, &obl) == (size_t) - 1)
{
if (errno == E2BIG)
{
logger(Protocol, Warning,
"rdp_in_unistr(), server sent an unexpectedly long string, truncating");
}
else
{
logger(Protocol, Warning, "rdp_in_unistr(), iconv fail, errno %d", errno);
free(*string);
*string = NULL;
*str_size = 0;
}
abort();
}
/* we must update the location of the current STREAM for future reads of s->p */
s->p += in_len;
*pout = 0;
if (*string)
*str_size = pout - *string;
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119 | rdp_in_unistr(STREAM s, int in_len, char **string, uint32 * str_size)
{
static iconv_t icv_utf16_to_local;
size_t ibl, obl;
char *pin, *pout;
struct stream packet = *s;
if ((in_len < 0) || ((uint32)in_len >= (RD_UINT32_MAX / 2)))
{
logger(Protocol, Error, "rdp_in_unistr(), length of unicode data is out of bounds.");
abort();
}
if (!s_check_rem(s, in_len))
{
rdp_protocol_error("rdp_in_unistr(), consume of unicode data from stream would overrun", &packet);
}
if (!icv_utf16_to_local)
{
icv_utf16_to_local = iconv_open(g_codepage, WINDOWS_CODEPAGE);
if (icv_utf16_to_local == (iconv_t) - 1)
{
logger(Protocol, Error, "rdp_in_unistr(), iconv_open[%s -> %s] fail %p",
WINDOWS_CODEPAGE, g_codepage, icv_utf16_to_local);
abort();
}
}
/* Dynamic allocate of destination string if not provided */
if (*string == NULL)
{
*string = xmalloc(in_len * 2);
*str_size = in_len * 2;
}
ibl = in_len;
obl = *str_size - 1;
pin = (char *) s->p;
pout = *string;
if (iconv(icv_utf16_to_local, (char **) &pin, &ibl, &pout, &obl) == (size_t) - 1)
{
if (errno == E2BIG)
{
logger(Protocol, Warning,
"rdp_in_unistr(), server sent an unexpectedly long string, truncating");
}
else
{
logger(Protocol, Warning, "rdp_in_unistr(), iconv fail, errno %d", errno);
free(*string);
*string = NULL;
*str_size = 0;
}
abort();
}
/* we must update the location of the current STREAM for future reads of s->p */
s->p += in_len;
*pout = 0;
if (*string)
*str_size = pout - *string;
}
| 169,804 |
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: xfs_attr_shortform_list(xfs_attr_list_context_t *context)
{
attrlist_cursor_kern_t *cursor;
xfs_attr_sf_sort_t *sbuf, *sbp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_inode_t *dp;
int sbsize, nsbuf, count, i;
int error;
ASSERT(context != NULL);
dp = context->dp;
ASSERT(dp != NULL);
ASSERT(dp->i_afp != NULL);
sf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data;
ASSERT(sf != NULL);
if (!sf->hdr.count)
return 0;
cursor = context->cursor;
ASSERT(cursor != NULL);
trace_xfs_attr_list_sf(context);
/*
* If the buffer is large enough and the cursor is at the start,
* do not bother with sorting since we will return everything in
* one buffer and another call using the cursor won't need to be
* made.
* Note the generous fudge factor of 16 overhead bytes per entry.
* If bufsize is zero then put_listent must be a search function
* and can just scan through what we have.
*/
if (context->bufsize == 0 ||
(XFS_ISRESET_CURSOR(cursor) &&
(dp->i_afp->if_bytes + sf->hdr.count * 16) < context->bufsize)) {
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
error = context->put_listent(context,
sfe->flags,
sfe->nameval,
(int)sfe->namelen,
(int)sfe->valuelen,
&sfe->nameval[sfe->namelen]);
/*
* Either search callback finished early or
* didn't fit it all in the buffer after all.
*/
if (context->seen_enough)
break;
if (error)
return error;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
trace_xfs_attr_list_sf_all(context);
return 0;
}
/* do no more for a search callback */
if (context->bufsize == 0)
return 0;
/*
* It didn't all fit, so we have to sort everything on hashval.
*/
sbsize = sf->hdr.count * sizeof(*sbuf);
sbp = sbuf = kmem_alloc(sbsize, KM_SLEEP | KM_NOFS);
/*
* Scan the attribute list for the rest of the entries, storing
* the relevant info from only those that match into a buffer.
*/
nsbuf = 0;
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
if (unlikely(
((char *)sfe < (char *)sf) ||
((char *)sfe >= ((char *)sf + dp->i_afp->if_bytes)))) {
XFS_CORRUPTION_ERROR("xfs_attr_shortform_list",
XFS_ERRLEVEL_LOW,
context->dp->i_mount, sfe);
kmem_free(sbuf);
return -EFSCORRUPTED;
}
sbp->entno = i;
sbp->hash = xfs_da_hashname(sfe->nameval, sfe->namelen);
sbp->name = sfe->nameval;
sbp->namelen = sfe->namelen;
/* These are bytes, and both on-disk, don't endian-flip */
sbp->valuelen = sfe->valuelen;
sbp->flags = sfe->flags;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
sbp++;
nsbuf++;
}
/*
* Sort the entries on hash then entno.
*/
xfs_sort(sbuf, nsbuf, sizeof(*sbuf), xfs_attr_shortform_compare);
/*
* Re-find our place IN THE SORTED LIST.
*/
count = 0;
cursor->initted = 1;
cursor->blkno = 0;
for (sbp = sbuf, i = 0; i < nsbuf; i++, sbp++) {
if (sbp->hash == cursor->hashval) {
if (cursor->offset == count) {
break;
}
count++;
} else if (sbp->hash > cursor->hashval) {
break;
}
}
if (i == nsbuf) {
kmem_free(sbuf);
return 0;
}
/*
* Loop putting entries into the user buffer.
*/
for ( ; i < nsbuf; i++, sbp++) {
if (cursor->hashval != sbp->hash) {
cursor->hashval = sbp->hash;
cursor->offset = 0;
}
error = context->put_listent(context,
sbp->flags,
sbp->name,
sbp->namelen,
sbp->valuelen,
&sbp->name[sbp->namelen]);
if (error)
return error;
if (context->seen_enough)
break;
cursor->offset++;
}
kmem_free(sbuf);
return 0;
}
Commit Message: xfs: fix two memory leaks in xfs_attr_list.c error paths
This plugs 2 trivial leaks in xfs_attr_shortform_list and
xfs_attr3_leaf_list_int.
Signed-off-by: Mateusz Guzik <[email protected]>
Cc: <[email protected]>
Reviewed-by: Eric Sandeen <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-400 | xfs_attr_shortform_list(xfs_attr_list_context_t *context)
{
attrlist_cursor_kern_t *cursor;
xfs_attr_sf_sort_t *sbuf, *sbp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_inode_t *dp;
int sbsize, nsbuf, count, i;
int error;
ASSERT(context != NULL);
dp = context->dp;
ASSERT(dp != NULL);
ASSERT(dp->i_afp != NULL);
sf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data;
ASSERT(sf != NULL);
if (!sf->hdr.count)
return 0;
cursor = context->cursor;
ASSERT(cursor != NULL);
trace_xfs_attr_list_sf(context);
/*
* If the buffer is large enough and the cursor is at the start,
* do not bother with sorting since we will return everything in
* one buffer and another call using the cursor won't need to be
* made.
* Note the generous fudge factor of 16 overhead bytes per entry.
* If bufsize is zero then put_listent must be a search function
* and can just scan through what we have.
*/
if (context->bufsize == 0 ||
(XFS_ISRESET_CURSOR(cursor) &&
(dp->i_afp->if_bytes + sf->hdr.count * 16) < context->bufsize)) {
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
error = context->put_listent(context,
sfe->flags,
sfe->nameval,
(int)sfe->namelen,
(int)sfe->valuelen,
&sfe->nameval[sfe->namelen]);
/*
* Either search callback finished early or
* didn't fit it all in the buffer after all.
*/
if (context->seen_enough)
break;
if (error)
return error;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
trace_xfs_attr_list_sf_all(context);
return 0;
}
/* do no more for a search callback */
if (context->bufsize == 0)
return 0;
/*
* It didn't all fit, so we have to sort everything on hashval.
*/
sbsize = sf->hdr.count * sizeof(*sbuf);
sbp = sbuf = kmem_alloc(sbsize, KM_SLEEP | KM_NOFS);
/*
* Scan the attribute list for the rest of the entries, storing
* the relevant info from only those that match into a buffer.
*/
nsbuf = 0;
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
if (unlikely(
((char *)sfe < (char *)sf) ||
((char *)sfe >= ((char *)sf + dp->i_afp->if_bytes)))) {
XFS_CORRUPTION_ERROR("xfs_attr_shortform_list",
XFS_ERRLEVEL_LOW,
context->dp->i_mount, sfe);
kmem_free(sbuf);
return -EFSCORRUPTED;
}
sbp->entno = i;
sbp->hash = xfs_da_hashname(sfe->nameval, sfe->namelen);
sbp->name = sfe->nameval;
sbp->namelen = sfe->namelen;
/* These are bytes, and both on-disk, don't endian-flip */
sbp->valuelen = sfe->valuelen;
sbp->flags = sfe->flags;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
sbp++;
nsbuf++;
}
/*
* Sort the entries on hash then entno.
*/
xfs_sort(sbuf, nsbuf, sizeof(*sbuf), xfs_attr_shortform_compare);
/*
* Re-find our place IN THE SORTED LIST.
*/
count = 0;
cursor->initted = 1;
cursor->blkno = 0;
for (sbp = sbuf, i = 0; i < nsbuf; i++, sbp++) {
if (sbp->hash == cursor->hashval) {
if (cursor->offset == count) {
break;
}
count++;
} else if (sbp->hash > cursor->hashval) {
break;
}
}
if (i == nsbuf) {
kmem_free(sbuf);
return 0;
}
/*
* Loop putting entries into the user buffer.
*/
for ( ; i < nsbuf; i++, sbp++) {
if (cursor->hashval != sbp->hash) {
cursor->hashval = sbp->hash;
cursor->offset = 0;
}
error = context->put_listent(context,
sbp->flags,
sbp->name,
sbp->namelen,
sbp->valuelen,
&sbp->name[sbp->namelen]);
if (error) {
kmem_free(sbuf);
return error;
}
if (context->seen_enough)
break;
cursor->offset++;
}
kmem_free(sbuf);
return 0;
}
| 166,853 |
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 trigger_fpga_config(void)
{
int ret = 0;
/* if the FPGA is already configured, we do not want to
* reconfigure it */
skip = 0;
if (fpga_done()) {
printf("PCIe FPGA config: skipped\n");
skip = 1;
return 0;
}
if (check_boco2()) {
/* we have a BOCO2, this has to be triggered here */
/* make sure the FPGA_can access the EEPROM */
ret = boco_clear_bits(SPI_REG, CFG_EEPROM);
if (ret)
return ret;
/* trigger the config start */
ret = boco_clear_bits(SPI_REG, FPGA_PROG | FPGA_INIT_B);
if (ret)
return ret;
/* small delay for the pulse */
udelay(10);
/* up signal for pulse end */
ret = boco_set_bits(SPI_REG, FPGA_PROG);
if (ret)
return ret;
/* finally, raise INIT_B to remove the config delay */
ret = boco_set_bits(SPI_REG, FPGA_INIT_B);
if (ret)
return ret;
} else {
/* we do it the old way, with the gpio pin */
kw_gpio_set_valid(KM_XLX_PROGRAM_B_PIN, 1);
kw_gpio_direction_output(KM_XLX_PROGRAM_B_PIN, 0);
/* small delay for the pulse */
udelay(10);
kw_gpio_direction_input(KM_XLX_PROGRAM_B_PIN);
}
return 0;
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787 | int trigger_fpga_config(void)
{
int ret = 0;
skip = 0;
#ifndef CONFIG_KM_FPGA_FORCE_CONFIG
/* if the FPGA is already configured, we do not want to
* reconfigure it */
skip = 0;
if (fpga_done()) {
printf("PCIe FPGA config: skipped\n");
skip = 1;
return 0;
}
#endif /* CONFIG_KM_FPGA_FORCE_CONFIG */
if (check_boco2()) {
/* we have a BOCO2, this has to be triggered here */
/* make sure the FPGA_can access the EEPROM */
ret = boco_clear_bits(SPI_REG, CFG_EEPROM);
if (ret)
return ret;
/* trigger the config start */
ret = boco_clear_bits(SPI_REG, FPGA_PROG | FPGA_INIT_B);
if (ret)
return ret;
/* small delay for the pulse */
udelay(10);
/* up signal for pulse end */
ret = boco_set_bits(SPI_REG, FPGA_PROG);
if (ret)
return ret;
/* finally, raise INIT_B to remove the config delay */
ret = boco_set_bits(SPI_REG, FPGA_INIT_B);
if (ret)
return ret;
} else {
/* we do it the old way, with the gpio pin */
kw_gpio_set_valid(KM_XLX_PROGRAM_B_PIN, 1);
kw_gpio_direction_output(KM_XLX_PROGRAM_B_PIN, 0);
/* small delay for the pulse */
udelay(10);
kw_gpio_direction_input(KM_XLX_PROGRAM_B_PIN);
}
return 0;
}
| 169,627 |
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: OMX_ERRORTYPE SoftG711::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nChannels < 1 || pcmParams->nChannels > 2) {
return OMX_ErrorUndefined;
}
if(pcmParams->nPortIndex == 0) {
mNumChannels = pcmParams->nChannels;
}
mSamplingRate = pcmParams->nSamplingRate;
return OMX_ErrorNone;
}
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (mIsMLaw) {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.g711mlaw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
} else {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.g711alaw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftG711::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nChannels < 1 || pcmParams->nChannels > 2) {
return OMX_ErrorUndefined;
}
if(pcmParams->nPortIndex == 0) {
mNumChannels = pcmParams->nChannels;
}
mSamplingRate = pcmParams->nSamplingRate;
return OMX_ErrorNone;
}
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (mIsMLaw) {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.g711mlaw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
} else {
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.g711alaw",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,206 |
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 asn1_find_indefinite_length(const unsigned char *data, size_t datalen,
size_t *_dp, size_t *_len,
const char **_errmsg)
{
unsigned char tag, tmp;
size_t dp = *_dp, len, n;
int indef_level = 1;
next_tag:
if (unlikely(datalen - dp < 2)) {
if (datalen == dp)
goto missing_eoc;
goto data_overrun_error;
}
/* Extract a tag from the data */
tag = data[dp++];
if (tag == 0) {
/* It appears to be an EOC. */
if (data[dp++] != 0)
goto invalid_eoc;
if (--indef_level <= 0) {
*_len = dp - *_dp;
*_dp = dp;
return 0;
}
goto next_tag;
}
if (unlikely((tag & 0x1f) == ASN1_LONG_TAG)) {
do {
if (unlikely(datalen - dp < 2))
goto data_overrun_error;
tmp = data[dp++];
} while (tmp & 0x80);
}
/* Extract the length */
len = data[dp++];
if (len <= 0x7f) {
dp += len;
goto next_tag;
}
if (unlikely(len == ASN1_INDEFINITE_LENGTH)) {
/* Indefinite length */
if (unlikely((tag & ASN1_CONS_BIT) == ASN1_PRIM << 5))
goto indefinite_len_primitive;
indef_level++;
goto next_tag;
}
n = len - 0x80;
if (unlikely(n > sizeof(size_t) - 1))
goto length_too_long;
if (unlikely(n > datalen - dp))
goto data_overrun_error;
for (len = 0; n > 0; n--) {
len <<= 8;
len |= data[dp++];
}
dp += len;
goto next_tag;
length_too_long:
*_errmsg = "Unsupported length";
goto error;
indefinite_len_primitive:
*_errmsg = "Indefinite len primitive not permitted";
goto error;
invalid_eoc:
*_errmsg = "Invalid length EOC";
goto error;
data_overrun_error:
*_errmsg = "Data overrun error";
goto error;
missing_eoc:
*_errmsg = "Missing EOC in indefinite len cons";
error:
*_dp = dp;
return -1;
}
Commit Message: KEYS: Fix ASN.1 indefinite length object parsing
This fixes CVE-2016-0758.
In the ASN.1 decoder, when the length field of an ASN.1 value is extracted,
it isn't validated against the remaining amount of data before being added
to the cursor. With a sufficiently large size indicated, the check:
datalen - dp < 2
may then fail due to integer overflow.
Fix this by checking the length indicated against the amount of remaining
data in both places a definite length is determined.
Whilst we're at it, make the following changes:
(1) Check the maximum size of extended length does not exceed the capacity
of the variable it's being stored in (len) rather than the type that
variable is assumed to be (size_t).
(2) Compare the EOC tag to the symbolic constant ASN1_EOC rather than the
integer 0.
(3) To reduce confusion, move the initialisation of len outside of:
for (len = 0; n > 0; n--) {
since it doesn't have anything to do with the loop counter n.
Signed-off-by: David Howells <[email protected]>
Reviewed-by: Mimi Zohar <[email protected]>
Acked-by: David Woodhouse <[email protected]>
Acked-by: Peter Jones <[email protected]>
CWE ID: | static int asn1_find_indefinite_length(const unsigned char *data, size_t datalen,
size_t *_dp, size_t *_len,
const char **_errmsg)
{
unsigned char tag, tmp;
size_t dp = *_dp, len, n;
int indef_level = 1;
next_tag:
if (unlikely(datalen - dp < 2)) {
if (datalen == dp)
goto missing_eoc;
goto data_overrun_error;
}
/* Extract a tag from the data */
tag = data[dp++];
if (tag == ASN1_EOC) {
/* It appears to be an EOC. */
if (data[dp++] != 0)
goto invalid_eoc;
if (--indef_level <= 0) {
*_len = dp - *_dp;
*_dp = dp;
return 0;
}
goto next_tag;
}
if (unlikely((tag & 0x1f) == ASN1_LONG_TAG)) {
do {
if (unlikely(datalen - dp < 2))
goto data_overrun_error;
tmp = data[dp++];
} while (tmp & 0x80);
}
/* Extract the length */
len = data[dp++];
if (len <= 0x7f)
goto check_length;
if (unlikely(len == ASN1_INDEFINITE_LENGTH)) {
/* Indefinite length */
if (unlikely((tag & ASN1_CONS_BIT) == ASN1_PRIM << 5))
goto indefinite_len_primitive;
indef_level++;
goto next_tag;
}
n = len - 0x80;
if (unlikely(n > sizeof(len) - 1))
goto length_too_long;
if (unlikely(n > datalen - dp))
goto data_overrun_error;
len = 0;
for (; n > 0; n--) {
len <<= 8;
len |= data[dp++];
}
check_length:
if (len > datalen - dp)
goto data_overrun_error;
dp += len;
goto next_tag;
length_too_long:
*_errmsg = "Unsupported length";
goto error;
indefinite_len_primitive:
*_errmsg = "Indefinite len primitive not permitted";
goto error;
invalid_eoc:
*_errmsg = "Invalid length EOC";
goto error;
data_overrun_error:
*_errmsg = "Data overrun error";
goto error;
missing_eoc:
*_errmsg = "Missing EOC in indefinite len cons";
error:
*_dp = dp;
return -1;
}
| 167,451 |
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: X11SurfaceFactory::GetAllowedGLImplementations() {
std::vector<gl::GLImplementation> impls;
impls.push_back(gl::kGLImplementationEGLGLES2);
impls.push_back(gl::kGLImplementationDesktopGL);
impls.push_back(gl::kGLImplementationOSMesaGL);
return impls;
}
Commit Message: Add ThreadChecker for Ozone X11 GPU.
Ensure Ozone X11 tests the same thread constraints we have in Ozone GBM.
BUG=none
Review-Url: https://codereview.chromium.org/2366643002
Cr-Commit-Position: refs/heads/master@{#421817}
CWE ID: CWE-284 | X11SurfaceFactory::GetAllowedGLImplementations() {
DCHECK(thread_checker_.CalledOnValidThread());
std::vector<gl::GLImplementation> impls;
impls.push_back(gl::kGLImplementationEGLGLES2);
impls.push_back(gl::kGLImplementationDesktopGL);
impls.push_back(gl::kGLImplementationOSMesaGL);
return impls;
}
| 171,602 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 char* getPreferredTag(const char* gf_tag)
{
char* result = NULL;
int grOffset = 0;
grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);
if(grOffset < 0) {
return NULL;
}
if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){
/* return preferred tag */
result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );
} else {
/* Return correct grandfathered language tag */
result = estrdup( LOC_GRANDFATHERED[grOffset] );
}
return result;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | static char* getPreferredTag(const char* gf_tag)
{
char* result = NULL;
int grOffset = 0;
grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);
if(grOffset < 0) {
return NULL;
}
if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){
/* return preferred tag */
result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );
} else {
/* Return correct grandfathered language tag */
result = estrdup( LOC_GRANDFATHERED[grOffset] );
}
return result;
}
| 167,201 |
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: xps_parse_gradient_stops(xps_document *doc, char *base_uri, fz_xml *node,
struct stop *stops, int maxcount)
{
fz_colorspace *colorspace;
float sample[8];
float rgb[3];
int before, after;
int count;
int i;
/* We may have to insert 2 extra stops when postprocessing */
maxcount -= 2;
count = 0;
while (node && count < maxcount)
{
if (!strcmp(fz_xml_tag(node), "GradientStop"))
{
char *offset = fz_xml_att(node, "Offset");
char *color = fz_xml_att(node, "Color");
if (offset && color)
{
stops[count].offset = fz_atof(offset);
stops[count].index = count;
xps_parse_color(doc, base_uri, color, &colorspace, sample);
fz_convert_color(doc->ctx, fz_device_rgb(doc->ctx), rgb, colorspace, sample + 1);
stops[count].r = rgb[0];
stops[count].g = rgb[1];
stops[count].b = rgb[2];
stops[count].a = sample[0];
count ++;
}
}
node = fz_xml_next(node);
}
if (count == 0)
{
fz_warn(doc->ctx, "gradient brush has no gradient stops");
stops[0].offset = 0;
stops[0].r = 0;
stops[0].g = 0;
stops[0].b = 0;
stops[0].a = 1;
stops[1].offset = 1;
stops[1].r = 1;
stops[1].g = 1;
stops[1].b = 1;
stops[1].a = 1;
return 2;
}
if (count == maxcount)
fz_warn(doc->ctx, "gradient brush exceeded maximum number of gradient stops");
/* Postprocess to make sure the range of offsets is 0.0 to 1.0 */
qsort(stops, count, sizeof(struct stop), cmp_stop);
before = -1;
after = -1;
for (i = 0; i < count; i++)
{
if (stops[i].offset < 0)
before = i;
if (stops[i].offset > 1)
{
after = i;
break;
}
}
/* Remove all stops < 0 except the largest one */
if (before > 0)
{
memmove(stops, stops + before, (count - before) * sizeof(struct stop));
count -= before;
}
/* Remove all stops > 1 except the smallest one */
if (after >= 0)
count = after + 1;
/* Expand single stop to 0 .. 1 */
if (count == 1)
{
stops[1] = stops[0];
stops[0].offset = 0;
stops[1].offset = 1;
return 2;
}
/* First stop < 0 -- interpolate value to 0 */
if (stops[0].offset < 0)
{
float d = -stops[0].offset / (stops[1].offset - stops[0].offset);
stops[0].offset = 0;
stops[0].r = lerp(stops[0].r, stops[1].r, d);
stops[0].g = lerp(stops[0].g, stops[1].g, d);
stops[0].b = lerp(stops[0].b, stops[1].b, d);
stops[0].a = lerp(stops[0].a, stops[1].a, d);
}
/* Last stop > 1 -- interpolate value to 1 */
if (stops[count-1].offset > 1)
{
float d = (1 - stops[count-2].offset) / (stops[count-1].offset - stops[count-2].offset);
stops[count-1].offset = 1;
stops[count-1].r = lerp(stops[count-2].r, stops[count-1].r, d);
stops[count-1].g = lerp(stops[count-2].g, stops[count-1].g, d);
stops[count-1].b = lerp(stops[count-2].b, stops[count-1].b, d);
stops[count-1].a = lerp(stops[count-2].a, stops[count-1].a, d);
}
/* First stop > 0 -- insert a duplicate at 0 */
if (stops[0].offset > 0)
{
memmove(stops + 1, stops, count * sizeof(struct stop));
stops[0] = stops[1];
stops[0].offset = 0;
count++;
}
/* Last stop < 1 -- insert a duplicate at 1 */
if (stops[count-1].offset < 1)
{
stops[count] = stops[count-1];
stops[count].offset = 1;
count++;
}
return count;
}
Commit Message:
CWE ID: CWE-119 | xps_parse_gradient_stops(xps_document *doc, char *base_uri, fz_xml *node,
struct stop *stops, int maxcount)
{
fz_colorspace *colorspace;
float sample[FZ_MAX_COLORS];
float rgb[3];
int before, after;
int count;
int i;
/* We may have to insert 2 extra stops when postprocessing */
maxcount -= 2;
count = 0;
while (node && count < maxcount)
{
if (!strcmp(fz_xml_tag(node), "GradientStop"))
{
char *offset = fz_xml_att(node, "Offset");
char *color = fz_xml_att(node, "Color");
if (offset && color)
{
stops[count].offset = fz_atof(offset);
stops[count].index = count;
xps_parse_color(doc, base_uri, color, &colorspace, sample);
fz_convert_color(doc->ctx, fz_device_rgb(doc->ctx), rgb, colorspace, sample + 1);
stops[count].r = rgb[0];
stops[count].g = rgb[1];
stops[count].b = rgb[2];
stops[count].a = sample[0];
count ++;
}
}
node = fz_xml_next(node);
}
if (count == 0)
{
fz_warn(doc->ctx, "gradient brush has no gradient stops");
stops[0].offset = 0;
stops[0].r = 0;
stops[0].g = 0;
stops[0].b = 0;
stops[0].a = 1;
stops[1].offset = 1;
stops[1].r = 1;
stops[1].g = 1;
stops[1].b = 1;
stops[1].a = 1;
return 2;
}
if (count == maxcount)
fz_warn(doc->ctx, "gradient brush exceeded maximum number of gradient stops");
/* Postprocess to make sure the range of offsets is 0.0 to 1.0 */
qsort(stops, count, sizeof(struct stop), cmp_stop);
before = -1;
after = -1;
for (i = 0; i < count; i++)
{
if (stops[i].offset < 0)
before = i;
if (stops[i].offset > 1)
{
after = i;
break;
}
}
/* Remove all stops < 0 except the largest one */
if (before > 0)
{
memmove(stops, stops + before, (count - before) * sizeof(struct stop));
count -= before;
}
/* Remove all stops > 1 except the smallest one */
if (after >= 0)
count = after + 1;
/* Expand single stop to 0 .. 1 */
if (count == 1)
{
stops[1] = stops[0];
stops[0].offset = 0;
stops[1].offset = 1;
return 2;
}
/* First stop < 0 -- interpolate value to 0 */
if (stops[0].offset < 0)
{
float d = -stops[0].offset / (stops[1].offset - stops[0].offset);
stops[0].offset = 0;
stops[0].r = lerp(stops[0].r, stops[1].r, d);
stops[0].g = lerp(stops[0].g, stops[1].g, d);
stops[0].b = lerp(stops[0].b, stops[1].b, d);
stops[0].a = lerp(stops[0].a, stops[1].a, d);
}
/* Last stop > 1 -- interpolate value to 1 */
if (stops[count-1].offset > 1)
{
float d = (1 - stops[count-2].offset) / (stops[count-1].offset - stops[count-2].offset);
stops[count-1].offset = 1;
stops[count-1].r = lerp(stops[count-2].r, stops[count-1].r, d);
stops[count-1].g = lerp(stops[count-2].g, stops[count-1].g, d);
stops[count-1].b = lerp(stops[count-2].b, stops[count-1].b, d);
stops[count-1].a = lerp(stops[count-2].a, stops[count-1].a, d);
}
/* First stop > 0 -- insert a duplicate at 0 */
if (stops[0].offset > 0)
{
memmove(stops + 1, stops, count * sizeof(struct stop));
stops[0] = stops[1];
stops[0].offset = 0;
count++;
}
/* Last stop < 1 -- insert a duplicate at 1 */
if (stops[count-1].offset < 1)
{
stops[count] = stops[count-1];
stops[count].offset = 1;
count++;
}
return count;
}
| 165,230 |
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);
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: Check mp3 output buffer size
Bug: 27793371
Change-Id: I0fe40a4cfd0a5b488f93d3f3ba6f9495235926ac
CWE ID: CWE-20 | 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 %lu, 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;
}
}
| 173,777 |
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 MagickBooleanType Get8BIMProperty(const Image *image,const char *key,
ExceptionInfo *exception)
{
char
*attribute,
format[MagickPathExtent],
name[MagickPathExtent],
*resource;
const StringInfo
*profile;
const unsigned char
*info;
long
start,
stop;
MagickBooleanType
status;
register ssize_t
i;
size_t
length;
ssize_t
count,
id,
sub_number;
/*
There are no newlines in path names, so it's safe as terminator.
*/
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop,
name,format);
if ((count != 2) && (count != 3) && (count != 4))
return(MagickFalse);
if (count < 4)
(void) CopyMagickString(format,"SVG",MagickPathExtent);
if (count < 3)
*name='\0';
sub_number=1;
if (*name == '#')
sub_number=(ssize_t) StringToLong(&name[1]);
sub_number=MagickMax(sub_number,1L);
resource=(char *) NULL;
status=MagickFalse;
length=GetStringInfoLength(profile);
info=GetStringInfoDatum(profile);
while ((length > 0) && (status == MagickFalse))
{
if (ReadPropertyByte(&info,&length) != (unsigned char) '8')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')
continue;
id=(ssize_t) ReadPropertyMSBShort(&info,&length);
if (id < (ssize_t) start)
continue;
if (id > (ssize_t) stop)
continue;
if (resource != (char *) NULL)
resource=DestroyString(resource);
count=(ssize_t) ReadPropertyByte(&info,&length);
if ((count != 0) && ((size_t) count <= length))
{
resource=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
resource=(char *) AcquireQuantumMemory((size_t) count+
MagickPathExtent,sizeof(*resource));
if (resource != (char *) NULL)
{
for (i=0; i < (ssize_t) count; i++)
resource[i]=(char) ReadPropertyByte(&info,&length);
resource[count]='\0';
}
}
if ((count & 0x01) == 0)
(void) ReadPropertyByte(&info,&length);
count=(ssize_t) ReadPropertyMSBLong(&info,&length);
if ((*name != '\0') && (*name != '#'))
if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))
{
/*
No name match, scroll forward and try next.
*/
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
if ((*name == '#') && (sub_number != 1))
{
/*
No numbered match, scroll forward and try next.
*/
sub_number--;
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
/*
We have the resource of interest.
*/
attribute=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,
sizeof(*attribute));
if (attribute != (char *) NULL)
{
(void) CopyMagickMemory(attribute,(char *) info,(size_t) count);
attribute[count]='\0';
info+=count;
length-=MagickMin(count,(ssize_t) length);
if ((id <= 1999) || (id >= 2999))
(void) SetImageProperty((Image *) image,key,(const char *)
attribute,exception);
else
{
char
*path;
if (LocaleCompare(format,"svg") == 0)
path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,
image->columns,image->rows);
else
path=TracePSClippath((unsigned char *) attribute,(size_t) count);
(void) SetImageProperty((Image *) image,key,(const char *) path,
exception);
path=DestroyString(path);
}
attribute=DestroyString(attribute);
status=MagickTrue;
}
}
if (resource != (char *) NULL)
resource=DestroyString(resource);
return(status);
}
Commit Message: Prevent buffer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static MagickBooleanType Get8BIMProperty(const Image *image,const char *key,
ExceptionInfo *exception)
{
char
*attribute,
format[MagickPathExtent],
name[MagickPathExtent],
*resource;
const StringInfo
*profile;
const unsigned char
*info;
long
start,
stop;
MagickBooleanType
status;
register ssize_t
i;
size_t
length;
ssize_t
count,
id,
sub_number;
/*
There are no newlines in path names, so it's safe as terminator.
*/
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop,
name,format);
if ((count != 2) && (count != 3) && (count != 4))
return(MagickFalse);
if (count < 4)
(void) CopyMagickString(format,"SVG",MagickPathExtent);
if (count < 3)
*name='\0';
sub_number=1;
if (*name == '#')
sub_number=(ssize_t) StringToLong(&name[1]);
sub_number=MagickMax(sub_number,1L);
resource=(char *) NULL;
status=MagickFalse;
length=GetStringInfoLength(profile);
info=GetStringInfoDatum(profile);
while ((length > 0) && (status == MagickFalse))
{
if (ReadPropertyByte(&info,&length) != (unsigned char) '8')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')
continue;
id=(ssize_t) ReadPropertyMSBShort(&info,&length);
if (id < (ssize_t) start)
continue;
if (id > (ssize_t) stop)
continue;
if (resource != (char *) NULL)
resource=DestroyString(resource);
count=(ssize_t) ReadPropertyByte(&info,&length);
if ((count != 0) && ((size_t) count <= length))
{
resource=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
resource=(char *) AcquireQuantumMemory((size_t) count+
MagickPathExtent,sizeof(*resource));
if (resource != (char *) NULL)
{
for (i=0; i < (ssize_t) count; i++)
resource[i]=(char) ReadPropertyByte(&info,&length);
resource[count]='\0';
}
}
if ((count & 0x01) == 0)
(void) ReadPropertyByte(&info,&length);
count=(ssize_t) ReadPropertyMSBLong(&info,&length);
if ((count < 0) || ((size_t) count > length))
{
length=0;
continue;
}
if ((*name != '\0') && (*name != '#'))
if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))
{
/*
No name match, scroll forward and try next.
*/
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
if ((*name == '#') && (sub_number != 1))
{
/*
No numbered match, scroll forward and try next.
*/
sub_number--;
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
/*
We have the resource of interest.
*/
attribute=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,
sizeof(*attribute));
if (attribute != (char *) NULL)
{
(void) CopyMagickMemory(attribute,(char *) info,(size_t) count);
attribute[count]='\0';
info+=count;
length-=MagickMin(count,(ssize_t) length);
if ((id <= 1999) || (id >= 2999))
(void) SetImageProperty((Image *) image,key,(const char *)
attribute,exception);
else
{
char
*path;
if (LocaleCompare(format,"svg") == 0)
path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,
image->columns,image->rows);
else
path=TracePSClippath((unsigned char *) attribute,(size_t) count);
(void) SetImageProperty((Image *) image,key,(const char *) path,
exception);
path=DestroyString(path);
}
attribute=DestroyString(attribute);
status=MagickTrue;
}
}
if (resource != (char *) NULL)
resource=DestroyString(resource);
return(status);
}
| 166,999 |
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 SyncTest::TriggerSetSyncTabs() {
ASSERT_TRUE(ServerSupportsErrorTriggering());
std::string path = "chromiumsync/synctabs";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Sync Tabs",
UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle()));
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void SyncTest::TriggerSetSyncTabs() {
| 170,790 |
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: OMX_ERRORTYPE SoftAVCEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (bitRate->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
bitRate->eControlRate = OMX_Video_ControlRateVariable;
bitRate->nTargetBitrate = mBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoAvc:
{
OMX_VIDEO_PARAM_AVCTYPE *avcParams =
(OMX_VIDEO_PARAM_AVCTYPE *)params;
if (avcParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
avcParams->eProfile = OMX_VIDEO_AVCProfileBaseline;
OMX_U32 omxLevel = AVC_LEVEL2;
if (OMX_ErrorNone !=
ConvertAvcSpecLevelToOmxAvcLevel(mAVCEncLevel, &omxLevel)) {
return OMX_ErrorUndefined;
}
avcParams->eLevel = (OMX_VIDEO_AVCLEVELTYPE) omxLevel;
avcParams->nRefFrames = 1;
avcParams->nBFrames = 0;
avcParams->bUseHadamard = OMX_TRUE;
avcParams->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
avcParams->nRefIdx10ActiveMinus1 = 0;
avcParams->nRefIdx11ActiveMinus1 = 0;
avcParams->bWeightedPPrediction = OMX_FALSE;
avcParams->bEntropyCodingCABAC = OMX_FALSE;
avcParams->bconstIpred = OMX_FALSE;
avcParams->bDirect8x8Inference = OMX_FALSE;
avcParams->bDirectSpatialTemporal = OMX_FALSE;
avcParams->nCabacInitIdc = 0;
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftAVCEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (!isValidOMXParam(bitRate)) {
return OMX_ErrorBadParameter;
}
if (bitRate->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
bitRate->eControlRate = OMX_Video_ControlRateVariable;
bitRate->nTargetBitrate = mBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoAvc:
{
OMX_VIDEO_PARAM_AVCTYPE *avcParams =
(OMX_VIDEO_PARAM_AVCTYPE *)params;
if (!isValidOMXParam(avcParams)) {
return OMX_ErrorBadParameter;
}
if (avcParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
avcParams->eProfile = OMX_VIDEO_AVCProfileBaseline;
OMX_U32 omxLevel = AVC_LEVEL2;
if (OMX_ErrorNone !=
ConvertAvcSpecLevelToOmxAvcLevel(mAVCEncLevel, &omxLevel)) {
return OMX_ErrorUndefined;
}
avcParams->eLevel = (OMX_VIDEO_AVCLEVELTYPE) omxLevel;
avcParams->nRefFrames = 1;
avcParams->nBFrames = 0;
avcParams->bUseHadamard = OMX_TRUE;
avcParams->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
avcParams->nRefIdx10ActiveMinus1 = 0;
avcParams->nRefIdx11ActiveMinus1 = 0;
avcParams->bWeightedPPrediction = OMX_FALSE;
avcParams->bEntropyCodingCABAC = OMX_FALSE;
avcParams->bconstIpred = OMX_FALSE;
avcParams->bDirect8x8Inference = OMX_FALSE;
avcParams->bDirectSpatialTemporal = OMX_FALSE;
avcParams->nCabacInitIdc = 0;
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
}
}
| 174,198 |
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: GlobalHistogramAllocator::ReleaseForTesting() {
GlobalHistogramAllocator* histogram_allocator = Get();
if (!histogram_allocator)
return nullptr;
PersistentMemoryAllocator* memory_allocator =
histogram_allocator->memory_allocator();
PersistentMemoryAllocator::Iterator iter(memory_allocator);
const PersistentHistogramData* data;
while ((data = iter.GetNextOfObject<PersistentHistogramData>()) != nullptr) {
StatisticsRecorder::ForgetHistogramForTesting(data->name);
DCHECK_NE(kResultHistogram, data->name);
}
subtle::Release_Store(&g_histogram_allocator, 0);
return WrapUnique(histogram_allocator);
};
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <[email protected]>
Reviewed-by: Alexei Svitkine <[email protected]>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264 | GlobalHistogramAllocator::ReleaseForTesting() {
GlobalHistogramAllocator* histogram_allocator = Get();
if (!histogram_allocator)
return nullptr;
PersistentMemoryAllocator* memory_allocator =
histogram_allocator->memory_allocator();
PersistentMemoryAllocator::Iterator iter(memory_allocator);
const PersistentHistogramData* data;
while ((data = iter.GetNextOfObject<PersistentHistogramData>()) != nullptr) {
StatisticsRecorder::ForgetHistogramForTesting(data->name);
}
subtle::Release_Store(&g_histogram_allocator, 0);
return WrapUnique(histogram_allocator);
};
| 172,136 |
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 main(void)
{
int fd, len, sock_opt;
int error;
struct cn_msg *message;
struct pollfd pfd;
struct nlmsghdr *incoming_msg;
struct cn_msg *incoming_cn_msg;
struct hv_kvp_msg *hv_msg;
char *p;
char *key_value;
char *key_name;
int op;
int pool;
char *if_name;
struct hv_kvp_ipaddr_value *kvp_ip_val;
daemon(1, 0);
openlog("KVP", 0, LOG_USER);
syslog(LOG_INFO, "KVP starting; pid is:%d", getpid());
/*
* Retrieve OS release information.
*/
kvp_get_os_info();
if (kvp_file_init()) {
syslog(LOG_ERR, "Failed to initialize the pools");
exit(EXIT_FAILURE);
}
fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
if (fd < 0) {
syslog(LOG_ERR, "netlink socket creation failed; error:%d", fd);
exit(EXIT_FAILURE);
}
addr.nl_family = AF_NETLINK;
addr.nl_pad = 0;
addr.nl_pid = 0;
addr.nl_groups = CN_KVP_IDX;
error = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
if (error < 0) {
syslog(LOG_ERR, "bind failed; error:%d", error);
close(fd);
exit(EXIT_FAILURE);
}
sock_opt = addr.nl_groups;
setsockopt(fd, 270, 1, &sock_opt, sizeof(sock_opt));
/*
* Register ourselves with the kernel.
*/
message = (struct cn_msg *)kvp_send_buffer;
message->id.idx = CN_KVP_IDX;
message->id.val = CN_KVP_VAL;
hv_msg = (struct hv_kvp_msg *)message->data;
hv_msg->kvp_hdr.operation = KVP_OP_REGISTER1;
message->ack = 0;
message->len = sizeof(struct hv_kvp_msg);
len = netlink_send(fd, message);
if (len < 0) {
syslog(LOG_ERR, "netlink_send failed; error:%d", len);
close(fd);
exit(EXIT_FAILURE);
}
pfd.fd = fd;
while (1) {
struct sockaddr *addr_p = (struct sockaddr *) &addr;
socklen_t addr_l = sizeof(addr);
pfd.events = POLLIN;
pfd.revents = 0;
poll(&pfd, 1, -1);
len = recvfrom(fd, kvp_recv_buffer, sizeof(kvp_recv_buffer), 0,
addr_p, &addr_l);
if (len < 0 || addr.nl_pid) {
syslog(LOG_ERR, "recvfrom failed; pid:%u error:%d %s",
addr.nl_pid, errno, strerror(errno));
close(fd);
return -1;
}
incoming_msg = (struct nlmsghdr *)kvp_recv_buffer;
incoming_cn_msg = (struct cn_msg *)NLMSG_DATA(incoming_msg);
hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data;
/*
* We will use the KVP header information to pass back
* the error from this daemon. So, first copy the state
* and set the error code to success.
*/
op = hv_msg->kvp_hdr.operation;
pool = hv_msg->kvp_hdr.pool;
hv_msg->error = HV_S_OK;
if ((in_hand_shake) && (op == KVP_OP_REGISTER1)) {
/*
* Driver is registering with us; stash away the version
* information.
*/
in_hand_shake = 0;
p = (char *)hv_msg->body.kvp_register.version;
lic_version = malloc(strlen(p) + 1);
if (lic_version) {
strcpy(lic_version, p);
syslog(LOG_INFO, "KVP LIC Version: %s",
lic_version);
} else {
syslog(LOG_ERR, "malloc failed");
}
continue;
}
switch (op) {
case KVP_OP_GET_IP_INFO:
kvp_ip_val = &hv_msg->body.kvp_ip_val;
if_name =
kvp_mac_to_if_name((char *)kvp_ip_val->adapter_id);
if (if_name == NULL) {
/*
* We could not map the mac address to an
* interface name; return error.
*/
hv_msg->error = HV_E_FAIL;
break;
}
error = kvp_get_ip_info(
0, if_name, KVP_OP_GET_IP_INFO,
kvp_ip_val,
(MAX_IP_ADDR_SIZE * 2));
if (error)
hv_msg->error = error;
free(if_name);
break;
case KVP_OP_SET_IP_INFO:
kvp_ip_val = &hv_msg->body.kvp_ip_val;
if_name = kvp_get_if_name(
(char *)kvp_ip_val->adapter_id);
if (if_name == NULL) {
/*
* We could not map the guid to an
* interface name; return error.
*/
hv_msg->error = HV_GUID_NOTFOUND;
break;
}
error = kvp_set_ip_info(if_name, kvp_ip_val);
if (error)
hv_msg->error = error;
free(if_name);
break;
case KVP_OP_SET:
if (kvp_key_add_or_modify(pool,
hv_msg->body.kvp_set.data.key,
hv_msg->body.kvp_set.data.key_size,
hv_msg->body.kvp_set.data.value,
hv_msg->body.kvp_set.data.value_size))
hv_msg->error = HV_S_CONT;
break;
case KVP_OP_GET:
if (kvp_get_value(pool,
hv_msg->body.kvp_set.data.key,
hv_msg->body.kvp_set.data.key_size,
hv_msg->body.kvp_set.data.value,
hv_msg->body.kvp_set.data.value_size))
hv_msg->error = HV_S_CONT;
break;
case KVP_OP_DELETE:
if (kvp_key_delete(pool,
hv_msg->body.kvp_delete.key,
hv_msg->body.kvp_delete.key_size))
hv_msg->error = HV_S_CONT;
break;
default:
break;
}
if (op != KVP_OP_ENUMERATE)
goto kvp_done;
/*
* If the pool is KVP_POOL_AUTO, dynamically generate
* both the key and the value; if not read from the
* appropriate pool.
*/
if (pool != KVP_POOL_AUTO) {
if (kvp_pool_enumerate(pool,
hv_msg->body.kvp_enum_data.index,
hv_msg->body.kvp_enum_data.data.key,
HV_KVP_EXCHANGE_MAX_KEY_SIZE,
hv_msg->body.kvp_enum_data.data.value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE))
hv_msg->error = HV_S_CONT;
goto kvp_done;
}
hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data;
key_name = (char *)hv_msg->body.kvp_enum_data.data.key;
key_value = (char *)hv_msg->body.kvp_enum_data.data.value;
switch (hv_msg->body.kvp_enum_data.index) {
case FullyQualifiedDomainName:
kvp_get_domain_name(key_value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
strcpy(key_name, "FullyQualifiedDomainName");
break;
case IntegrationServicesVersion:
strcpy(key_name, "IntegrationServicesVersion");
strcpy(key_value, lic_version);
break;
case NetworkAddressIPv4:
kvp_get_ip_info(AF_INET, NULL, KVP_OP_ENUMERATE,
key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
strcpy(key_name, "NetworkAddressIPv4");
break;
case NetworkAddressIPv6:
kvp_get_ip_info(AF_INET6, NULL, KVP_OP_ENUMERATE,
key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
strcpy(key_name, "NetworkAddressIPv6");
break;
case OSBuildNumber:
strcpy(key_value, os_build);
strcpy(key_name, "OSBuildNumber");
break;
case OSName:
strcpy(key_value, os_name);
strcpy(key_name, "OSName");
break;
case OSMajorVersion:
strcpy(key_value, os_major);
strcpy(key_name, "OSMajorVersion");
break;
case OSMinorVersion:
strcpy(key_value, os_minor);
strcpy(key_name, "OSMinorVersion");
break;
case OSVersion:
strcpy(key_value, os_version);
strcpy(key_name, "OSVersion");
break;
case ProcessorArchitecture:
strcpy(key_value, processor_arch);
strcpy(key_name, "ProcessorArchitecture");
break;
default:
hv_msg->error = HV_S_CONT;
break;
}
/*
* Send the value back to the kernel. The response is
* already in the receive buffer. Update the cn_msg header to
* reflect the key value that has been added to the message
*/
kvp_done:
incoming_cn_msg->id.idx = CN_KVP_IDX;
incoming_cn_msg->id.val = CN_KVP_VAL;
incoming_cn_msg->ack = 0;
incoming_cn_msg->len = sizeof(struct hv_kvp_msg);
len = netlink_send(fd, incoming_cn_msg);
if (len < 0) {
syslog(LOG_ERR, "net_link send failed; error:%d", len);
exit(EXIT_FAILURE);
}
}
}
Commit Message: tools: hv: Netlink source address validation allows DoS
The source code without this patch caused hypervkvpd to exit when it processed
a spoofed Netlink packet which has been sent from an untrusted local user.
Now Netlink messages with a non-zero nl_pid source address are ignored
and a warning is printed into the syslog.
Signed-off-by: Tomas Hozza <[email protected]>
Acked-by: K. Y. Srinivasan <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: | int main(void)
{
int fd, len, sock_opt;
int error;
struct cn_msg *message;
struct pollfd pfd;
struct nlmsghdr *incoming_msg;
struct cn_msg *incoming_cn_msg;
struct hv_kvp_msg *hv_msg;
char *p;
char *key_value;
char *key_name;
int op;
int pool;
char *if_name;
struct hv_kvp_ipaddr_value *kvp_ip_val;
daemon(1, 0);
openlog("KVP", 0, LOG_USER);
syslog(LOG_INFO, "KVP starting; pid is:%d", getpid());
/*
* Retrieve OS release information.
*/
kvp_get_os_info();
if (kvp_file_init()) {
syslog(LOG_ERR, "Failed to initialize the pools");
exit(EXIT_FAILURE);
}
fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
if (fd < 0) {
syslog(LOG_ERR, "netlink socket creation failed; error:%d", fd);
exit(EXIT_FAILURE);
}
addr.nl_family = AF_NETLINK;
addr.nl_pad = 0;
addr.nl_pid = 0;
addr.nl_groups = CN_KVP_IDX;
error = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
if (error < 0) {
syslog(LOG_ERR, "bind failed; error:%d", error);
close(fd);
exit(EXIT_FAILURE);
}
sock_opt = addr.nl_groups;
setsockopt(fd, 270, 1, &sock_opt, sizeof(sock_opt));
/*
* Register ourselves with the kernel.
*/
message = (struct cn_msg *)kvp_send_buffer;
message->id.idx = CN_KVP_IDX;
message->id.val = CN_KVP_VAL;
hv_msg = (struct hv_kvp_msg *)message->data;
hv_msg->kvp_hdr.operation = KVP_OP_REGISTER1;
message->ack = 0;
message->len = sizeof(struct hv_kvp_msg);
len = netlink_send(fd, message);
if (len < 0) {
syslog(LOG_ERR, "netlink_send failed; error:%d", len);
close(fd);
exit(EXIT_FAILURE);
}
pfd.fd = fd;
while (1) {
struct sockaddr *addr_p = (struct sockaddr *) &addr;
socklen_t addr_l = sizeof(addr);
pfd.events = POLLIN;
pfd.revents = 0;
poll(&pfd, 1, -1);
len = recvfrom(fd, kvp_recv_buffer, sizeof(kvp_recv_buffer), 0,
addr_p, &addr_l);
if (len < 0) {
syslog(LOG_ERR, "recvfrom failed; pid:%u error:%d %s",
addr.nl_pid, errno, strerror(errno));
close(fd);
return -1;
}
if (addr.nl_pid) {
syslog(LOG_WARNING, "Received packet from untrusted pid:%u",
addr.nl_pid);
continue;
}
incoming_msg = (struct nlmsghdr *)kvp_recv_buffer;
incoming_cn_msg = (struct cn_msg *)NLMSG_DATA(incoming_msg);
hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data;
/*
* We will use the KVP header information to pass back
* the error from this daemon. So, first copy the state
* and set the error code to success.
*/
op = hv_msg->kvp_hdr.operation;
pool = hv_msg->kvp_hdr.pool;
hv_msg->error = HV_S_OK;
if ((in_hand_shake) && (op == KVP_OP_REGISTER1)) {
/*
* Driver is registering with us; stash away the version
* information.
*/
in_hand_shake = 0;
p = (char *)hv_msg->body.kvp_register.version;
lic_version = malloc(strlen(p) + 1);
if (lic_version) {
strcpy(lic_version, p);
syslog(LOG_INFO, "KVP LIC Version: %s",
lic_version);
} else {
syslog(LOG_ERR, "malloc failed");
}
continue;
}
switch (op) {
case KVP_OP_GET_IP_INFO:
kvp_ip_val = &hv_msg->body.kvp_ip_val;
if_name =
kvp_mac_to_if_name((char *)kvp_ip_val->adapter_id);
if (if_name == NULL) {
/*
* We could not map the mac address to an
* interface name; return error.
*/
hv_msg->error = HV_E_FAIL;
break;
}
error = kvp_get_ip_info(
0, if_name, KVP_OP_GET_IP_INFO,
kvp_ip_val,
(MAX_IP_ADDR_SIZE * 2));
if (error)
hv_msg->error = error;
free(if_name);
break;
case KVP_OP_SET_IP_INFO:
kvp_ip_val = &hv_msg->body.kvp_ip_val;
if_name = kvp_get_if_name(
(char *)kvp_ip_val->adapter_id);
if (if_name == NULL) {
/*
* We could not map the guid to an
* interface name; return error.
*/
hv_msg->error = HV_GUID_NOTFOUND;
break;
}
error = kvp_set_ip_info(if_name, kvp_ip_val);
if (error)
hv_msg->error = error;
free(if_name);
break;
case KVP_OP_SET:
if (kvp_key_add_or_modify(pool,
hv_msg->body.kvp_set.data.key,
hv_msg->body.kvp_set.data.key_size,
hv_msg->body.kvp_set.data.value,
hv_msg->body.kvp_set.data.value_size))
hv_msg->error = HV_S_CONT;
break;
case KVP_OP_GET:
if (kvp_get_value(pool,
hv_msg->body.kvp_set.data.key,
hv_msg->body.kvp_set.data.key_size,
hv_msg->body.kvp_set.data.value,
hv_msg->body.kvp_set.data.value_size))
hv_msg->error = HV_S_CONT;
break;
case KVP_OP_DELETE:
if (kvp_key_delete(pool,
hv_msg->body.kvp_delete.key,
hv_msg->body.kvp_delete.key_size))
hv_msg->error = HV_S_CONT;
break;
default:
break;
}
if (op != KVP_OP_ENUMERATE)
goto kvp_done;
/*
* If the pool is KVP_POOL_AUTO, dynamically generate
* both the key and the value; if not read from the
* appropriate pool.
*/
if (pool != KVP_POOL_AUTO) {
if (kvp_pool_enumerate(pool,
hv_msg->body.kvp_enum_data.index,
hv_msg->body.kvp_enum_data.data.key,
HV_KVP_EXCHANGE_MAX_KEY_SIZE,
hv_msg->body.kvp_enum_data.data.value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE))
hv_msg->error = HV_S_CONT;
goto kvp_done;
}
hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data;
key_name = (char *)hv_msg->body.kvp_enum_data.data.key;
key_value = (char *)hv_msg->body.kvp_enum_data.data.value;
switch (hv_msg->body.kvp_enum_data.index) {
case FullyQualifiedDomainName:
kvp_get_domain_name(key_value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
strcpy(key_name, "FullyQualifiedDomainName");
break;
case IntegrationServicesVersion:
strcpy(key_name, "IntegrationServicesVersion");
strcpy(key_value, lic_version);
break;
case NetworkAddressIPv4:
kvp_get_ip_info(AF_INET, NULL, KVP_OP_ENUMERATE,
key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
strcpy(key_name, "NetworkAddressIPv4");
break;
case NetworkAddressIPv6:
kvp_get_ip_info(AF_INET6, NULL, KVP_OP_ENUMERATE,
key_value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
strcpy(key_name, "NetworkAddressIPv6");
break;
case OSBuildNumber:
strcpy(key_value, os_build);
strcpy(key_name, "OSBuildNumber");
break;
case OSName:
strcpy(key_value, os_name);
strcpy(key_name, "OSName");
break;
case OSMajorVersion:
strcpy(key_value, os_major);
strcpy(key_name, "OSMajorVersion");
break;
case OSMinorVersion:
strcpy(key_value, os_minor);
strcpy(key_name, "OSMinorVersion");
break;
case OSVersion:
strcpy(key_value, os_version);
strcpy(key_name, "OSVersion");
break;
case ProcessorArchitecture:
strcpy(key_value, processor_arch);
strcpy(key_name, "ProcessorArchitecture");
break;
default:
hv_msg->error = HV_S_CONT;
break;
}
/*
* Send the value back to the kernel. The response is
* already in the receive buffer. Update the cn_msg header to
* reflect the key value that has been added to the message
*/
kvp_done:
incoming_cn_msg->id.idx = CN_KVP_IDX;
incoming_cn_msg->id.val = CN_KVP_VAL;
incoming_cn_msg->ack = 0;
incoming_cn_msg->len = sizeof(struct hv_kvp_msg);
len = netlink_send(fd, incoming_cn_msg);
if (len < 0) {
syslog(LOG_ERR, "net_link send failed; error:%d", len);
exit(EXIT_FAILURE);
}
}
}
| 165,528 |
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 clie_5_attach(struct usb_serial *serial)
{
struct usb_serial_port *port;
unsigned int pipe;
int j;
/* TH55 registers 2 ports.
Communication in from the UX50/TH55 uses bulk_in_endpointAddress
from port 0. Communication out to the UX50/TH55 uses
bulk_out_endpointAddress from port 1
Lets do a quick and dirty mapping
*/
/* some sanity check */
if (serial->num_ports < 2)
return -1;
/* port 0 now uses the modified endpoint Address */
port = serial->port[0];
port->bulk_out_endpointAddress =
serial->port[1]->bulk_out_endpointAddress;
pipe = usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress);
for (j = 0; j < ARRAY_SIZE(port->write_urbs); ++j)
port->write_urbs[j]->pipe = pipe;
return 0;
}
Commit Message: USB: serial: visor: fix crash on detecting device without write_urbs
The visor driver crashes in clie_5_attach() when a specially crafted USB
device without bulk-out endpoint is detected. This fix adds a check that
the device has proper configuration expected by the driver.
Reported-by: Ralf Spenneberg <[email protected]>
Signed-off-by: Vladis Dronov <[email protected]>
Fixes: cfb8da8f69b8 ("USB: visor: fix initialisation of UX50/TH55 devices")
Cc: stable <[email protected]>
Signed-off-by: Johan Hovold <[email protected]>
CWE ID: | static int clie_5_attach(struct usb_serial *serial)
{
struct usb_serial_port *port;
unsigned int pipe;
int j;
/* TH55 registers 2 ports.
Communication in from the UX50/TH55 uses bulk_in_endpointAddress
from port 0. Communication out to the UX50/TH55 uses
bulk_out_endpointAddress from port 1
Lets do a quick and dirty mapping
*/
/* some sanity check */
if (serial->num_bulk_out < 2) {
dev_err(&serial->interface->dev, "missing bulk out endpoints\n");
return -ENODEV;
}
/* port 0 now uses the modified endpoint Address */
port = serial->port[0];
port->bulk_out_endpointAddress =
serial->port[1]->bulk_out_endpointAddress;
pipe = usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress);
for (j = 0; j < ARRAY_SIZE(port->write_urbs); ++j)
port->write_urbs[j]->pipe = pipe;
return 0;
}
| 167,557 |
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 get_sda(void)
{
return qrio_get_gpio(DEBLOCK_PORT1, DEBLOCK_SDA1);
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787 | int get_sda(void)
| 169,630 |
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 *ReadSCREENSHOTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
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=(Image *) NULL;
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
{
BITMAPINFO
bmi;
DISPLAY_DEVICE
device;
HBITMAP
bitmap,
bitmapOld;
HDC
bitmapDC,
hDC;
Image
*screen;
int
i;
register PixelPacket
*q;
register ssize_t
x;
RGBTRIPLE
*p;
ssize_t
y;
assert(image_info != (const ImageInfo *) NULL);
i=0;
device.cb = sizeof(device);
image=(Image *) NULL;
while(EnumDisplayDevices(NULL,i,&device,0) && ++i)
{
if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE)
continue;
hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL);
if (hDC == (HDC) NULL)
ThrowReaderException(CoderError,"UnableToCreateDC");
screen=AcquireImage(image_info);
screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES);
screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES);
screen->storage_class=DirectClass;
if (image == (Image *) NULL)
image=screen;
else
AppendImageToList(&image,screen);
bitmapDC=CreateCompatibleDC(hDC);
if (bitmapDC == (HDC) NULL)
{
DeleteDC(hDC);
ThrowReaderException(CoderError,"UnableToCreateDC");
}
(void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO));
bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth=(LONG) screen->columns;
bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows;
bmi.bmiHeader.biPlanes=1;
bmi.bmiHeader.biBitCount=24;
bmi.bmiHeader.biCompression=BI_RGB;
bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0);
if (bitmap == (HBITMAP) NULL)
{
DeleteDC(hDC);
DeleteDC(bitmapDC);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap);
if (bitmapOld == (HBITMAP) NULL)
{
DeleteDC(hDC);
DeleteDC(bitmapDC);
DeleteObject(bitmap);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0,
SRCCOPY);
(void) SelectObject(bitmapDC,bitmapOld);
for (y=0; y < (ssize_t) screen->rows; y++)
{
q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) screen->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(p->rgbtRed));
SetPixelGreen(q,ScaleCharToQuantum(p->rgbtGreen));
SetPixelBlue(q,ScaleCharToQuantum(p->rgbtBlue));
SetPixelOpacity(q,OpaqueOpacity);
p++;
q++;
}
if (SyncAuthenticPixels(screen,exception) == MagickFalse)
break;
}
DeleteDC(hDC);
DeleteDC(bitmapDC);
DeleteObject(bitmap);
}
}
#elif defined(MAGICKCORE_X11_DELEGATE)
{
const char
*option;
XImportInfo
ximage_info;
(void) exception;
XGetImportInfo(&ximage_info);
option=GetImageOption(image_info,"x:screen");
if (option != (const char *) NULL)
ximage_info.screen=IsMagickTrue(option);
option=GetImageOption(image_info,"x:silent");
if (option != (const char *) NULL)
ximage_info.silent=IsMagickTrue(option);
image=XImportImage(image_info,&ximage_info);
}
#endif
return(image);
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadSCREENSHOTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
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=(Image *) NULL;
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
{
BITMAPINFO
bmi;
DISPLAY_DEVICE
device;
HBITMAP
bitmap,
bitmapOld;
HDC
bitmapDC,
hDC;
Image
*screen;
int
i;
MagickBooleanType
status;
register PixelPacket
*q;
register ssize_t
x;
RGBTRIPLE
*p;
ssize_t
y;
assert(image_info != (const ImageInfo *) NULL);
i=0;
device.cb = sizeof(device);
image=(Image *) NULL;
while(EnumDisplayDevices(NULL,i,&device,0) && ++i)
{
if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE)
continue;
hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL);
if (hDC == (HDC) NULL)
ThrowReaderException(CoderError,"UnableToCreateDC");
screen=AcquireImage(image_info);
screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES);
screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES);
screen->storage_class=DirectClass;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (image == (Image *) NULL)
image=screen;
else
AppendImageToList(&image,screen);
bitmapDC=CreateCompatibleDC(hDC);
if (bitmapDC == (HDC) NULL)
{
DeleteDC(hDC);
ThrowReaderException(CoderError,"UnableToCreateDC");
}
(void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO));
bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth=(LONG) screen->columns;
bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows;
bmi.bmiHeader.biPlanes=1;
bmi.bmiHeader.biBitCount=24;
bmi.bmiHeader.biCompression=BI_RGB;
bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0);
if (bitmap == (HBITMAP) NULL)
{
DeleteDC(hDC);
DeleteDC(bitmapDC);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap);
if (bitmapOld == (HBITMAP) NULL)
{
DeleteDC(hDC);
DeleteDC(bitmapDC);
DeleteObject(bitmap);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0,
SRCCOPY);
(void) SelectObject(bitmapDC,bitmapOld);
for (y=0; y < (ssize_t) screen->rows; y++)
{
q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) screen->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(p->rgbtRed));
SetPixelGreen(q,ScaleCharToQuantum(p->rgbtGreen));
SetPixelBlue(q,ScaleCharToQuantum(p->rgbtBlue));
SetPixelOpacity(q,OpaqueOpacity);
p++;
q++;
}
if (SyncAuthenticPixels(screen,exception) == MagickFalse)
break;
}
DeleteDC(hDC);
DeleteDC(bitmapDC);
DeleteObject(bitmap);
}
}
#elif defined(MAGICKCORE_X11_DELEGATE)
{
const char
*option;
XImportInfo
ximage_info;
(void) exception;
XGetImportInfo(&ximage_info);
option=GetImageOption(image_info,"x:screen");
if (option != (const char *) NULL)
ximage_info.screen=IsMagickTrue(option);
option=GetImageOption(image_info,"x:silent");
if (option != (const char *) NULL)
ximage_info.silent=IsMagickTrue(option);
image=XImportImage(image_info,&ximage_info);
}
#endif
return(image);
}
| 168,602 |
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 setup_test_dir(char *tmp_dir, const char *files, ...) {
va_list ap;
assert_se(mkdtemp(tmp_dir) != NULL);
va_start(ap, files);
while (files != NULL) {
_cleanup_free_ char *path = strappend(tmp_dir, files);
assert_se(touch_file(path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0) == 0);
files = va_arg(ap, const char *);
}
va_end(ap);
}
Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere
CWE ID: CWE-264 | static void setup_test_dir(char *tmp_dir, const char *files, ...) {
va_list ap;
assert_se(mkdtemp(tmp_dir) != NULL);
va_start(ap, files);
while (files != NULL) {
_cleanup_free_ char *path = strappend(tmp_dir, files);
assert_se(touch_file(path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID) == 0);
files = va_arg(ap, const char *);
}
va_end(ap);
}
| 170,108 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 CSPSourceList::matches(const KURL& url, ContentSecurityPolicy::RedirectStatus redirectStatus) const
{
if (m_allowStar)
return true;
KURL effectiveURL = m_policy->selfMatchesInnerURL() && SecurityOrigin::shouldUseInnerURL(url) ? SecurityOrigin::extractInnerURL(url) : url;
if (m_allowSelf && m_policy->urlMatchesSelf(effectiveURL))
return true;
for (size_t i = 0; i < m_list.size(); ++i) {
if (m_list[i].matches(effectiveURL, redirectStatus))
return true;
}
return false;
}
Commit Message: Disallow CSP source * matching of data:, blob:, and filesystem: URLs
The CSP spec specifically excludes matching of data:, blob:, and
filesystem: URLs with the source '*' wildcard. This adds checks to make
sure that doesn't happen, along with tests.
BUG=534570
[email protected]
Review URL: https://codereview.chromium.org/1361763005
Cr-Commit-Position: refs/heads/master@{#350950}
CWE ID: CWE-264 | bool CSPSourceList::matches(const KURL& url, ContentSecurityPolicy::RedirectStatus redirectStatus) const
{
// The CSP spec specifically states that data:, blob:, and filesystem URLs
// should not be captured by a '*" source
// (http://www.w3.org/TR/CSP2/#source-list-guid-matching). Thus, in the
// case of a full wildcard, data:, blob:, and filesystem: URLs are
// explicitly checked for in the source list before allowing them through.
if (m_allowStar) {
if (url.protocolIs("blob") || url.protocolIs("data") || url.protocolIs("filesystem"))
return hasSourceMatchInList(url, redirectStatus);
return true;
}
KURL effectiveURL = m_policy->selfMatchesInnerURL() && SecurityOrigin::shouldUseInnerURL(url) ? SecurityOrigin::extractInnerURL(url) : url;
if (m_allowSelf && m_policy->urlMatchesSelf(effectiveURL))
return true;
return hasSourceMatchInList(effectiveURL, redirectStatus);
}
| 171,789 |
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 compat_get_timex(struct timex *txc, const struct compat_timex __user *utp)
{
struct compat_timex tx32;
if (copy_from_user(&tx32, utp, sizeof(struct compat_timex)))
return -EFAULT;
txc->modes = tx32.modes;
txc->offset = tx32.offset;
txc->freq = tx32.freq;
txc->maxerror = tx32.maxerror;
txc->esterror = tx32.esterror;
txc->status = tx32.status;
txc->constant = tx32.constant;
txc->precision = tx32.precision;
txc->tolerance = tx32.tolerance;
txc->time.tv_sec = tx32.time.tv_sec;
txc->time.tv_usec = tx32.time.tv_usec;
txc->tick = tx32.tick;
txc->ppsfreq = tx32.ppsfreq;
txc->jitter = tx32.jitter;
txc->shift = tx32.shift;
txc->stabil = tx32.stabil;
txc->jitcnt = tx32.jitcnt;
txc->calcnt = tx32.calcnt;
txc->errcnt = tx32.errcnt;
txc->stbcnt = tx32.stbcnt;
return 0;
}
Commit Message: compat: fix 4-byte infoleak via uninitialized struct field
Commit 3a4d44b61625 ("ntp: Move adjtimex related compat syscalls to
native counterparts") removed the memset() in compat_get_timex(). Since
then, the compat adjtimex syscall can invoke do_adjtimex() with an
uninitialized ->tai.
If do_adjtimex() doesn't write to ->tai (e.g. because the arguments are
invalid), compat_put_timex() then copies the uninitialized ->tai field
to userspace.
Fix it by adding the memset() back.
Fixes: 3a4d44b61625 ("ntp: Move adjtimex related compat syscalls to native counterparts")
Signed-off-by: Jann Horn <[email protected]>
Acked-by: Kees Cook <[email protected]>
Acked-by: Al Viro <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200 | int compat_get_timex(struct timex *txc, const struct compat_timex __user *utp)
{
struct compat_timex tx32;
memset(txc, 0, sizeof(struct timex));
if (copy_from_user(&tx32, utp, sizeof(struct compat_timex)))
return -EFAULT;
txc->modes = tx32.modes;
txc->offset = tx32.offset;
txc->freq = tx32.freq;
txc->maxerror = tx32.maxerror;
txc->esterror = tx32.esterror;
txc->status = tx32.status;
txc->constant = tx32.constant;
txc->precision = tx32.precision;
txc->tolerance = tx32.tolerance;
txc->time.tv_sec = tx32.time.tv_sec;
txc->time.tv_usec = tx32.time.tv_usec;
txc->tick = tx32.tick;
txc->ppsfreq = tx32.ppsfreq;
txc->jitter = tx32.jitter;
txc->shift = tx32.shift;
txc->stabil = tx32.stabil;
txc->jitcnt = tx32.jitcnt;
txc->calcnt = tx32.calcnt;
txc->errcnt = tx32.errcnt;
txc->stbcnt = tx32.stbcnt;
return 0;
}
| 169,219 |
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 setup_token_decoder(VP8D_COMP *pbi,
const unsigned char* token_part_sizes)
{
vp8_reader *bool_decoder = &pbi->mbc[0];
unsigned int partition_idx;
unsigned int fragment_idx;
unsigned int num_token_partitions;
const unsigned char *first_fragment_end = pbi->fragments.ptrs[0] +
pbi->fragments.sizes[0];
TOKEN_PARTITION multi_token_partition =
(TOKEN_PARTITION)vp8_read_literal(&pbi->mbc[8], 2);
if (!vp8dx_bool_error(&pbi->mbc[8]))
pbi->common.multi_token_partition = multi_token_partition;
num_token_partitions = 1 << pbi->common.multi_token_partition;
/* Check for partitions within the fragments and unpack the fragments
* so that each fragment pointer points to its corresponding partition. */
for (fragment_idx = 0; fragment_idx < pbi->fragments.count; ++fragment_idx)
{
unsigned int fragment_size = pbi->fragments.sizes[fragment_idx];
const unsigned char *fragment_end = pbi->fragments.ptrs[fragment_idx] +
fragment_size;
/* Special case for handling the first partition since we have already
* read its size. */
if (fragment_idx == 0)
{
/* Size of first partition + token partition sizes element */
ptrdiff_t ext_first_part_size = token_part_sizes -
pbi->fragments.ptrs[0] + 3 * (num_token_partitions - 1);
fragment_size -= (unsigned int)ext_first_part_size;
if (fragment_size > 0)
{
pbi->fragments.sizes[0] = (unsigned int)ext_first_part_size;
/* The fragment contains an additional partition. Move to
* next. */
fragment_idx++;
pbi->fragments.ptrs[fragment_idx] = pbi->fragments.ptrs[0] +
pbi->fragments.sizes[0];
}
}
/* Split the chunk into partitions read from the bitstream */
while (fragment_size > 0)
{
ptrdiff_t partition_size = read_available_partition_size(
pbi,
token_part_sizes,
pbi->fragments.ptrs[fragment_idx],
first_fragment_end,
fragment_end,
fragment_idx - 1,
num_token_partitions);
pbi->fragments.sizes[fragment_idx] = (unsigned int)partition_size;
fragment_size -= (unsigned int)partition_size;
assert(fragment_idx <= num_token_partitions);
if (fragment_size > 0)
{
/* The fragment contains an additional partition.
* Move to next. */
fragment_idx++;
pbi->fragments.ptrs[fragment_idx] =
pbi->fragments.ptrs[fragment_idx - 1] + partition_size;
}
}
}
pbi->fragments.count = num_token_partitions + 1;
for (partition_idx = 1; partition_idx < pbi->fragments.count; ++partition_idx)
{
if (vp8dx_start_decode(bool_decoder,
pbi->fragments.ptrs[partition_idx],
pbi->fragments.sizes[partition_idx],
pbi->decrypt_cb, pbi->decrypt_state))
vpx_internal_error(&pbi->common.error, VPX_CODEC_MEM_ERROR,
"Failed to allocate bool decoder %d",
partition_idx);
bool_decoder++;
}
#if CONFIG_MULTITHREAD
/* Clamp number of decoder threads */
if (pbi->decoding_thread_count > num_token_partitions - 1)
pbi->decoding_thread_count = num_token_partitions - 1;
#endif
}
Commit Message: vp8:fix threading issues
1 - stops de allocating before threads are closed.
2 - limits threads to mb_rows when mb_rows < partitions
BUG=webm:851
Bug: 30436808
Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b
(cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e)
CWE ID: | static void setup_token_decoder(VP8D_COMP *pbi,
const unsigned char* token_part_sizes)
{
vp8_reader *bool_decoder = &pbi->mbc[0];
unsigned int partition_idx;
unsigned int fragment_idx;
unsigned int num_token_partitions;
const unsigned char *first_fragment_end = pbi->fragments.ptrs[0] +
pbi->fragments.sizes[0];
TOKEN_PARTITION multi_token_partition =
(TOKEN_PARTITION)vp8_read_literal(&pbi->mbc[8], 2);
if (!vp8dx_bool_error(&pbi->mbc[8]))
pbi->common.multi_token_partition = multi_token_partition;
num_token_partitions = 1 << pbi->common.multi_token_partition;
/* Check for partitions within the fragments and unpack the fragments
* so that each fragment pointer points to its corresponding partition. */
for (fragment_idx = 0; fragment_idx < pbi->fragments.count; ++fragment_idx)
{
unsigned int fragment_size = pbi->fragments.sizes[fragment_idx];
const unsigned char *fragment_end = pbi->fragments.ptrs[fragment_idx] +
fragment_size;
/* Special case for handling the first partition since we have already
* read its size. */
if (fragment_idx == 0)
{
/* Size of first partition + token partition sizes element */
ptrdiff_t ext_first_part_size = token_part_sizes -
pbi->fragments.ptrs[0] + 3 * (num_token_partitions - 1);
fragment_size -= (unsigned int)ext_first_part_size;
if (fragment_size > 0)
{
pbi->fragments.sizes[0] = (unsigned int)ext_first_part_size;
/* The fragment contains an additional partition. Move to
* next. */
fragment_idx++;
pbi->fragments.ptrs[fragment_idx] = pbi->fragments.ptrs[0] +
pbi->fragments.sizes[0];
}
}
/* Split the chunk into partitions read from the bitstream */
while (fragment_size > 0)
{
ptrdiff_t partition_size = read_available_partition_size(
pbi,
token_part_sizes,
pbi->fragments.ptrs[fragment_idx],
first_fragment_end,
fragment_end,
fragment_idx - 1,
num_token_partitions);
pbi->fragments.sizes[fragment_idx] = (unsigned int)partition_size;
fragment_size -= (unsigned int)partition_size;
assert(fragment_idx <= num_token_partitions);
if (fragment_size > 0)
{
/* The fragment contains an additional partition.
* Move to next. */
fragment_idx++;
pbi->fragments.ptrs[fragment_idx] =
pbi->fragments.ptrs[fragment_idx - 1] + partition_size;
}
}
}
pbi->fragments.count = num_token_partitions + 1;
for (partition_idx = 1; partition_idx < pbi->fragments.count; ++partition_idx)
{
if (vp8dx_start_decode(bool_decoder,
pbi->fragments.ptrs[partition_idx],
pbi->fragments.sizes[partition_idx],
pbi->decrypt_cb, pbi->decrypt_state))
vpx_internal_error(&pbi->common.error, VPX_CODEC_MEM_ERROR,
"Failed to allocate bool decoder %d",
partition_idx);
bool_decoder++;
}
#if CONFIG_MULTITHREAD
/* Clamp number of decoder threads */
if (pbi->decoding_thread_count > num_token_partitions - 1) {
pbi->decoding_thread_count = num_token_partitions - 1;
}
if (pbi->decoding_thread_count > pbi->common.mb_rows - 1) {
pbi->decoding_thread_count = pbi->common.mb_rows - 1;
}
#endif
}
| 174,064 |
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 bool check_solid_tile(VncState *vs, int x, int y, int w, int h,
uint32_t* color, bool samecolor)
{
VncDisplay *vd = vs->vd;
switch(vd->server->pf.bytes_per_pixel) {
case 4:
return check_solid_tile32(vs, x, y, w, h, color, samecolor);
case 2:
switch(vd->server->pf.bytes_per_pixel) {
case 4:
return check_solid_tile32(vs, x, y, w, h, color, samecolor);
case 2:
return check_solid_tile16(vs, x, y, w, h, color, samecolor);
default:
return check_solid_tile8(vs, x, y, w, h, color, samecolor);
}
}
static void find_best_solid_area(VncState *vs, int x, int y, int w, int h,
uint32_t color, int *w_ptr, int *h_ptr)
{
int dx, dy, dw, dh;
int w_prev;
int w_best = 0, h_best = 0;
w_prev = w;
for (dy = y; dy < y + h; dy += VNC_TIGHT_MAX_SPLIT_TILE_SIZE) {
dh = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, y + h - dy);
dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, w_prev);
if (!check_solid_tile(vs, x, dy, dw, dh, &color, true)) {
break;
}
for (dx = x + dw; dx < x + w_prev;) {
dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, x + w_prev - dx);
if (!check_solid_tile(vs, dx, dy, dw, dh, &color, true)) {
break;
}
dx += dw;
}
w_prev = dx - x;
if (w_prev * (dy + dh - y) > w_best * h_best) {
w_best = w_prev;
h_best = dy + dh - y;
}
}
*w_ptr = w_best;
*h_ptr = h_best;
}
static void extend_solid_area(VncState *vs, int x, int y, int w, int h,
uint32_t color, int *x_ptr, int *y_ptr,
int *w_ptr, int *h_ptr)
{
int cx, cy;
/* Try to extend the area upwards. */
for ( cy = *y_ptr - 1;
cy >= y && check_solid_tile(vs, *x_ptr, cy, *w_ptr, 1, &color, true);
cy-- );
*h_ptr += *y_ptr - (cy + 1);
*y_ptr = cy + 1;
/* ... downwards. */
for ( cy = *y_ptr + *h_ptr;
cy < y + h &&
check_solid_tile(vs, *x_ptr, cy, *w_ptr, 1, &color, true);
cy++ );
*h_ptr += cy - (*y_ptr + *h_ptr);
/* ... to the left. */
for ( cx = *x_ptr - 1;
cx >= x && check_solid_tile(vs, cx, *y_ptr, 1, *h_ptr, &color, true);
cx-- );
*w_ptr += *x_ptr - (cx + 1);
*x_ptr = cx + 1;
/* ... to the right. */
for ( cx = *x_ptr + *w_ptr;
cx < x + w &&
check_solid_tile(vs, cx, *y_ptr, 1, *h_ptr, &color, true);
cx++ );
*w_ptr += cx - (*x_ptr + *w_ptr);
}
static int tight_init_stream(VncState *vs, int stream_id,
int level, int strategy)
{
z_streamp zstream = &vs->tight.stream[stream_id];
if (zstream->opaque == NULL) {
int err;
VNC_DEBUG("VNC: TIGHT: initializing zlib stream %d\n", stream_id);
VNC_DEBUG("VNC: TIGHT: opaque = %p | vs = %p\n", zstream->opaque, vs);
zstream->zalloc = vnc_zlib_zalloc;
zstream->zfree = vnc_zlib_zfree;
err = deflateInit2(zstream, level, Z_DEFLATED, MAX_WBITS,
MAX_MEM_LEVEL, strategy);
if (err != Z_OK) {
fprintf(stderr, "VNC: error initializing zlib\n");
return -1;
}
vs->tight.levels[stream_id] = level;
zstream->opaque = vs;
}
if (vs->tight.levels[stream_id] != level) {
if (deflateParams(zstream, level, strategy) != Z_OK) {
return -1;
}
vs->tight.levels[stream_id] = level;
}
return 0;
}
static void tight_send_compact_size(VncState *vs, size_t len)
{
int lpc = 0;
int bytes = 0;
char buf[3] = {0, 0, 0};
buf[bytes++] = len & 0x7F;
if (len > 0x7F) {
buf[bytes-1] |= 0x80;
buf[bytes++] = (len >> 7) & 0x7F;
if (len > 0x3FFF) {
buf[bytes-1] |= 0x80;
buf[bytes++] = (len >> 14) & 0xFF;
}
}
for (lpc = 0; lpc < bytes; lpc++) {
vnc_write_u8(vs, buf[lpc]);
}
}
static int tight_compress_data(VncState *vs, int stream_id, size_t bytes,
int level, int strategy)
{
z_streamp zstream = &vs->tight.stream[stream_id];
int previous_out;
if (bytes < VNC_TIGHT_MIN_TO_COMPRESS) {
vnc_write(vs, vs->tight.tight.buffer, vs->tight.tight.offset);
return bytes;
}
if (tight_init_stream(vs, stream_id, level, strategy)) {
return -1;
}
/* reserve memory in output buffer */
buffer_reserve(&vs->tight.zlib, bytes + 64);
/* set pointers */
zstream->next_in = vs->tight.tight.buffer;
zstream->avail_in = vs->tight.tight.offset;
zstream->next_out = vs->tight.zlib.buffer + vs->tight.zlib.offset;
zstream->avail_out = vs->tight.zlib.capacity - vs->tight.zlib.offset;
previous_out = zstream->avail_out;
zstream->data_type = Z_BINARY;
/* start encoding */
if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
fprintf(stderr, "VNC: error during tight compression\n");
return -1;
}
vs->tight.zlib.offset = vs->tight.zlib.capacity - zstream->avail_out;
/* ...how much data has actually been produced by deflate() */
bytes = previous_out - zstream->avail_out;
tight_send_compact_size(vs, bytes);
vnc_write(vs, vs->tight.zlib.buffer, bytes);
buffer_reset(&vs->tight.zlib);
return bytes;
}
/*
* Subencoding implementations.
*/
static void tight_pack24(VncState *vs, uint8_t *buf, size_t count, size_t *ret)
buf32 = (uint32_t *)buf;
if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
(vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG)) {
rshift = vs->clientds.pf.rshift;
gshift = vs->clientds.pf.gshift;
bshift = vs->clientds.pf.bshift;
} else {
rshift = 24 - vs->clientds.pf.rshift;
gshift = 24 - vs->clientds.pf.gshift;
bshift = 24 - vs->clientds.pf.bshift;
}
if (ret) {
bshift = 24 - vs->clientds.pf.bshift;
}
if (ret) {
*ret = count * 3;
}
while (count--) {
pix = *buf32++;
*buf++ = (char)(pix >> rshift);
*buf++ = (char)(pix >> gshift);
*buf++ = (char)(pix >> bshift);
}
}
Commit Message:
CWE ID: CWE-125 | static bool check_solid_tile(VncState *vs, int x, int y, int w, int h,
uint32_t* color, bool samecolor)
{
switch (VNC_SERVER_FB_BYTES) {
case 4:
return check_solid_tile32(vs, x, y, w, h, color, samecolor);
case 2:
switch(vd->server->pf.bytes_per_pixel) {
case 4:
return check_solid_tile32(vs, x, y, w, h, color, samecolor);
case 2:
return check_solid_tile16(vs, x, y, w, h, color, samecolor);
default:
return check_solid_tile8(vs, x, y, w, h, color, samecolor);
}
}
static void find_best_solid_area(VncState *vs, int x, int y, int w, int h,
uint32_t color, int *w_ptr, int *h_ptr)
{
int dx, dy, dw, dh;
int w_prev;
int w_best = 0, h_best = 0;
w_prev = w;
for (dy = y; dy < y + h; dy += VNC_TIGHT_MAX_SPLIT_TILE_SIZE) {
dh = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, y + h - dy);
dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, w_prev);
if (!check_solid_tile(vs, x, dy, dw, dh, &color, true)) {
break;
}
for (dx = x + dw; dx < x + w_prev;) {
dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, x + w_prev - dx);
if (!check_solid_tile(vs, dx, dy, dw, dh, &color, true)) {
break;
}
dx += dw;
}
w_prev = dx - x;
if (w_prev * (dy + dh - y) > w_best * h_best) {
w_best = w_prev;
h_best = dy + dh - y;
}
}
*w_ptr = w_best;
*h_ptr = h_best;
}
static void extend_solid_area(VncState *vs, int x, int y, int w, int h,
uint32_t color, int *x_ptr, int *y_ptr,
int *w_ptr, int *h_ptr)
{
int cx, cy;
/* Try to extend the area upwards. */
for ( cy = *y_ptr - 1;
cy >= y && check_solid_tile(vs, *x_ptr, cy, *w_ptr, 1, &color, true);
cy-- );
*h_ptr += *y_ptr - (cy + 1);
*y_ptr = cy + 1;
/* ... downwards. */
for ( cy = *y_ptr + *h_ptr;
cy < y + h &&
check_solid_tile(vs, *x_ptr, cy, *w_ptr, 1, &color, true);
cy++ );
*h_ptr += cy - (*y_ptr + *h_ptr);
/* ... to the left. */
for ( cx = *x_ptr - 1;
cx >= x && check_solid_tile(vs, cx, *y_ptr, 1, *h_ptr, &color, true);
cx-- );
*w_ptr += *x_ptr - (cx + 1);
*x_ptr = cx + 1;
/* ... to the right. */
for ( cx = *x_ptr + *w_ptr;
cx < x + w &&
check_solid_tile(vs, cx, *y_ptr, 1, *h_ptr, &color, true);
cx++ );
*w_ptr += cx - (*x_ptr + *w_ptr);
}
static int tight_init_stream(VncState *vs, int stream_id,
int level, int strategy)
{
z_streamp zstream = &vs->tight.stream[stream_id];
if (zstream->opaque == NULL) {
int err;
VNC_DEBUG("VNC: TIGHT: initializing zlib stream %d\n", stream_id);
VNC_DEBUG("VNC: TIGHT: opaque = %p | vs = %p\n", zstream->opaque, vs);
zstream->zalloc = vnc_zlib_zalloc;
zstream->zfree = vnc_zlib_zfree;
err = deflateInit2(zstream, level, Z_DEFLATED, MAX_WBITS,
MAX_MEM_LEVEL, strategy);
if (err != Z_OK) {
fprintf(stderr, "VNC: error initializing zlib\n");
return -1;
}
vs->tight.levels[stream_id] = level;
zstream->opaque = vs;
}
if (vs->tight.levels[stream_id] != level) {
if (deflateParams(zstream, level, strategy) != Z_OK) {
return -1;
}
vs->tight.levels[stream_id] = level;
}
return 0;
}
static void tight_send_compact_size(VncState *vs, size_t len)
{
int lpc = 0;
int bytes = 0;
char buf[3] = {0, 0, 0};
buf[bytes++] = len & 0x7F;
if (len > 0x7F) {
buf[bytes-1] |= 0x80;
buf[bytes++] = (len >> 7) & 0x7F;
if (len > 0x3FFF) {
buf[bytes-1] |= 0x80;
buf[bytes++] = (len >> 14) & 0xFF;
}
}
for (lpc = 0; lpc < bytes; lpc++) {
vnc_write_u8(vs, buf[lpc]);
}
}
static int tight_compress_data(VncState *vs, int stream_id, size_t bytes,
int level, int strategy)
{
z_streamp zstream = &vs->tight.stream[stream_id];
int previous_out;
if (bytes < VNC_TIGHT_MIN_TO_COMPRESS) {
vnc_write(vs, vs->tight.tight.buffer, vs->tight.tight.offset);
return bytes;
}
if (tight_init_stream(vs, stream_id, level, strategy)) {
return -1;
}
/* reserve memory in output buffer */
buffer_reserve(&vs->tight.zlib, bytes + 64);
/* set pointers */
zstream->next_in = vs->tight.tight.buffer;
zstream->avail_in = vs->tight.tight.offset;
zstream->next_out = vs->tight.zlib.buffer + vs->tight.zlib.offset;
zstream->avail_out = vs->tight.zlib.capacity - vs->tight.zlib.offset;
previous_out = zstream->avail_out;
zstream->data_type = Z_BINARY;
/* start encoding */
if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
fprintf(stderr, "VNC: error during tight compression\n");
return -1;
}
vs->tight.zlib.offset = vs->tight.zlib.capacity - zstream->avail_out;
/* ...how much data has actually been produced by deflate() */
bytes = previous_out - zstream->avail_out;
tight_send_compact_size(vs, bytes);
vnc_write(vs, vs->tight.zlib.buffer, bytes);
buffer_reset(&vs->tight.zlib);
return bytes;
}
/*
* Subencoding implementations.
*/
static void tight_pack24(VncState *vs, uint8_t *buf, size_t count, size_t *ret)
buf32 = (uint32_t *)buf;
if (1 /* FIXME: (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
(vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) */) {
rshift = vs->client_pf.rshift;
gshift = vs->client_pf.gshift;
bshift = vs->client_pf.bshift;
} else {
rshift = 24 - vs->client_pf.rshift;
gshift = 24 - vs->client_pf.gshift;
bshift = 24 - vs->client_pf.bshift;
}
if (ret) {
bshift = 24 - vs->clientds.pf.bshift;
}
if (ret) {
*ret = count * 3;
}
while (count--) {
pix = *buf32++;
*buf++ = (char)(pix >> rshift);
*buf++ = (char)(pix >> gshift);
*buf++ = (char)(pix >> bshift);
}
}
| 165,460 |
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 mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) {
major = 1;
minor = 0;
build = 0;
revision = 28;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) {
IMkvReader::~IMkvReader() {}
template<typename Type> Type* SafeArrayAlloc(unsigned long long num_elements,
unsigned long long element_size) {
if (num_elements == 0 || element_size == 0)
return NULL;
const size_t kMaxAllocSize = 0x80000000; // 2GiB
const unsigned long long num_bytes = num_elements * element_size;
if (element_size > (kMaxAllocSize / num_elements))
return NULL;
return new (std::nothrow) Type[num_bytes];
}
void GetVersion(int& major, int& minor, int& build, int& revision) {
major = 1;
minor = 0;
build = 0;
revision = 30;
}
| 173,825 |
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 Splash::scaleMaskYuXd(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest) {
Guchar *lineBuf;
Guint pix;
Guchar *destPtr0, *destPtr;
int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx, d, d0, d1;
int i;
yp = scaledHeight / srcHeight;
lineBuf = (Guchar *)gmalloc(srcWidth);
yt = 0;
destPtr0 = dest->data;
for (y = 0; y < srcHeight; ++y) {
yt = 0;
destPtr0 = dest->data;
for (y = 0; y < srcHeight; ++y) {
}
(*src)(srcData, lineBuf);
xt = 0;
d0 = (255 << 23) / xp;
d1 = (255 << 23) / (xp + 1);
xx = 0;
for (x = 0; x < scaledWidth; ++x) {
if ((xt += xq) >= scaledWidth) {
xt -= scaledWidth;
xStep = xp + 1;
d = d1;
} else {
xStep = xp;
d = d0;
}
pix = 0;
for (i = 0; i < xStep; ++i) {
pix += lineBuf[xx++];
}
pix = (pix * d) >> 23;
for (i = 0; i < yStep; ++i) {
destPtr = destPtr0 + i * scaledWidth + x;
*destPtr = (Guchar)pix;
}
}
destPtr0 += yStep * scaledWidth;
}
gfree(lineBuf);
}
Commit Message:
CWE ID: CWE-119 | void Splash::scaleMaskYuXd(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest) {
Guchar *lineBuf;
Guint pix;
Guchar *destPtr0, *destPtr;
int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx, d, d0, d1;
int i;
destPtr0 = dest->data;
if (destPtr0 == NULL) {
error(errInternal, -1, "dest->data is NULL in Splash::scaleMaskYuXd");
return;
}
yp = scaledHeight / srcHeight;
lineBuf = (Guchar *)gmalloc(srcWidth);
yt = 0;
destPtr0 = dest->data;
for (y = 0; y < srcHeight; ++y) {
yt = 0;
for (y = 0; y < srcHeight; ++y) {
}
(*src)(srcData, lineBuf);
xt = 0;
d0 = (255 << 23) / xp;
d1 = (255 << 23) / (xp + 1);
xx = 0;
for (x = 0; x < scaledWidth; ++x) {
if ((xt += xq) >= scaledWidth) {
xt -= scaledWidth;
xStep = xp + 1;
d = d1;
} else {
xStep = xp;
d = d0;
}
pix = 0;
for (i = 0; i < xStep; ++i) {
pix += lineBuf[xx++];
}
pix = (pix * d) >> 23;
for (i = 0; i < yStep; ++i) {
destPtr = destPtr0 + i * scaledWidth + x;
*destPtr = (Guchar)pix;
}
}
destPtr0 += yStep * scaledWidth;
}
gfree(lineBuf);
}
| 164,735 |
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 SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
const base::CommandLine& command_line) {
bool enableExperimentalWebPlatformFeatures = command_line.HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
if (enableExperimentalWebPlatformFeatures)
WebRuntimeFeatures::EnableExperimentalFeatures(true);
SetRuntimeFeatureDefaultsForPlatform();
WebRuntimeFeatures::EnableOriginTrials(
base::FeatureList::IsEnabled(features::kOriginTrials));
if (!base::FeatureList::IsEnabled(features::kWebUsb))
WebRuntimeFeatures::EnableWebUsb(false);
WebRuntimeFeatures::EnableBlinkHeapIncrementalMarking(
base::FeatureList::IsEnabled(features::kBlinkHeapIncrementalMarking));
WebRuntimeFeatures::EnableBlinkHeapUnifiedGarbageCollection(
base::FeatureList::IsEnabled(
features::kBlinkHeapUnifiedGarbageCollection));
if (base::FeatureList::IsEnabled(features::kBloatedRendererDetection))
WebRuntimeFeatures::EnableBloatedRendererDetection(true);
if (command_line.HasSwitch(switches::kDisableDatabases))
WebRuntimeFeatures::EnableDatabase(false);
if (command_line.HasSwitch(switches::kDisableNotifications)) {
WebRuntimeFeatures::EnableNotifications(false);
WebRuntimeFeatures::EnablePushMessaging(false);
}
if (!base::FeatureList::IsEnabled(features::kNotificationContentImage))
WebRuntimeFeatures::EnableNotificationContentImage(false);
WebRuntimeFeatures::EnableSharedArrayBuffer(
base::FeatureList::IsEnabled(features::kSharedArrayBuffer) ||
base::FeatureList::IsEnabled(features::kWebAssemblyThreads));
if (command_line.HasSwitch(switches::kDisableSharedWorkers))
WebRuntimeFeatures::EnableSharedWorker(false);
if (command_line.HasSwitch(switches::kDisableSpeechAPI))
WebRuntimeFeatures::EnableScriptedSpeech(false);
if (command_line.HasSwitch(switches::kDisableFileSystem))
WebRuntimeFeatures::EnableFileSystem(false);
if (!command_line.HasSwitch(switches::kDisableAcceleratedJpegDecoding))
WebRuntimeFeatures::EnableDecodeToYUV(true);
#if defined(SUPPORT_WEBGL2_COMPUTE_CONTEXT)
if (command_line.HasSwitch(switches::kEnableWebGL2ComputeContext)) {
WebRuntimeFeatures::EnableWebGL2ComputeContext(true);
}
#endif
if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions))
WebRuntimeFeatures::EnableWebGLDraftExtensions(true);
if (command_line.HasSwitch(switches::kEnableAutomation) ||
command_line.HasSwitch(switches::kHeadless)) {
WebRuntimeFeatures::EnableAutomationControlled(true);
}
#if defined(OS_MACOSX)
const bool enable_canvas_2d_image_chromium =
command_line.HasSwitch(
switches::kEnableGpuMemoryBufferCompositorResources) &&
!command_line.HasSwitch(switches::kDisable2dCanvasImageChromium) &&
!command_line.HasSwitch(switches::kDisableGpu) &&
base::FeatureList::IsEnabled(features::kCanvas2DImageChromium);
#else
constexpr bool enable_canvas_2d_image_chromium = false;
#endif
WebRuntimeFeatures::EnableCanvas2dImageChromium(
enable_canvas_2d_image_chromium);
#if defined(OS_MACOSX)
const bool enable_web_gl_image_chromium =
command_line.HasSwitch(
switches::kEnableGpuMemoryBufferCompositorResources) &&
!command_line.HasSwitch(switches::kDisableWebGLImageChromium) &&
!command_line.HasSwitch(switches::kDisableGpu) &&
base::FeatureList::IsEnabled(features::kWebGLImageChromium);
#else
const bool enable_web_gl_image_chromium =
command_line.HasSwitch(switches::kEnableWebGLImageChromium);
#endif
WebRuntimeFeatures::EnableWebGLImageChromium(enable_web_gl_image_chromium);
if (command_line.HasSwitch(switches::kForceOverlayFullscreenVideo))
WebRuntimeFeatures::ForceOverlayFullscreenVideo(true);
if (ui::IsOverlayScrollbarEnabled())
WebRuntimeFeatures::EnableOverlayScrollbars(true);
if (command_line.HasSwitch(switches::kEnablePreciseMemoryInfo))
WebRuntimeFeatures::EnablePreciseMemoryInfo(true);
if (command_line.HasSwitch(switches::kEnablePrintBrowser))
WebRuntimeFeatures::EnablePrintBrowser(true);
if (command_line.HasSwitch(switches::kEnableNetworkInformationDownlinkMax) ||
enableExperimentalWebPlatformFeatures) {
WebRuntimeFeatures::EnableNetInfoDownlinkMax(true);
}
if (command_line.HasSwitch(switches::kReducedReferrerGranularity))
WebRuntimeFeatures::EnableReducedReferrerGranularity(true);
if (command_line.HasSwitch(switches::kDisablePermissionsAPI))
WebRuntimeFeatures::EnablePermissionsAPI(false);
if (command_line.HasSwitch(switches::kDisableV8IdleTasks))
WebRuntimeFeatures::EnableV8IdleTasks(false);
else
WebRuntimeFeatures::EnableV8IdleTasks(true);
if (command_line.HasSwitch(switches::kEnableUnsafeWebGPU))
WebRuntimeFeatures::EnableWebGPU(true);
if (command_line.HasSwitch(switches::kEnableWebVR))
WebRuntimeFeatures::EnableWebVR(true);
if (base::FeatureList::IsEnabled(features::kWebXr))
WebRuntimeFeatures::EnableWebXR(true);
if (base::FeatureList::IsEnabled(features::kWebXrGamepadSupport))
WebRuntimeFeatures::EnableWebXRGamepadSupport(true);
if (base::FeatureList::IsEnabled(features::kWebXrHitTest))
WebRuntimeFeatures::EnableWebXRHitTest(true);
if (command_line.HasSwitch(switches::kDisablePresentationAPI))
WebRuntimeFeatures::EnablePresentationAPI(false);
if (command_line.HasSwitch(switches::kDisableRemotePlaybackAPI))
WebRuntimeFeatures::EnableRemotePlaybackAPI(false);
WebRuntimeFeatures::EnableSecMetadata(
base::FeatureList::IsEnabled(features::kSecMetadata) ||
enableExperimentalWebPlatformFeatures);
WebRuntimeFeatures::EnableUserActivationV2(
base::FeatureList::IsEnabled(features::kUserActivationV2));
if (base::FeatureList::IsEnabled(features::kScrollAnchorSerialization))
WebRuntimeFeatures::EnableScrollAnchorSerialization(true);
if (command_line.HasSwitch(switches::kEnableBlinkGenPropertyTrees))
WebRuntimeFeatures::EnableFeatureFromString("BlinkGenPropertyTrees", true);
if (command_line.HasSwitch(switches::kEnableSlimmingPaintV2))
WebRuntimeFeatures::EnableFeatureFromString("SlimmingPaintV2", true);
WebRuntimeFeatures::EnablePassiveDocumentEventListeners(
base::FeatureList::IsEnabled(features::kPassiveDocumentEventListeners));
WebRuntimeFeatures::EnablePassiveDocumentWheelEventListeners(
base::FeatureList::IsEnabled(
features::kPassiveDocumentWheelEventListeners));
WebRuntimeFeatures::EnableFeatureFromString(
"FontCacheScaling",
base::FeatureList::IsEnabled(features::kFontCacheScaling));
WebRuntimeFeatures::EnableFeatureFromString(
"FontSrcLocalMatching",
base::FeatureList::IsEnabled(features::kFontSrcLocalMatching));
WebRuntimeFeatures::EnableFeatureFromString(
"FramebustingNeedsSameOriginOrUserGesture",
base::FeatureList::IsEnabled(
features::kFramebustingNeedsSameOriginOrUserGesture));
if (command_line.HasSwitch(switches::kDisableBackgroundTimerThrottling))
WebRuntimeFeatures::EnableTimerThrottlingForBackgroundTabs(false);
WebRuntimeFeatures::EnableExpensiveBackgroundTimerThrottling(
base::FeatureList::IsEnabled(
features::kExpensiveBackgroundTimerThrottling));
if (base::FeatureList::IsEnabled(features::kHeapCompaction))
WebRuntimeFeatures::EnableHeapCompaction(true);
WebRuntimeFeatures::EnableRenderingPipelineThrottling(
base::FeatureList::IsEnabled(features::kRenderingPipelineThrottling));
WebRuntimeFeatures::EnableTimerThrottlingForHiddenFrames(
base::FeatureList::IsEnabled(features::kTimerThrottlingForHiddenFrames));
if (base::FeatureList::IsEnabled(
features::kSendBeaconThrowForBlobWithNonSimpleType))
WebRuntimeFeatures::EnableSendBeaconThrowForBlobWithNonSimpleType(true);
#if defined(OS_ANDROID)
if (command_line.HasSwitch(switches::kDisableMediaSessionAPI))
WebRuntimeFeatures::EnableMediaSession(false);
#endif
WebRuntimeFeatures::EnablePaymentRequest(
base::FeatureList::IsEnabled(features::kWebPayments));
if (base::FeatureList::IsEnabled(features::kServiceWorkerPaymentApps))
WebRuntimeFeatures::EnablePaymentApp(true);
WebRuntimeFeatures::EnableNetworkService(
base::FeatureList::IsEnabled(network::features::kNetworkService));
if (base::FeatureList::IsEnabled(features::kGamepadExtensions))
WebRuntimeFeatures::EnableGamepadExtensions(true);
if (base::FeatureList::IsEnabled(features::kGamepadVibration))
WebRuntimeFeatures::EnableGamepadVibration(true);
if (base::FeatureList::IsEnabled(features::kCompositeOpaqueFixedPosition))
WebRuntimeFeatures::EnableFeatureFromString("CompositeOpaqueFixedPosition",
true);
if (!base::FeatureList::IsEnabled(features::kCompositeOpaqueScrollers))
WebRuntimeFeatures::EnableFeatureFromString("CompositeOpaqueScrollers",
false);
if (base::FeatureList::IsEnabled(features::kCompositorTouchAction))
WebRuntimeFeatures::EnableCompositorTouchAction(true);
if (base::FeatureList::IsEnabled(features::kCSSFragmentIdentifiers))
WebRuntimeFeatures::EnableCSSFragmentIdentifiers(true);
if (!base::FeatureList::IsEnabled(features::kGenericSensor))
WebRuntimeFeatures::EnableGenericSensor(false);
if (base::FeatureList::IsEnabled(features::kGenericSensorExtraClasses))
WebRuntimeFeatures::EnableGenericSensorExtraClasses(true);
if (base::FeatureList::IsEnabled(network::features::kOutOfBlinkCORS))
WebRuntimeFeatures::EnableOutOfBlinkCORS(true);
WebRuntimeFeatures::EnableMediaCastOverlayButton(
base::FeatureList::IsEnabled(media::kMediaCastOverlayButton));
if (!base::FeatureList::IsEnabled(features::kBlockCredentialedSubresources)) {
WebRuntimeFeatures::EnableFeatureFromString("BlockCredentialedSubresources",
false);
}
if (base::FeatureList::IsEnabled(features::kRasterInducingScroll))
WebRuntimeFeatures::EnableRasterInducingScroll(true);
WebRuntimeFeatures::EnableFeatureFromString(
"AllowContentInitiatedDataUrlNavigations",
base::FeatureList::IsEnabled(
features::kAllowContentInitiatedDataUrlNavigations));
#if defined(OS_ANDROID)
if (base::FeatureList::IsEnabled(features::kWebNfc))
WebRuntimeFeatures::EnableWebNfc(true);
#endif
WebRuntimeFeatures::EnableWebAuth(
base::FeatureList::IsEnabled(features::kWebAuth));
WebRuntimeFeatures::EnableWebAuthGetTransports(
base::FeatureList::IsEnabled(features::kWebAuthGetTransports) ||
enableExperimentalWebPlatformFeatures);
WebRuntimeFeatures::EnableClientPlaceholdersForServerLoFi(
base::GetFieldTrialParamValue("PreviewsClientLoFi",
"replace_server_placeholders") != "false");
WebRuntimeFeatures::EnableResourceLoadScheduler(
base::FeatureList::IsEnabled(features::kResourceLoadScheduler));
if (base::FeatureList::IsEnabled(features::kLayeredAPI))
WebRuntimeFeatures::EnableLayeredAPI(true);
if (base::FeatureList::IsEnabled(blink::features::kLayoutNG))
WebRuntimeFeatures::EnableLayoutNG(true);
WebRuntimeFeatures::EnableLazyInitializeMediaControls(
base::FeatureList::IsEnabled(features::kLazyInitializeMediaControls));
WebRuntimeFeatures::EnableMediaEngagementBypassAutoplayPolicies(
base::FeatureList::IsEnabled(
media::kMediaEngagementBypassAutoplayPolicies));
WebRuntimeFeatures::EnableOverflowIconsForMediaControls(
base::FeatureList::IsEnabled(media::kOverflowIconsForMediaControls));
WebRuntimeFeatures::EnableAllowActivationDelegationAttr(
base::FeatureList::IsEnabled(features::kAllowActivationDelegationAttr));
WebRuntimeFeatures::EnableModernMediaControls(
base::FeatureList::IsEnabled(media::kUseModernMediaControls));
WebRuntimeFeatures::EnableWorkStealingInScriptRunner(
base::FeatureList::IsEnabled(features::kWorkStealingInScriptRunner));
WebRuntimeFeatures::EnableScheduledScriptStreaming(
base::FeatureList::IsEnabled(features::kScheduledScriptStreaming));
WebRuntimeFeatures::EnableMergeBlockingNonBlockingPools(
base::FeatureList::IsEnabled(base::kMergeBlockingNonBlockingPools));
if (base::FeatureList::IsEnabled(features::kLazyFrameLoading))
WebRuntimeFeatures::EnableLazyFrameLoading(true);
if (base::FeatureList::IsEnabled(features::kLazyFrameVisibleLoadTimeMetrics))
WebRuntimeFeatures::EnableLazyFrameVisibleLoadTimeMetrics(true);
if (base::FeatureList::IsEnabled(features::kLazyImageLoading))
WebRuntimeFeatures::EnableLazyImageLoading(true);
if (base::FeatureList::IsEnabled(features::kLazyImageVisibleLoadTimeMetrics))
WebRuntimeFeatures::EnableLazyImageVisibleLoadTimeMetrics(true);
WebRuntimeFeatures::EnableV8ContextSnapshot(
base::FeatureList::IsEnabled(features::kV8ContextSnapshot));
WebRuntimeFeatures::EnableRequireCSSExtensionForFile(
base::FeatureList::IsEnabled(features::kRequireCSSExtensionForFile));
WebRuntimeFeatures::EnablePictureInPicture(
base::FeatureList::IsEnabled(media::kPictureInPicture));
WebRuntimeFeatures::EnableCacheInlineScriptCode(
base::FeatureList::IsEnabled(features::kCacheInlineScriptCode));
WebRuntimeFeatures::EnableIsolatedCodeCache(
base::FeatureList::IsEnabled(net::features::kIsolatedCodeCache));
if (base::FeatureList::IsEnabled(features::kSignedHTTPExchange)) {
WebRuntimeFeatures::EnableSignedHTTPExchange(true);
WebRuntimeFeatures::EnablePreloadImageSrcSetEnabled(true);
}
WebRuntimeFeatures::EnableNestedWorkers(
base::FeatureList::IsEnabled(blink::features::kNestedWorkers));
if (base::FeatureList::IsEnabled(
features::kExperimentalProductivityFeatures)) {
WebRuntimeFeatures::EnableExperimentalProductivityFeatures(true);
}
if (base::FeatureList::IsEnabled(features::kPageLifecycle))
WebRuntimeFeatures::EnablePageLifecycle(true);
#if defined(OS_ANDROID)
if (base::FeatureList::IsEnabled(features::kDisplayCutoutAPI) &&
base::android::BuildInfo::GetInstance()->sdk_int() >=
base::android::SDK_VERSION_P) {
WebRuntimeFeatures::EnableDisplayCutoutAPI(true);
}
#endif
if (command_line.HasSwitch(switches::kEnableAccessibilityObjectModel))
WebRuntimeFeatures::EnableAccessibilityObjectModel(true);
if (base::FeatureList::IsEnabled(blink::features::kWritableFilesAPI))
WebRuntimeFeatures::EnableFeatureFromString("WritableFiles", true);
if (command_line.HasSwitch(
switches::kDisableOriginTrialControlledBlinkFeatures)) {
WebRuntimeFeatures::EnableOriginTrialControlledFeatures(false);
}
WebRuntimeFeatures::EnableAutoplayIgnoresWebAudio(
base::FeatureList::IsEnabled(media::kAutoplayIgnoreWebAudio));
#if defined(OS_ANDROID)
WebRuntimeFeatures::EnableMediaControlsExpandGesture(
base::FeatureList::IsEnabled(media::kMediaControlsExpandGesture));
#endif
for (const std::string& feature :
FeaturesFromSwitch(command_line, switches::kEnableBlinkFeatures)) {
WebRuntimeFeatures::EnableFeatureFromString(feature, true);
}
for (const std::string& feature :
FeaturesFromSwitch(command_line, switches::kDisableBlinkFeatures)) {
WebRuntimeFeatures::EnableFeatureFromString(feature, false);
}
WebRuntimeFeatures::EnablePortals(
base::FeatureList::IsEnabled(blink::features::kPortals));
if (!base::FeatureList::IsEnabled(features::kBackgroundFetch))
WebRuntimeFeatures::EnableBackgroundFetch(false);
WebRuntimeFeatures::EnableBackgroundFetchUploads(
base::FeatureList::IsEnabled(features::kBackgroundFetchUploads));
WebRuntimeFeatures::EnableNoHoverAfterLayoutChange(
base::FeatureList::IsEnabled(features::kNoHoverAfterLayoutChange));
WebRuntimeFeatures::EnableJankTracking(
base::FeatureList::IsEnabled(blink::features::kJankTracking) ||
enableExperimentalWebPlatformFeatures);
WebRuntimeFeatures::EnableNoHoverDuringScroll(
base::FeatureList::IsEnabled(features::kNoHoverDuringScroll));
}
Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag.
The feature has long since been stable (since M64) and doesn't seem
to be a need for this flag.
BUG=788936
Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0
Reviewed-on: https://chromium-review.googlesource.com/c/1324143
Reviewed-by: Mike West <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Dave Tapuska <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607329}
CWE ID: CWE-254 | void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
const base::CommandLine& command_line) {
bool enableExperimentalWebPlatformFeatures = command_line.HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
if (enableExperimentalWebPlatformFeatures)
WebRuntimeFeatures::EnableExperimentalFeatures(true);
SetRuntimeFeatureDefaultsForPlatform();
WebRuntimeFeatures::EnableOriginTrials(
base::FeatureList::IsEnabled(features::kOriginTrials));
if (!base::FeatureList::IsEnabled(features::kWebUsb))
WebRuntimeFeatures::EnableWebUsb(false);
WebRuntimeFeatures::EnableBlinkHeapIncrementalMarking(
base::FeatureList::IsEnabled(features::kBlinkHeapIncrementalMarking));
WebRuntimeFeatures::EnableBlinkHeapUnifiedGarbageCollection(
base::FeatureList::IsEnabled(
features::kBlinkHeapUnifiedGarbageCollection));
if (base::FeatureList::IsEnabled(features::kBloatedRendererDetection))
WebRuntimeFeatures::EnableBloatedRendererDetection(true);
if (command_line.HasSwitch(switches::kDisableDatabases))
WebRuntimeFeatures::EnableDatabase(false);
if (command_line.HasSwitch(switches::kDisableNotifications)) {
WebRuntimeFeatures::EnableNotifications(false);
WebRuntimeFeatures::EnablePushMessaging(false);
}
if (!base::FeatureList::IsEnabled(features::kNotificationContentImage))
WebRuntimeFeatures::EnableNotificationContentImage(false);
WebRuntimeFeatures::EnableSharedArrayBuffer(
base::FeatureList::IsEnabled(features::kSharedArrayBuffer) ||
base::FeatureList::IsEnabled(features::kWebAssemblyThreads));
if (command_line.HasSwitch(switches::kDisableSharedWorkers))
WebRuntimeFeatures::EnableSharedWorker(false);
if (command_line.HasSwitch(switches::kDisableSpeechAPI))
WebRuntimeFeatures::EnableScriptedSpeech(false);
if (command_line.HasSwitch(switches::kDisableFileSystem))
WebRuntimeFeatures::EnableFileSystem(false);
if (!command_line.HasSwitch(switches::kDisableAcceleratedJpegDecoding))
WebRuntimeFeatures::EnableDecodeToYUV(true);
#if defined(SUPPORT_WEBGL2_COMPUTE_CONTEXT)
if (command_line.HasSwitch(switches::kEnableWebGL2ComputeContext)) {
WebRuntimeFeatures::EnableWebGL2ComputeContext(true);
}
#endif
if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions))
WebRuntimeFeatures::EnableWebGLDraftExtensions(true);
if (command_line.HasSwitch(switches::kEnableAutomation) ||
command_line.HasSwitch(switches::kHeadless)) {
WebRuntimeFeatures::EnableAutomationControlled(true);
}
#if defined(OS_MACOSX)
const bool enable_canvas_2d_image_chromium =
command_line.HasSwitch(
switches::kEnableGpuMemoryBufferCompositorResources) &&
!command_line.HasSwitch(switches::kDisable2dCanvasImageChromium) &&
!command_line.HasSwitch(switches::kDisableGpu) &&
base::FeatureList::IsEnabled(features::kCanvas2DImageChromium);
#else
constexpr bool enable_canvas_2d_image_chromium = false;
#endif
WebRuntimeFeatures::EnableCanvas2dImageChromium(
enable_canvas_2d_image_chromium);
#if defined(OS_MACOSX)
const bool enable_web_gl_image_chromium =
command_line.HasSwitch(
switches::kEnableGpuMemoryBufferCompositorResources) &&
!command_line.HasSwitch(switches::kDisableWebGLImageChromium) &&
!command_line.HasSwitch(switches::kDisableGpu) &&
base::FeatureList::IsEnabled(features::kWebGLImageChromium);
#else
const bool enable_web_gl_image_chromium =
command_line.HasSwitch(switches::kEnableWebGLImageChromium);
#endif
WebRuntimeFeatures::EnableWebGLImageChromium(enable_web_gl_image_chromium);
if (command_line.HasSwitch(switches::kForceOverlayFullscreenVideo))
WebRuntimeFeatures::ForceOverlayFullscreenVideo(true);
if (ui::IsOverlayScrollbarEnabled())
WebRuntimeFeatures::EnableOverlayScrollbars(true);
if (command_line.HasSwitch(switches::kEnablePreciseMemoryInfo))
WebRuntimeFeatures::EnablePreciseMemoryInfo(true);
if (command_line.HasSwitch(switches::kEnablePrintBrowser))
WebRuntimeFeatures::EnablePrintBrowser(true);
if (command_line.HasSwitch(switches::kEnableNetworkInformationDownlinkMax) ||
enableExperimentalWebPlatformFeatures) {
WebRuntimeFeatures::EnableNetInfoDownlinkMax(true);
}
if (command_line.HasSwitch(switches::kReducedReferrerGranularity))
WebRuntimeFeatures::EnableReducedReferrerGranularity(true);
if (command_line.HasSwitch(switches::kDisablePermissionsAPI))
WebRuntimeFeatures::EnablePermissionsAPI(false);
if (command_line.HasSwitch(switches::kDisableV8IdleTasks))
WebRuntimeFeatures::EnableV8IdleTasks(false);
else
WebRuntimeFeatures::EnableV8IdleTasks(true);
if (command_line.HasSwitch(switches::kEnableUnsafeWebGPU))
WebRuntimeFeatures::EnableWebGPU(true);
if (command_line.HasSwitch(switches::kEnableWebVR))
WebRuntimeFeatures::EnableWebVR(true);
if (base::FeatureList::IsEnabled(features::kWebXr))
WebRuntimeFeatures::EnableWebXR(true);
if (base::FeatureList::IsEnabled(features::kWebXrGamepadSupport))
WebRuntimeFeatures::EnableWebXRGamepadSupport(true);
if (base::FeatureList::IsEnabled(features::kWebXrHitTest))
WebRuntimeFeatures::EnableWebXRHitTest(true);
if (command_line.HasSwitch(switches::kDisablePresentationAPI))
WebRuntimeFeatures::EnablePresentationAPI(false);
if (command_line.HasSwitch(switches::kDisableRemotePlaybackAPI))
WebRuntimeFeatures::EnableRemotePlaybackAPI(false);
WebRuntimeFeatures::EnableSecMetadata(
base::FeatureList::IsEnabled(features::kSecMetadata) ||
enableExperimentalWebPlatformFeatures);
WebRuntimeFeatures::EnableUserActivationV2(
base::FeatureList::IsEnabled(features::kUserActivationV2));
if (base::FeatureList::IsEnabled(features::kScrollAnchorSerialization))
WebRuntimeFeatures::EnableScrollAnchorSerialization(true);
if (command_line.HasSwitch(switches::kEnableBlinkGenPropertyTrees))
WebRuntimeFeatures::EnableFeatureFromString("BlinkGenPropertyTrees", true);
if (command_line.HasSwitch(switches::kEnableSlimmingPaintV2))
WebRuntimeFeatures::EnableFeatureFromString("SlimmingPaintV2", true);
WebRuntimeFeatures::EnablePassiveDocumentEventListeners(
base::FeatureList::IsEnabled(features::kPassiveDocumentEventListeners));
WebRuntimeFeatures::EnablePassiveDocumentWheelEventListeners(
base::FeatureList::IsEnabled(
features::kPassiveDocumentWheelEventListeners));
WebRuntimeFeatures::EnableFeatureFromString(
"FontCacheScaling",
base::FeatureList::IsEnabled(features::kFontCacheScaling));
WebRuntimeFeatures::EnableFeatureFromString(
"FontSrcLocalMatching",
base::FeatureList::IsEnabled(features::kFontSrcLocalMatching));
WebRuntimeFeatures::EnableFeatureFromString(
"FramebustingNeedsSameOriginOrUserGesture",
base::FeatureList::IsEnabled(
features::kFramebustingNeedsSameOriginOrUserGesture));
if (command_line.HasSwitch(switches::kDisableBackgroundTimerThrottling))
WebRuntimeFeatures::EnableTimerThrottlingForBackgroundTabs(false);
WebRuntimeFeatures::EnableExpensiveBackgroundTimerThrottling(
base::FeatureList::IsEnabled(
features::kExpensiveBackgroundTimerThrottling));
if (base::FeatureList::IsEnabled(features::kHeapCompaction))
WebRuntimeFeatures::EnableHeapCompaction(true);
WebRuntimeFeatures::EnableRenderingPipelineThrottling(
base::FeatureList::IsEnabled(features::kRenderingPipelineThrottling));
WebRuntimeFeatures::EnableTimerThrottlingForHiddenFrames(
base::FeatureList::IsEnabled(features::kTimerThrottlingForHiddenFrames));
if (base::FeatureList::IsEnabled(
features::kSendBeaconThrowForBlobWithNonSimpleType))
WebRuntimeFeatures::EnableSendBeaconThrowForBlobWithNonSimpleType(true);
#if defined(OS_ANDROID)
if (command_line.HasSwitch(switches::kDisableMediaSessionAPI))
WebRuntimeFeatures::EnableMediaSession(false);
#endif
WebRuntimeFeatures::EnablePaymentRequest(
base::FeatureList::IsEnabled(features::kWebPayments));
if (base::FeatureList::IsEnabled(features::kServiceWorkerPaymentApps))
WebRuntimeFeatures::EnablePaymentApp(true);
WebRuntimeFeatures::EnableNetworkService(
base::FeatureList::IsEnabled(network::features::kNetworkService));
if (base::FeatureList::IsEnabled(features::kGamepadExtensions))
WebRuntimeFeatures::EnableGamepadExtensions(true);
if (base::FeatureList::IsEnabled(features::kGamepadVibration))
WebRuntimeFeatures::EnableGamepadVibration(true);
if (base::FeatureList::IsEnabled(features::kCompositeOpaqueFixedPosition))
WebRuntimeFeatures::EnableFeatureFromString("CompositeOpaqueFixedPosition",
true);
if (!base::FeatureList::IsEnabled(features::kCompositeOpaqueScrollers))
WebRuntimeFeatures::EnableFeatureFromString("CompositeOpaqueScrollers",
false);
if (base::FeatureList::IsEnabled(features::kCompositorTouchAction))
WebRuntimeFeatures::EnableCompositorTouchAction(true);
if (base::FeatureList::IsEnabled(features::kCSSFragmentIdentifiers))
WebRuntimeFeatures::EnableCSSFragmentIdentifiers(true);
if (!base::FeatureList::IsEnabled(features::kGenericSensor))
WebRuntimeFeatures::EnableGenericSensor(false);
if (base::FeatureList::IsEnabled(features::kGenericSensorExtraClasses))
WebRuntimeFeatures::EnableGenericSensorExtraClasses(true);
if (base::FeatureList::IsEnabled(network::features::kOutOfBlinkCORS))
WebRuntimeFeatures::EnableOutOfBlinkCORS(true);
WebRuntimeFeatures::EnableMediaCastOverlayButton(
base::FeatureList::IsEnabled(media::kMediaCastOverlayButton));
if (!base::FeatureList::IsEnabled(features::kBlockCredentialedSubresources)) {
WebRuntimeFeatures::EnableFeatureFromString("BlockCredentialedSubresources",
false);
}
if (base::FeatureList::IsEnabled(features::kRasterInducingScroll))
WebRuntimeFeatures::EnableRasterInducingScroll(true);
WebRuntimeFeatures::EnableFeatureFromString(
"AllowContentInitiatedDataUrlNavigations",
base::FeatureList::IsEnabled(
features::kAllowContentInitiatedDataUrlNavigations));
#if defined(OS_ANDROID)
if (base::FeatureList::IsEnabled(features::kWebNfc))
WebRuntimeFeatures::EnableWebNfc(true);
#endif
WebRuntimeFeatures::EnableWebAuth(
base::FeatureList::IsEnabled(features::kWebAuth));
WebRuntimeFeatures::EnableWebAuthGetTransports(
base::FeatureList::IsEnabled(features::kWebAuthGetTransports) ||
enableExperimentalWebPlatformFeatures);
WebRuntimeFeatures::EnableClientPlaceholdersForServerLoFi(
base::GetFieldTrialParamValue("PreviewsClientLoFi",
"replace_server_placeholders") != "false");
WebRuntimeFeatures::EnableResourceLoadScheduler(
base::FeatureList::IsEnabled(features::kResourceLoadScheduler));
if (base::FeatureList::IsEnabled(features::kLayeredAPI))
WebRuntimeFeatures::EnableLayeredAPI(true);
if (base::FeatureList::IsEnabled(blink::features::kLayoutNG))
WebRuntimeFeatures::EnableLayoutNG(true);
WebRuntimeFeatures::EnableLazyInitializeMediaControls(
base::FeatureList::IsEnabled(features::kLazyInitializeMediaControls));
WebRuntimeFeatures::EnableMediaEngagementBypassAutoplayPolicies(
base::FeatureList::IsEnabled(
media::kMediaEngagementBypassAutoplayPolicies));
WebRuntimeFeatures::EnableOverflowIconsForMediaControls(
base::FeatureList::IsEnabled(media::kOverflowIconsForMediaControls));
WebRuntimeFeatures::EnableAllowActivationDelegationAttr(
base::FeatureList::IsEnabled(features::kAllowActivationDelegationAttr));
WebRuntimeFeatures::EnableModernMediaControls(
base::FeatureList::IsEnabled(media::kUseModernMediaControls));
WebRuntimeFeatures::EnableWorkStealingInScriptRunner(
base::FeatureList::IsEnabled(features::kWorkStealingInScriptRunner));
WebRuntimeFeatures::EnableScheduledScriptStreaming(
base::FeatureList::IsEnabled(features::kScheduledScriptStreaming));
WebRuntimeFeatures::EnableMergeBlockingNonBlockingPools(
base::FeatureList::IsEnabled(base::kMergeBlockingNonBlockingPools));
if (base::FeatureList::IsEnabled(features::kLazyFrameLoading))
WebRuntimeFeatures::EnableLazyFrameLoading(true);
if (base::FeatureList::IsEnabled(features::kLazyFrameVisibleLoadTimeMetrics))
WebRuntimeFeatures::EnableLazyFrameVisibleLoadTimeMetrics(true);
if (base::FeatureList::IsEnabled(features::kLazyImageLoading))
WebRuntimeFeatures::EnableLazyImageLoading(true);
if (base::FeatureList::IsEnabled(features::kLazyImageVisibleLoadTimeMetrics))
WebRuntimeFeatures::EnableLazyImageVisibleLoadTimeMetrics(true);
WebRuntimeFeatures::EnableV8ContextSnapshot(
base::FeatureList::IsEnabled(features::kV8ContextSnapshot));
WebRuntimeFeatures::EnablePictureInPicture(
base::FeatureList::IsEnabled(media::kPictureInPicture));
WebRuntimeFeatures::EnableCacheInlineScriptCode(
base::FeatureList::IsEnabled(features::kCacheInlineScriptCode));
WebRuntimeFeatures::EnableIsolatedCodeCache(
base::FeatureList::IsEnabled(net::features::kIsolatedCodeCache));
if (base::FeatureList::IsEnabled(features::kSignedHTTPExchange)) {
WebRuntimeFeatures::EnableSignedHTTPExchange(true);
WebRuntimeFeatures::EnablePreloadImageSrcSetEnabled(true);
}
WebRuntimeFeatures::EnableNestedWorkers(
base::FeatureList::IsEnabled(blink::features::kNestedWorkers));
if (base::FeatureList::IsEnabled(
features::kExperimentalProductivityFeatures)) {
WebRuntimeFeatures::EnableExperimentalProductivityFeatures(true);
}
if (base::FeatureList::IsEnabled(features::kPageLifecycle))
WebRuntimeFeatures::EnablePageLifecycle(true);
#if defined(OS_ANDROID)
if (base::FeatureList::IsEnabled(features::kDisplayCutoutAPI) &&
base::android::BuildInfo::GetInstance()->sdk_int() >=
base::android::SDK_VERSION_P) {
WebRuntimeFeatures::EnableDisplayCutoutAPI(true);
}
#endif
if (command_line.HasSwitch(switches::kEnableAccessibilityObjectModel))
WebRuntimeFeatures::EnableAccessibilityObjectModel(true);
if (base::FeatureList::IsEnabled(blink::features::kWritableFilesAPI))
WebRuntimeFeatures::EnableFeatureFromString("WritableFiles", true);
if (command_line.HasSwitch(
switches::kDisableOriginTrialControlledBlinkFeatures)) {
WebRuntimeFeatures::EnableOriginTrialControlledFeatures(false);
}
WebRuntimeFeatures::EnableAutoplayIgnoresWebAudio(
base::FeatureList::IsEnabled(media::kAutoplayIgnoreWebAudio));
#if defined(OS_ANDROID)
WebRuntimeFeatures::EnableMediaControlsExpandGesture(
base::FeatureList::IsEnabled(media::kMediaControlsExpandGesture));
#endif
for (const std::string& feature :
FeaturesFromSwitch(command_line, switches::kEnableBlinkFeatures)) {
WebRuntimeFeatures::EnableFeatureFromString(feature, true);
}
for (const std::string& feature :
FeaturesFromSwitch(command_line, switches::kDisableBlinkFeatures)) {
WebRuntimeFeatures::EnableFeatureFromString(feature, false);
}
WebRuntimeFeatures::EnablePortals(
base::FeatureList::IsEnabled(blink::features::kPortals));
if (!base::FeatureList::IsEnabled(features::kBackgroundFetch))
WebRuntimeFeatures::EnableBackgroundFetch(false);
WebRuntimeFeatures::EnableBackgroundFetchUploads(
base::FeatureList::IsEnabled(features::kBackgroundFetchUploads));
WebRuntimeFeatures::EnableNoHoverAfterLayoutChange(
base::FeatureList::IsEnabled(features::kNoHoverAfterLayoutChange));
WebRuntimeFeatures::EnableJankTracking(
base::FeatureList::IsEnabled(blink::features::kJankTracking) ||
enableExperimentalWebPlatformFeatures);
WebRuntimeFeatures::EnableNoHoverDuringScroll(
base::FeatureList::IsEnabled(features::kNoHoverDuringScroll));
}
| 173,185 |
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 yr_re_fast_exec(
uint8_t* code,
uint8_t* input_data,
size_t input_forwards_size,
size_t input_backwards_size,
int flags,
RE_MATCH_CALLBACK_FUNC callback,
void* callback_args,
int* matches)
{
RE_REPEAT_ANY_ARGS* repeat_any_args;
uint8_t* code_stack[MAX_FAST_RE_STACK];
uint8_t* input_stack[MAX_FAST_RE_STACK];
int matches_stack[MAX_FAST_RE_STACK];
uint8_t* ip = code;
uint8_t* input = input_data;
uint8_t* next_input;
uint8_t* next_opcode;
uint8_t mask;
uint8_t value;
int i;
int stop;
int input_incr;
int sp = 0;
int bytes_matched;
int max_bytes_matched;
max_bytes_matched = flags & RE_FLAGS_BACKWARDS ?
(int) input_backwards_size :
(int) input_forwards_size;
input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1;
if (flags & RE_FLAGS_BACKWARDS)
input--;
code_stack[sp] = code;
input_stack[sp] = input;
matches_stack[sp] = 0;
sp++;
while (sp > 0)
{
sp--;
ip = code_stack[sp];
input = input_stack[sp];
bytes_matched = matches_stack[sp];
stop = FALSE;
while(!stop)
{
if (*ip == RE_OPCODE_MATCH)
{
if (flags & RE_FLAGS_EXHAUSTIVE)
{
FAIL_ON_ERROR(callback(
flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data,
bytes_matched,
flags,
callback_args));
break;
}
else
{
if (matches != NULL)
*matches = bytes_matched;
return ERROR_SUCCESS;
}
}
if (bytes_matched >= max_bytes_matched)
break;
switch(*ip)
{
case RE_OPCODE_LITERAL:
if (*input == *(ip + 1))
{
bytes_matched++;
input += input_incr;
ip += 2;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_MASKED_LITERAL:
value = *(int16_t*)(ip + 1) & 0xFF;
mask = *(int16_t*)(ip + 1) >> 8;
if ((*input & mask) == value)
{
bytes_matched++;
input += input_incr;
ip += 3;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_ANY:
bytes_matched++;
input += input_incr;
ip += 1;
break;
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1);
next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS);
for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++)
{
next_input = input + i * input_incr;
if (bytes_matched + i >= max_bytes_matched)
break;
if ( *(next_opcode) != RE_OPCODE_LITERAL ||
(*(next_opcode) == RE_OPCODE_LITERAL &&
*(next_opcode + 1) == *next_input))
{
if (sp >= MAX_FAST_RE_STACK)
return -4;
code_stack[sp] = next_opcode;
input_stack[sp] = next_input;
matches_stack[sp] = bytes_matched + i;
sp++;
}
}
input += input_incr * repeat_any_args->min;
bytes_matched += repeat_any_args->min;
ip = next_opcode;
break;
default:
assert(FALSE);
}
}
}
if (matches != NULL)
*matches = -1;
return ERROR_SUCCESS;
}
Commit Message: Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier.
CWE ID: CWE-125 | int yr_re_fast_exec(
uint8_t* code,
uint8_t* input_data,
size_t input_forwards_size,
size_t input_backwards_size,
int flags,
RE_MATCH_CALLBACK_FUNC callback,
void* callback_args,
int* matches)
{
RE_REPEAT_ANY_ARGS* repeat_any_args;
uint8_t* code_stack[MAX_FAST_RE_STACK];
uint8_t* input_stack[MAX_FAST_RE_STACK];
int matches_stack[MAX_FAST_RE_STACK];
uint8_t* ip = code;
uint8_t* input = input_data;
uint8_t* next_input;
uint8_t* next_opcode;
uint8_t mask;
uint8_t value;
int i;
int stop;
int input_incr;
int sp = 0;
int bytes_matched;
int max_bytes_matched;
max_bytes_matched = flags & RE_FLAGS_BACKWARDS ?
(int) input_backwards_size :
(int) input_forwards_size;
input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1;
if (flags & RE_FLAGS_BACKWARDS)
input--;
code_stack[sp] = code;
input_stack[sp] = input;
matches_stack[sp] = 0;
sp++;
while (sp > 0)
{
sp--;
ip = code_stack[sp];
input = input_stack[sp];
bytes_matched = matches_stack[sp];
stop = FALSE;
while(!stop)
{
if (*ip == RE_OPCODE_MATCH)
{
if (flags & RE_FLAGS_EXHAUSTIVE)
{
FAIL_ON_ERROR(callback(
flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data,
bytes_matched,
flags,
callback_args));
break;
}
else
{
if (matches != NULL)
*matches = bytes_matched;
return ERROR_SUCCESS;
}
}
if (bytes_matched >= max_bytes_matched)
break;
switch(*ip)
{
case RE_OPCODE_LITERAL:
if (*input == *(ip + 1))
{
bytes_matched++;
input += input_incr;
ip += 2;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_MASKED_LITERAL:
value = *(int16_t*)(ip + 1) & 0xFF;
mask = *(int16_t*)(ip + 1) >> 8;
if ((*input & mask) == value)
{
bytes_matched++;
input += input_incr;
ip += 3;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_ANY:
bytes_matched++;
input += input_incr;
ip += 1;
break;
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1);
next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS);
for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++)
{
if (bytes_matched + i >= max_bytes_matched)
break;
next_input = input + i * input_incr;
if ( *(next_opcode) != RE_OPCODE_LITERAL ||
(*(next_opcode) == RE_OPCODE_LITERAL &&
*(next_opcode + 1) == *next_input))
{
if (sp >= MAX_FAST_RE_STACK)
return -4;
code_stack[sp] = next_opcode;
input_stack[sp] = next_input;
matches_stack[sp] = bytes_matched + i;
sp++;
}
}
input += input_incr * repeat_any_args->min;
bytes_matched += repeat_any_args->min;
bytes_matched = yr_min(bytes_matched, max_bytes_matched);
ip = next_opcode;
break;
default:
assert(FALSE);
}
}
}
if (matches != NULL)
*matches = -1;
return ERROR_SUCCESS;
}
| 168,098 |
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: CreateSampleTransformNodeWithElementId() {
TransformPaintPropertyNode::State state;
state.matrix.Rotate(90);
state.origin = FloatPoint3D(100, 100, 0);
state.direct_compositing_reasons = CompositingReason::k3DTransform;
state.compositor_element_id = CompositorElementId(3);
return TransformPaintPropertyNode::Create(TransformPaintPropertyNode::Root(),
std::move(state));
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | CreateSampleTransformNodeWithElementId() {
TransformPaintPropertyNode::State state;
state.matrix.Rotate(90);
state.origin = FloatPoint3D(100, 100, 0);
state.direct_compositing_reasons = CompositingReason::k3DTransform;
state.compositor_element_id = CompositorElementId(3);
return TransformPaintPropertyNode::Create(t0(), std::move(state));
}
| 171,818 |
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 mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
const mbedtls_ecp_point *G,
mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
size_t n_size = ( grp->nbits + 7 ) / 8;
#if defined(ECP_MONTGOMERY)
if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )
{
/* [M225] page 5 */
size_t b;
do {
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
} while( mbedtls_mpi_bitlen( d ) == 0);
/* Make sure the most significant bit is nbits */
b = mbedtls_mpi_bitlen( d ) - 1; /* mbedtls_mpi_bitlen is one-based */
if( b > grp->nbits )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - grp->nbits ) );
else
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) );
/* Make sure the last three bits are unset */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) );
}
else
#endif /* ECP_MONTGOMERY */
#if defined(ECP_SHORTWEIERSTRASS)
if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )
{
/* SEC1 3.2.1: Generate d such that 1 <= n < N */
int count = 0;
/*
* Match the procedure given in RFC 6979 (deterministic ECDSA):
* - use the same byte ordering;
* - keep the leftmost nbits bits of the generated octet string;
* - try until result is in the desired range.
* This also avoids any biais, which is especially important for ECDSA.
*/
do
{
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) );
/*
* Each try has at worst a probability 1/2 of failing (the msb has
* a probability 1/2 of being 0, and then the result will be < N),
* so after 30 tries failure probability is a most 2**(-30).
*
* For most curves, 1 try is enough with overwhelming probability,
* since N starts with a lot of 1s in binary, but some curves
* such as secp224k1 are actually very close to the worst case.
*/
if( ++count > 30 )
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
}
while( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 );
}
else
#endif /* ECP_SHORTWEIERSTRASS */
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
cleanup:
if( ret != 0 )
return( ret );
return( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) );
}
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted
CWE ID: CWE-200 | int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp,
mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
size_t n_size = ( grp->nbits + 7 ) / 8;
#if defined(ECP_MONTGOMERY)
if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )
{
/* [M225] page 5 */
size_t b;
do {
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
} while( mbedtls_mpi_bitlen( d ) == 0);
/* Make sure the most significant bit is nbits */
b = mbedtls_mpi_bitlen( d ) - 1; /* mbedtls_mpi_bitlen is one-based */
if( b > grp->nbits )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - grp->nbits ) );
else
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) );
/* Make sure the last three bits are unset */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) );
}
#endif /* ECP_MONTGOMERY */
#if defined(ECP_SHORTWEIERSTRASS)
if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )
{
/* SEC1 3.2.1: Generate d such that 1 <= n < N */
int count = 0;
/*
* Match the procedure given in RFC 6979 (deterministic ECDSA):
* - use the same byte ordering;
* - keep the leftmost nbits bits of the generated octet string;
* - try until result is in the desired range.
* This also avoids any biais, which is especially important for ECDSA.
*/
do
{
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) );
/*
* Each try has at worst a probability 1/2 of failing (the msb has
* a probability 1/2 of being 0, and then the result will be < N),
* so after 30 tries failure probability is a most 2**(-30).
*
* For most curves, 1 try is enough with overwhelming probability,
* since N starts with a lot of 1s in binary, but some curves
* such as secp224k1 are actually very close to the worst case.
*/
if( ++count > 30 )
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
}
while( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 );
}
#endif /* ECP_SHORTWEIERSTRASS */
cleanup:
return( ret );
}
/*
* Generate a keypair with configurable base point
*/
int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
const mbedtls_ecp_point *G,
mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, d, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) );
cleanup:
return( ret );
}
| 170,183 |
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: WORD32 ih264d_parse_islice_data_cavlc(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD8 uc_more_data_flag;
UWORD8 u1_num_mbs, u1_mb_idx;
dec_mb_info_t *ps_cur_mb_info;
deblk_mb_t *ps_cur_deblk_mb;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
WORD16 i2_cur_mb_addr;
UWORD8 u1_mbaff;
UWORD8 u1_num_mbs_next, u1_end_of_row, u1_tfr_n_mb;
WORD32 ret = OK;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
/* initializations */
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
uc_more_data_flag = 1;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
do
{
UWORD8 u1_mb_type;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_mb_info->u1_end_of_slice = 0;
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 0);
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
ps_cur_deblk_mb->u1_mb_type = ps_cur_deblk_mb->u1_mb_type | D_INTRA_MB;
/**************************************************************/
/* Macroblock Layer Begins, Decode the u1_mb_type */
/**************************************************************/
{
UWORD32 u4_bitstream_offset = *pu4_bitstrm_ofst;
UWORD32 u4_word, u4_ldz, u4_temp;
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf);
u4_ldz = CLZ(u4_word);
/* Flush the ps_bitstrm */
u4_bitstream_offset += (u4_ldz + 1);
/* Read the suffix from the ps_bitstrm */
u4_word = 0;
if(u4_ldz)
GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf,
u4_ldz);
*pu4_bitstrm_ofst = u4_bitstream_offset;
u4_temp = ((1 << u4_ldz) + u4_word - 1);
if(u4_temp > 25)
return ERROR_MB_TYPE;
u1_mb_type = u4_temp;
}
ps_cur_mb_info->u1_mb_type = u1_mb_type;
COPYTHECONTEXT("u1_mb_type", u1_mb_type);
/**************************************************************/
/* Parse Macroblock data */
/**************************************************************/
if(25 == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = 0;
}
else
{
ret = ih264d_parse_imb_cavlc(ps_dec, ps_cur_mb_info, u1_num_mbs, u1_mb_type);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
}
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/**************************************************************/
/* Get next Macroblock address */
/**************************************************************/
i2_cur_mb_addr++;
uc_more_data_flag = MORE_RBSP_DATA(ps_bitstrm);
/* Store the colocated information */
{
mv_pred_t *ps_mv_nmb_start = ps_dec->ps_mv_cur + (u1_num_mbs << 4);
mv_pred_t s_mvPred =
{
{ 0, 0, 0, 0 },
{ -1, -1 }, 0, 0};
ih264d_rep_mv_colz(ps_dec, &s_mvPred, ps_mv_nmb_start, 0,
(UWORD8)(ps_dec->u1_cur_mb_fld_dec_flag << 1), 4,
4);
}
/*if num _cores is set to 3,compute bs will be done in another thread*/
if(ps_dec->u4_num_cores < 3)
{
if(ps_dec->u4_app_disable_deblk_frm == 0)
ps_dec->pf_compute_bs(ps_dec, ps_cur_mb_info,
(UWORD16)(u1_num_mbs >> u1_mbaff));
}
u1_num_mbs++;
/****************************************************************/
/* Check for End Of Row */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| (!uc_more_data_flag);
ps_cur_mb_info->u1_end_of_slice = (!uc_more_data_flag);
/*H264_DEC_DEBUG_PRINT("Pic: %d Mb_X=%d Mb_Y=%d",
ps_slice->i4_poc >> ps_slice->u1_field_pic_flag,
ps_dec->u2_mbx,ps_dec->u2_mby + (1 - ps_cur_mb_info->u1_topmb));
H264_DEC_DEBUG_PRINT("u1_tfr_n_mb || (!uc_more_data_flag): %d", u1_tfr_n_mb || (!uc_more_data_flag));*/
if(u1_tfr_n_mb || (!uc_more_data_flag))
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
while(uc_more_data_flag);
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
Commit Message: Fix in returning end of bitstream error for MBAFF
In case of MBAFF streams, slices should terminate on
even MB boundary. If bytes are exhausted with odd number
of MBs decoded for MBAff, then treat that as error.
Bug: 33933140
Change-Id: Ifc26b66ff8ebdb3aec5c0d6c512e4cac3f54c5b7
CWE ID: | WORD32 ih264d_parse_islice_data_cavlc(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD8 uc_more_data_flag;
UWORD8 u1_num_mbs, u1_mb_idx;
dec_mb_info_t *ps_cur_mb_info;
deblk_mb_t *ps_cur_deblk_mb;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
WORD16 i2_cur_mb_addr;
UWORD8 u1_mbaff;
UWORD8 u1_num_mbs_next, u1_end_of_row, u1_tfr_n_mb;
WORD32 ret = OK;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
/* initializations */
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
uc_more_data_flag = 1;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
do
{
UWORD8 u1_mb_type;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_mb_info->u1_end_of_slice = 0;
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 0);
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
ps_cur_deblk_mb->u1_mb_type = ps_cur_deblk_mb->u1_mb_type | D_INTRA_MB;
/**************************************************************/
/* Macroblock Layer Begins, Decode the u1_mb_type */
/**************************************************************/
{
UWORD32 u4_bitstream_offset = *pu4_bitstrm_ofst;
UWORD32 u4_word, u4_ldz, u4_temp;
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf);
u4_ldz = CLZ(u4_word);
/* Flush the ps_bitstrm */
u4_bitstream_offset += (u4_ldz + 1);
/* Read the suffix from the ps_bitstrm */
u4_word = 0;
if(u4_ldz)
GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf,
u4_ldz);
*pu4_bitstrm_ofst = u4_bitstream_offset;
u4_temp = ((1 << u4_ldz) + u4_word - 1);
if(u4_temp > 25)
return ERROR_MB_TYPE;
u1_mb_type = u4_temp;
}
ps_cur_mb_info->u1_mb_type = u1_mb_type;
COPYTHECONTEXT("u1_mb_type", u1_mb_type);
/**************************************************************/
/* Parse Macroblock data */
/**************************************************************/
if(25 == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = 0;
}
else
{
ret = ih264d_parse_imb_cavlc(ps_dec, ps_cur_mb_info, u1_num_mbs, u1_mb_type);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
}
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
if(!uc_more_data_flag && (0 == (i2_cur_mb_addr & 1)))
{
return ERROR_EOB_FLUSHBITS_T;
}
}
/**************************************************************/
/* Get next Macroblock address */
/**************************************************************/
i2_cur_mb_addr++;
uc_more_data_flag = MORE_RBSP_DATA(ps_bitstrm);
/* Store the colocated information */
{
mv_pred_t *ps_mv_nmb_start = ps_dec->ps_mv_cur + (u1_num_mbs << 4);
mv_pred_t s_mvPred =
{
{ 0, 0, 0, 0 },
{ -1, -1 }, 0, 0};
ih264d_rep_mv_colz(ps_dec, &s_mvPred, ps_mv_nmb_start, 0,
(UWORD8)(ps_dec->u1_cur_mb_fld_dec_flag << 1), 4,
4);
}
/*if num _cores is set to 3,compute bs will be done in another thread*/
if(ps_dec->u4_num_cores < 3)
{
if(ps_dec->u4_app_disable_deblk_frm == 0)
ps_dec->pf_compute_bs(ps_dec, ps_cur_mb_info,
(UWORD16)(u1_num_mbs >> u1_mbaff));
}
u1_num_mbs++;
/****************************************************************/
/* Check for End Of Row */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| (!uc_more_data_flag);
ps_cur_mb_info->u1_end_of_slice = (!uc_more_data_flag);
/*H264_DEC_DEBUG_PRINT("Pic: %d Mb_X=%d Mb_Y=%d",
ps_slice->i4_poc >> ps_slice->u1_field_pic_flag,
ps_dec->u2_mbx,ps_dec->u2_mby + (1 - ps_cur_mb_info->u1_topmb));
H264_DEC_DEBUG_PRINT("u1_tfr_n_mb || (!uc_more_data_flag): %d", u1_tfr_n_mb || (!uc_more_data_flag));*/
if(u1_tfr_n_mb || (!uc_more_data_flag))
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
while(uc_more_data_flag);
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
| 174,045 |
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 jsTestObjPrototypeFunctionConvert1(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
a* (toa(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->convert1();
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 jsTestObjPrototypeFunctionConvert1(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
a* (toa(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->convert1();
return JSValue::encode(jsUndefined());
}
| 170,583 |
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: VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::VaapiVP9Accelerator(
VaapiVideoDecodeAccelerator* vaapi_dec,
VaapiWrapper* vaapi_wrapper)
: vaapi_wrapper_(vaapi_wrapper), vaapi_dec_(vaapi_dec) {
DCHECK(vaapi_wrapper_);
DCHECK(vaapi_dec_);
}
Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup()
This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and
posts the destruction of those objects to the appropriate thread on
Cleanup().
Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@
comment in
https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f
TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build
unstripped, let video play for a few seconds then navigate back; no
crashes. Unittests as before:
video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12
video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11
video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1
Bug: 789160
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2
Reviewed-on: https://chromium-review.googlesource.com/794091
Reviewed-by: Pawel Osciak <[email protected]>
Commit-Queue: Miguel Casas <[email protected]>
Cr-Commit-Position: refs/heads/master@{#523372}
CWE ID: CWE-362 | VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::VaapiVP9Accelerator(
VaapiVideoDecodeAccelerator* vaapi_dec,
VaapiWrapper* vaapi_wrapper)
: vaapi_wrapper_(vaapi_wrapper), vaapi_dec_(vaapi_dec) {
DCHECK(vaapi_wrapper_);
DCHECK(vaapi_dec_);
DETACH_FROM_SEQUENCE(sequence_checker_);
}
| 172,817 |
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 i8042_start(struct serio *serio)
{
struct i8042_port *port = serio->port_data;
port->exists = true;
mb();
return 0;
}
Commit Message: Input: i8042 - fix crash at boot time
The driver checks port->exists twice in i8042_interrupt(), first when
trying to assign temporary "serio" variable, and second time when deciding
whether it should call serio_interrupt(). The value of port->exists may
change between the 2 checks, and we may end up calling serio_interrupt()
with a NULL pointer:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000050
IP: [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40
PGD 0
Oops: 0002 [#1] SMP
last sysfs file:
CPU 0
Modules linked in:
Pid: 1, comm: swapper Not tainted 2.6.32-358.el6.x86_64 #1 QEMU Standard PC (i440FX + PIIX, 1996)
RIP: 0010:[<ffffffff8150feaf>] [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40
RSP: 0018:ffff880028203cc0 EFLAGS: 00010082
RAX: 0000000000010000 RBX: 0000000000000000 RCX: 0000000000000000
RDX: 0000000000000282 RSI: 0000000000000098 RDI: 0000000000000050
RBP: ffff880028203cc0 R08: ffff88013e79c000 R09: ffff880028203ee0
R10: 0000000000000298 R11: 0000000000000282 R12: 0000000000000050
R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000098
FS: 0000000000000000(0000) GS:ffff880028200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b
CR2: 0000000000000050 CR3: 0000000001a85000 CR4: 00000000001407f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
Process swapper (pid: 1, threadinfo ffff88013e79c000, task ffff88013e79b500)
Stack:
ffff880028203d00 ffffffff813de186 ffffffffffffff02 0000000000000000
<d> 0000000000000000 0000000000000000 0000000000000000 0000000000000098
<d> ffff880028203d70 ffffffff813e0162 ffff880028203d20 ffffffff8103b8ac
Call Trace:
<IRQ>
[<ffffffff813de186>] serio_interrupt+0x36/0xa0
[<ffffffff813e0162>] i8042_interrupt+0x132/0x3a0
[<ffffffff8103b8ac>] ? kvm_clock_read+0x1c/0x20
[<ffffffff8103b8b9>] ? kvm_clock_get_cycles+0x9/0x10
[<ffffffff810e1640>] handle_IRQ_event+0x60/0x170
[<ffffffff8103b154>] ? kvm_guest_apic_eoi_write+0x44/0x50
[<ffffffff810e3d8e>] handle_edge_irq+0xde/0x180
[<ffffffff8100de89>] handle_irq+0x49/0xa0
[<ffffffff81516c8c>] do_IRQ+0x6c/0xf0
[<ffffffff8100b9d3>] ret_from_intr+0x0/0x11
[<ffffffff81076f63>] ? __do_softirq+0x73/0x1e0
[<ffffffff8109b75b>] ? hrtimer_interrupt+0x14b/0x260
[<ffffffff8100c1cc>] ? call_softirq+0x1c/0x30
[<ffffffff8100de05>] ? do_softirq+0x65/0xa0
[<ffffffff81076d95>] ? irq_exit+0x85/0x90
[<ffffffff81516d80>] ? smp_apic_timer_interrupt+0x70/0x9b
[<ffffffff8100bb93>] ? apic_timer_interrupt+0x13/0x20
To avoid the issue let's change the second check to test whether serio is
NULL or not.
Also, let's take i8042_lock in i8042_start() and i8042_stop() instead of
trying to be overly smart and using memory barriers.
Signed-off-by: Chen Hong <[email protected]>
[dtor: take lock in i8042_start()/i8042_stop()]
Cc: [email protected]
Signed-off-by: Dmitry Torokhov <[email protected]>
CWE ID: CWE-476 | static int i8042_start(struct serio *serio)
{
struct i8042_port *port = serio->port_data;
spin_lock_irq(&i8042_lock);
port->exists = true;
spin_unlock_irq(&i8042_lock);
return 0;
}
| 169,422 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.