instruction
stringclasses
1 value
input
stringlengths
90
9.3k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: METHODDEF(JDIMENSION) get_word_gray_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-word-format PGM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr)sinfo; register JSAMPROW ptr; register U_CHAR *bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; unsigned int maxval = source->maxval; if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { register unsigned int temp; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_TOOLARGE); *ptr++ = rescale[temp]; } return 1; } Commit Message: cjpeg: Fix OOB read caused by malformed 8-bit BMP ... in which one or more of the color indices is out of range for the number of palette entries. Fix partly borrowed from jpeg-9c. This commit also adopts Guido's JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific JERR_PPM_TOOLARGE enum value. Fixes #258 CWE ID: CWE-125
METHODDEF(JDIMENSION) get_word_gray_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-word-format PGM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr)sinfo; register JSAMPROW ptr; register U_CHAR *bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; unsigned int maxval = source->maxval; if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { register unsigned int temp; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_OUTOFRANGE); *ptr++ = rescale[temp]; } return 1; }
169,838
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: poppler_page_prepare_output_dev (PopplerPage *page, double scale, int rotation, gboolean transparent, OutputDevData *output_dev_data) { CairoOutputDev *output_dev; cairo_surface_t *surface; double width, height; int cairo_width, cairo_height, cairo_rowstride, rotate; unsigned char *cairo_data; rotate = rotation + page->page->getRotate (); if (rotate == 90 || rotate == 270) { height = page->page->getCropWidth (); width = page->page->getCropHeight (); } else { width = page->page->getCropWidth (); height = page->page->getCropHeight (); } cairo_width = (int) ceil(width * scale); cairo_height = (int) ceil(height * scale); output_dev = page->document->output_dev; cairo_rowstride = cairo_width * 4; cairo_data = (guchar *) gmalloc (cairo_height * cairo_rowstride); if (transparent) memset (cairo_data, 0x00, cairo_height * cairo_rowstride); else memset (cairo_data, 0xff, cairo_height * cairo_rowstride); surface = cairo_image_surface_create_for_data(cairo_data, CAIRO_FORMAT_ARGB32, cairo_width, cairo_height, cairo_rowstride); output_dev_data->cairo_data = cairo_data; output_dev_data->surface = surface; output_dev_data->cairo = cairo_create (surface); output_dev->setCairo (output_dev_data->cairo); } Commit Message: CWE ID: CWE-189
poppler_page_prepare_output_dev (PopplerPage *page, double scale, int rotation, gboolean transparent, OutputDevData *output_dev_data) { CairoOutputDev *output_dev; cairo_surface_t *surface; double width, height; int cairo_width, cairo_height, cairo_rowstride, rotate; unsigned char *cairo_data; rotate = rotation + page->page->getRotate (); if (rotate == 90 || rotate == 270) { height = page->page->getCropWidth (); width = page->page->getCropHeight (); } else { width = page->page->getCropWidth (); height = page->page->getCropHeight (); } cairo_width = (int) ceil(width * scale); cairo_height = (int) ceil(height * scale); output_dev = page->document->output_dev; cairo_rowstride = cairo_width * 4; cairo_data = (guchar *) gmallocn (cairo_height, cairo_rowstride); if (transparent) memset (cairo_data, 0x00, cairo_height * cairo_rowstride); else memset (cairo_data, 0xff, cairo_height * cairo_rowstride); surface = cairo_image_surface_create_for_data(cairo_data, CAIRO_FORMAT_ARGB32, cairo_width, cairo_height, cairo_rowstride); output_dev_data->cairo_data = cairo_data; output_dev_data->surface = surface; output_dev_data->cairo = cairo_create (surface); output_dev->setCairo (output_dev_data->cairo); }
164,617
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int btif_hl_select_wakeup(void){ char sig_on = btif_hl_signal_select_wakeup; BTIF_TRACE_DEBUG("btif_hl_select_wakeup"); return send(signal_fds[1], &sig_on, sizeof(sig_on), 0); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static inline int btif_hl_select_wakeup(void){ char sig_on = btif_hl_signal_select_wakeup; BTIF_TRACE_DEBUG("btif_hl_select_wakeup"); return TEMP_FAILURE_RETRY(send(signal_fds[1], &sig_on, sizeof(sig_on), 0)); }
173,444
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long BlockGroup::GetPrevTimeCode() const { return m_prev; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long BlockGroup::GetPrevTimeCode() const
174,351
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int asymmetric_key_match_preparse(struct key_match_data *match_data) { match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE; return 0; } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <dhowells@redhat.com> Acked-by: Vivek Goyal <vgoyal@redhat.com> CWE ID: CWE-476
static int asymmetric_key_match_preparse(struct key_match_data *match_data) { match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE; match_data->cmp = asymmetric_key_cmp; return 0; }
168,437
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ExtensionTtsController::IsSpeaking() const { return current_utterance_ != NULL; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool ExtensionTtsController::IsSpeaking() const {
170,382
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftAVC::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } if (mEOSStatus == OUTPUT_FRAMES_FLUSHED) { return; } List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); if (mHeadersDecoded) { drainAllOutputBuffers(false /* eos */); } H264SwDecRet ret = H264SWDEC_PIC_RDY; bool portWillReset = false; while ((mEOSStatus != INPUT_DATA_AVAILABLE || !inQueue.empty()) && outQueue.size() == kNumOutputBuffers) { if (mEOSStatus == INPUT_EOS_SEEN) { drainAllOutputBuffers(true /* eos */); return; } BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; ++mPicId; OMX_BUFFERHEADERTYPE *header = new OMX_BUFFERHEADERTYPE; memset(header, 0, sizeof(OMX_BUFFERHEADERTYPE)); header->nTimeStamp = inHeader->nTimeStamp; header->nFlags = inHeader->nFlags; if (header->nFlags & OMX_BUFFERFLAG_EOS) { mEOSStatus = INPUT_EOS_SEEN; } mPicToHeaderMap.add(mPicId, header); inQueue.erase(inQueue.begin()); H264SwDecInput inPicture; H264SwDecOutput outPicture; memset(&inPicture, 0, sizeof(inPicture)); inPicture.dataLen = inHeader->nFilledLen; inPicture.pStream = inHeader->pBuffer + inHeader->nOffset; inPicture.picId = mPicId; inPicture.intraConcealmentMethod = 1; H264SwDecPicture decodedPicture; while (inPicture.dataLen > 0) { ret = H264SwDecDecode(mHandle, &inPicture, &outPicture); if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY || ret == H264SWDEC_PIC_RDY_BUFF_NOT_EMPTY) { inPicture.dataLen -= (u32)(outPicture.pStrmCurrPos - inPicture.pStream); inPicture.pStream = outPicture.pStrmCurrPos; if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY) { mHeadersDecoded = true; H264SwDecInfo decoderInfo; CHECK(H264SwDecGetInfo(mHandle, &decoderInfo) == H264SWDEC_OK); SoftVideoDecoderOMXComponent::CropSettingsMode cropSettingsMode = handleCropParams(decoderInfo); handlePortSettingsChange( &portWillReset, decoderInfo.picWidth, decoderInfo.picHeight, cropSettingsMode); } } else { if (portWillReset) { if (H264SwDecNextPicture(mHandle, &decodedPicture, 0) == H264SWDEC_PIC_RDY) { saveFirstOutputBuffer( decodedPicture.picId, (uint8_t *)decodedPicture.pOutputPicture); } } inPicture.dataLen = 0; if (ret < 0) { ALOGE("Decoder failed: %d", ret); notify(OMX_EventError, OMX_ErrorUndefined, ERROR_MALFORMED, NULL); mSignalledError = true; return; } } } inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); if (portWillReset) { return; } if (mFirstPicture && !outQueue.empty()) { drainOneOutputBuffer(mFirstPictureId, mFirstPicture); delete[] mFirstPicture; mFirstPicture = NULL; mFirstPictureId = -1; } drainAllOutputBuffers(false /* eos */); } } Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec Bug: 27833616 Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0 CWE ID: CWE-20
void SoftAVC::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } if (mEOSStatus == OUTPUT_FRAMES_FLUSHED) { return; } List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); if (mHeadersDecoded) { drainAllOutputBuffers(false /* eos */); } H264SwDecRet ret = H264SWDEC_PIC_RDY; bool portWillReset = false; while ((mEOSStatus != INPUT_DATA_AVAILABLE || !inQueue.empty()) && outQueue.size() == kNumOutputBuffers) { if (mEOSStatus == INPUT_EOS_SEEN) { drainAllOutputBuffers(true /* eos */); return; } BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; ++mPicId; OMX_BUFFERHEADERTYPE *header = new OMX_BUFFERHEADERTYPE; memset(header, 0, sizeof(OMX_BUFFERHEADERTYPE)); header->nTimeStamp = inHeader->nTimeStamp; header->nFlags = inHeader->nFlags; if (header->nFlags & OMX_BUFFERFLAG_EOS) { mEOSStatus = INPUT_EOS_SEEN; } mPicToHeaderMap.add(mPicId, header); inQueue.erase(inQueue.begin()); H264SwDecInput inPicture; H264SwDecOutput outPicture; memset(&inPicture, 0, sizeof(inPicture)); inPicture.dataLen = inHeader->nFilledLen; inPicture.pStream = inHeader->pBuffer + inHeader->nOffset; inPicture.picId = mPicId; inPicture.intraConcealmentMethod = 1; H264SwDecPicture decodedPicture; while (inPicture.dataLen > 0) { ret = H264SwDecDecode(mHandle, &inPicture, &outPicture); if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY || ret == H264SWDEC_PIC_RDY_BUFF_NOT_EMPTY) { inPicture.dataLen -= (u32)(outPicture.pStrmCurrPos - inPicture.pStream); inPicture.pStream = outPicture.pStrmCurrPos; if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY) { mHeadersDecoded = true; H264SwDecInfo decoderInfo; CHECK(H264SwDecGetInfo(mHandle, &decoderInfo) == H264SWDEC_OK); SoftVideoDecoderOMXComponent::CropSettingsMode cropSettingsMode = handleCropParams(decoderInfo); handlePortSettingsChange( &portWillReset, decoderInfo.picWidth, decoderInfo.picHeight, cropSettingsMode); } } else { if (portWillReset) { if (H264SwDecNextPicture(mHandle, &decodedPicture, 0) == H264SWDEC_PIC_RDY) { saveFirstOutputBuffer( decodedPicture.picId, (uint8_t *)decodedPicture.pOutputPicture); } } inPicture.dataLen = 0; if (ret < 0) { ALOGE("Decoder failed: %d", ret); notify(OMX_EventError, OMX_ErrorUndefined, ERROR_MALFORMED, NULL); mSignalledError = true; return; } } } inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); if (portWillReset) { return; } if (mFirstPicture && !outQueue.empty()) { if (!drainOneOutputBuffer(mFirstPictureId, mFirstPicture)) { ALOGE("Drain failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } delete[] mFirstPicture; mFirstPicture = NULL; mFirstPictureId = -1; } drainAllOutputBuffers(false /* eos */); } }
174,178
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int sdp_parse_fmtp_config_h264(AVFormatContext *s, AVStream *stream, PayloadContext *h264_data, const char *attr, const char *value) { AVCodecParameters *par = stream->codecpar; if (!strcmp(attr, "packetization-mode")) { av_log(s, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value)); h264_data->packetization_mode = atoi(value); /* * Packetization Mode: * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed) * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed. * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A), * and 29 (FU-B) are allowed. */ if (h264_data->packetization_mode > 1) av_log(s, AV_LOG_ERROR, "Interleaved RTP mode is not supported yet.\n"); } else if (!strcmp(attr, "profile-level-id")) { if (strlen(value) == 6) parse_profile_level_id(s, h264_data, value); } else if (!strcmp(attr, "sprop-parameter-sets")) { int ret; if (value[strlen(value) - 1] == ',') { av_log(s, AV_LOG_WARNING, "Missing PPS in sprop-parameter-sets, ignoring\n"); return 0; } par->extradata_size = 0; av_freep(&par->extradata); ret = ff_h264_parse_sprop_parameter_sets(s, &par->extradata, &par->extradata_size, value); av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)\n", par->extradata, par->extradata_size); return ret; } return 0; } Commit Message: avformat/rtpdec_h264: Fix heap-buffer-overflow Fixes: rtp_sdp/poc.sdp Found-by: Bingchang <l.bing.chang.bc@gmail.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-119
static int sdp_parse_fmtp_config_h264(AVFormatContext *s, AVStream *stream, PayloadContext *h264_data, const char *attr, const char *value) { AVCodecParameters *par = stream->codecpar; if (!strcmp(attr, "packetization-mode")) { av_log(s, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value)); h264_data->packetization_mode = atoi(value); /* * Packetization Mode: * 0 or not present: Single NAL mode (Only nals from 1-23 are allowed) * 1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed. * 2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A), * and 29 (FU-B) are allowed. */ if (h264_data->packetization_mode > 1) av_log(s, AV_LOG_ERROR, "Interleaved RTP mode is not supported yet.\n"); } else if (!strcmp(attr, "profile-level-id")) { if (strlen(value) == 6) parse_profile_level_id(s, h264_data, value); } else if (!strcmp(attr, "sprop-parameter-sets")) { int ret; if (*value == 0 || value[strlen(value) - 1] == ',') { av_log(s, AV_LOG_WARNING, "Missing PPS in sprop-parameter-sets, ignoring\n"); return 0; } par->extradata_size = 0; av_freep(&par->extradata); ret = ff_h264_parse_sprop_parameter_sets(s, &par->extradata, &par->extradata_size, value); av_log(s, AV_LOG_DEBUG, "Extradata set to %p (size: %d)\n", par->extradata, par->extradata_size); return ret; } return 0; }
167,744
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AudioSource::AudioSource( audio_source_t inputSource, const String16 &opPackageName, uint32_t sampleRate, uint32_t channelCount, uint32_t outSampleRate) : mStarted(false), mSampleRate(sampleRate), mOutSampleRate(outSampleRate > 0 ? outSampleRate : sampleRate), mPrevSampleTimeUs(0), mFirstSampleTimeUs(-1ll), mNumFramesReceived(0), mNumClientOwnedBuffers(0) { ALOGV("sampleRate: %u, outSampleRate: %u, channelCount: %u", sampleRate, outSampleRate, channelCount); CHECK(channelCount == 1 || channelCount == 2); CHECK(sampleRate > 0); size_t minFrameCount; status_t status = AudioRecord::getMinFrameCount(&minFrameCount, sampleRate, AUDIO_FORMAT_PCM_16_BIT, audio_channel_in_mask_from_count(channelCount)); if (status == OK) { uint32_t frameCount = kMaxBufferSize / sizeof(int16_t) / channelCount; size_t bufCount = 2; while ((bufCount * frameCount) < minFrameCount) { bufCount++; } mRecord = new AudioRecord( inputSource, sampleRate, AUDIO_FORMAT_PCM_16_BIT, audio_channel_in_mask_from_count(channelCount), opPackageName, (size_t) (bufCount * frameCount), AudioRecordCallbackFunction, this, frameCount /*notificationFrames*/); mInitCheck = mRecord->initCheck(); if (mInitCheck != OK) { mRecord.clear(); } } else { mInitCheck = status; } } Commit Message: AudioSource: initialize variables to prevent info leak Bug: 27855172 Change-Id: I3d33e0a9cc5cf8a758d7b0794590b09c43a24561 CWE ID: CWE-200
AudioSource::AudioSource( audio_source_t inputSource, const String16 &opPackageName, uint32_t sampleRate, uint32_t channelCount, uint32_t outSampleRate) : mStarted(false), mSampleRate(sampleRate), mOutSampleRate(outSampleRate > 0 ? outSampleRate : sampleRate), mTrackMaxAmplitude(false), mStartTimeUs(0), mMaxAmplitude(0), mPrevSampleTimeUs(0), mFirstSampleTimeUs(-1ll), mInitialReadTimeUs(0), mNumFramesReceived(0), mNumClientOwnedBuffers(0) { ALOGV("sampleRate: %u, outSampleRate: %u, channelCount: %u", sampleRate, outSampleRate, channelCount); CHECK(channelCount == 1 || channelCount == 2); CHECK(sampleRate > 0); size_t minFrameCount; status_t status = AudioRecord::getMinFrameCount(&minFrameCount, sampleRate, AUDIO_FORMAT_PCM_16_BIT, audio_channel_in_mask_from_count(channelCount)); if (status == OK) { uint32_t frameCount = kMaxBufferSize / sizeof(int16_t) / channelCount; size_t bufCount = 2; while ((bufCount * frameCount) < minFrameCount) { bufCount++; } mRecord = new AudioRecord( inputSource, sampleRate, AUDIO_FORMAT_PCM_16_BIT, audio_channel_in_mask_from_count(channelCount), opPackageName, (size_t) (bufCount * frameCount), AudioRecordCallbackFunction, this, frameCount /*notificationFrames*/); mInitCheck = mRecord->initCheck(); if (mInitCheck != OK) { mRecord.clear(); } } else { mInitCheck = status; } }
173,770
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Chapters::Atom::Init() { m_string_uid = NULL; m_uid = 0; m_start_timecode = -1; m_stop_timecode = -1; m_displays = NULL; m_displays_size = 0; m_displays_count = 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Chapters::Atom::Init()
174,387
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FrameLoader::ReplaceDocumentWhileExecutingJavaScriptURL( const String& source, Document* owner_document) { Document* document = frame_->GetDocument(); if (!document_loader_ || document->PageDismissalEventBeingDispatched() != Document::kNoDismissal) return; UseCounter::Count(*document, WebFeature::kReplaceDocumentViaJavaScriptURL); const KURL& url = document->Url(); WebGlobalObjectReusePolicy global_object_reuse_policy = frame_->ShouldReuseDefaultView(url) ? WebGlobalObjectReusePolicy::kUseExisting : WebGlobalObjectReusePolicy::kCreateNew; StopAllLoaders(); SubframeLoadingDisabler disabler(document); frame_->DetachChildren(); if (!frame_->IsAttached() || document != frame_->GetDocument()) return; frame_->GetDocument()->Shutdown(); Client()->TransitionToCommittedForNewPage(); document_loader_->ReplaceDocumentWhileExecutingJavaScriptURL( url, owner_document, global_object_reuse_policy, source); } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <andypaicu@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285
void FrameLoader::ReplaceDocumentWhileExecutingJavaScriptURL( const String& source, Document* owner_document) { Document* document = frame_->GetDocument(); if (!document_loader_ || document->PageDismissalEventBeingDispatched() != Document::kNoDismissal) return; UseCounter::Count(*document, WebFeature::kReplaceDocumentViaJavaScriptURL); const KURL& url = document->Url(); // The document CSP is the correct one as it is used for CSP checks // done previously before getting here: // HTMLFormElement::ScheduleFormSubmission // HTMLFrameElementBase::OpenURL WebGlobalObjectReusePolicy global_object_reuse_policy = frame_->ShouldReuseDefaultView(url, document->GetContentSecurityPolicy()) ? WebGlobalObjectReusePolicy::kUseExisting : WebGlobalObjectReusePolicy::kCreateNew; StopAllLoaders(); SubframeLoadingDisabler disabler(document); frame_->DetachChildren(); if (!frame_->IsAttached() || document != frame_->GetDocument()) return; frame_->GetDocument()->Shutdown(); Client()->TransitionToCommittedForNewPage(); document_loader_->ReplaceDocumentWhileExecutingJavaScriptURL( url, owner_document, global_object_reuse_policy, source); }
173,198
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintViewManager::OnShowScriptedPrintPreview(content::RenderFrameHost* rfh, bool source_is_modifiable) { DCHECK(print_preview_rfh_); if (rfh != print_preview_rfh_) return; PrintPreviewDialogController* dialog_controller = PrintPreviewDialogController::GetInstance(); if (!dialog_controller) { PrintPreviewDone(); return; } dialog_controller->PrintPreview(web_contents()); PrintHostMsg_RequestPrintPreview_Params params; params.is_modifiable = source_is_modifiable; PrintPreviewUI::SetInitialParams( dialog_controller->GetPrintPreviewForContents(web_contents()), params); } Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen. BUG=670135, 550017, 726761, 728276 Review-Url: https://codereview.chromium.org/2906133004 Cr-Commit-Position: refs/heads/master@{#478884} CWE ID: CWE-20
void PrintViewManager::OnShowScriptedPrintPreview(content::RenderFrameHost* rfh, bool source_is_modifiable) { DCHECK(print_preview_rfh_); if (rfh != print_preview_rfh_) return; PrintPreviewDialogController* dialog_controller = PrintPreviewDialogController::GetInstance(); if (!dialog_controller) { PrintPreviewDone(); return; } // Running a dialog causes an exit to webpage-initiated fullscreen. // http://crbug.com/728276 if (web_contents()->IsFullscreenForCurrentTab()) web_contents()->ExitFullscreen(true); dialog_controller->PrintPreview(web_contents()); PrintHostMsg_RequestPrintPreview_Params params; params.is_modifiable = source_is_modifiable; PrintPreviewUI::SetInitialParams( dialog_controller->GetPrintPreviewForContents(web_contents()), params); }
172,314
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UpdatePolicyForEvent(const WebInputEvent* input_event, NavigationPolicy* policy) { if (!input_event) return; unsigned short button_number = 0; if (input_event->GetType() == WebInputEvent::kMouseUp) { const WebMouseEvent* mouse_event = static_cast<const WebMouseEvent*>(input_event); switch (mouse_event->button) { case WebMouseEvent::Button::kLeft: button_number = 0; break; case WebMouseEvent::Button::kMiddle: button_number = 1; break; case WebMouseEvent::Button::kRight: button_number = 2; break; default: return; } } else if ((WebInputEvent::IsKeyboardEventType(input_event->GetType()) && static_cast<const WebKeyboardEvent*>(input_event) ->windows_key_code == VKEY_RETURN) || WebInputEvent::IsGestureEventType(input_event->GetType())) { button_number = 0; } else { return; } bool ctrl = input_event->GetModifiers() & WebInputEvent::kControlKey; bool shift = input_event->GetModifiers() & WebInputEvent::kShiftKey; bool alt = input_event->GetModifiers() & WebInputEvent::kAltKey; bool meta = input_event->GetModifiers() & WebInputEvent::kMetaKey; NavigationPolicy user_policy = *policy; NavigationPolicyFromMouseEvent(button_number, ctrl, shift, alt, meta, &user_policy); if (user_policy == kNavigationPolicyDownload && *policy != kNavigationPolicyIgnore) return; if (user_policy == kNavigationPolicyNewWindow && *policy == kNavigationPolicyNewPopup) return; *policy = user_policy; } Commit Message: Only allow downloading in response to real keyboard modifiers BUG=848531 Change-Id: I97554c8d312243b55647f1376945aee32dbd95bf Reviewed-on: https://chromium-review.googlesource.com/1082216 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Jochen Eisinger <jochen@chromium.org> Cr-Commit-Position: refs/heads/master@{#564051} CWE ID:
void UpdatePolicyForEvent(const WebInputEvent* input_event, NavigationPolicy* policy) { if (!input_event) return; unsigned short button_number = 0; if (input_event->GetType() == WebInputEvent::kMouseUp) { const WebMouseEvent* mouse_event = static_cast<const WebMouseEvent*>(input_event); switch (mouse_event->button) { case WebMouseEvent::Button::kLeft: button_number = 0; break; case WebMouseEvent::Button::kMiddle: button_number = 1; break; case WebMouseEvent::Button::kRight: button_number = 2; break; default: return; } } else if ((WebInputEvent::IsKeyboardEventType(input_event->GetType()) && static_cast<const WebKeyboardEvent*>(input_event) ->windows_key_code == VKEY_RETURN) || WebInputEvent::IsGestureEventType(input_event->GetType())) { button_number = 0; } else { return; } bool ctrl = input_event->GetModifiers() & WebInputEvent::kControlKey; bool shift = input_event->GetModifiers() & WebInputEvent::kShiftKey; bool alt = input_event->GetModifiers() & WebInputEvent::kAltKey; bool meta = input_event->GetModifiers() & WebInputEvent::kMetaKey; NavigationPolicy user_policy = *policy; NavigationPolicyFromMouseEvent(button_number, ctrl, shift, alt, meta, &user_policy); if (user_policy == kNavigationPolicyNewWindow && *policy == kNavigationPolicyNewPopup) return; *policy = user_policy; }
173,194
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SSLManager::OnSSLCertificateError( base::WeakPtr<SSLErrorHandler::Delegate> delegate, const content::GlobalRequestID& id, const ResourceType::Type resource_type, const GURL& url, int render_process_id, int render_view_id, const net::SSLInfo& ssl_info, bool fatal) { DCHECK(delegate); DVLOG(1) << "OnSSLCertificateError() cert_error: " << net::MapCertStatusToNetError(ssl_info.cert_status) << " id: " << id.child_id << "," << id.request_id << " resource_type: " << resource_type << " url: " << url.spec() << " render_process_id: " << render_process_id << " render_view_id: " << render_view_id << " cert_status: " << std::hex << ssl_info.cert_status; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&SSLCertErrorHandler::Dispatch, new SSLCertErrorHandler(delegate, id, resource_type, url, render_process_id, render_view_id, ssl_info, fatal))); } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void SSLManager::OnSSLCertificateError( const base::WeakPtr<SSLErrorHandler::Delegate>& delegate, const content::GlobalRequestID& id, const ResourceType::Type resource_type, const GURL& url, int render_process_id, int render_view_id, const net::SSLInfo& ssl_info, bool fatal) { DCHECK(delegate); DVLOG(1) << "OnSSLCertificateError() cert_error: " << net::MapCertStatusToNetError(ssl_info.cert_status) << " id: " << id.child_id << "," << id.request_id << " resource_type: " << resource_type << " url: " << url.spec() << " render_process_id: " << render_process_id << " render_view_id: " << render_view_id << " cert_status: " << std::hex << ssl_info.cert_status; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&SSLCertErrorHandler::Dispatch, new SSLCertErrorHandler(delegate, id, resource_type, url, render_process_id, render_view_id, ssl_info, fatal))); }
170,996
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void detect_allow_debuggers(int argc, char **argv) { int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--allow-debuggers") == 0) { arg_allow_debuggers = 1; break; } if (strcmp(argv[i], "--") == 0) break; if (strncmp(argv[i], "--", 2) != 0) break; } } Commit Message: security fix CWE ID:
static void detect_allow_debuggers(int argc, char **argv) { int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--allow-debuggers") == 0) { // check kernel version struct utsname u; int rv = uname(&u); if (rv != 0) errExit("uname"); int major; int minor; if (2 != sscanf(u.release, "%d.%d", &major, &minor)) { fprintf(stderr, "Error: cannot extract Linux kernel version: %s\n", u.version); exit(1); } if (major < 4 || (major == 4 && minor < 8)) { fprintf(stderr, "Error: --allow-debuggers is disabled on Linux kernels prior to 4.8. " "A bug in ptrace call allows a full bypass of the seccomp filter. " "Your current kernel version is %d.%d.\n", major, minor); exit(1); } arg_allow_debuggers = 1; break; } if (strcmp(argv[i], "--") == 0) break; if (strncmp(argv[i], "--", 2) != 0) break; } }
168,419
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_cmap_t *cmap = &box->data.cmap; jp2_cmapent_t *ent; unsigned int i; cmap->numchans = (box->datalen) / 4; if (!(cmap->ents = jas_alloc2(cmap->numchans, sizeof(jp2_cmapent_t)))) { return -1; } for (i = 0; i < cmap->numchans; ++i) { ent = &cmap->ents[i]; if (jp2_getuint16(in, &ent->cmptno) || jp2_getuint8(in, &ent->map) || jp2_getuint8(in, &ent->pcol)) { return -1; } } return 0; } Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems. CWE ID: CWE-476
static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_cmap_t *cmap = &box->data.cmap; jp2_cmapent_t *ent; unsigned int i; cmap->ents = 0; cmap->numchans = (box->datalen) / 4; if (!(cmap->ents = jas_alloc2(cmap->numchans, sizeof(jp2_cmapent_t)))) { return -1; } for (i = 0; i < cmap->numchans; ++i) { ent = &cmap->ents[i]; if (jp2_getuint16(in, &ent->cmptno) || jp2_getuint8(in, &ent->map) || jp2_getuint8(in, &ent->pcol)) { return -1; } } return 0; }
168,322
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Chapters::ExpandEditionsArray() { if (m_editions_size > m_editions_count) return true; // nothing else to do const int size = (m_editions_size == 0) ? 1 : 2 * m_editions_size; Edition* const editions = new (std::nothrow) Edition[size]; if (editions == NULL) return false; for (int idx = 0; idx < m_editions_count; ++idx) { m_editions[idx].ShallowCopy(editions[idx]); } delete[] m_editions; m_editions = editions; m_editions_size = size; return true; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
bool Chapters::ExpandEditionsArray() Edition& e = m_editions[m_editions_count++]; e.Init(); return e.Parse(m_pSegment->m_pReader, pos, size); } Chapters::Edition::Edition() {} Chapters::Edition::~Edition() {} int Chapters::Edition::GetAtomCount() const { return m_atoms_count; } const Chapters::Atom* Chapters::Edition::GetAtom(int index) const { if (index < 0) return NULL; if (index >= m_atoms_count) return NULL; return m_atoms + index; } void Chapters::Edition::Init() { m_atoms = NULL; m_atoms_size = 0; m_atoms_count = 0; } void Chapters::Edition::ShallowCopy(Edition& rhs) const { rhs.m_atoms = m_atoms; rhs.m_atoms_size = m_atoms_size; rhs.m_atoms_count = m_atoms_count; } void Chapters::Edition::Clear() { while (m_atoms_count > 0) { Atom& a = m_atoms[--m_atoms_count]; a.Clear(); } delete[] m_atoms; m_atoms = NULL; m_atoms_size = 0; } long Chapters::Edition::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) { // Atom ID status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; }
174,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Track::Info::CopyStr(char* Info::*str, Info& dst_) const { if (str == static_cast<char * Info::*>(NULL)) return -1; char*& dst = dst_.*str; if (dst) // should be NULL already return -1; const char* const src = this->*str; if (src == NULL) return 0; const size_t len = strlen(src); dst = new (std::nothrow) char[len + 1]; if (dst == NULL) return -1; strcpy(dst, src); return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
int Track::Info::CopyStr(char* Info::*str, Info& dst_) const { if (str == static_cast<char * Info::*>(NULL)) return -1; char*& dst = dst_.*str; if (dst) // should be NULL already return -1; const char* const src = this->*str; if (src == NULL) return 0; const size_t len = strlen(src); dst = SafeArrayAlloc<char>(1, len + 1); if (dst == NULL) return -1; strcpy(dst, src); return 0; }
173,803
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_ext_data(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_start_code; IMPEG2D_ERROR_CODES_T e_error; e_error = (IMPEG2D_ERROR_CODES_T) IVD_ERROR_NONE; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while( (u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE) && (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE == e_error) { if(u4_start_code == USER_DATA_START_CODE) { impeg2d_dec_user_data(ps_dec); } else { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN); switch(u4_start_code) { case SEQ_DISPLAY_EXT_ID: impeg2d_dec_seq_disp_ext(ps_dec); break; case SEQ_SCALABLE_EXT_ID: e_error = IMPEG2D_SCALABILITIY_NOT_SUPPORTED; break; default: /* In case its a reserved extension code */ impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN); impeg2d_peek_next_start_code(ps_dec); break; } } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } return e_error; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254
IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_ext_data(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_start_code; IMPEG2D_ERROR_CODES_T e_error; e_error = (IMPEG2D_ERROR_CODES_T) IVD_ERROR_NONE; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while( (u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE) && (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE == e_error && (ps_stream->u4_offset < ps_stream->u4_max_offset)) { if(u4_start_code == USER_DATA_START_CODE) { impeg2d_dec_user_data(ps_dec); } else { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN); switch(u4_start_code) { case SEQ_DISPLAY_EXT_ID: impeg2d_dec_seq_disp_ext(ps_dec); break; case SEQ_SCALABLE_EXT_ID: e_error = IMPEG2D_SCALABILITIY_NOT_SUPPORTED; break; default: /* In case its a reserved extension code */ impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN); impeg2d_peek_next_start_code(ps_dec); break; } } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } return e_error; }
173,946
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Chapters::Atom::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x00) { // Display ID status = ParseDisplay(pReader, pos, size); if (status < 0) // error return status; } else if (id == 0x1654) { // StringUID ID status = UnserializeString(pReader, pos, size, m_string_uid); if (status < 0) // error return status; } else if (id == 0x33C4) { // UID ID long long val; status = UnserializeInt(pReader, pos, size, val); if (status < 0) // error return status; m_uid = static_cast<unsigned long long>(val); } else if (id == 0x11) { // TimeStart ID const long long val = UnserializeUInt(pReader, pos, size); if (val < 0) // error return static_cast<long>(val); m_start_timecode = val; } else if (id == 0x12) { // TimeEnd ID const long long val = UnserializeUInt(pReader, pos, size); if (val < 0) // error return static_cast<long>(val); m_stop_timecode = val; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Chapters::Atom::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x00) { // Display ID status = ParseDisplay(pReader, pos, size); if (status < 0) // error return status; } else if (id == 0x1654) { // StringUID ID status = UnserializeString(pReader, pos, size, m_string_uid); if (status < 0) // error return status; } else if (id == 0x33C4) { // UID ID long long val; status = UnserializeInt(pReader, pos, size, val); if (status < 0) // error return status; m_uid = static_cast<unsigned long long>(val); } else if (id == 0x11) { // TimeStart ID const long long val = UnserializeUInt(pReader, pos, size); if (val < 0) // error return static_cast<long>(val); m_start_timecode = val; } else if (id == 0x12) { // TimeEnd ID const long long val = UnserializeUInt(pReader, pos, size); if (val < 0) // error return static_cast<long>(val); m_stop_timecode = val; } pos += size; if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; return 0; }
173,840
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: psh_glyph_find_strong_points( PSH_Glyph glyph, FT_Int dimension ) { /* a point is `strong' if it is located on a stem edge and */ /* has an `in' or `out' tangent parallel to the hint's direction */ PSH_Hint_Table table = &glyph->hint_tables[dimension]; PS_Mask mask = table->hint_masks->masks; FT_UInt num_masks = table->hint_masks->num_masks; FT_UInt first = 0; FT_Int major_dir = dimension == 0 ? PSH_DIR_VERTICAL : PSH_DIR_HORIZONTAL; PSH_Dimension dim = &glyph->globals->dimension[dimension]; FT_Fixed scale = dim->scale_mult; FT_Int threshold; threshold = (FT_Int)FT_DivFix( PSH_STRONG_THRESHOLD, scale ); if ( threshold > PSH_STRONG_THRESHOLD_MAXIMUM ) threshold = PSH_STRONG_THRESHOLD_MAXIMUM; /* process secondary hints to `selected' points */ /* process secondary hints to `selected' points */ if ( num_masks > 1 && glyph->num_points > 0 ) { first = mask->end_point; mask++; for ( ; num_masks > 1; num_masks--, mask++ ) { next = mask->end_point; FT_Int count; next = mask->end_point; count = next - first; if ( count > 0 ) { threshold, major_dir ); } first = next; } } /* process primary hints for all points */ if ( num_masks == 1 ) { FT_UInt count = glyph->num_points; PSH_Point point = glyph->points; psh_hint_table_activate_mask( table, table->hint_masks->masks ); psh_hint_table_find_strong_points( table, point, count, threshold, major_dir ); } /* now, certain points may have been attached to a hint and */ /* not marked as strong; update their flags then */ { FT_UInt count = glyph->num_points; PSH_Point point = glyph->points; for ( ; count > 0; count--, point++ ) if ( point->hint && !psh_point_is_strong( point ) ) psh_point_set_strong( point ); } } Commit Message: CWE ID: CWE-399
psh_glyph_find_strong_points( PSH_Glyph glyph, FT_Int dimension ) { /* a point is `strong' if it is located on a stem edge and */ /* has an `in' or `out' tangent parallel to the hint's direction */ PSH_Hint_Table table = &glyph->hint_tables[dimension]; PS_Mask mask = table->hint_masks->masks; FT_UInt num_masks = table->hint_masks->num_masks; FT_UInt first = 0; FT_Int major_dir = dimension == 0 ? PSH_DIR_VERTICAL : PSH_DIR_HORIZONTAL; PSH_Dimension dim = &glyph->globals->dimension[dimension]; FT_Fixed scale = dim->scale_mult; FT_Int threshold; threshold = (FT_Int)FT_DivFix( PSH_STRONG_THRESHOLD, scale ); if ( threshold > PSH_STRONG_THRESHOLD_MAXIMUM ) threshold = PSH_STRONG_THRESHOLD_MAXIMUM; /* process secondary hints to `selected' points */ /* process secondary hints to `selected' points */ if ( num_masks > 1 && glyph->num_points > 0 ) { /* the `endchar' op can reduce the number of points */ first = mask->end_point > glyph->num_points ? glyph->num_points : mask->end_point; mask++; for ( ; num_masks > 1; num_masks--, mask++ ) { next = mask->end_point; FT_Int count; next = mask->end_point > glyph->num_points ? glyph->num_points : mask->end_point; count = next - first; if ( count > 0 ) { threshold, major_dir ); } first = next; } } /* process primary hints for all points */ if ( num_masks == 1 ) { FT_UInt count = glyph->num_points; PSH_Point point = glyph->points; psh_hint_table_activate_mask( table, table->hint_masks->masks ); psh_hint_table_find_strong_points( table, point, count, threshold, major_dir ); } /* now, certain points may have been attached to a hint and */ /* not marked as strong; update their flags then */ { FT_UInt count = glyph->num_points; PSH_Point point = glyph->points; for ( ; count > 0; count--, point++ ) if ( point->hint && !psh_point_is_strong( point ) ) psh_point_set_strong( point ); } }
165,007
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void nsc_rle_decompress_data(NSC_CONTEXT* context) { UINT16 i; BYTE* rle; UINT32 planeSize; UINT32 originalSize; rle = context->Planes; for (i = 0; i < 4; i++) { originalSize = context->OrgByteCount[i]; planeSize = context->PlaneByteCount[i]; if (planeSize == 0) FillMemory(context->priv->PlaneBuffers[i], originalSize, 0xFF); else if (planeSize < originalSize) nsc_rle_decode(rle, context->priv->PlaneBuffers[i], originalSize); else CopyMemory(context->priv->PlaneBuffers[i], rle, originalSize); rle += planeSize; } } Commit Message: Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-787
static void nsc_rle_decompress_data(NSC_CONTEXT* context) static BOOL nsc_rle_decompress_data(NSC_CONTEXT* context) { UINT16 i; BYTE* rle; UINT32 planeSize; UINT32 originalSize; if (!context) return FALSE; rle = context->Planes; for (i = 0; i < 4; i++) { originalSize = context->OrgByteCount[i]; planeSize = context->PlaneByteCount[i]; if (planeSize == 0) { if (context->priv->PlaneBuffersLength < originalSize) return FALSE; FillMemory(context->priv->PlaneBuffers[i], originalSize, 0xFF); } else if (planeSize < originalSize) { if (!nsc_rle_decode(rle, context->priv->PlaneBuffers[i], context->priv->PlaneBuffersLength, originalSize)) return FALSE; } else { if (context->priv->PlaneBuffersLength < originalSize) return FALSE; CopyMemory(context->priv->PlaneBuffers[i], rle, originalSize); } rle += planeSize; } return TRUE; }
169,285
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: read_packet(int fd, gss_buffer_t buf, int timeout, int first) { int ret; static uint32_t len = 0; static char len_buf[4]; static int len_buf_pos = 0; static char * tmpbuf = 0; static int tmpbuf_pos = 0; if (first) { len_buf_pos = 0; return -2; } if (len_buf_pos < 4) { ret = timed_read(fd, &len_buf[len_buf_pos], 4 - len_buf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); return -1; } if (ret == 0) { /* EOF */ /* Failure to read ANY length just means we're done */ if (len_buf_pos == 0) return 0; /* * Otherwise, we got EOF mid-length, and that's * a protocol error. */ LOG(LOG_INFO, ("EOF reading packet len")); return -1; } len_buf_pos += ret; } /* Not done reading the length? */ if (len_buf_pos != 4) return -2; /* We have the complete length */ len = ntohl(*(uint32_t *)len_buf); /* * We make sure recvd length is reasonable, allowing for some * slop in enc overhead, beyond the actual maximum number of * bytes of decrypted payload. */ if (len > GSTD_MAXPACKETCONTENTS + 512) { LOG(LOG_ERR, ("ridiculous length, %ld", len)); return -1; } if (!tmpbuf) { if ((tmpbuf = malloc(len)) == NULL) { LOG(LOG_CRIT, ("malloc failure, %ld bytes", len)); return -1; } } ret = timed_read(fd, tmpbuf + tmpbuf_pos, len - tmpbuf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); return -1; } if (ret == 0) { LOG(LOG_ERR, ("EOF while reading packet (len=%d)", len)); return -1; } tmpbuf_pos += ret; if (tmpbuf_pos == len) { buf->length = len; buf->value = tmpbuf; len = len_buf_pos = tmpbuf_pos = 0; tmpbuf = NULL; LOG(LOG_DEBUG, ("read packet of length %d", buf->length)); return 1; } return -2; } Commit Message: knc: fix a couple of memory leaks. One of these can be remotely triggered during the authentication phase which leads to a remote DoS possibility. Pointed out by: Imre Rad <radimre83@gmail.com> CWE ID: CWE-400
read_packet(int fd, gss_buffer_t buf, int timeout, int first) { int ret; static uint32_t len = 0; static char len_buf[4]; static int len_buf_pos = 0; static char * tmpbuf = 0; static int tmpbuf_pos = 0; if (first) { len_buf_pos = 0; return -2; } if (len_buf_pos < 4) { ret = timed_read(fd, &len_buf[len_buf_pos], 4 - len_buf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); goto bail; } if (ret == 0) { /* EOF */ /* Failure to read ANY length just means we're done */ if (len_buf_pos == 0) return 0; /* * Otherwise, we got EOF mid-length, and that's * a protocol error. */ LOG(LOG_INFO, ("EOF reading packet len")); goto bail; } len_buf_pos += ret; } /* Not done reading the length? */ if (len_buf_pos != 4) return -2; /* We have the complete length */ len = ntohl(*(uint32_t *)len_buf); /* * We make sure recvd length is reasonable, allowing for some * slop in enc overhead, beyond the actual maximum number of * bytes of decrypted payload. */ if (len > GSTD_MAXPACKETCONTENTS + 512) { LOG(LOG_ERR, ("ridiculous length, %ld", len)); goto bail; } if (!tmpbuf) { if ((tmpbuf = malloc(len)) == NULL) { LOG(LOG_CRIT, ("malloc failure, %ld bytes", len)); goto bail; } } ret = timed_read(fd, tmpbuf + tmpbuf_pos, len - tmpbuf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); goto bail; } if (ret == 0) { LOG(LOG_ERR, ("EOF while reading packet (len=%d)", len)); goto bail; } tmpbuf_pos += ret; if (tmpbuf_pos == len) { buf->length = len; buf->value = tmpbuf; len = len_buf_pos = tmpbuf_pos = 0; tmpbuf = NULL; LOG(LOG_DEBUG, ("read packet of length %d", buf->length)); return 1; } return -2; bail: free(tmpbuf); tmpbuf = NULL; return -1; }
169,433
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Utterance::~Utterance() { DCHECK_EQ(completion_task_, static_cast<Task *>(NULL)); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
Utterance::~Utterance() {
170,397
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int sock_send_fd(int sock_fd, const uint8_t* buf, int len, int send_fd) { ssize_t ret; struct msghdr msg; unsigned char *buffer = (unsigned char *)buf; memset(&msg, 0, sizeof(msg)); struct cmsghdr *cmsg; char msgbuf[CMSG_SPACE(1)]; asrt(send_fd != -1); if(sock_fd == -1 || send_fd == -1) return -1; msg.msg_control = msgbuf; msg.msg_controllen = sizeof msgbuf; cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof send_fd); memcpy(CMSG_DATA(cmsg), &send_fd, sizeof send_fd); int ret_len = len; while (len > 0) { struct iovec iv; memset(&iv, 0, sizeof(iv)); iv.iov_base = buffer; iv.iov_len = len; msg.msg_iov = &iv; msg.msg_iovlen = 1; do { ret = sendmsg(sock_fd, &msg, MSG_NOSIGNAL); } while (ret < 0 && errno == EINTR); if (ret < 0) { BTIF_TRACE_ERROR("fd:%d, send_fd:%d, sendmsg ret:%d, errno:%d, %s", sock_fd, send_fd, (int)ret, errno, strerror(errno)); ret_len = -1; break; } buffer += ret; len -= ret; memset(&msg, 0, sizeof(msg)); } BTIF_TRACE_DEBUG("close fd:%d after sent", send_fd); close(send_fd); return ret_len; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
int sock_send_fd(int sock_fd, const uint8_t* buf, int len, int send_fd) { ssize_t ret; struct msghdr msg; unsigned char *buffer = (unsigned char *)buf; memset(&msg, 0, sizeof(msg)); struct cmsghdr *cmsg; char msgbuf[CMSG_SPACE(1)]; asrt(send_fd != -1); if(sock_fd == -1 || send_fd == -1) return -1; msg.msg_control = msgbuf; msg.msg_controllen = sizeof msgbuf; cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof send_fd); memcpy(CMSG_DATA(cmsg), &send_fd, sizeof send_fd); int ret_len = len; while (len > 0) { struct iovec iv; memset(&iv, 0, sizeof(iv)); iv.iov_base = buffer; iv.iov_len = len; msg.msg_iov = &iv; msg.msg_iovlen = 1; do { ret = TEMP_FAILURE_RETRY(sendmsg(sock_fd, &msg, MSG_NOSIGNAL)); } while (ret < 0 && errno == EINTR); if (ret < 0) { BTIF_TRACE_ERROR("fd:%d, send_fd:%d, sendmsg ret:%d, errno:%d, %s", sock_fd, send_fd, (int)ret, errno, strerror(errno)); ret_len = -1; break; } buffer += ret; len -= ret; memset(&msg, 0, sizeof(msg)); } BTIF_TRACE_DEBUG("close fd:%d after sent", send_fd); close(send_fd); return ret_len; }
173,470
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static __u8 *ch_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 17 && rdesc[11] == 0x3c && rdesc[12] == 0x02) { hid_info(hdev, "fixing up Cherry Cymotion report descriptor\n"); rdesc[11] = rdesc[16] = 0xff; rdesc[12] = rdesc[17] = 0x03; } return rdesc; } Commit Message: HID: fix a couple of off-by-ones There are a few very theoretical off-by-one bugs in report descriptor size checking when performing a pre-parsing fixup. Fix those. Cc: stable@vger.kernel.org Reported-by: Ben Hawkes <hawkes@google.com> Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com> Signed-off-by: Jiri Kosina <jkosina@suse.cz> CWE ID: CWE-119
static __u8 *ch_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 18 && rdesc[11] == 0x3c && rdesc[12] == 0x02) { hid_info(hdev, "fixing up Cherry Cymotion report descriptor\n"); rdesc[11] = rdesc[16] = 0xff; rdesc[12] = rdesc[17] = 0x03; } return rdesc; }
166,370
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: svc_set_num_threads(struct svc_serv *serv, struct svc_pool *pool, int nrservs) { struct svc_rqst *rqstp; struct task_struct *task; struct svc_pool *chosen_pool; int error = 0; unsigned int state = serv->sv_nrthreads-1; int node; if (pool == NULL) { /* The -1 assumes caller has done a svc_get() */ nrservs -= (serv->sv_nrthreads-1); } else { spin_lock_bh(&pool->sp_lock); nrservs -= pool->sp_nrthreads; spin_unlock_bh(&pool->sp_lock); } /* create new threads */ while (nrservs > 0) { nrservs--; chosen_pool = choose_pool(serv, pool, &state); node = svc_pool_map_get_node(chosen_pool->sp_id); rqstp = svc_prepare_thread(serv, chosen_pool, node); if (IS_ERR(rqstp)) { error = PTR_ERR(rqstp); break; } __module_get(serv->sv_ops->svo_module); task = kthread_create_on_node(serv->sv_ops->svo_function, rqstp, node, "%s", serv->sv_name); if (IS_ERR(task)) { error = PTR_ERR(task); module_put(serv->sv_ops->svo_module); svc_exit_thread(rqstp); break; } rqstp->rq_task = task; if (serv->sv_nrpools > 1) svc_pool_map_set_cpumask(task, chosen_pool->sp_id); svc_sock_update_bufs(serv); wake_up_process(task); } /* destroy old threads */ while (nrservs < 0 && (task = choose_victim(serv, pool, &state)) != NULL) { send_sig(SIGINT, task, 1); nrservs++; } return error; } 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
svc_set_num_threads(struct svc_serv *serv, struct svc_pool *pool, int nrservs) /* create new threads */ static int svc_start_kthreads(struct svc_serv *serv, struct svc_pool *pool, int nrservs) { struct svc_rqst *rqstp; struct task_struct *task; struct svc_pool *chosen_pool; unsigned int state = serv->sv_nrthreads-1; int node; do { nrservs--; chosen_pool = choose_pool(serv, pool, &state); node = svc_pool_map_get_node(chosen_pool->sp_id); rqstp = svc_prepare_thread(serv, chosen_pool, node); if (IS_ERR(rqstp)) return PTR_ERR(rqstp); __module_get(serv->sv_ops->svo_module); task = kthread_create_on_node(serv->sv_ops->svo_function, rqstp, node, "%s", serv->sv_name); if (IS_ERR(task)) { module_put(serv->sv_ops->svo_module); svc_exit_thread(rqstp); return PTR_ERR(task); } rqstp->rq_task = task; if (serv->sv_nrpools > 1) svc_pool_map_set_cpumask(task, chosen_pool->sp_id); svc_sock_update_bufs(serv); wake_up_process(task); } while (nrservs > 0); return 0; } /* destroy old threads */ static int svc_signal_kthreads(struct svc_serv *serv, struct svc_pool *pool, int nrservs) { struct task_struct *task; unsigned int state = serv->sv_nrthreads-1; /* destroy old threads */ do { task = choose_victim(serv, pool, &state); if (task == NULL) break; send_sig(SIGINT, task, 1); nrservs++; } while (nrservs < 0); return 0; } /* * Create or destroy enough new threads to make the number * of threads the given number. If `pool' is non-NULL, applies * only to threads in that pool, otherwise round-robins between * all pools. Caller must ensure that mutual exclusion between this and * server startup or shutdown. * * Destroying threads relies on the service threads filling in * rqstp->rq_task, which only the nfs ones do. Assumes the serv * has been created using svc_create_pooled(). * * Based on code that used to be in nfsd_svc() but tweaked * to be pool-aware. */ int svc_set_num_threads(struct svc_serv *serv, struct svc_pool *pool, int nrservs) { if (pool == NULL) { /* The -1 assumes caller has done a svc_get() */ nrservs -= (serv->sv_nrthreads-1); } else { spin_lock_bh(&pool->sp_lock); nrservs -= pool->sp_nrthreads; spin_unlock_bh(&pool->sp_lock); } if (nrservs > 0) return svc_start_kthreads(serv, pool, nrservs); if (nrservs < 0) return svc_signal_kthreads(serv, pool, nrservs); return 0; }
168,155
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len) { const sp<ProcessState> proc(ProcessState::self()); status_t err; const uint8_t *data = parcel->mData; const binder_size_t *objects = parcel->mObjects; size_t size = parcel->mObjectsSize; int startPos = mDataPos; int firstIndex = -1, lastIndex = -2; if (len == 0) { return NO_ERROR; } if ((offset > parcel->mDataSize) || (len > parcel->mDataSize) || (offset + len > parcel->mDataSize)) { return BAD_VALUE; } for (int i = 0; i < (int) size; i++) { size_t off = objects[i]; if ((off >= offset) && (off < offset + len)) { if (firstIndex == -1) { firstIndex = i; } lastIndex = i; } } int numObjects = lastIndex - firstIndex + 1; if ((mDataSize+len) > mDataCapacity) { err = growData(len); if (err != NO_ERROR) { return err; } } memcpy(mData + mDataPos, data + offset, len); mDataPos += len; mDataSize += len; err = NO_ERROR; if (numObjects > 0) { if (mObjectsCapacity < mObjectsSize + numObjects) { int newSize = ((mObjectsSize + numObjects)*3)/2; binder_size_t *objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t)); if (objects == (binder_size_t*)0) { return NO_MEMORY; } mObjects = objects; mObjectsCapacity = newSize; } int idx = mObjectsSize; for (int i = firstIndex; i <= lastIndex; i++) { size_t off = objects[i] - offset + startPos; mObjects[idx++] = off; mObjectsSize++; flat_binder_object* flat = reinterpret_cast<flat_binder_object*>(mData + off); acquire_object(proc, *flat, this); if (flat->type == BINDER_TYPE_FD) { flat->handle = dup(flat->handle); flat->cookie = 1; mHasFds = mFdsKnown = true; if (!mAllowFds) { err = FDS_NOT_ALLOWED; } } } } return err; } Commit Message: Disregard alleged binder entities beyond parcel bounds When appending one parcel's contents to another, ignore binder objects within the source Parcel that appear to lie beyond the formal bounds of that Parcel's data buffer. Bug 17312693 Change-Id: If592a260f3fcd9a56fc160e7feb2c8b44c73f514 (cherry picked from commit 27182be9f20f4f5b48316666429f09b9ecc1f22e) CWE ID: CWE-264
status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len) { const sp<ProcessState> proc(ProcessState::self()); status_t err; const uint8_t *data = parcel->mData; const binder_size_t *objects = parcel->mObjects; size_t size = parcel->mObjectsSize; int startPos = mDataPos; int firstIndex = -1, lastIndex = -2; if (len == 0) { return NO_ERROR; } if ((offset > parcel->mDataSize) || (len > parcel->mDataSize) || (offset + len > parcel->mDataSize)) { return BAD_VALUE; } for (int i = 0; i < (int) size; i++) { size_t off = objects[i]; if ((off >= offset) && (off + sizeof(flat_binder_object) <= offset + len)) { if (firstIndex == -1) { firstIndex = i; } lastIndex = i; } } int numObjects = lastIndex - firstIndex + 1; if ((mDataSize+len) > mDataCapacity) { err = growData(len); if (err != NO_ERROR) { return err; } } memcpy(mData + mDataPos, data + offset, len); mDataPos += len; mDataSize += len; err = NO_ERROR; if (numObjects > 0) { if (mObjectsCapacity < mObjectsSize + numObjects) { int newSize = ((mObjectsSize + numObjects)*3)/2; binder_size_t *objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t)); if (objects == (binder_size_t*)0) { return NO_MEMORY; } mObjects = objects; mObjectsCapacity = newSize; } int idx = mObjectsSize; for (int i = firstIndex; i <= lastIndex; i++) { size_t off = objects[i] - offset + startPos; mObjects[idx++] = off; mObjectsSize++; flat_binder_object* flat = reinterpret_cast<flat_binder_object*>(mData + off); acquire_object(proc, *flat, this); if (flat->type == BINDER_TYPE_FD) { flat->handle = dup(flat->handle); flat->cookie = 1; mHasFds = mFdsKnown = true; if (!mAllowFds) { err = FDS_NOT_ALLOWED; } } } } return err; }
173,342
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) /* Note: this does not properly handle chunks that are > 64K under DOS */ { png_byte compression_type; png_bytep pC; png_charp profile; png_uint_32 skip = 0; png_uint_32 profile_size, profile_length; png_size_t slength, prefix_length, data_length; png_debug(1, "in png_handle_iCCP"); if (!(png_ptr->mode & PNG_HAVE_IHDR)) png_error(png_ptr, "Missing IHDR before iCCP"); else if (png_ptr->mode & PNG_HAVE_IDAT) { png_warning(png_ptr, "Invalid iCCP after IDAT"); png_crc_finish(png_ptr, length); return; } else if (png_ptr->mode & PNG_HAVE_PLTE) /* Should be an error, but we can cope with it */ png_warning(png_ptr, "Out of place iCCP chunk"); if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)) { png_warning(png_ptr, "Duplicate iCCP chunk"); png_crc_finish(png_ptr, length); return; } #ifdef PNG_MAX_MALLOC_64K if (length > (png_uint_32)65535L) { png_warning(png_ptr, "iCCP chunk too large to fit in memory"); skip = length - (png_uint_32)65535L; length = (png_uint_32)65535L; } #endif png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = (png_charp)png_malloc(png_ptr, length + 1); slength = (png_size_t)length; png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); if (png_crc_finish(png_ptr, skip)) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; return; } png_ptr->chunkdata[slength] = 0x00; for (profile = png_ptr->chunkdata; *profile; profile++) /* Empty loop to find end of name */ ; ++profile; /* There should be at least one zero (the compression type byte) * following the separator, and we should be on it */ if ( profile >= png_ptr->chunkdata + slength - 1) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Malformed iCCP chunk"); return; } /* Compression_type should always be zero */ compression_type = *profile++; if (compression_type) { png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk"); compression_type = 0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8 wrote nonzero) */ } prefix_length = profile - png_ptr->chunkdata; png_decompress_chunk(png_ptr, compression_type, slength, prefix_length, &data_length); profile_length = data_length - prefix_length; if ( prefix_length > data_length || profile_length < 4) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Profile size field missing from iCCP chunk"); return; } /* Check the profile_size recorded in the first 32 bits of the ICC profile */ pC = (png_bytep)(png_ptr->chunkdata + prefix_length); profile_size = ((*(pC ))<<24) | ((*(pC + 1))<<16) | ((*(pC + 2))<< 8) | ((*(pC + 3)) ); if (profile_size < profile_length) profile_length = profile_size; if (profile_size > profile_length) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Ignoring truncated iCCP profile."); return; } png_set_iCCP(png_ptr, info_ptr, png_ptr->chunkdata, compression_type, png_ptr->chunkdata + prefix_length, profile_length); png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) /* Note: this does not properly handle chunks that are > 64K under DOS */ { png_byte compression_type; png_bytep pC; png_charp profile; png_uint_32 skip = 0; png_uint_32 profile_size, profile_length; png_size_t slength, prefix_length, data_length; png_debug(1, "in png_handle_iCCP"); if (!(png_ptr->mode & PNG_HAVE_IHDR)) png_error(png_ptr, "Missing IHDR before iCCP"); else if (png_ptr->mode & PNG_HAVE_IDAT) { png_warning(png_ptr, "Invalid iCCP after IDAT"); png_crc_finish(png_ptr, length); return; } else if (png_ptr->mode & PNG_HAVE_PLTE) /* Should be an error, but we can cope with it */ png_warning(png_ptr, "Out of place iCCP chunk"); if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)) { png_warning(png_ptr, "Duplicate iCCP chunk"); png_crc_finish(png_ptr, length); return; } #ifdef PNG_MAX_MALLOC_64K if (length > (png_uint_32)65535L) { png_warning(png_ptr, "iCCP chunk too large to fit in memory"); skip = length - (png_uint_32)65535L; length = (png_uint_32)65535L; } #endif png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = (png_charp)png_malloc(png_ptr, length + 1); slength = (png_size_t)length; png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); if (png_crc_finish(png_ptr, skip)) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; return; } png_ptr->chunkdata[slength] = 0x00; for (profile = png_ptr->chunkdata; *profile; profile++) /* Empty loop to find end of name */ ; ++profile; /* There should be at least one zero (the compression type byte) * following the separator, and we should be on it */ if ( profile >= png_ptr->chunkdata + slength - 1) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Malformed iCCP chunk"); return; } /* Compression_type should always be zero */ compression_type = *profile++; if (compression_type) { png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk"); compression_type = 0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8 wrote nonzero) */ } prefix_length = profile - png_ptr->chunkdata; png_decompress_chunk(png_ptr, compression_type, slength, prefix_length, &data_length); profile_length = data_length - prefix_length; if ( prefix_length > data_length || profile_length < 4) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Profile size field missing from iCCP chunk"); return; } /* Check the profile_size recorded in the first 32 bits of the ICC profile */ pC = (png_bytep)(png_ptr->chunkdata + prefix_length); profile_size = ((png_uint_32) (*(pC )<<24)) | ((png_uint_32) (*(pC + 1)<<16)) | ((png_uint_32) (*(pC + 2)<< 8)) | ((png_uint_32) (*(pC + 3) )); if (profile_size < profile_length) profile_length = profile_size; if (profile_size > profile_length) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Ignoring truncated iCCP profile."); return; } png_set_iCCP(png_ptr, info_ptr, png_ptr->chunkdata, compression_type, png_ptr->chunkdata + prefix_length, profile_length); png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; }
172,178
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); ND_TCHECK_32BITS(obj_tptr + offset + 4); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); trunc: return -1; } Commit Message: (for 4.9.3) LMP: Add some missing bounds checks In lmp_print_data_link_subobjs(), these problems were identified through code review. Moreover: Add and use tstr[]. Update two tests outputs accordingly. CWE ID: CWE-20
lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { ND_TCHECK_16BITS(obj_tptr + offset); subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_TCHECK_8BITS(obj_tptr + offset + 2); ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_TCHECK_8BITS(obj_tptr + offset + 3); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); ND_TCHECK_32BITS(obj_tptr + offset + 4); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); ND_TCHECK_32BITS(obj_tptr + offset + 8); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_TCHECK_32BITS(obj_tptr + offset + 4); ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); trunc: return -1; }
169,538
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int db_interception(struct vcpu_svm *svm) { struct kvm_run *kvm_run = svm->vcpu.run; if (!(svm->vcpu.guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) && !svm->nmi_singlestep) { kvm_queue_exception(&svm->vcpu, DB_VECTOR); return 1; } if (svm->nmi_singlestep) { svm->nmi_singlestep = false; if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) svm->vmcb->save.rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF); update_db_bp_intercept(&svm->vcpu); } if (svm->vcpu.guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) { kvm_run->exit_reason = KVM_EXIT_DEBUG; kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip; kvm_run->debug.arch.exception = DB_VECTOR; return 0; } return 1; } Commit Message: KVM: svm: unconditionally intercept #DB This is needed to avoid the possibility that the guest triggers an infinite stream of #DB exceptions (CVE-2015-8104). VMX is not affected: because it does not save DR6 in the VMCS, it already intercepts #DB unconditionally. Reported-by: Jan Beulich <jbeulich@suse.com> Cc: stable@vger.kernel.org Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-399
static int db_interception(struct vcpu_svm *svm) { struct kvm_run *kvm_run = svm->vcpu.run; if (!(svm->vcpu.guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) && !svm->nmi_singlestep) { kvm_queue_exception(&svm->vcpu, DB_VECTOR); return 1; } if (svm->nmi_singlestep) { svm->nmi_singlestep = false; if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) svm->vmcb->save.rflags &= ~(X86_EFLAGS_TF | X86_EFLAGS_RF); } if (svm->vcpu.guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) { kvm_run->exit_reason = KVM_EXIT_DEBUG; kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip; kvm_run->debug.arch.exception = DB_VECTOR; return 0; } return 1; }
166,568
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) { fwd_txfm_(in, out, stride); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) { void RunFwdTxfm(const int16_t *in, tran_low_t *out, int stride) { fwd_txfm_(in, out, stride); }
174,549
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: build_config(char *prefix, struct server *server) { char *path = NULL; int path_size = strlen(prefix) + strlen(server->port) + 20; path = ss_malloc(path_size); snprintf(path, path_size, "%s/.shadowsocks_%s.conf", prefix, server->port); FILE *f = fopen(path, "w+"); if (f == NULL) { if (verbose) { LOGE("unable to open config file"); } ss_free(path); return; } fprintf(f, "{\n"); fprintf(f, "\"server_port\":%d,\n", atoi(server->port)); fprintf(f, "\"password\":\"%s\"", server->password); if (server->fast_open[0]) fprintf(f, ",\n\"fast_open\": %s", server->fast_open); if (server->mode) fprintf(f, ",\n\"mode\":\"%s\"", server->mode); if (server->method) fprintf(f, ",\n\"method\":\"%s\"", server->method); if (server->plugin) fprintf(f, ",\n\"plugin\":\"%s\"", server->plugin); if (server->plugin_opts) fprintf(f, ",\n\"plugin_opts\":\"%s\"", server->plugin_opts); fprintf(f, "\n}\n"); fclose(f); ss_free(path); } Commit Message: Fix #1734 CWE ID: CWE-78
build_config(char *prefix, struct server *server) build_config(char *prefix, struct manager_ctx *manager, struct server *server) { char *path = NULL; int path_size = strlen(prefix) + strlen(server->port) + 20; path = ss_malloc(path_size); snprintf(path, path_size, "%s/.shadowsocks_%s.conf", prefix, server->port); FILE *f = fopen(path, "w+"); if (f == NULL) { if (verbose) { LOGE("unable to open config file"); } ss_free(path); return; } fprintf(f, "{\n"); fprintf(f, "\"server_port\":%d,\n", atoi(server->port)); fprintf(f, "\"password\":\"%s\"", server->password); if (server->method) fprintf(f, ",\n\"method\":\"%s\"", server->method); else if (manager->method) fprintf(f, ",\n\"method\":\"%s\"", manager->method); if (server->fast_open[0]) fprintf(f, ",\n\"fast_open\": %s", server->fast_open); if (server->mode) fprintf(f, ",\n\"mode\":\"%s\"", server->mode); if (server->plugin) fprintf(f, ",\n\"plugin\":\"%s\"", server->plugin); if (server->plugin_opts) fprintf(f, ",\n\"plugin_opts\":\"%s\"", server->plugin_opts); fprintf(f, "\n}\n"); fclose(f); ss_free(path); }
167,713
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char *curl_easy_escape(CURL *handle, const char *string, int inlength) { size_t alloc = (inlength?(size_t)inlength:strlen(string))+1; char *ns; char *testing_ptr = NULL; unsigned char in; /* we need to treat the characters unsigned */ size_t newlen = alloc; int strindex=0; size_t length; CURLcode res; ns = malloc(alloc); if(!ns) return NULL; length = alloc-1; while(length--) { in = *string; if(Curl_isunreserved(in)) /* just copy this */ ns[strindex++]=in; else { /* encode it */ newlen += 2; /* the size grows with two, since this'll become a %XX */ if(newlen > alloc) { alloc *= 2; testing_ptr = realloc(ns, alloc); if(!testing_ptr) { free( ns ); return NULL; } else { ns = testing_ptr; } } res = Curl_convert_to_network(handle, &in, 1); if(res) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); return NULL; } snprintf(&ns[strindex], 4, "%%%02X", in); strindex+=3; } string++; } ns[strindex]=0; /* terminate it */ return ns; } Commit Message: URL sanitize: reject URLs containing bad data Protocols (IMAP, POP3 and SMTP) that use the path part of a URL in a decoded manner now use the new Curl_urldecode() function to reject URLs with embedded control codes (anything that is or decodes to a byte value less than 32). URLs containing such codes could easily otherwise be used to do harm and allow users to do unintended actions with otherwise innocent tools and applications. Like for example using a URL like pop3://pop3.example.com/1%0d%0aDELE%201 when the app wants a URL to get a mail and instead this would delete one. This flaw is considered a security vulnerability: CVE-2012-0036 Security advisory at: http://curl.haxx.se/docs/adv_20120124.html Reported by: Dan Fandrich CWE ID: CWE-89
char *curl_easy_escape(CURL *handle, const char *string, int inlength) { size_t alloc = (inlength?(size_t)inlength:strlen(string))+1; char *ns; char *testing_ptr = NULL; unsigned char in; /* we need to treat the characters unsigned */ size_t newlen = alloc; size_t strindex=0; size_t length; CURLcode res; ns = malloc(alloc); if(!ns) return NULL; length = alloc-1; while(length--) { in = *string; if(Curl_isunreserved(in)) /* just copy this */ ns[strindex++]=in; else { /* encode it */ newlen += 2; /* the size grows with two, since this'll become a %XX */ if(newlen > alloc) { alloc *= 2; testing_ptr = realloc(ns, alloc); if(!testing_ptr) { free( ns ); return NULL; } else { ns = testing_ptr; } } res = Curl_convert_to_network(handle, &in, 1); if(res) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); return NULL; } snprintf(&ns[strindex], 4, "%%%02X", in); strindex+=3; } string++; } ns[strindex]=0; /* terminate it */ return ns; }
165,664
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DateTimeChooserImpl::writeDocument(SharedBuffer* data) { String stepString = String::number(m_parameters.step); String stepBaseString = String::number(m_parameters.stepBase, 11, WTF::TruncateTrailingZeros); IntRect anchorRectInScreen = m_chromeClient->rootViewToScreen(m_parameters.anchorRectInRootView); String todayLabelString; String otherDateLabelString; if (m_parameters.type == InputTypeNames::month) { todayLabelString = locale().queryString(WebLocalizedString::ThisMonthButtonLabel); otherDateLabelString = locale().queryString(WebLocalizedString::OtherMonthLabel); } else if (m_parameters.type == InputTypeNames::week) { todayLabelString = locale().queryString(WebLocalizedString::ThisWeekButtonLabel); otherDateLabelString = locale().queryString(WebLocalizedString::OtherWeekLabel); } else { todayLabelString = locale().queryString(WebLocalizedString::CalendarToday); otherDateLabelString = locale().queryString(WebLocalizedString::OtherDateLabel); } addString("<!DOCTYPE html><head><meta charset='UTF-8'><style>\n", data); data->append(Platform::current()->loadResource("pickerCommon.css")); data->append(Platform::current()->loadResource("pickerButton.css")); data->append(Platform::current()->loadResource("suggestionPicker.css")); data->append(Platform::current()->loadResource("calendarPicker.css")); addString("</style></head><body><div id=main>Loading...</div><script>\n" "window.dialogArguments = {\n", data); addProperty("anchorRectInScreen", anchorRectInScreen, data); addProperty("min", valueToDateTimeString(m_parameters.minimum, m_parameters.type), data); addProperty("max", valueToDateTimeString(m_parameters.maximum, m_parameters.type), data); addProperty("step", stepString, data); addProperty("stepBase", stepBaseString, data); addProperty("required", m_parameters.required, data); addProperty("currentValue", valueToDateTimeString(m_parameters.doubleValue, m_parameters.type), data); addProperty("locale", m_parameters.locale.string(), data); addProperty("todayLabel", todayLabelString, data); addProperty("clearLabel", locale().queryString(WebLocalizedString::CalendarClear), data); addProperty("weekLabel", locale().queryString(WebLocalizedString::WeekNumberLabel), data); addProperty("weekStartDay", m_locale->firstDayOfWeek(), data); addProperty("shortMonthLabels", m_locale->shortMonthLabels(), data); addProperty("dayLabels", m_locale->weekDayShortLabels(), data); addProperty("isLocaleRTL", m_locale->isRTL(), data); addProperty("isRTL", m_parameters.isAnchorElementRTL, data); addProperty("mode", m_parameters.type.string(), data); if (m_parameters.suggestions.size()) { Vector<String> suggestionValues; Vector<String> localizedSuggestionValues; Vector<String> suggestionLabels; for (unsigned i = 0; i < m_parameters.suggestions.size(); i++) { suggestionValues.append(valueToDateTimeString(m_parameters.suggestions[i].value, m_parameters.type)); localizedSuggestionValues.append(m_parameters.suggestions[i].localizedValue); suggestionLabels.append(m_parameters.suggestions[i].label); } addProperty("suggestionValues", suggestionValues, data); addProperty("localizedSuggestionValues", localizedSuggestionValues, data); addProperty("suggestionLabels", suggestionLabels, data); addProperty("inputWidth", static_cast<unsigned>(m_parameters.anchorRectInRootView.width()), data); addProperty("showOtherDateEntry", RenderTheme::theme().supportsCalendarPicker(m_parameters.type), data); addProperty("otherDateLabel", otherDateLabelString, data); addProperty("suggestionHighlightColor", RenderTheme::theme().activeListBoxSelectionBackgroundColor().serialized(), data); addProperty("suggestionHighlightTextColor", RenderTheme::theme().activeListBoxSelectionForegroundColor().serialized(), data); } addString("}\n", data); data->append(Platform::current()->loadResource("pickerCommon.js")); data->append(Platform::current()->loadResource("suggestionPicker.js")); data->append(Platform::current()->loadResource("calendarPicker.js")); addString("</script></body>\n", data); } Commit Message: AX: Calendar Picker: Add AX labels to MonthPopupButton and CalendarNavigationButtons. This CL adds no new tests. Will add tests after a Chromium change for string resource. BUG=123896 Review URL: https://codereview.chromium.org/552163002 git-svn-id: svn://svn.chromium.org/blink/trunk@181617 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-22
void DateTimeChooserImpl::writeDocument(SharedBuffer* data) { String stepString = String::number(m_parameters.step); String stepBaseString = String::number(m_parameters.stepBase, 11, WTF::TruncateTrailingZeros); IntRect anchorRectInScreen = m_chromeClient->rootViewToScreen(m_parameters.anchorRectInRootView); String todayLabelString; String otherDateLabelString; if (m_parameters.type == InputTypeNames::month) { todayLabelString = locale().queryString(WebLocalizedString::ThisMonthButtonLabel); otherDateLabelString = locale().queryString(WebLocalizedString::OtherMonthLabel); } else if (m_parameters.type == InputTypeNames::week) { todayLabelString = locale().queryString(WebLocalizedString::ThisWeekButtonLabel); otherDateLabelString = locale().queryString(WebLocalizedString::OtherWeekLabel); } else { todayLabelString = locale().queryString(WebLocalizedString::CalendarToday); otherDateLabelString = locale().queryString(WebLocalizedString::OtherDateLabel); } addString("<!DOCTYPE html><head><meta charset='UTF-8'><style>\n", data); data->append(Platform::current()->loadResource("pickerCommon.css")); data->append(Platform::current()->loadResource("pickerButton.css")); data->append(Platform::current()->loadResource("suggestionPicker.css")); data->append(Platform::current()->loadResource("calendarPicker.css")); addString("</style></head><body><div id=main>Loading...</div><script>\n" "window.dialogArguments = {\n", data); addProperty("anchorRectInScreen", anchorRectInScreen, data); addProperty("min", valueToDateTimeString(m_parameters.minimum, m_parameters.type), data); addProperty("max", valueToDateTimeString(m_parameters.maximum, m_parameters.type), data); addProperty("step", stepString, data); addProperty("stepBase", stepBaseString, data); addProperty("required", m_parameters.required, data); addProperty("currentValue", valueToDateTimeString(m_parameters.doubleValue, m_parameters.type), data); addProperty("locale", m_parameters.locale.string(), data); addProperty("todayLabel", todayLabelString, data); addProperty("clearLabel", locale().queryString(WebLocalizedString::CalendarClear), data); addProperty("weekLabel", locale().queryString(WebLocalizedString::WeekNumberLabel), data); addProperty("axShowMonthSelector", locale().queryString(WebLocalizedString::AXCalendarShowMonthSelector), data); addProperty("axShowNextMonth", locale().queryString(WebLocalizedString::AXCalendarShowNextMonth), data); addProperty("axShowPreviousMonth", locale().queryString(WebLocalizedString::AXCalendarShowPreviousMonth), data); addProperty("weekStartDay", m_locale->firstDayOfWeek(), data); addProperty("shortMonthLabels", m_locale->shortMonthLabels(), data); addProperty("dayLabels", m_locale->weekDayShortLabels(), data); addProperty("isLocaleRTL", m_locale->isRTL(), data); addProperty("isRTL", m_parameters.isAnchorElementRTL, data); addProperty("mode", m_parameters.type.string(), data); if (m_parameters.suggestions.size()) { Vector<String> suggestionValues; Vector<String> localizedSuggestionValues; Vector<String> suggestionLabels; for (unsigned i = 0; i < m_parameters.suggestions.size(); i++) { suggestionValues.append(valueToDateTimeString(m_parameters.suggestions[i].value, m_parameters.type)); localizedSuggestionValues.append(m_parameters.suggestions[i].localizedValue); suggestionLabels.append(m_parameters.suggestions[i].label); } addProperty("suggestionValues", suggestionValues, data); addProperty("localizedSuggestionValues", localizedSuggestionValues, data); addProperty("suggestionLabels", suggestionLabels, data); addProperty("inputWidth", static_cast<unsigned>(m_parameters.anchorRectInRootView.width()), data); addProperty("showOtherDateEntry", RenderTheme::theme().supportsCalendarPicker(m_parameters.type), data); addProperty("otherDateLabel", otherDateLabelString, data); addProperty("suggestionHighlightColor", RenderTheme::theme().activeListBoxSelectionBackgroundColor().serialized(), data); addProperty("suggestionHighlightTextColor", RenderTheme::theme().activeListBoxSelectionForegroundColor().serialized(), data); } addString("}\n", data); data->append(Platform::current()->loadResource("pickerCommon.js")); data->append(Platform::current()->loadResource("suggestionPicker.js")); data->append(Platform::current()->loadResource("calendarPicker.js")); addString("</script></body>\n", data); }
171,196
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WM_SYMBOL midi *WildMidi_OpenBuffer(uint8_t *midibuffer, uint32_t size) { uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' }; midi * ret = NULL; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (midibuffer == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL midi data buffer)", 0); return (NULL); } if (size > WM_MAXFILESIZE) { /* don't bother loading suspiciously long files */ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_LONGFIL, NULL, 0); return (NULL); } if (memcmp(midibuffer,"HMIMIDIP", 8) == 0) { ret = (void *) _WM_ParseNewHmp(midibuffer, size); } else if (memcmp(midibuffer, "HMI-MIDISONG061595", 18) == 0) { ret = (void *) _WM_ParseNewHmi(midibuffer, size); } else if (memcmp(midibuffer, mus_hdr, 4) == 0) { ret = (void *) _WM_ParseNewMus(midibuffer, size); } else if (memcmp(midibuffer, xmi_hdr, 4) == 0) { ret = (void *) _WM_ParseNewXmi(midibuffer, size); } else { ret = (void *) _WM_ParseNewMidi(midibuffer, size); } if (ret) { if (add_handle(ret) != 0) { WildMidi_Close(ret); ret = NULL; } } return (ret); } Commit Message: wildmidi_lib.c (WildMidi_Open, WildMidi_OpenBuffer): refuse to proceed if less then 18 bytes of input Fixes bug #178. CWE ID: CWE-119
WM_SYMBOL midi *WildMidi_OpenBuffer(uint8_t *midibuffer, uint32_t size) { uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' }; midi * ret = NULL; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (midibuffer == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL midi data buffer)", 0); return (NULL); } if (size > WM_MAXFILESIZE) { /* don't bother loading suspiciously long files */ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_LONGFIL, NULL, 0); return (NULL); } if (size < 18) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0); return (NULL); } if (memcmp(midibuffer,"HMIMIDIP", 8) == 0) { ret = (void *) _WM_ParseNewHmp(midibuffer, size); } else if (memcmp(midibuffer, "HMI-MIDISONG061595", 18) == 0) { ret = (void *) _WM_ParseNewHmi(midibuffer, size); } else if (memcmp(midibuffer, mus_hdr, 4) == 0) { ret = (void *) _WM_ParseNewMus(midibuffer, size); } else if (memcmp(midibuffer, xmi_hdr, 4) == 0) { ret = (void *) _WM_ParseNewXmi(midibuffer, size); } else { ret = (void *) _WM_ParseNewMidi(midibuffer, size); } if (ret) { if (add_handle(ret) != 0) { WildMidi_Close(ret); ret = NULL; } } return (ret); }
169,370
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const SegmentInfo* Segment::GetInfo() const { return m_pInfo; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const SegmentInfo* Segment::GetInfo() const Chapters::~Chapters() { while (m_editions_count > 0) { Edition& e = m_editions[--m_editions_count]; e.Clear(); } }
174,330
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: krb5_gss_context_time(minor_status, context_handle, time_rec) OM_uint32 *minor_status; gss_ctx_id_t context_handle; OM_uint32 *time_rec; { krb5_error_code code; krb5_gss_ctx_id_rec *ctx; krb5_timestamp now; krb5_deltat lifetime; ctx = (krb5_gss_ctx_id_rec *) context_handle; if (! ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } if ((code = krb5_timeofday(ctx->k5_context, &now))) { *minor_status = code; save_error_info(*minor_status, ctx->k5_context); return(GSS_S_FAILURE); } if ((lifetime = ctx->krb_times.endtime - now) <= 0) { *time_rec = 0; *minor_status = 0; return(GSS_S_CONTEXT_EXPIRED); } else { *time_rec = lifetime; *minor_status = 0; return(GSS_S_COMPLETE); } } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID:
krb5_gss_context_time(minor_status, context_handle, time_rec) OM_uint32 *minor_status; gss_ctx_id_t context_handle; OM_uint32 *time_rec; { krb5_error_code code; krb5_gss_ctx_id_rec *ctx; krb5_timestamp now; krb5_deltat lifetime; ctx = (krb5_gss_ctx_id_rec *) context_handle; if (ctx->terminated || !ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } if ((code = krb5_timeofday(ctx->k5_context, &now))) { *minor_status = code; save_error_info(*minor_status, ctx->k5_context); return(GSS_S_FAILURE); } if ((lifetime = ctx->krb_times.endtime - now) <= 0) { *time_rec = 0; *minor_status = 0; return(GSS_S_CONTEXT_EXPIRED); } else { *time_rec = lifetime; *minor_status = 0; return(GSS_S_COMPLETE); } }
166,813
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CrosLibrary::TestApi::SetBurnLibrary( BurnLibrary* library, bool own) { library_->burn_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void CrosLibrary::TestApi::SetBurnLibrary(
170,636
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) { asn1_write_enumerated(data, result->resultcode); asn1_write_OctetString(data, result->dn, (result->dn) ? strlen(result->dn) : 0); asn1_write_OctetString(data, result->errormessage, (result->errormessage) ? strlen(result->errormessage) : 0); if (result->referral) { asn1_push_tag(data, ASN1_CONTEXT(3)); asn1_write_OctetString(data, result->referral, strlen(result->referral)); asn1_pop_tag(data); } } Commit Message: CWE ID: CWE-399
static void ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) static bool ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) { if (!asn1_write_enumerated(data, result->resultcode)) return false; if (!asn1_write_OctetString(data, result->dn, (result->dn) ? strlen(result->dn) : 0)) return false; if (!asn1_write_OctetString(data, result->errormessage, (result->errormessage) ? strlen(result->errormessage) : 0)) return false; if (result->referral) { if (!asn1_push_tag(data, ASN1_CONTEXT(3))) return false; if (!asn1_write_OctetString(data, result->referral, strlen(result->referral))) return false; if (!asn1_pop_tag(data)) return false; } return true; }
164,593
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LauncherView::ButtonPressed(views::Button* sender, const views::Event& event) { if (dragging_) return; if (sender == overflow_button_) ShowOverflowMenu(); if (!delegate_) return; int view_index = view_model_->GetIndexOfView(sender); if (view_index == -1) return; switch (model_->items()[view_index].type) { case TYPE_TABBED: case TYPE_APP_PANEL: case TYPE_APP_SHORTCUT: case TYPE_PLATFORM_APP: delegate_->ItemClicked(model_->items()[view_index], event.flags()); break; case TYPE_APP_LIST: Shell::GetInstance()->ToggleAppList(); break; case TYPE_BROWSER_SHORTCUT: if (event.flags() & ui::EF_CONTROL_DOWN) delegate_->CreateNewWindow(); else delegate_->CreateNewTab(); break; } } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void LauncherView::ButtonPressed(views::Button* sender, const views::Event& event) { if (dragging_) return; if (sender == overflow_button_) { ShowOverflowBubble(); return; } if (!delegate_) return; int view_index = view_model_->GetIndexOfView(sender); if (view_index == -1) return; switch (model_->items()[view_index].type) { case TYPE_TABBED: case TYPE_APP_PANEL: case TYPE_APP_SHORTCUT: case TYPE_PLATFORM_APP: delegate_->ItemClicked(model_->items()[view_index], event.flags()); break; case TYPE_APP_LIST: Shell::GetInstance()->ToggleAppList(); break; case TYPE_BROWSER_SHORTCUT: if (event.flags() & ui::EF_CONTROL_DOWN) delegate_->CreateNewWindow(); else delegate_->CreateNewTab(); break; } }
170,887
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserEventRouter::TabPinnedStateChanged(WebContents* contents, int index) { TabStripModel* tab_strip = NULL; int tab_index; if (ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index)) { DictionaryValue* changed_properties = new DictionaryValue(); changed_properties->SetBoolean(tab_keys::kPinnedKey, tab_strip->IsTabPinned(tab_index)); DispatchTabUpdatedEvent(contents, changed_properties); } } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void BrowserEventRouter::TabPinnedStateChanged(WebContents* contents, int index) { TabStripModel* tab_strip = NULL; int tab_index; if (ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index)) { scoped_ptr<DictionaryValue> changed_properties(new DictionaryValue()); changed_properties->SetBoolean(tab_keys::kPinnedKey, tab_strip->IsTabPinned(tab_index)); DispatchTabUpdatedEvent(contents, changed_properties.Pass()); } }
171,451
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CoordinatorImpl::RequestGlobalMemoryDump( MemoryDumpType dump_type, MemoryDumpLevelOfDetail level_of_detail, const std::vector<std::string>& allocator_dump_names, const RequestGlobalMemoryDumpCallback& callback) { auto adapter = [](const RequestGlobalMemoryDumpCallback& callback, bool success, uint64_t, mojom::GlobalMemoryDumpPtr global_memory_dump) { callback.Run(success, std::move(global_memory_dump)); }; QueuedRequest::Args args(dump_type, level_of_detail, allocator_dump_names, false /* add_to_trace */, base::kNullProcessId); RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback)); } Commit Message: memory-infra: split up memory-infra coordinator service into two This allows for heap profiler to use its own service with correct capabilities and all other instances to use the existing coordinator service. Bug: 792028 Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd Reviewed-on: https://chromium-review.googlesource.com/836896 Commit-Queue: Lalit Maganti <lalitm@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: oysteine <oysteine@chromium.org> Reviewed-by: Albert J. Wong <ajwong@chromium.org> Reviewed-by: Hector Dearman <hjd@chromium.org> Cr-Commit-Position: refs/heads/master@{#529059} CWE ID: CWE-269
void CoordinatorImpl::RequestGlobalMemoryDump( MemoryDumpType dump_type, MemoryDumpLevelOfDetail level_of_detail, const std::vector<std::string>& allocator_dump_names, const RequestGlobalMemoryDumpCallback& callback) { // Don't allow arbitary processes to obtain VM regions. Only the heap profiler // is allowed to obtain them using the special method on the different // interface. if (level_of_detail == MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER) { bindings_.ReportBadMessage( "Requested global memory dump using level of detail reserved for the " "heap profiler."); return; } auto adapter = [](const RequestGlobalMemoryDumpCallback& callback, bool success, uint64_t, mojom::GlobalMemoryDumpPtr global_memory_dump) { callback.Run(success, std::move(global_memory_dump)); }; QueuedRequest::Args args(dump_type, level_of_detail, allocator_dump_names, false /* add_to_trace */, base::kNullProcessId); RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback)); }
172,915
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */
167,077
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void get_icu_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS) { const char* loc_name = NULL; int loc_name_len = 0; char* tag_value = NULL; char* empty_result = ""; int result = 0; char* msg = NULL; UErrorCode status = U_ZERO_ERROR; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name ,&loc_name_len ) == FAILURE) { spprintf(&msg , 0, "locale_get_%s : unable to parse input params", tag_name ); intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC ); efree(msg); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Call ICU get */ tag_value = get_icu_value_internal( loc_name , tag_name , &result ,0); /* No value found */ if( result == -1 ) { if( tag_value){ efree( tag_value); } RETURN_STRING( empty_result , TRUE); } /* value found */ if( tag_value){ RETURN_STRING( tag_value , FALSE); } /* Error encountered while fetching the value */ if( result ==0) { spprintf(&msg , 0, "locale_get_%s : unable to get locale %s", tag_name , tag_name ); intl_error_set( NULL, status, msg , 1 TSRMLS_CC ); efree(msg); RETURN_NULL(); } } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
static void get_icu_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS) static void get_icu_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS) { const char* loc_name = NULL; int loc_name_len = 0; char* tag_value = NULL; char* empty_result = ""; int result = 0; char* msg = NULL; UErrorCode status = U_ZERO_ERROR; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name ,&loc_name_len ) == FAILURE) { spprintf(&msg , 0, "locale_get_%s : unable to parse input params", tag_name ); intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC ); efree(msg); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Call ICU get */ tag_value = get_icu_value_internal( loc_name , tag_name , &result ,0); /* No value found */ if( result == -1 ) { if( tag_value){ efree( tag_value); } RETURN_STRING( empty_result , TRUE); } /* value found */ if( tag_value){ RETURN_STRING( tag_value , FALSE); } /* Error encountered while fetching the value */ if( result ==0) { spprintf(&msg , 0, "locale_get_%s : unable to get locale %s", tag_name , tag_name ); intl_error_set( NULL, status, msg , 1 TSRMLS_CC ); efree(msg); RETURN_NULL(); } }
167,206
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame) { const uint8_t* as_pack; int freq, stype, smpls, quant, i, ach; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack || !c->sys) { /* No audio ? */ c->ach = 0; return 0; } smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ stype = (as_pack[3] & 0x1f); /* 0 - 2CH, 2 - 4CH, 3 - 8CH */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ /* note: ach counts PAIRS of channels (i.e. stereo channels) */ ach = ((int[4]){ 1, 0, 2, 4})[stype]; if (ach == 1 && quant && freq == 2) if (!c->ast[i]) break; avpriv_set_pts_info(c->ast[i], 64, 1, 30000); c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO; c->ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE; av_init_packet(&c->audio_pkt[i]); c->audio_pkt[i].size = 0; c->audio_pkt[i].data = c->audio_buf[i]; c->audio_pkt[i].stream_index = c->ast[i]->index; c->audio_pkt[i].flags |= AV_PKT_FLAG_KEY; } Commit Message: CWE ID: CWE-20
static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame) { const uint8_t* as_pack; int freq, stype, smpls, quant, i, ach; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack || !c->sys) { /* No audio ? */ c->ach = 0; return 0; } smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ stype = (as_pack[3] & 0x1f); /* 0 - 2CH, 2 - 4CH, 3 - 8CH */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ if (stype > 3) { av_log(c->fctx, AV_LOG_ERROR, "stype %d is invalid\n", stype); c->ach = 0; return 0; } /* note: ach counts PAIRS of channels (i.e. stereo channels) */ ach = ((int[4]){ 1, 0, 2, 4})[stype]; if (ach == 1 && quant && freq == 2) if (!c->ast[i]) break; avpriv_set_pts_info(c->ast[i], 64, 1, 30000); c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO; c->ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE; av_init_packet(&c->audio_pkt[i]); c->audio_pkt[i].size = 0; c->audio_pkt[i].data = c->audio_buf[i]; c->audio_pkt[i].stream_index = c->ast[i]->index; c->audio_pkt[i].flags |= AV_PKT_FLAG_KEY; }
165,243
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(pg_trace) { char *z_filename, *mode = "w"; int z_filename_len, mode_len; zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; FILE *fp = NULL; php_stream *stream; id = PGG(default_link); if (zend_parse_parameters(argc TSRMLS_CC, "s|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) { return; } if (argc < 3) { CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL); if (!stream) { RETURN_FALSE; } if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { php_stream_close(stream); RETURN_FALSE; } php_stream_auto_cleanup(stream); PQtrace(pgsql, fp); RETURN_TRUE; } Commit Message: CWE ID: CWE-254
PHP_FUNCTION(pg_trace) { char *z_filename, *mode = "w"; int z_filename_len, mode_len; zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; FILE *fp = NULL; php_stream *stream; id = PGG(default_link); if (zend_parse_parameters(argc TSRMLS_CC, "p|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) { return; } if (argc < 3) { CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL); if (!stream) { RETURN_FALSE; } if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { php_stream_close(stream); RETURN_FALSE; } php_stream_auto_cleanup(stream); PQtrace(pgsql, fp); RETURN_TRUE; }
165,314
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DelegatedFrameHost::CopyFromCompositingSurface( const gfx::Rect& src_subrect, const gfx::Size& dst_size, const base::Callback<void(bool, const SkBitmap&)>& callback, const SkColorType color_type) { bool format_support = ((color_type == kRGB_565_SkColorType) || (color_type == kN32_SkColorType)); DCHECK(format_support); if (!CanCopyToBitmap()) { callback.Run(false, SkBitmap()); return; } const gfx::Size& dst_size_in_pixel = client_->ConvertViewSizeToPixel(dst_size); scoped_ptr<cc::CopyOutputRequest> request = cc::CopyOutputRequest::CreateRequest(base::Bind( &DelegatedFrameHost::CopyFromCompositingSurfaceHasResult, dst_size_in_pixel, color_type, callback)); gfx::Rect src_subrect_in_pixel = ConvertRectToPixel(client_->CurrentDeviceScaleFactor(), src_subrect); request->set_area(src_subrect_in_pixel); client_->RequestCopyOfOutput(request.Pass()); } Commit Message: repairs CopyFromCompositingSurface in HighDPI This CL removes the DIP=>Pixel transform in DelegatedFrameHost::CopyFromCompositingSurface(), because said transformation seems to be happening later in the copy logic and is currently being applied twice. BUG=397708 Review URL: https://codereview.chromium.org/421293002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@286414 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void DelegatedFrameHost::CopyFromCompositingSurface( const gfx::Rect& src_subrect, const gfx::Size& output_size, const base::Callback<void(bool, const SkBitmap&)>& callback, const SkColorType color_type) { bool format_support = ((color_type == kRGB_565_SkColorType) || (color_type == kN32_SkColorType)); DCHECK(format_support); if (!CanCopyToBitmap()) { callback.Run(false, SkBitmap()); return; } scoped_ptr<cc::CopyOutputRequest> request = cc::CopyOutputRequest::CreateRequest(base::Bind( &DelegatedFrameHost::CopyFromCompositingSurfaceHasResult, output_size, color_type, callback)); request->set_area(src_subrect); client_->RequestCopyOfOutput(request.Pass()); }
171,193
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlChar *prefix, const xmlChar *URI, int line, int nsNr, int tlen) { const xmlChar *name; GROW; if ((RAW != '<') || (NXT(1) != '/')) { xmlFatalErr(ctxt, XML_ERR_LTSLASH_REQUIRED, NULL); return; } SKIP(2); if ((tlen > 0) && (xmlStrncmp(ctxt->input->cur, ctxt->name, tlen) == 0)) { if (ctxt->input->cur[tlen] == '>') { ctxt->input->cur += tlen + 1; goto done; } ctxt->input->cur += tlen; name = (xmlChar*)1; } else { if (prefix == NULL) name = xmlParseNameAndCompare(ctxt, ctxt->name); else name = xmlParseQNameAndCompare(ctxt, ctxt->name, prefix); } /* * We should definitely be at the ending "S? '>'" part */ GROW; SKIP_BLANKS; if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) { xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL); } else NEXT1; /* * [ WFC: Element Type Match ] * The Name in an element's end-tag must match the element type in the * start-tag. * */ if (name != (xmlChar*)1) { if (name == NULL) name = BAD_CAST "unparseable"; if ((line == 0) && (ctxt->node != NULL)) line = ctxt->node->line; xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH, "Opening and ending tag mismatch: %s line %d and %s\n", ctxt->name, line, name); } /* * SAX: End of Tag */ done: if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, ctxt->name, prefix, URI); spacePop(ctxt); if (nsNr != 0) nsPop(ctxt, nsNr); return; } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlChar *prefix, const xmlChar *URI, int line, int nsNr, int tlen) { const xmlChar *name; GROW; if ((RAW != '<') || (NXT(1) != '/')) { xmlFatalErr(ctxt, XML_ERR_LTSLASH_REQUIRED, NULL); return; } SKIP(2); if ((tlen > 0) && (xmlStrncmp(ctxt->input->cur, ctxt->name, tlen) == 0)) { if (ctxt->input->cur[tlen] == '>') { ctxt->input->cur += tlen + 1; goto done; } ctxt->input->cur += tlen; name = (xmlChar*)1; } else { if (prefix == NULL) name = xmlParseNameAndCompare(ctxt, ctxt->name); else name = xmlParseQNameAndCompare(ctxt, ctxt->name, prefix); } /* * We should definitely be at the ending "S? '>'" part */ GROW; if (ctxt->instate == XML_PARSER_EOF) return; SKIP_BLANKS; if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) { xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL); } else NEXT1; /* * [ WFC: Element Type Match ] * The Name in an element's end-tag must match the element type in the * start-tag. * */ if (name != (xmlChar*)1) { if (name == NULL) name = BAD_CAST "unparseable"; if ((line == 0) && (ctxt->node != NULL)) line = ctxt->node->line; xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH, "Opening and ending tag mismatch: %s line %d and %s\n", ctxt->name, line, name); } /* * SAX: End of Tag */ done: if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, ctxt->name, prefix, URI); spacePop(ctxt); if (nsNr != 0) nsPop(ctxt, nsNr); return; }
171,287
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int UDPSocketWin::InternalConnect(const IPEndPoint& address) { DCHECK(!is_connected()); DCHECK(!remote_address_.get()); int addr_family = address.GetSockAddrFamily(); int rv = CreateSocket(addr_family); if (rv < 0) return rv; if (bind_type_ == DatagramSocket::RANDOM_BIND) { size_t addr_size = addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize; IPAddressNumber addr_any(addr_size); rv = RandomBind(addr_any); } if (rv < 0) { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", rv); Close(); return rv; } SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_ADDRESS_INVALID; rv = connect(socket_, storage.addr, storage.addr_len); if (rv < 0) { int result = MapSystemError(WSAGetLastError()); Close(); return result; } remote_address_.reset(new IPEndPoint(address)); return rv; } Commit Message: Map posix error codes in bind better, and fix one windows mapping. r=wtc BUG=330233 Review URL: https://codereview.chromium.org/101193008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
int UDPSocketWin::InternalConnect(const IPEndPoint& address) { DCHECK(!is_connected()); DCHECK(!remote_address_.get()); int addr_family = address.GetSockAddrFamily(); int rv = CreateSocket(addr_family); if (rv < 0) return rv; if (bind_type_ == DatagramSocket::RANDOM_BIND) { size_t addr_size = addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize; IPAddressNumber addr_any(addr_size); rv = RandomBind(addr_any); } if (rv < 0) { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", -rv); Close(); return rv; } SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_ADDRESS_INVALID; rv = connect(socket_, storage.addr, storage.addr_len); if (rv < 0) { int result = MapSystemError(WSAGetLastError()); Close(); return result; } remote_address_.reset(new IPEndPoint(address)); return rv; }
171,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MediaStreamImpl::~MediaStreamImpl() { DCHECK(!peer_connection_handler_); if (dependency_factory_.get()) dependency_factory_->ReleasePeerConnectionFactory(); if (network_manager_) { if (chrome_worker_thread_.IsRunning()) { chrome_worker_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &MediaStreamImpl::DeleteIpcNetworkManager, base::Unretained(this))); } else { NOTREACHED() << "Worker thread not running."; } } } Commit Message: Explicitly stopping thread in MediaStreamImpl dtor to avoid any racing issues. This may solve the below bugs. BUG=112408,111202 TEST=content_unittests Review URL: https://chromiumcodereview.appspot.com/9307058 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120222 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
MediaStreamImpl::~MediaStreamImpl() { DCHECK(!peer_connection_handler_); if (dependency_factory_.get()) dependency_factory_->ReleasePeerConnectionFactory(); if (network_manager_) { if (chrome_worker_thread_.IsRunning()) { chrome_worker_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &MediaStreamImpl::DeleteIpcNetworkManager, base::Unretained(this))); // Stopping the thread will wait until all tasks have been // processed before returning. We wait for the above task to finish before // letting the destructor continue to avoid any potential race issues. chrome_worker_thread_.Stop(); } else { NOTREACHED() << "Worker thread not running."; } } }
170,957
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nf_ct_frag6_reasm(struct nf_ct_frag6_queue *fq, struct net_device *dev) { struct sk_buff *fp, *op, *head = fq->q.fragments; int payload_len; fq_kill(fq); WARN_ON(head == NULL); WARN_ON(NFCT_FRAG6_CB(head)->offset != 0); /* Unfragmented part is taken from the first segment. */ payload_len = ((head->data - skb_network_header(head)) - sizeof(struct ipv6hdr) + fq->q.len - sizeof(struct frag_hdr)); if (payload_len > IPV6_MAXPLEN) { pr_debug("payload len is too large.\n"); goto out_oversize; } /* Head of list must not be cloned. */ if (skb_cloned(head) && pskb_expand_head(head, 0, 0, GFP_ATOMIC)) { pr_debug("skb is cloned but can't expand head"); goto out_oom; } /* If the first fragment is fragmented itself, we split * it to two chunks: the first with data and paged part * and the second, holding only fragments. */ if (skb_has_frags(head)) { struct sk_buff *clone; int i, plen = 0; if ((clone = alloc_skb(0, GFP_ATOMIC)) == NULL) { pr_debug("Can't alloc skb\n"); goto out_oom; } clone->next = head->next; head->next = clone; skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list; skb_frag_list_init(head); for (i=0; i<skb_shinfo(head)->nr_frags; i++) plen += skb_shinfo(head)->frags[i].size; clone->len = clone->data_len = head->data_len - plen; head->data_len -= clone->len; head->len -= clone->len; clone->csum = 0; clone->ip_summed = head->ip_summed; NFCT_FRAG6_CB(clone)->orig = NULL; atomic_add(clone->truesize, &nf_init_frags.mem); } /* We have to remove fragment header from datagram and to relocate * header in order to calculate ICV correctly. */ skb_network_header(head)[fq->nhoffset] = skb_transport_header(head)[0]; memmove(head->head + sizeof(struct frag_hdr), head->head, (head->data - head->head) - sizeof(struct frag_hdr)); head->mac_header += sizeof(struct frag_hdr); head->network_header += sizeof(struct frag_hdr); skb_shinfo(head)->frag_list = head->next; skb_reset_transport_header(head); skb_push(head, head->data - skb_network_header(head)); atomic_sub(head->truesize, &nf_init_frags.mem); for (fp=head->next; fp; fp = fp->next) { head->data_len += fp->len; head->len += fp->len; if (head->ip_summed != fp->ip_summed) head->ip_summed = CHECKSUM_NONE; else if (head->ip_summed == CHECKSUM_COMPLETE) head->csum = csum_add(head->csum, fp->csum); head->truesize += fp->truesize; atomic_sub(fp->truesize, &nf_init_frags.mem); } head->next = NULL; head->dev = dev; head->tstamp = fq->q.stamp; ipv6_hdr(head)->payload_len = htons(payload_len); /* Yes, and fold redundant checksum back. 8) */ if (head->ip_summed == CHECKSUM_COMPLETE) head->csum = csum_partial(skb_network_header(head), skb_network_header_len(head), head->csum); fq->q.fragments = NULL; /* all original skbs are linked into the NFCT_FRAG6_CB(head).orig */ fp = skb_shinfo(head)->frag_list; if (NFCT_FRAG6_CB(fp)->orig == NULL) /* at above code, head skb is divided into two skbs. */ fp = fp->next; op = NFCT_FRAG6_CB(head)->orig; for (; fp; fp = fp->next) { struct sk_buff *orig = NFCT_FRAG6_CB(fp)->orig; op->next = orig; op = orig; NFCT_FRAG6_CB(fp)->orig = NULL; } return head; out_oversize: if (net_ratelimit()) printk(KERN_DEBUG "nf_ct_frag6_reasm: payload len = %d\n", payload_len); goto out_fail; out_oom: if (net_ratelimit()) printk(KERN_DEBUG "nf_ct_frag6_reasm: no memory for reassembly\n"); out_fail: return NULL; } Commit Message: netfilter: nf_conntrack_reasm: properly handle packets fragmented into a single fragment When an ICMPV6_PKT_TOOBIG message is received with a MTU below 1280, all further packets include a fragment header. Unlike regular defragmentation, conntrack also needs to "reassemble" those fragments in order to obtain a packet without the fragment header for connection tracking. Currently nf_conntrack_reasm checks whether a fragment has either IP6_MF set or an offset != 0, which makes it ignore those fragments. Remove the invalid check and make reassembly handle fragment queues containing only a single fragment. Reported-and-tested-by: Ulrich Weber <uweber@astaro.com> Signed-off-by: Patrick McHardy <kaber@trash.net> CWE ID:
nf_ct_frag6_reasm(struct nf_ct_frag6_queue *fq, struct net_device *dev) { struct sk_buff *fp, *op, *head = fq->q.fragments; int payload_len; fq_kill(fq); WARN_ON(head == NULL); WARN_ON(NFCT_FRAG6_CB(head)->offset != 0); /* Unfragmented part is taken from the first segment. */ payload_len = ((head->data - skb_network_header(head)) - sizeof(struct ipv6hdr) + fq->q.len - sizeof(struct frag_hdr)); if (payload_len > IPV6_MAXPLEN) { pr_debug("payload len is too large.\n"); goto out_oversize; } /* Head of list must not be cloned. */ if (skb_cloned(head) && pskb_expand_head(head, 0, 0, GFP_ATOMIC)) { pr_debug("skb is cloned but can't expand head"); goto out_oom; } /* If the first fragment is fragmented itself, we split * it to two chunks: the first with data and paged part * and the second, holding only fragments. */ if (skb_has_frags(head)) { struct sk_buff *clone; int i, plen = 0; if ((clone = alloc_skb(0, GFP_ATOMIC)) == NULL) { pr_debug("Can't alloc skb\n"); goto out_oom; } clone->next = head->next; head->next = clone; skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list; skb_frag_list_init(head); for (i=0; i<skb_shinfo(head)->nr_frags; i++) plen += skb_shinfo(head)->frags[i].size; clone->len = clone->data_len = head->data_len - plen; head->data_len -= clone->len; head->len -= clone->len; clone->csum = 0; clone->ip_summed = head->ip_summed; NFCT_FRAG6_CB(clone)->orig = NULL; atomic_add(clone->truesize, &nf_init_frags.mem); } /* We have to remove fragment header from datagram and to relocate * header in order to calculate ICV correctly. */ skb_network_header(head)[fq->nhoffset] = skb_transport_header(head)[0]; memmove(head->head + sizeof(struct frag_hdr), head->head, (head->data - head->head) - sizeof(struct frag_hdr)); head->mac_header += sizeof(struct frag_hdr); head->network_header += sizeof(struct frag_hdr); skb_shinfo(head)->frag_list = head->next; skb_reset_transport_header(head); skb_push(head, head->data - skb_network_header(head)); atomic_sub(head->truesize, &nf_init_frags.mem); for (fp=head->next; fp; fp = fp->next) { head->data_len += fp->len; head->len += fp->len; if (head->ip_summed != fp->ip_summed) head->ip_summed = CHECKSUM_NONE; else if (head->ip_summed == CHECKSUM_COMPLETE) head->csum = csum_add(head->csum, fp->csum); head->truesize += fp->truesize; atomic_sub(fp->truesize, &nf_init_frags.mem); } head->next = NULL; head->dev = dev; head->tstamp = fq->q.stamp; ipv6_hdr(head)->payload_len = htons(payload_len); /* Yes, and fold redundant checksum back. 8) */ if (head->ip_summed == CHECKSUM_COMPLETE) head->csum = csum_partial(skb_network_header(head), skb_network_header_len(head), head->csum); fq->q.fragments = NULL; /* all original skbs are linked into the NFCT_FRAG6_CB(head).orig */ fp = skb_shinfo(head)->frag_list; if (fp && NFCT_FRAG6_CB(fp)->orig == NULL) /* at above code, head skb is divided into two skbs. */ fp = fp->next; op = NFCT_FRAG6_CB(head)->orig; for (; fp; fp = fp->next) { struct sk_buff *orig = NFCT_FRAG6_CB(fp)->orig; op->next = orig; op = orig; NFCT_FRAG6_CB(fp)->orig = NULL; } return head; out_oversize: if (net_ratelimit()) printk(KERN_DEBUG "nf_ct_frag6_reasm: payload len = %d\n", payload_len); goto out_fail; out_oom: if (net_ratelimit()) printk(KERN_DEBUG "nf_ct_frag6_reasm: no memory for reassembly\n"); out_fail: return NULL; }
165,591
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) { assert(pReader); assert(pos >= 0); int status; len = 1; unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) // error or underflow return status; if (status > 0) // interpreted as "underflow" return E_BUFFER_NOT_FULL; if (b == 0) // we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } long long result = b & (~m); ++pos; for (int i = 1; i < len; ++i) { status = pReader->Read(pos, 1, &b); if (status < 0) { len = 1; return status; } if (status > 0) { len = 1; return E_BUFFER_NOT_FULL; } result <<= 8; result |= b; ++pos; } return result; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) { long long ReadUInt(IMkvReader* pReader, long long pos, long& len) { if (!pReader || pos < 0) return E_FILE_FORMAT_INVALID; len = 1; unsigned char b; int status = pReader->Read(pos, 1, &b); if (status < 0) // error or underflow return status; if (status > 0) // interpreted as "underflow" return E_BUFFER_NOT_FULL; if (b == 0) // we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } long long result = b & (~m); ++pos; for (int i = 1; i < len; ++i) { status = pReader->Read(pos, 1, &b); if (status < 0) { len = 1; return status; } if (status > 0) { len = 1; return E_BUFFER_NOT_FULL; } result <<= 8; result |= b; ++pos; } return result; }
173,862
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AddMainWebResources(content::WebUIDataSource* html_source) { html_source->AddResourcePath("media_router.js", IDR_MEDIA_ROUTER_JS); html_source->AddResourcePath("media_router_common.css", IDR_MEDIA_ROUTER_COMMON_CSS); html_source->AddResourcePath("media_router.css", IDR_MEDIA_ROUTER_CSS); html_source->AddResourcePath("media_router_data.js", IDR_MEDIA_ROUTER_DATA_JS); html_source->AddResourcePath("media_router_ui_interface.js", IDR_MEDIA_ROUTER_UI_INTERFACE_JS); html_source->AddResourcePath("polymer_config.js", IDR_MEDIA_ROUTER_POLYMER_CONFIG_JS); } Commit Message: One polymer_config.js to rule them all. R=michaelpg@chromium.org,fukino@chromium.org,mfoltz@chromium.org BUG=425626 Review URL: https://codereview.chromium.org/1224783005 Cr-Commit-Position: refs/heads/master@{#337882} CWE ID: CWE-399
void AddMainWebResources(content::WebUIDataSource* html_source) { html_source->AddResourcePath("media_router.js", IDR_MEDIA_ROUTER_JS); html_source->AddResourcePath("media_router_common.css", IDR_MEDIA_ROUTER_COMMON_CSS); html_source->AddResourcePath("media_router.css", IDR_MEDIA_ROUTER_CSS); html_source->AddResourcePath("media_router_data.js", IDR_MEDIA_ROUTER_DATA_JS); html_source->AddResourcePath("media_router_ui_interface.js", IDR_MEDIA_ROUTER_UI_INTERFACE_JS); }
171,708
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_write_destroy(png_structp png_ptr) { #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* Save jump buffer */ #endif png_error_ptr error_fn; png_error_ptr warning_fn; png_voidp error_ptr; #ifdef PNG_USER_MEM_SUPPORTED png_free_ptr free_fn; #endif png_debug(1, "in png_write_destroy"); /* Free any memory zlib uses */ deflateEnd(&png_ptr->zstream); /* Free our memory. png_free checks NULL for us. */ png_free(png_ptr, png_ptr->zbuf); png_free(png_ptr, png_ptr->row_buf); #ifdef PNG_WRITE_FILTER_SUPPORTED png_free(png_ptr, png_ptr->prev_row); png_free(png_ptr, png_ptr->sub_row); png_free(png_ptr, png_ptr->up_row); png_free(png_ptr, png_ptr->avg_row); png_free(png_ptr, png_ptr->paeth_row); #endif #ifdef PNG_TIME_RFC1123_SUPPORTED png_free(png_ptr, png_ptr->time_buffer); #endif #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED png_free(png_ptr, png_ptr->prev_filters); png_free(png_ptr, png_ptr->filter_weights); png_free(png_ptr, png_ptr->inv_filter_weights); png_free(png_ptr, png_ptr->filter_costs); png_free(png_ptr, png_ptr->inv_filter_costs); #endif #ifdef PNG_SETJMP_SUPPORTED /* Reset structure */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif error_fn = png_ptr->error_fn; warning_fn = png_ptr->warning_fn; error_ptr = png_ptr->error_ptr; #ifdef PNG_USER_MEM_SUPPORTED free_fn = png_ptr->free_fn; #endif png_memset(png_ptr, 0, png_sizeof(png_struct)); png_ptr->error_fn = error_fn; png_ptr->warning_fn = warning_fn; png_ptr->error_ptr = error_ptr; #ifdef PNG_USER_MEM_SUPPORTED png_ptr->free_fn = free_fn; #endif #ifdef PNG_SETJMP_SUPPORTED png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_write_destroy(png_structp png_ptr) { #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* Save jump buffer */ #endif png_error_ptr error_fn; png_error_ptr warning_fn; png_voidp error_ptr; #ifdef PNG_USER_MEM_SUPPORTED png_free_ptr free_fn; #endif png_debug(1, "in png_write_destroy"); /* Free any memory zlib uses */ deflateEnd(&png_ptr->zstream); /* Free our memory. png_free checks NULL for us. */ png_free(png_ptr, png_ptr->zbuf); png_free(png_ptr, png_ptr->row_buf); #ifdef PNG_WRITE_FILTER_SUPPORTED png_free(png_ptr, png_ptr->prev_row); png_free(png_ptr, png_ptr->sub_row); png_free(png_ptr, png_ptr->up_row); png_free(png_ptr, png_ptr->avg_row); png_free(png_ptr, png_ptr->paeth_row); #endif #ifdef PNG_TIME_RFC1123_SUPPORTED png_free(png_ptr, png_ptr->time_buffer); #endif #ifdef PNG_SETJMP_SUPPORTED /* Reset structure */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif error_fn = png_ptr->error_fn; warning_fn = png_ptr->warning_fn; error_ptr = png_ptr->error_ptr; #ifdef PNG_USER_MEM_SUPPORTED free_fn = png_ptr->free_fn; #endif png_memset(png_ptr, 0, png_sizeof(png_struct)); png_ptr->error_fn = error_fn; png_ptr->warning_fn = warning_fn; png_ptr->error_ptr = error_ptr; #ifdef PNG_USER_MEM_SUPPORTED png_ptr->free_fn = free_fn; #endif #ifdef PNG_SETJMP_SUPPORTED png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif }
172,189
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: dissect_rpcap_packet (tvbuff_t *tvb, packet_info *pinfo, proto_tree *top_tree, proto_tree *parent_tree, gint offset, proto_item *top_item) { proto_tree *tree; proto_item *ti; nstime_t ts; tvbuff_t *new_tvb; guint caplen, len, frame_no; gint reported_length_remaining; ti = proto_tree_add_item (parent_tree, hf_packet, tvb, offset, 20, ENC_NA); tree = proto_item_add_subtree (ti, ett_packet); ts.secs = tvb_get_ntohl (tvb, offset); ts.nsecs = tvb_get_ntohl (tvb, offset + 4) * 1000; proto_tree_add_time(tree, hf_timestamp, tvb, offset, 8, &ts); offset += 8; caplen = tvb_get_ntohl (tvb, offset); ti = proto_tree_add_item (tree, hf_caplen, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; len = tvb_get_ntohl (tvb, offset); proto_tree_add_item (tree, hf_len, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; frame_no = tvb_get_ntohl (tvb, offset); proto_tree_add_item (tree, hf_npkt, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; proto_item_append_text (ti, ", Frame %u", frame_no); proto_item_append_text (top_item, " Frame %u", frame_no); /* * reported_length_remaining should not be -1, as offset is at * most right past the end of the available data in the packet. */ reported_length_remaining = tvb_reported_length_remaining (tvb, offset); if (caplen > (guint)reported_length_remaining) { expert_add_info(pinfo, ti, &ei_caplen_too_big); return; } new_tvb = tvb_new_subset (tvb, offset, caplen, len); if (decode_content && linktype != WTAP_ENCAP_UNKNOWN) { dissector_try_uint(wtap_encap_dissector_table, linktype, new_tvb, pinfo, top_tree); if (!info_added) { /* Only indicate when not added before */ /* Indicate RPCAP in the protocol column */ col_prepend_fence_fstr(pinfo->cinfo, COL_PROTOCOL, "R|"); /* Indicate RPCAP in the info column */ col_prepend_fence_fstr (pinfo->cinfo, COL_INFO, "Remote | "); info_added = TRUE; register_frame_end_routine(pinfo, rpcap_frame_end); } } else { if (linktype == WTAP_ENCAP_UNKNOWN) { proto_item_append_text (ti, ", Unknown link-layer type"); } call_dissector (data_handle, new_tvb, pinfo, top_tree); } } Commit Message: The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr. We now require that. Make it so. Bug: 12440 Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76 Reviewed-on: https://code.wireshark.org/review/15424 Reviewed-by: Guy Harris <guy@alum.mit.edu> CWE ID: CWE-20
dissect_rpcap_packet (tvbuff_t *tvb, packet_info *pinfo, proto_tree *top_tree, proto_tree *parent_tree, gint offset, proto_item *top_item) { proto_tree *tree; proto_item *ti; nstime_t ts; tvbuff_t *new_tvb; guint caplen, len, frame_no; gint reported_length_remaining; struct eth_phdr eth; void *phdr; ti = proto_tree_add_item (parent_tree, hf_packet, tvb, offset, 20, ENC_NA); tree = proto_item_add_subtree (ti, ett_packet); ts.secs = tvb_get_ntohl (tvb, offset); ts.nsecs = tvb_get_ntohl (tvb, offset + 4) * 1000; proto_tree_add_time(tree, hf_timestamp, tvb, offset, 8, &ts); offset += 8; caplen = tvb_get_ntohl (tvb, offset); ti = proto_tree_add_item (tree, hf_caplen, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; len = tvb_get_ntohl (tvb, offset); proto_tree_add_item (tree, hf_len, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; frame_no = tvb_get_ntohl (tvb, offset); proto_tree_add_item (tree, hf_npkt, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; proto_item_append_text (ti, ", Frame %u", frame_no); proto_item_append_text (top_item, " Frame %u", frame_no); /* * reported_length_remaining should not be -1, as offset is at * most right past the end of the available data in the packet. */ reported_length_remaining = tvb_reported_length_remaining (tvb, offset); if (caplen > (guint)reported_length_remaining) { expert_add_info(pinfo, ti, &ei_caplen_too_big); return; } new_tvb = tvb_new_subset (tvb, offset, caplen, len); if (decode_content && linktype != WTAP_ENCAP_UNKNOWN) { switch (linktype) { case WTAP_ENCAP_ETHERNET: eth.fcs_len = -1; /* Unknown whether we have an FCS */ phdr = &eth; break; default: phdr = NULL; break; } dissector_try_uint_new(wtap_encap_dissector_table, linktype, new_tvb, pinfo, top_tree, TRUE, phdr); if (!info_added) { /* Only indicate when not added before */ /* Indicate RPCAP in the protocol column */ col_prepend_fence_fstr(pinfo->cinfo, COL_PROTOCOL, "R|"); /* Indicate RPCAP in the info column */ col_prepend_fence_fstr (pinfo->cinfo, COL_INFO, "Remote | "); info_added = TRUE; register_frame_end_routine(pinfo, rpcap_frame_end); } } else { if (linktype == WTAP_ENCAP_UNKNOWN) { proto_item_append_text (ti, ", Unknown link-layer type"); } call_dissector (data_handle, new_tvb, pinfo, top_tree); } }
167,145
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfs4_xdr_dec_getacl(struct rpc_rqst *rqstp, struct xdr_stream *xdr, struct nfs_getaclres *res) { struct compound_hdr hdr; int status; status = decode_compound_hdr(xdr, &hdr); if (status) goto out; status = decode_sequence(xdr, &res->seq_res, rqstp); if (status) goto out; status = decode_putfh(xdr); if (status) goto out; status = decode_getacl(xdr, rqstp, &res->acl_len); out: return status; } Commit Message: NFSv4: include bitmap in nfsv4 get acl data The NFSv4 bitmap size is unbounded: a server can return an arbitrary sized bitmap in an FATTR4_WORD0_ACL request. Replace using the nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data xdr length to the (cached) acl page data. This is a general solution to commit e5012d1f "NFSv4.1: update nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead when getting ACLs. Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved. Cc: stable@kernel.org Signed-off-by: Andy Adamson <andros@netapp.com> Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID: CWE-189
nfs4_xdr_dec_getacl(struct rpc_rqst *rqstp, struct xdr_stream *xdr, struct nfs_getaclres *res) { struct compound_hdr hdr; int status; status = decode_compound_hdr(xdr, &hdr); if (status) goto out; status = decode_sequence(xdr, &res->seq_res, rqstp); if (status) goto out; status = decode_putfh(xdr); if (status) goto out; status = decode_getacl(xdr, rqstp, res); out: return status; }
165,720
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui) : ConstrainedWebDialogUI(web_ui), initial_preview_start_time_(base::TimeTicks::Now()), handler_(NULL), source_is_modifiable_(true), tab_closed_(false) { Profile* profile = Profile::FromWebUI(web_ui); ChromeURLDataManager::AddDataSource(profile, new PrintPreviewDataSource()); handler_ = new PrintPreviewHandler(); web_ui->AddMessageHandler(handler_); preview_ui_addr_str_ = GetPrintPreviewUIAddress(); g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, -1); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui) : ConstrainedWebDialogUI(web_ui), initial_preview_start_time_(base::TimeTicks::Now()), id_(g_print_preview_ui_id_map.Get().Add(this)), handler_(NULL), source_is_modifiable_(true), tab_closed_(false) { Profile* profile = Profile::FromWebUI(web_ui); ChromeURLDataManager::AddDataSource(profile, new PrintPreviewDataSource()); handler_ = new PrintPreviewHandler(); web_ui->AddMessageHandler(handler_); g_print_preview_request_id_map.Get().Set(id_, -1); }
170,841
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool check_client_passwd(PgSocket *client, const char *passwd) { char md5[MD5_PASSWD_LEN + 1]; const char *correct; PgUser *user = client->auth_user; /* disallow empty passwords */ if (!*passwd || !*user->passwd) return false; switch (cf_auth_type) { case AUTH_PLAIN: return strcmp(user->passwd, passwd) == 0; case AUTH_CRYPT: correct = crypt(user->passwd, (char *)client->tmp_login_salt); return correct && strcmp(correct, passwd) == 0; case AUTH_MD5: if (strlen(passwd) != MD5_PASSWD_LEN) return false; if (!isMD5(user->passwd)) pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd); pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5); return strcmp(md5, passwd) == 0; } return false; } Commit Message: Check if auth_user is set. Fixes a crash if password packet appears before startup packet (#42). CWE ID: CWE-476
static bool check_client_passwd(PgSocket *client, const char *passwd) { char md5[MD5_PASSWD_LEN + 1]; const char *correct; PgUser *user = client->auth_user; /* auth_user may be missing */ if (!user) { slog_error(client, "Password packet before auth packet?"); return false; } /* disallow empty passwords */ if (!*passwd || !*user->passwd) return false; switch (cf_auth_type) { case AUTH_PLAIN: return strcmp(user->passwd, passwd) == 0; case AUTH_CRYPT: correct = crypt(user->passwd, (char *)client->tmp_login_salt); return correct && strcmp(correct, passwd) == 0; case AUTH_MD5: if (strlen(passwd) != MD5_PASSWD_LEN) return false; if (!isMD5(user->passwd)) pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd); pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5); return strcmp(md5, passwd) == 0; } return false; }
170,132
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ResetScreenHandler::UpdateStatusChanged( const UpdateEngineClient::Status& status) { if (status.status == UpdateEngineClient::UPDATE_STATUS_ERROR) { base::DictionaryValue params; params.SetInteger("uiState", kErrorUIStateRollback); ShowScreen(OobeUI::kScreenErrorMessage, &params); } else if (status.status == UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT) { DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart(); } } Commit Message: Rollback option put behind the flag. BUG=368860 Review URL: https://codereview.chromium.org/267393011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@269753 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void ResetScreenHandler::UpdateStatusChanged( const UpdateEngineClient::Status& status) { VLOG(1) << "Update status change to " << status.status; if (status.status == UpdateEngineClient::UPDATE_STATUS_ERROR) { base::DictionaryValue params; params.SetInteger("uiState", kErrorUIStateRollback); ShowScreen(OobeUI::kScreenErrorMessage, &params); } else if (status.status == UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT) { DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart(); } }
171,182
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GesturePoint::IsOverMinFlickSpeed() { return velocity_calculator_.VelocitySquared() > kMinFlickSpeedSquared; } Commit Message: Add setters for the aura gesture recognizer constants. BUG=113227 TEST=none Review URL: http://codereview.chromium.org/9372040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool GesturePoint::IsOverMinFlickSpeed() { return velocity_calculator_.VelocitySquared() > GestureConfiguration::min_flick_speed_squared(); }
171,045
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: usage(int iExitCode) { char word[32]; sprintf( word, getJobActionString(mode) ); fprintf( stderr, "Usage: %s [options] [constraints]\n", MyName ); fprintf( stderr, " where [options] is zero or more of:\n" ); fprintf( stderr, " -help Display this message and exit\n" ); fprintf( stderr, " -version Display version information and exit\n" ); fprintf( stderr, " -name schedd_name Connect to the given schedd\n" ); fprintf( stderr, " -pool hostname Use the given central manager to find daemons\n" ); fprintf( stderr, " -addr <ip:port> Connect directly to the given \"sinful string\"\n" ); if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) { fprintf( stderr, " -reason reason Use the given RemoveReason\n"); } else if( mode == JA_RELEASE_JOBS ) { fprintf( stderr, " -reason reason Use the given ReleaseReason\n"); } else if( mode == JA_HOLD_JOBS ) { fprintf( stderr, " -reason reason Use the given HoldReason\n"); fprintf( stderr, " -subcode number Set HoldReasonSubCode\n"); } if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) { fprintf( stderr, " -forcex Force the immediate local removal of jobs in the X state\n" " (only affects jobs already being removed)\n" ); } if( mode == JA_VACATE_JOBS || mode == JA_VACATE_FAST_JOBS ) { fprintf( stderr, " -fast Use a fast vacate (hardkill)\n" ); } fprintf( stderr, " and where [constraints] is one of:\n" ); fprintf( stderr, " cluster.proc %s the given job\n", word ); fprintf( stderr, " cluster %s the given cluster of jobs\n", word ); fprintf( stderr, " user %s all jobs owned by user\n", word ); fprintf( stderr, " -constraint expr %s all jobs matching the boolean expression\n", word ); fprintf( stderr, " -all %s all jobs " "(cannot be used with other constraints)\n", word ); exit( iExitCode ); } Commit Message: CWE ID: CWE-134
usage(int iExitCode) { char word[32]; sprintf( word, "%s", getJobActionString(mode) ); fprintf( stderr, "Usage: %s [options] [constraints]\n", MyName ); fprintf( stderr, " where [options] is zero or more of:\n" ); fprintf( stderr, " -help Display this message and exit\n" ); fprintf( stderr, " -version Display version information and exit\n" ); fprintf( stderr, " -name schedd_name Connect to the given schedd\n" ); fprintf( stderr, " -pool hostname Use the given central manager to find daemons\n" ); fprintf( stderr, " -addr <ip:port> Connect directly to the given \"sinful string\"\n" ); if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) { fprintf( stderr, " -reason reason Use the given RemoveReason\n"); } else if( mode == JA_RELEASE_JOBS ) { fprintf( stderr, " -reason reason Use the given ReleaseReason\n"); } else if( mode == JA_HOLD_JOBS ) { fprintf( stderr, " -reason reason Use the given HoldReason\n"); fprintf( stderr, " -subcode number Set HoldReasonSubCode\n"); } if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) { fprintf( stderr, " -forcex Force the immediate local removal of jobs in the X state\n" " (only affects jobs already being removed)\n" ); } if( mode == JA_VACATE_JOBS || mode == JA_VACATE_FAST_JOBS ) { fprintf( stderr, " -fast Use a fast vacate (hardkill)\n" ); } fprintf( stderr, " and where [constraints] is one of:\n" ); fprintf( stderr, " cluster.proc %s the given job\n", word ); fprintf( stderr, " cluster %s the given cluster of jobs\n", word ); fprintf( stderr, " user %s all jobs owned by user\n", word ); fprintf( stderr, " -constraint expr %s all jobs matching the boolean expression\n", word ); fprintf( stderr, " -all %s all jobs " "(cannot be used with other constraints)\n", word ); exit( iExitCode ); }
165,375
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderFrameImpl::OnSelectPopupMenuItems( bool canceled, const std::vector<int>& selected_indices) { if (!external_popup_menu_) return; blink::WebScopedUserGesture gesture(frame_); external_popup_menu_->DidSelectItems(canceled, selected_indices); external_popup_menu_.reset(); } Commit Message: Fix crashes in RenderFrameImpl::OnSelectPopupMenuItem(s) ExternalPopupMenu::DidSelectItem(s) can delete the RenderFrameImpl. We need to reset external_popup_menu_ before calling it. Bug: 912211 Change-Id: Ia9a628e144464a2ebb14ab77d3a693fd5cead6fc Reviewed-on: https://chromium-review.googlesource.com/c/1381325 Commit-Queue: Kent Tamura <tkent@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#618026} CWE ID: CWE-416
void RenderFrameImpl::OnSelectPopupMenuItems( bool canceled, const std::vector<int>& selected_indices) { if (!external_popup_menu_) return; blink::WebScopedUserGesture gesture(frame_); // We need to reset |external_popup_menu_| before calling DidSelectItems(), // which might delete |this|. // See ExternalPopupMenuRemoveTest.RemoveFrameOnChange std::unique_ptr<ExternalPopupMenu> popup; popup.swap(external_popup_menu_); popup->DidSelectItems(canceled, selected_indices); }
173,073
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AppCacheBackendImpl::SelectCache( int host_id, const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { AppCacheHost* host = GetHost(host_id); if (!host || host->was_select_cache_called()) return false; host->SelectCache(document_url, cache_document_was_loaded_from, manifest_url); return true; } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
bool AppCacheBackendImpl::SelectCache( int host_id, const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { AppCacheHost* host = GetHost(host_id); if (!host) return false; return host->SelectCache(document_url, cache_document_was_loaded_from, manifest_url); }
171,736
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int http_connect(http_subtransport *t) { int error; char *proxy_url; if (t->connected && http_should_keep_alive(&t->parser) && t->parse_finished) return 0; if (t->io) { git_stream_close(t->io); git_stream_free(t->io); t->io = NULL; t->connected = 0; } if (t->connection_data.use_ssl) { error = git_tls_stream_new(&t->io, t->connection_data.host, t->connection_data.port); } else { #ifdef GIT_CURL error = git_curl_stream_new(&t->io, t->connection_data.host, t->connection_data.port); #else error = git_socket_stream_new(&t->io, t->connection_data.host, t->connection_data.port); #endif } if (error < 0) return error; GITERR_CHECK_VERSION(t->io, GIT_STREAM_VERSION, "git_stream"); if (git_stream_supports_proxy(t->io) && !git_remote__get_http_proxy(t->owner->owner, !!t->connection_data.use_ssl, &proxy_url)) { error = git_stream_set_proxy(t->io, proxy_url); git__free(proxy_url); if (error < 0) return error; } error = git_stream_connect(t->io); #if defined(GIT_OPENSSL) || defined(GIT_SECURE_TRANSPORT) || defined(GIT_CURL) if ((!error || error == GIT_ECERTIFICATE) && t->owner->certificate_check_cb != NULL && git_stream_is_encrypted(t->io)) { git_cert *cert; int is_valid; if ((error = git_stream_certificate(&cert, t->io)) < 0) return error; giterr_clear(); is_valid = error != GIT_ECERTIFICATE; error = t->owner->certificate_check_cb(cert, is_valid, t->connection_data.host, t->owner->message_cb_payload); if (error < 0) { if (!giterr_last()) giterr_set(GITERR_NET, "user cancelled certificate check"); return error; } } #endif if (error < 0) return error; t->connected = 1; return 0; } Commit Message: http: check certificate validity before clobbering the error variable CWE ID: CWE-284
static int http_connect(http_subtransport *t) { int error; char *proxy_url; if (t->connected && http_should_keep_alive(&t->parser) && t->parse_finished) return 0; if (t->io) { git_stream_close(t->io); git_stream_free(t->io); t->io = NULL; t->connected = 0; } if (t->connection_data.use_ssl) { error = git_tls_stream_new(&t->io, t->connection_data.host, t->connection_data.port); } else { #ifdef GIT_CURL error = git_curl_stream_new(&t->io, t->connection_data.host, t->connection_data.port); #else error = git_socket_stream_new(&t->io, t->connection_data.host, t->connection_data.port); #endif } if (error < 0) return error; GITERR_CHECK_VERSION(t->io, GIT_STREAM_VERSION, "git_stream"); if (git_stream_supports_proxy(t->io) && !git_remote__get_http_proxy(t->owner->owner, !!t->connection_data.use_ssl, &proxy_url)) { error = git_stream_set_proxy(t->io, proxy_url); git__free(proxy_url); if (error < 0) return error; } error = git_stream_connect(t->io); #if defined(GIT_OPENSSL) || defined(GIT_SECURE_TRANSPORT) || defined(GIT_CURL) if ((!error || error == GIT_ECERTIFICATE) && t->owner->certificate_check_cb != NULL && git_stream_is_encrypted(t->io)) { git_cert *cert; int is_valid = (error == GIT_OK); if ((error = git_stream_certificate(&cert, t->io)) < 0) return error; giterr_clear(); error = t->owner->certificate_check_cb(cert, is_valid, t->connection_data.host, t->owner->message_cb_payload); if (error < 0) { if (!giterr_last()) giterr_set(GITERR_NET, "user cancelled certificate check"); return error; } } #endif if (error < 0) return error; t->connected = 1; return 0; }
170,109
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly) { ASSERT(&topResolver.runs() == &bidiRuns); ASSERT(topResolver.position() != endOfRuns); RenderObject* currentRoot = topResolver.position().root(); topResolver.createBidiRunsForLine(endOfRuns, override, previousLineBrokeCleanly); while (!topResolver.isolatedRuns().isEmpty()) { BidiRun* isolatedRun = topResolver.isolatedRuns().last(); topResolver.isolatedRuns().removeLast(); RenderObject* startObj = isolatedRun->object(); RenderInline* isolatedInline = toRenderInline(containingIsolate(startObj, currentRoot)); InlineBidiResolver isolatedResolver; EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi(); TextDirection direction = isolatedInline->style()->direction(); if (unicodeBidi == Plaintext) direction = determinePlaintextDirectionality(isolatedInline, startObj); else { ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride); direction = isolatedInline->style()->direction(); } isolatedResolver.setStatus(statusWithDirection(direction, isOverride(unicodeBidi))); setupResolverToResumeInIsolate(isolatedResolver, isolatedInline, startObj); InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start); isolatedResolver.setPositionIgnoringNestedIsolates(iter); isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly); if (isolatedResolver.runs().runCount()) bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs()); if (!isolatedResolver.isolatedRuns().isEmpty()) { topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns()); isolatedResolver.isolatedRuns().clear(); currentRoot = isolatedInline; } } } Commit Message: Update containtingIsolate to go back all the way to top isolate from current root, rather than stopping at the first isolate it finds. This works because the current root is always updated with each isolate run. BUG=279277 Review URL: https://chromiumcodereview.appspot.com/23972003 git-svn-id: svn://svn.chromium.org/blink/trunk@157268 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly) { ASSERT(&topResolver.runs() == &bidiRuns); ASSERT(topResolver.position() != endOfRuns); RenderObject* currentRoot = topResolver.position().root(); topResolver.createBidiRunsForLine(endOfRuns, override, previousLineBrokeCleanly); while (!topResolver.isolatedRuns().isEmpty()) { BidiRun* isolatedRun = topResolver.isolatedRuns().last(); topResolver.isolatedRuns().removeLast(); RenderObject* startObj = isolatedRun->object(); RenderInline* isolatedInline = toRenderInline(highestContainingIsolateWithinRoot(startObj, currentRoot)); ASSERT(isolatedInline); InlineBidiResolver isolatedResolver; EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi(); TextDirection direction = isolatedInline->style()->direction(); if (unicodeBidi == Plaintext) direction = determinePlaintextDirectionality(isolatedInline, startObj); else { ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride); direction = isolatedInline->style()->direction(); } isolatedResolver.setStatus(statusWithDirection(direction, isOverride(unicodeBidi))); setupResolverToResumeInIsolate(isolatedResolver, isolatedInline, startObj); InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start); isolatedResolver.setPositionIgnoringNestedIsolates(iter); isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly); if (isolatedResolver.runs().runCount()) bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs()); if (!isolatedResolver.isolatedRuns().isEmpty()) { topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns()); isolatedResolver.isolatedRuns().clear(); currentRoot = isolatedInline; } } }
171,180
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CloudPolicyController::StopAutoRetry() { scheduler_->CancelDelayedWork(); backend_.reset(); } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void CloudPolicyController::StopAutoRetry() { void CloudPolicyController::Reset() { SetState(STATE_TOKEN_UNAVAILABLE); }
170,282
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { ////jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))))); stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); } } Commit Message: Changed the JPC bitstream code to more gracefully handle a request for a larger sized integer than what can be handled (i.e., return with an error instead of failing an assert). CWE ID:
static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { ////jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))))); stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); } }
168,735
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CheckSADs() { unsigned int reference_sad, exp_sad[4]; SADs(exp_sad); for (int block = 0; block < 4; block++) { reference_sad = ReferenceSAD(UINT_MAX, block); EXPECT_EQ(exp_sad[block], reference_sad) << "block " << block; } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void CheckSADs() { unsigned int reference_sad, exp_sad[4]; SADs(exp_sad); for (int block = 0; block < 4; ++block) { reference_sad = ReferenceSAD(block); EXPECT_EQ(reference_sad, exp_sad[block]) << "block " << block; } }
174,569
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void tokenadd(struct jv_parser* p, char c) { assert(p->tokenpos <= p->tokenlen); if (p->tokenpos == p->tokenlen) { p->tokenlen = p->tokenlen*2 + 256; p->tokenbuf = jv_mem_realloc(p->tokenbuf, p->tokenlen); } assert(p->tokenpos < p->tokenlen); p->tokenbuf[p->tokenpos++] = c; } Commit Message: Heap buffer overflow in tokenadd() (fix #105) This was an off-by one: the NUL terminator byte was not allocated on resize. This was triggered by JSON-encoded numbers longer than 256 bytes. CWE ID: CWE-119
static void tokenadd(struct jv_parser* p, char c) { assert(p->tokenpos <= p->tokenlen); if (p->tokenpos >= (p->tokenlen - 1)) { p->tokenlen = p->tokenlen*2 + 256; p->tokenbuf = jv_mem_realloc(p->tokenbuf, p->tokenlen); } assert(p->tokenpos < p->tokenlen); p->tokenbuf[p->tokenpos++] = c; }
167,477
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static opj_bool pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } Commit Message: [MJ2] Avoid index out of bounds access to pi->include[] Signed-off-by: Young_X <YangX92@hotmail.com> CWE ID: CWE-20
static opj_bool pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; /* Avoids index out of bounds access with include*/ if (index >= pi->include_size) { opj_pi_emit_error(pi, "Invalid access to pi->include"); return OPJ_FALSE; } if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; }
169,767
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode) { long err = 0; unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; DECLARE_BITMAP(bm, MAX_NUMNODES); nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { err = compat_get_bitmap(bm, nmask, nr_bits); nm = compat_alloc_user_space(alloc_size); err |= copy_to_user(nm, bm, alloc_size); } if (err) return -EFAULT; return sys_set_mempolicy(mode, nm, nr_bits+1); } Commit Message: mm/mempolicy.c: fix error handling in set_mempolicy and mbind. In the case that compat_get_bitmap fails we do not want to copy the bitmap to the user as it will contain uninitialized stack data and leak sensitive data. Signed-off-by: Chris Salls <salls@cs.ucsb.edu> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-388
COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode) { unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; DECLARE_BITMAP(bm, MAX_NUMNODES); nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { if (compat_get_bitmap(bm, nmask, nr_bits)) return -EFAULT; nm = compat_alloc_user_space(alloc_size); if (copy_to_user(nm, bm, alloc_size)) return -EFAULT; } return sys_set_mempolicy(mode, nm, nr_bits+1); }
168,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: base::MessageLoopProxy* ProxyChannelDelegate::GetIPCMessageLoop() { return RenderThread::Get()->GetIOMessageLoopProxy().get(); } 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 TBR=bbudge@chromium.org 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
base::MessageLoopProxy* ProxyChannelDelegate::GetIPCMessageLoop() {
170,733
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval; zval tmp; int compiler_result; zend_bool original_in_compilation = CG(in_compilation); if (source_string->value.str.len==0) { efree(op_array); return NULL; } CG(in_compilation) = 1; tmp = *source_string; zval_copy_ctor(&tmp); convert_to_string(&tmp); source_string = &tmp; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) { efree(op_array); retval = NULL; } else { zend_bool orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; CG(active_op_array) = op_array; zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); BEGIN(ST_IN_SCRIPTING); compiler_result = zendparse(TSRMLS_C); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } if (compiler_result==1) { CG(active_op_array) = original_active_op_array; CG(unclean_shutdown)=1; destroy_op_array(op_array TSRMLS_CC); efree(op_array); retval = NULL; } else { zend_do_return(NULL, 0 TSRMLS_CC); CG(active_op_array) = original_active_op_array; pass_two(op_array TSRMLS_CC); zend_release_labels(0 TSRMLS_CC); retval = op_array; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&tmp); CG(in_compilation) = original_in_compilation; return retval; } Commit Message: fix bug #64660 - yyparse can return 2, not only 1 CWE ID: CWE-20
zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval; zval tmp; int compiler_result; zend_bool original_in_compilation = CG(in_compilation); if (source_string->value.str.len==0) { efree(op_array); return NULL; } CG(in_compilation) = 1; tmp = *source_string; zval_copy_ctor(&tmp); convert_to_string(&tmp); source_string = &tmp; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) { efree(op_array); retval = NULL; } else { zend_bool orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; CG(active_op_array) = op_array; zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); BEGIN(ST_IN_SCRIPTING); compiler_result = zendparse(TSRMLS_C); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } if (compiler_result != 0) { CG(active_op_array) = original_active_op_array; CG(unclean_shutdown)=1; destroy_op_array(op_array TSRMLS_CC); efree(op_array); retval = NULL; } else { zend_do_return(NULL, 0 TSRMLS_CC); CG(active_op_array) = original_active_op_array; pass_two(op_array TSRMLS_CC); zend_release_labels(0 TSRMLS_CC); retval = op_array; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&tmp); CG(in_compilation) = original_in_compilation; return retval; }
166,024
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintWebViewHelper::OnPrintForPrintPreview( const base::DictionaryValue& job_settings) { if (prep_frame_view_) return; if (!render_view()->GetWebView()) return; blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); if (!main_frame) return; blink::WebDocument document = main_frame->document(); blink::WebElement pdf_element = document.getElementById("pdf-viewer"); if (pdf_element.isNull()) { NOTREACHED(); return; } blink::WebLocalFrame* plugin_frame = pdf_element.document().frame(); blink::WebElement plugin_element = pdf_element; if (pdf_element.hasHTMLTagName("iframe")) { plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element); plugin_element = delegate_->GetPdfElement(plugin_frame); if (plugin_element.isNull()) { NOTREACHED(); return; } } base::AutoReset<bool> set_printing_flag(&print_for_preview_, true); if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PRINT); return; } PrintMsg_Print_Params& print_params = print_pages_params_->params; print_params.printable_area = gfx::Rect(print_params.page_size); if (!RenderPagesForPrint(plugin_frame, plugin_element)) { LOG(ERROR) << "RenderPagesForPrint failed"; DidFinishPrinting(FAIL_PRINT); } } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
void PrintWebViewHelper::OnPrintForPrintPreview( const base::DictionaryValue& job_settings) { CHECK_LE(ipc_nesting_level_, 1); if (prep_frame_view_) return; if (!render_view()->GetWebView()) return; blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); if (!main_frame) return; blink::WebDocument document = main_frame->document(); blink::WebElement pdf_element = document.getElementById("pdf-viewer"); if (pdf_element.isNull()) { NOTREACHED(); return; } blink::WebLocalFrame* plugin_frame = pdf_element.document().frame(); blink::WebElement plugin_element = pdf_element; if (pdf_element.hasHTMLTagName("iframe")) { plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element); plugin_element = delegate_->GetPdfElement(plugin_frame); if (plugin_element.isNull()) { NOTREACHED(); return; } } base::AutoReset<bool> set_printing_flag(&print_for_preview_, true); if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PRINT); return; } PrintMsg_Print_Params& print_params = print_pages_params_->params; print_params.printable_area = gfx::Rect(print_params.page_size); if (!RenderPagesForPrint(plugin_frame, plugin_element)) { LOG(ERROR) << "RenderPagesForPrint failed"; DidFinishPrinting(FAIL_PRINT); } }
171,873
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ikev2_parent_inR1outI2_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct dh_continuation *dh = (struct dh_continuation *)pcrc; struct msg_digest *md = dh->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inR1outI2: calculating g^{xy}, sending I2")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (dh->md) release_md(dh->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == dh->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inR1outI2_tail(pcrc, r); if (dh->md != NULL) { complete_v2_state_transition(&dh->md, e); if (dh->md) release_md(dh->md); } reset_globals(); passert(GLOBALS_ARE_RESET()); } Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload CWE ID: CWE-20
static void ikev2_parent_inR1outI2_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct dh_continuation *dh = (struct dh_continuation *)pcrc; struct msg_digest *md = dh->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inR1outI2: calculating g^{xy}, sending I2")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (dh->md) release_md(dh->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == dh->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inR1outI2_tail(pcrc, r); if (dh->md != NULL) { complete_v2_state_transition(&dh->md, e); if (dh->md) release_md(dh->md); } reset_globals(); }
166,472
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ElementsUploadDataStreamTest::FileChangedHelper( const base::FilePath& file_path, const base::Time& time, bool error_expected) { std::vector<std::unique_ptr<UploadElementReader>> element_readers; element_readers.push_back(base::MakeUnique<UploadFileElementReader>( base::ThreadTaskRunnerHandle::Get().get(), file_path, 1, 2, time)); TestCompletionCallback init_callback; std::unique_ptr<UploadDataStream> stream( new ElementsUploadDataStream(std::move(element_readers), 0)); ASSERT_THAT(stream->Init(init_callback.callback(), NetLogWithSource()), IsError(ERR_IO_PENDING)); int error_code = init_callback.WaitForResult(); if (error_expected) ASSERT_THAT(error_code, IsError(ERR_UPLOAD_FILE_CHANGED)); else ASSERT_THAT(error_code, IsOk()); } Commit Message: Replace base::MakeUnique with std::make_unique in net/. base/memory/ptr_util.h includes will be cleaned up later. Bug: 755727 Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434 Reviewed-on: https://chromium-review.googlesource.com/627300 Commit-Queue: Jeremy Roman <jbroman@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Bence Béky <bnc@chromium.org> Cr-Commit-Position: refs/heads/master@{#498123} CWE ID: CWE-311
void ElementsUploadDataStreamTest::FileChangedHelper( const base::FilePath& file_path, const base::Time& time, bool error_expected) { std::vector<std::unique_ptr<UploadElementReader>> element_readers; element_readers.push_back(std::make_unique<UploadFileElementReader>( base::ThreadTaskRunnerHandle::Get().get(), file_path, 1, 2, time)); TestCompletionCallback init_callback; std::unique_ptr<UploadDataStream> stream( new ElementsUploadDataStream(std::move(element_readers), 0)); ASSERT_THAT(stream->Init(init_callback.callback(), NetLogWithSource()), IsError(ERR_IO_PENDING)); int error_code = init_callback.WaitForResult(); if (error_expected) ASSERT_THAT(error_code, IsError(ERR_UPLOAD_FILE_CHANGED)); else ASSERT_THAT(error_code, IsOk()); }
173,261
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftVideoDecoderOMXComponent::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { const int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, mComponentRole, OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamVideoPortFormat: { OMX_VIDEO_PARAM_PORTFORMATTYPE *formatParams = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > kMaxPortIndex) { return OMX_ErrorBadPortIndex; } if (formatParams->nIndex != 0) { return OMX_ErrorNoMore; } if (formatParams->nPortIndex == kInputPortIndex) { if (formatParams->eCompressionFormat != mCodingType || formatParams->eColorFormat != OMX_COLOR_FormatUnused) { return OMX_ErrorUnsupportedSetting; } } else { if (formatParams->eCompressionFormat != OMX_VIDEO_CodingUnused || formatParams->eColorFormat != OMX_COLOR_FormatYUV420Planar) { return OMX_ErrorUnsupportedSetting; } } return OMX_ErrorNone; } case kPrepareForAdaptivePlaybackIndex: { const PrepareForAdaptivePlaybackParams* adaptivePlaybackParams = (const PrepareForAdaptivePlaybackParams *)params; mIsAdaptive = adaptivePlaybackParams->bEnable; if (mIsAdaptive) { mAdaptiveMaxWidth = adaptivePlaybackParams->nMaxFrameWidth; mAdaptiveMaxHeight = adaptivePlaybackParams->nMaxFrameHeight; mWidth = mAdaptiveMaxWidth; mHeight = mAdaptiveMaxHeight; } else { mAdaptiveMaxWidth = 0; mAdaptiveMaxHeight = 0; } updatePortDefinitions(true /* updateCrop */, true /* updateInputSize */); return OMX_ErrorNone; } case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *newParams = (OMX_PARAM_PORTDEFINITIONTYPE *)params; OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &newParams->format.video; OMX_PARAM_PORTDEFINITIONTYPE *def = &editPortInfo(newParams->nPortIndex)->mDef; uint32_t oldWidth = def->format.video.nFrameWidth; uint32_t oldHeight = def->format.video.nFrameHeight; uint32_t newWidth = video_def->nFrameWidth; uint32_t newHeight = video_def->nFrameHeight; if (newWidth != oldWidth || newHeight != oldHeight) { bool outputPort = (newParams->nPortIndex == kOutputPortIndex); if (outputPort) { mWidth = newWidth; mHeight = newHeight; updatePortDefinitions(true /* updateCrop */, true /* updateInputSize */); newParams->nBufferSize = def->nBufferSize; } else { def->format.video.nFrameWidth = newWidth; def->format.video.nFrameHeight = newHeight; } } return SimpleSoftOMXComponent::internalSetParameter(index, params); } 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 SoftVideoDecoderOMXComponent::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { const int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, mComponentRole, OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamVideoPortFormat: { OMX_VIDEO_PARAM_PORTFORMATTYPE *formatParams = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > kMaxPortIndex) { return OMX_ErrorBadPortIndex; } if (formatParams->nIndex != 0) { return OMX_ErrorNoMore; } if (formatParams->nPortIndex == kInputPortIndex) { if (formatParams->eCompressionFormat != mCodingType || formatParams->eColorFormat != OMX_COLOR_FormatUnused) { return OMX_ErrorUnsupportedSetting; } } else { if (formatParams->eCompressionFormat != OMX_VIDEO_CodingUnused || formatParams->eColorFormat != OMX_COLOR_FormatYUV420Planar) { return OMX_ErrorUnsupportedSetting; } } return OMX_ErrorNone; } case kPrepareForAdaptivePlaybackIndex: { const PrepareForAdaptivePlaybackParams* adaptivePlaybackParams = (const PrepareForAdaptivePlaybackParams *)params; if (!isValidOMXParam(adaptivePlaybackParams)) { return OMX_ErrorBadParameter; } mIsAdaptive = adaptivePlaybackParams->bEnable; if (mIsAdaptive) { mAdaptiveMaxWidth = adaptivePlaybackParams->nMaxFrameWidth; mAdaptiveMaxHeight = adaptivePlaybackParams->nMaxFrameHeight; mWidth = mAdaptiveMaxWidth; mHeight = mAdaptiveMaxHeight; } else { mAdaptiveMaxWidth = 0; mAdaptiveMaxHeight = 0; } updatePortDefinitions(true /* updateCrop */, true /* updateInputSize */); return OMX_ErrorNone; } case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *newParams = (OMX_PARAM_PORTDEFINITIONTYPE *)params; if (!isValidOMXParam(newParams)) { return OMX_ErrorBadParameter; } OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &newParams->format.video; OMX_PARAM_PORTDEFINITIONTYPE *def = &editPortInfo(newParams->nPortIndex)->mDef; uint32_t oldWidth = def->format.video.nFrameWidth; uint32_t oldHeight = def->format.video.nFrameHeight; uint32_t newWidth = video_def->nFrameWidth; uint32_t newHeight = video_def->nFrameHeight; if (newWidth != oldWidth || newHeight != oldHeight) { bool outputPort = (newParams->nPortIndex == kOutputPortIndex); if (outputPort) { mWidth = newWidth; mHeight = newHeight; updatePortDefinitions(true /* updateCrop */, true /* updateInputSize */); newParams->nBufferSize = def->nBufferSize; } else { def->format.video.nFrameWidth = newWidth; def->format.video.nFrameHeight = newHeight; } } return SimpleSoftOMXComponent::internalSetParameter(index, params); } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,226
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UserSelectionScreen::OnBeforeUserRemoved(const AccountId& account_id) { for (user_manager::UserList::iterator it = users_.begin(); it != users_.end(); ++it) { if ((*it)->GetAccountId() == account_id) { users_.erase(it); break; } } } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <xiaoyinh@chromium.org> Commit-Queue: Jacob Dufault <jdufault@chromium.org> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
void UserSelectionScreen::OnBeforeUserRemoved(const AccountId& account_id) { for (auto it = users_.cbegin(); it != users_.cend(); ++it) { if ((*it)->GetAccountId() == account_id) { users_.erase(it); break; } } }
172,202
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: vmnc_handle_wmvi_rectangle (GstVMncDec * dec, struct RfbRectangle *rect, const guint8 * data, int len, gboolean decode) { GstVideoFormat format; gint bpp, tc; guint32 redmask, greenmask, bluemask; guint32 endianness, dataendianness; GstVideoCodecState *state; /* A WMVi rectangle has a 16byte payload */ if (len < 16) { GST_DEBUG_OBJECT (dec, "Bad WMVi rect: too short"); return ERROR_INSUFFICIENT_DATA; } /* We only compare 13 bytes; ignoring the 3 padding bytes at the end */ if (dec->have_format && memcmp (data, dec->format.descriptor, 13) == 0) { /* Nothing changed, so just exit */ return 16; } /* Store the whole block for simple comparison later */ memcpy (dec->format.descriptor, data, 16); if (rect->x != 0 || rect->y != 0) { GST_WARNING_OBJECT (dec, "Bad WMVi rect: wrong coordinates"); return ERROR_INVALID; } bpp = data[0]; dec->format.depth = data[1]; dec->format.big_endian = data[2]; dataendianness = data[2] ? G_BIG_ENDIAN : G_LITTLE_ENDIAN; tc = data[3]; if (bpp != 8 && bpp != 16 && bpp != 32) { GST_WARNING_OBJECT (dec, "Bad bpp value: %d", bpp); return ERROR_INVALID; } if (!tc) { GST_WARNING_OBJECT (dec, "Paletted video not supported"); return ERROR_INVALID; } dec->format.bytes_per_pixel = bpp / 8; dec->format.width = rect->width; dec->format.height = rect->height; redmask = (guint32) (RFB_GET_UINT16 (data + 4)) << data[10]; greenmask = (guint32) (RFB_GET_UINT16 (data + 6)) << data[11]; bluemask = (guint32) (RFB_GET_UINT16 (data + 8)) << data[12]; GST_DEBUG_OBJECT (dec, "Red: mask %d, shift %d", RFB_GET_UINT16 (data + 4), data[10]); GST_DEBUG_OBJECT (dec, "Green: mask %d, shift %d", RFB_GET_UINT16 (data + 6), data[11]); GST_DEBUG_OBJECT (dec, "Blue: mask %d, shift %d", RFB_GET_UINT16 (data + 8), data[12]); GST_DEBUG_OBJECT (dec, "BPP: %d. endianness: %s", bpp, data[2] ? "big" : "little"); /* GStreamer's RGB caps are a bit weird. */ if (bpp == 8) { endianness = G_BYTE_ORDER; /* Doesn't matter */ } else if (bpp == 16) { /* We require host-endian. */ endianness = G_BYTE_ORDER; } else { /* bpp == 32 */ /* We require big endian */ endianness = G_BIG_ENDIAN; if (endianness != dataendianness) { redmask = GUINT32_SWAP_LE_BE (redmask); greenmask = GUINT32_SWAP_LE_BE (greenmask); bluemask = GUINT32_SWAP_LE_BE (bluemask); } } format = gst_video_format_from_masks (dec->format.depth, bpp, endianness, redmask, greenmask, bluemask, 0); GST_DEBUG_OBJECT (dec, "From depth: %d bpp: %u endianess: %s redmask: %X " "greenmask: %X bluemask: %X got format %s", dec->format.depth, bpp, endianness == G_BIG_ENDIAN ? "BE" : "LE", GUINT32_FROM_BE (redmask), GUINT32_FROM_BE (greenmask), GUINT32_FROM_BE (bluemask), format == GST_VIDEO_FORMAT_UNKNOWN ? "UNKOWN" : gst_video_format_to_string (format)); if (format == GST_VIDEO_FORMAT_UNKNOWN) { GST_WARNING_OBJECT (dec, "Video format unknown to GStreamer"); return ERROR_INVALID; } dec->have_format = TRUE; if (!decode) { GST_LOG_OBJECT (dec, "Parsing, not setting caps"); return 16; } state = gst_video_decoder_set_output_state (GST_VIDEO_DECODER (dec), format, rect->width, rect->height, dec->input_state); gst_video_codec_state_unref (state); g_free (dec->imagedata); dec->imagedata = g_malloc (dec->format.width * dec->format.height * dec->format.bytes_per_pixel); GST_DEBUG_OBJECT (dec, "Allocated image data at %p", dec->imagedata); dec->format.stride = dec->format.width * dec->format.bytes_per_pixel; return 16; } Commit Message: CWE ID: CWE-200
vmnc_handle_wmvi_rectangle (GstVMncDec * dec, struct RfbRectangle *rect, const guint8 * data, int len, gboolean decode) { GstVideoFormat format; gint bpp, tc; guint32 redmask, greenmask, bluemask; guint32 endianness, dataendianness; GstVideoCodecState *state; /* A WMVi rectangle has a 16byte payload */ if (len < 16) { GST_DEBUG_OBJECT (dec, "Bad WMVi rect: too short"); return ERROR_INSUFFICIENT_DATA; } /* We only compare 13 bytes; ignoring the 3 padding bytes at the end */ if (dec->have_format && memcmp (data, dec->format.descriptor, 13) == 0) { /* Nothing changed, so just exit */ return 16; } /* Store the whole block for simple comparison later */ memcpy (dec->format.descriptor, data, 16); if (rect->x != 0 || rect->y != 0) { GST_WARNING_OBJECT (dec, "Bad WMVi rect: wrong coordinates"); return ERROR_INVALID; } bpp = data[0]; dec->format.depth = data[1]; dec->format.big_endian = data[2]; dataendianness = data[2] ? G_BIG_ENDIAN : G_LITTLE_ENDIAN; tc = data[3]; if (bpp != 8 && bpp != 16 && bpp != 32) { GST_WARNING_OBJECT (dec, "Bad bpp value: %d", bpp); return ERROR_INVALID; } if (!tc) { GST_WARNING_OBJECT (dec, "Paletted video not supported"); return ERROR_INVALID; } dec->format.bytes_per_pixel = bpp / 8; dec->format.width = rect->width; dec->format.height = rect->height; redmask = (guint32) (RFB_GET_UINT16 (data + 4)) << data[10]; greenmask = (guint32) (RFB_GET_UINT16 (data + 6)) << data[11]; bluemask = (guint32) (RFB_GET_UINT16 (data + 8)) << data[12]; GST_DEBUG_OBJECT (dec, "Red: mask %d, shift %d", RFB_GET_UINT16 (data + 4), data[10]); GST_DEBUG_OBJECT (dec, "Green: mask %d, shift %d", RFB_GET_UINT16 (data + 6), data[11]); GST_DEBUG_OBJECT (dec, "Blue: mask %d, shift %d", RFB_GET_UINT16 (data + 8), data[12]); GST_DEBUG_OBJECT (dec, "BPP: %d. endianness: %s", bpp, data[2] ? "big" : "little"); /* GStreamer's RGB caps are a bit weird. */ if (bpp == 8) { endianness = G_BYTE_ORDER; /* Doesn't matter */ } else if (bpp == 16) { /* We require host-endian. */ endianness = G_BYTE_ORDER; } else { /* bpp == 32 */ /* We require big endian */ endianness = G_BIG_ENDIAN; if (endianness != dataendianness) { redmask = GUINT32_SWAP_LE_BE (redmask); greenmask = GUINT32_SWAP_LE_BE (greenmask); bluemask = GUINT32_SWAP_LE_BE (bluemask); } } format = gst_video_format_from_masks (dec->format.depth, bpp, endianness, redmask, greenmask, bluemask, 0); GST_DEBUG_OBJECT (dec, "From depth: %d bpp: %u endianess: %s redmask: %X " "greenmask: %X bluemask: %X got format %s", dec->format.depth, bpp, endianness == G_BIG_ENDIAN ? "BE" : "LE", GUINT32_FROM_BE (redmask), GUINT32_FROM_BE (greenmask), GUINT32_FROM_BE (bluemask), format == GST_VIDEO_FORMAT_UNKNOWN ? "UNKOWN" : gst_video_format_to_string (format)); if (format == GST_VIDEO_FORMAT_UNKNOWN) { GST_WARNING_OBJECT (dec, "Video format unknown to GStreamer"); return ERROR_INVALID; } dec->have_format = TRUE; if (!decode) { GST_LOG_OBJECT (dec, "Parsing, not setting caps"); return 16; } state = gst_video_decoder_set_output_state (GST_VIDEO_DECODER (dec), format, rect->width, rect->height, dec->input_state); gst_video_codec_state_unref (state); g_free (dec->imagedata); dec->imagedata = g_malloc0 (dec->format.width * dec->format.height * dec->format.bytes_per_pixel); GST_DEBUG_OBJECT (dec, "Allocated image data at %p", dec->imagedata); dec->format.stride = dec->format.width * dec->format.bytes_per_pixel; return 16; }
165,252
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Chapters::Display::Parse( IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x05) // ChapterString ID { status = UnserializeString(pReader, pos, size, m_string); if (status) return status; } else if (id == 0x037C) // ChapterLanguage ID { status = UnserializeString(pReader, pos, size, m_language); if (status) return status; } else if (id == 0x037E) // ChapterCountry ID { status = UnserializeString(pReader, pos, size, m_country); if (status) return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Chapters::Display::Parse(
174,403
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mrb_class_real(struct RClass* cl) { if (cl == 0) return NULL; while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) { cl = cl->super; } return cl; } Commit Message: `mrb_class_real()` did not work for `BasicObject`; fix #4037 CWE ID: CWE-476
mrb_class_real(struct RClass* cl) { if (cl == 0) return NULL; while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) { cl = cl->super; if (cl == 0) return NULL; } return cl; }
169,200
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mp_dss_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_dss *mdss = (const struct mp_dss *) opt; if ((opt_len != mp_dss_len(mdss, 1) && opt_len != mp_dss_len(mdss, 0)) || flags & TH_SYN) return 0; if (mdss->flags & MP_DSS_F) ND_PRINT((ndo, " fin")); opt += 4; if (mdss->flags & MP_DSS_A) { ND_PRINT((ndo, " ack ")); if (mdss->flags & MP_DSS_a) { ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt))); opt += 8; } else { ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt))); opt += 4; } } if (mdss->flags & MP_DSS_M) { ND_PRINT((ndo, " seq ")); if (mdss->flags & MP_DSS_m) { ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt))); opt += 8; } else { ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt))); opt += 4; } ND_PRINT((ndo, " subseq %u", EXTRACT_32BITS(opt))); opt += 4; ND_PRINT((ndo, " len %u", EXTRACT_16BITS(opt))); opt += 2; if (opt_len == mp_dss_len(mdss, 1)) ND_PRINT((ndo, " csum 0x%x", EXTRACT_16BITS(opt))); } return 1; } Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption. Do the length checking inline; that means we print stuff up to the point at which we run out of option data. First check to make sure we have at least 4 bytes of option, so we have flags to check. This fixes a buffer over-read discovered by Kim Gwan Yeong. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
mp_dss_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_dss *mdss = (const struct mp_dss *) opt; /* We need the flags, at a minimum. */ if (opt_len < 4) return 0; if (flags & TH_SYN) return 0; if (mdss->flags & MP_DSS_F) ND_PRINT((ndo, " fin")); opt += 4; opt_len -= 4; if (mdss->flags & MP_DSS_A) { /* Ack present */ ND_PRINT((ndo, " ack ")); /* * If the a flag is set, we have an 8-byte ack; if it's * clear, we have a 4-byte ack. */ if (mdss->flags & MP_DSS_a) { if (opt_len < 8) return 0; ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt))); opt += 8; opt_len -= 8; } else { if (opt_len < 4) return 0; ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt))); opt += 4; opt_len -= 4; } } if (mdss->flags & MP_DSS_M) { /* * Data Sequence Number (DSN), Subflow Sequence Number (SSN), * Data-Level Length present, and Checksum possibly present. */ ND_PRINT((ndo, " seq ")); /* * If the m flag is set, we have an 8-byte NDS; if it's clear, * we have a 4-byte DSN. */ if (mdss->flags & MP_DSS_m) { if (opt_len < 8) return 0; ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt))); opt += 8; opt_len -= 8; } else { if (opt_len < 4) return 0; ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt))); opt += 4; opt_len -= 4; } if (opt_len < 4) return 0; ND_PRINT((ndo, " subseq %u", EXTRACT_32BITS(opt))); opt += 4; opt_len -= 4; if (opt_len < 2) return 0; ND_PRINT((ndo, " len %u", EXTRACT_16BITS(opt))); opt += 2; opt_len -= 2; /* * The Checksum is present only if negotiated. * If there are at least 2 bytes left, process the next 2 * bytes as the Checksum. */ if (opt_len >= 2) { ND_PRINT((ndo, " csum 0x%x", EXTRACT_16BITS(opt))); opt_len -= 2; } } if (opt_len != 0) return 0; return 1; }
167,837
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeOSSetImeConfig(InputMethodStatusConnection* connection, const char* section, const char* config_name, const ImeConfigValue& value) { DCHECK(section); DCHECK(config_name); g_return_val_if_fail(connection, FALSE); return connection->SetImeConfig(section, config_name, value); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ChromeOSSetImeConfig(InputMethodStatusConnection* connection,
170,526
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MostVisitedSitesBridge::JavaObserver::OnIconMadeAvailable( const GURL& site_url) { JNIEnv* env = AttachCurrentThread(); Java_MostVisitedURLsObserver_onIconMadeAvailable( env, observer_, ConvertUTF8ToJavaString(env, site_url.spec())); } Commit Message: Rename MostVisitedSites.MostVisitedURLsObserver to Observer. BUG=677672 Review-Url: https://codereview.chromium.org/2697543002 Cr-Commit-Position: refs/heads/master@{#449958} CWE ID: CWE-17
void MostVisitedSitesBridge::JavaObserver::OnIconMadeAvailable( const GURL& site_url) { JNIEnv* env = AttachCurrentThread(); Java_Observer_onIconMadeAvailable( env, observer_, ConvertUTF8ToJavaString(env, site_url.spec())); }
172,034
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(imagetruecolortopalette) { zval *IM; zend_bool dither; long ncolors; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (ncolors <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero"); RETURN_FALSE; } gdImageTrueColorToPalette(im, dither, ncolors); RETURN_TRUE; } Commit Message: Fix bug#72697 - select_colors write out-of-bounds CWE ID: CWE-787
PHP_FUNCTION(imagetruecolortopalette) { zval *IM; zend_bool dither; long ncolors; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (ncolors <= 0 || ncolors > INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero and no more than %d", INT_MAX); RETURN_FALSE; } gdImageTrueColorToPalette(im, dither, (int)ncolors); RETURN_TRUE; }
166,953
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mojom::AppPtr AppControllerImpl::CreateAppPtr(const apps::AppUpdate& update) { auto app = chromeos::kiosk_next_home::mojom::App::New(); app->app_id = update.AppId(); app->type = update.AppType(); app->display_name = update.Name(); app->readiness = update.Readiness(); if (app->type == apps::mojom::AppType::kArc) { app->android_package_name = MaybeGetAndroidPackageName(app->app_id); } return app; } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <michaelpg@chromium.org> Commit-Queue: Lucas Tenório <ltenorio@chromium.org> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
mojom::AppPtr AppControllerImpl::CreateAppPtr(const apps::AppUpdate& update) { mojom::AppPtr AppControllerService::CreateAppPtr( const apps::AppUpdate& update) { auto app = chromeos::kiosk_next_home::mojom::App::New(); app->app_id = update.AppId(); app->type = update.AppType(); app->display_name = update.Name(); app->readiness = update.Readiness(); if (app->type == apps::mojom::AppType::kArc) { app->android_package_name = MaybeGetAndroidPackageName(app->app_id); } return app; }
172,081
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned int, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; if (len > INT_MAX) len = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; iov.iov_base = buff; iov.iov_len = len; msg.msg_name = NULL; iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len); msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg, len); out_put: fput_light(sock->file, fput_needed); out: return err; } Commit Message: net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom Cc: stable@vger.kernel.org # v3.19 Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-264
SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned int, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; if (len > INT_MAX) len = INT_MAX; if (unlikely(!access_ok(VERIFY_READ, buff, len))) return -EFAULT; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; iov.iov_base = buff; iov.iov_len = len; msg.msg_name = NULL; iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len); msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg, len); out_put: fput_light(sock->file, fput_needed); out: return err; }
167,570
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ConfirmInfoBar::ConfirmInfoBar(std::unique_ptr<ConfirmInfoBarDelegate> delegate) : InfoBarView(std::move(delegate)) { auto* delegate_ptr = GetDelegate(); label_ = CreateLabel(delegate_ptr->GetMessageText()); AddChildView(label_); const auto buttons = delegate_ptr->GetButtons(); if (buttons & ConfirmInfoBarDelegate::BUTTON_OK) { ok_button_ = CreateButton(ConfirmInfoBarDelegate::BUTTON_OK); ok_button_->SetProminent(true); if (delegate_ptr->OKButtonTriggersUACPrompt()) { elevation_icon_setter_.reset(new ElevationIconSetter( ok_button_, base::BindOnce(&ConfirmInfoBar::Layout, base::Unretained(this)))); } } if (buttons & ConfirmInfoBarDelegate::BUTTON_CANCEL) { cancel_button_ = CreateButton(ConfirmInfoBarDelegate::BUTTON_CANCEL); if (buttons == ConfirmInfoBarDelegate::BUTTON_CANCEL) cancel_button_->SetProminent(true); } link_ = CreateLink(delegate_ptr->GetLinkText(), this); AddChildView(link_); } Commit Message: Allow to specify elide behavior for confrim infobar message Used in "<extension name> is debugging this browser" infobar. Bug: 823194 Change-Id: Iff6627097c020cccca8f7cc3e21a803a41fd8f2c Reviewed-on: https://chromium-review.googlesource.com/1048064 Commit-Queue: Dmitry Gozman <dgozman@chromium.org> Reviewed-by: Devlin <rdevlin.cronin@chromium.org> Reviewed-by: Peter Kasting <pkasting@chromium.org> Cr-Commit-Position: refs/heads/master@{#557245} CWE ID: CWE-254
ConfirmInfoBar::ConfirmInfoBar(std::unique_ptr<ConfirmInfoBarDelegate> delegate) : InfoBarView(std::move(delegate)) { auto* delegate_ptr = GetDelegate(); label_ = CreateLabel(delegate_ptr->GetMessageText()); label_->SetElideBehavior(delegate_ptr->GetMessageElideBehavior()); AddChildView(label_); const auto buttons = delegate_ptr->GetButtons(); if (buttons & ConfirmInfoBarDelegate::BUTTON_OK) { ok_button_ = CreateButton(ConfirmInfoBarDelegate::BUTTON_OK); ok_button_->SetProminent(true); if (delegate_ptr->OKButtonTriggersUACPrompt()) { elevation_icon_setter_.reset(new ElevationIconSetter( ok_button_, base::BindOnce(&ConfirmInfoBar::Layout, base::Unretained(this)))); } } if (buttons & ConfirmInfoBarDelegate::BUTTON_CANCEL) { cancel_button_ = CreateButton(ConfirmInfoBarDelegate::BUTTON_CANCEL); if (buttons == ConfirmInfoBarDelegate::BUTTON_CANCEL) cancel_button_->SetProminent(true); } link_ = CreateLink(delegate_ptr->GetLinkText(), this); AddChildView(link_); }
173,165
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltResolveSASCallback(xsltAttrElemPtr values, xsltStylesheetPtr style, const xmlChar *name, const xmlChar *ns, ATTRIBUTE_UNUSED const xmlChar *ignored) { xsltAttrElemPtr tmp; xsltAttrElemPtr refs; tmp = values; while (tmp != NULL) { if (tmp->set != NULL) { /* * Check against cycles ! */ if ((xmlStrEqual(name, tmp->set)) && (xmlStrEqual(ns, tmp->ns))) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : use-attribute-sets recursion detected on %s\n", name); } else { #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "Importing attribute list %s\n", tmp->set); #endif refs = xsltGetSAS(style, tmp->set, tmp->ns); if (refs == NULL) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : use-attribute-sets %s reference missing %s\n", name, tmp->set); } else { /* * recurse first for cleanup */ xsltResolveSASCallback(refs, style, name, ns, NULL); /* * Then merge */ xsltMergeAttrElemList(style, values, refs); /* * Then suppress the reference */ tmp->set = NULL; tmp->ns = NULL; } } } tmp = tmp->next; } } 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
xsltResolveSASCallback(xsltAttrElemPtr values, xsltStylesheetPtr style, xsltResolveSASCallbackInt(xsltAttrElemPtr values, xsltStylesheetPtr style, const xmlChar *name, const xmlChar *ns, int depth) { xsltAttrElemPtr tmp; xsltAttrElemPtr refs; tmp = values; if ((name == NULL) || (name[0] == 0)) return; if (depth > 100) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : use-attribute-sets recursion detected on %s\n", name); return; } while (tmp != NULL) { if (tmp->set != NULL) { /* * Check against cycles ! */ if ((xmlStrEqual(name, tmp->set)) && (xmlStrEqual(ns, tmp->ns))) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : use-attribute-sets recursion detected on %s\n", name); } else { #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "Importing attribute list %s\n", tmp->set); #endif refs = xsltGetSAS(style, tmp->set, tmp->ns); if (refs == NULL) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : use-attribute-sets %s reference missing %s\n", name, tmp->set); } else { /* * recurse first for cleanup */ xsltResolveSASCallbackInt(refs, style, name, ns, depth + 1); /* * Then merge */ xsltMergeAttrElemList(style, values, refs); /* * Then suppress the reference */ tmp->set = NULL; tmp->ns = NULL; } } } tmp = tmp->next; } }
173,299
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree, struct cifs_tcon *tcon, const struct nls_table *cp) { struct smb2_tree_connect_req *req; struct smb2_tree_connect_rsp *rsp = NULL; struct kvec iov[2]; int rc = 0; int resp_buftype; int unc_path_len; struct TCP_Server_Info *server; __le16 *unc_path = NULL; cifs_dbg(FYI, "TCON\n"); if ((ses->server) && tree) server = ses->server; else return -EIO; if (tcon && tcon->bad_network_name) return -ENOENT; unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL); if (unc_path == NULL) return -ENOMEM; unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1; unc_path_len *= 2; if (unc_path_len < 2) { kfree(unc_path); return -EINVAL; } rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req); if (rc) { kfree(unc_path); return rc; } if (tcon == NULL) { /* since no tcon, smb2_init can not do this, so do here */ req->hdr.SessionId = ses->Suid; /* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED) req->hdr.Flags |= SMB2_FLAGS_SIGNED; */ } iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field and 1 for pad */ iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; /* Testing shows that buffer offset must be at location of Buffer[0] */ req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req) - 1 /* pad */ - 4 /* do not count rfc1001 len field */); req->PathLength = cpu_to_le16(unc_path_len - 2); iov[1].iov_base = unc_path; iov[1].iov_len = unc_path_len; inc_rfc1001_len(req, unc_path_len - 1 /* pad */); rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0); rsp = (struct smb2_tree_connect_rsp *)iov[0].iov_base; if (rc != 0) { if (tcon) { cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE); tcon->need_reconnect = true; } goto tcon_error_exit; } if (tcon == NULL) { ses->ipc_tid = rsp->hdr.TreeId; goto tcon_exit; } if (rsp->ShareType & SMB2_SHARE_TYPE_DISK) cifs_dbg(FYI, "connection to disk share\n"); else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) { tcon->ipc = true; cifs_dbg(FYI, "connection to pipe share\n"); } else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) { tcon->print = true; cifs_dbg(FYI, "connection to printer\n"); } else { cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType); rc = -EOPNOTSUPP; goto tcon_error_exit; } tcon->share_flags = le32_to_cpu(rsp->ShareFlags); tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */ tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess); tcon->tidStatus = CifsGood; tcon->need_reconnect = false; tcon->tid = rsp->hdr.TreeId; strlcpy(tcon->treeName, tree, sizeof(tcon->treeName)); if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) && ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0)) cifs_dbg(VFS, "DFS capability contradicts DFS flag\n"); init_copy_chunk_defaults(tcon); if (tcon->ses->server->ops->validate_negotiate) rc = tcon->ses->server->ops->validate_negotiate(xid, tcon); tcon_exit: free_rsp_buf(resp_buftype, rsp); kfree(unc_path); return rc; tcon_error_exit: if (rsp->hdr.Status == STATUS_BAD_NETWORK_NAME) { cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree); tcon->bad_network_name = true; } goto tcon_exit; } Commit Message: [CIFS] Possible null ptr deref in SMB2_tcon As Raphael Geissert pointed out, tcon_error_exit can dereference tcon and there is one path in which tcon can be null. Signed-off-by: Steve French <smfrench@gmail.com> CC: Stable <stable@vger.kernel.org> # v3.7+ Reported-by: Raphael Geissert <geissert@debian.org> CWE ID: CWE-399
SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree, struct cifs_tcon *tcon, const struct nls_table *cp) { struct smb2_tree_connect_req *req; struct smb2_tree_connect_rsp *rsp = NULL; struct kvec iov[2]; int rc = 0; int resp_buftype; int unc_path_len; struct TCP_Server_Info *server; __le16 *unc_path = NULL; cifs_dbg(FYI, "TCON\n"); if ((ses->server) && tree) server = ses->server; else return -EIO; if (tcon && tcon->bad_network_name) return -ENOENT; unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL); if (unc_path == NULL) return -ENOMEM; unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1; unc_path_len *= 2; if (unc_path_len < 2) { kfree(unc_path); return -EINVAL; } rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req); if (rc) { kfree(unc_path); return rc; } if (tcon == NULL) { /* since no tcon, smb2_init can not do this, so do here */ req->hdr.SessionId = ses->Suid; /* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED) req->hdr.Flags |= SMB2_FLAGS_SIGNED; */ } iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field and 1 for pad */ iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; /* Testing shows that buffer offset must be at location of Buffer[0] */ req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req) - 1 /* pad */ - 4 /* do not count rfc1001 len field */); req->PathLength = cpu_to_le16(unc_path_len - 2); iov[1].iov_base = unc_path; iov[1].iov_len = unc_path_len; inc_rfc1001_len(req, unc_path_len - 1 /* pad */); rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0); rsp = (struct smb2_tree_connect_rsp *)iov[0].iov_base; if (rc != 0) { if (tcon) { cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE); tcon->need_reconnect = true; } goto tcon_error_exit; } if (tcon == NULL) { ses->ipc_tid = rsp->hdr.TreeId; goto tcon_exit; } if (rsp->ShareType & SMB2_SHARE_TYPE_DISK) cifs_dbg(FYI, "connection to disk share\n"); else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) { tcon->ipc = true; cifs_dbg(FYI, "connection to pipe share\n"); } else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) { tcon->print = true; cifs_dbg(FYI, "connection to printer\n"); } else { cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType); rc = -EOPNOTSUPP; goto tcon_error_exit; } tcon->share_flags = le32_to_cpu(rsp->ShareFlags); tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */ tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess); tcon->tidStatus = CifsGood; tcon->need_reconnect = false; tcon->tid = rsp->hdr.TreeId; strlcpy(tcon->treeName, tree, sizeof(tcon->treeName)); if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) && ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0)) cifs_dbg(VFS, "DFS capability contradicts DFS flag\n"); init_copy_chunk_defaults(tcon); if (tcon->ses->server->ops->validate_negotiate) rc = tcon->ses->server->ops->validate_negotiate(xid, tcon); tcon_exit: free_rsp_buf(resp_buftype, rsp); kfree(unc_path); return rc; tcon_error_exit: if (rsp->hdr.Status == STATUS_BAD_NETWORK_NAME) { cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree); if (tcon) tcon->bad_network_name = true; } goto tcon_exit; }
166,261
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int er_supported(ERContext *s) { if(s->avctx->hwaccel && s->avctx->hwaccel->decode_slice || !s->cur_pic.f || s->cur_pic.field_picture || s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO ) return 0; return 1; } Commit Message: avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile The profile field is changed by code inside and outside the decoder, its not a reliable indicator of the internal codec state. Maintaining it consistency with studio_profile is messy. Its easier to just avoid it and use only studio_profile Fixes: assertion failure Fixes: ffmpeg_crash_9.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-617
static int er_supported(ERContext *s) { if(s->avctx->hwaccel && s->avctx->hwaccel->decode_slice || !s->cur_pic.f || s->cur_pic.field_picture ) return 0; return 1; }
169,154
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAMR::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (mMode == MODE_NARROW) { if (strncmp((const char *)roleParams->cRole, "audio_decoder.amrnb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } } else { if (strncmp((const char *)roleParams->cRole, "audio_decoder.amrwb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } } return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { const OMX_AUDIO_PARAM_AMRTYPE *aacParams = (const OMX_AUDIO_PARAM_AMRTYPE *)params; if (aacParams->nPortIndex != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 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 SoftAMR::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (mMode == MODE_NARROW) { if (strncmp((const char *)roleParams->cRole, "audio_decoder.amrnb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } } else { if (strncmp((const char *)roleParams->cRole, "audio_decoder.amrwb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } } return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { const OMX_AUDIO_PARAM_AMRTYPE *aacParams = (const OMX_AUDIO_PARAM_AMRTYPE *)params; if (!isValidOMXParam(aacParams)) { return OMX_ErrorBadParameter; } if (aacParams->nPortIndex != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,193
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: fst_get_iface(struct fst_card_info *card, struct fst_port_info *port, struct ifreq *ifr) { sync_serial_settings sync; int i; /* First check what line type is set, we'll default to reporting X.21 * if nothing is set as IF_IFACE_SYNC_SERIAL implies it can't be * changed */ switch (port->hwif) { case E1: ifr->ifr_settings.type = IF_IFACE_E1; break; case T1: ifr->ifr_settings.type = IF_IFACE_T1; break; case V35: ifr->ifr_settings.type = IF_IFACE_V35; break; case V24: ifr->ifr_settings.type = IF_IFACE_V24; break; case X21D: ifr->ifr_settings.type = IF_IFACE_X21D; break; case X21: default: ifr->ifr_settings.type = IF_IFACE_X21; break; } if (ifr->ifr_settings.size == 0) { return 0; /* only type requested */ } if (ifr->ifr_settings.size < sizeof (sync)) { return -ENOMEM; } i = port->index; sync.clock_rate = FST_RDL(card, portConfig[i].lineSpeed); /* Lucky card and linux use same encoding here */ sync.clock_type = FST_RDB(card, portConfig[i].internalClock) == INTCLK ? CLOCK_INT : CLOCK_EXT; sync.loopback = 0; if (copy_to_user(ifr->ifr_settings.ifs_ifsu.sync, &sync, sizeof (sync))) { return -EFAULT; } ifr->ifr_settings.size = sizeof (sync); return 0; } Commit Message: farsync: fix info leak in ioctl The fst_get_iface() code fails to initialize the two padding bytes of struct sync_serial_settings after the ->loopback member. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
fst_get_iface(struct fst_card_info *card, struct fst_port_info *port, struct ifreq *ifr) { sync_serial_settings sync; int i; /* First check what line type is set, we'll default to reporting X.21 * if nothing is set as IF_IFACE_SYNC_SERIAL implies it can't be * changed */ switch (port->hwif) { case E1: ifr->ifr_settings.type = IF_IFACE_E1; break; case T1: ifr->ifr_settings.type = IF_IFACE_T1; break; case V35: ifr->ifr_settings.type = IF_IFACE_V35; break; case V24: ifr->ifr_settings.type = IF_IFACE_V24; break; case X21D: ifr->ifr_settings.type = IF_IFACE_X21D; break; case X21: default: ifr->ifr_settings.type = IF_IFACE_X21; break; } if (ifr->ifr_settings.size == 0) { return 0; /* only type requested */ } if (ifr->ifr_settings.size < sizeof (sync)) { return -ENOMEM; } i = port->index; memset(&sync, 0, sizeof(sync)); sync.clock_rate = FST_RDL(card, portConfig[i].lineSpeed); /* Lucky card and linux use same encoding here */ sync.clock_type = FST_RDB(card, portConfig[i].internalClock) == INTCLK ? CLOCK_INT : CLOCK_EXT; sync.loopback = 0; if (copy_to_user(ifr->ifr_settings.ifs_ifsu.sync, &sync, sizeof (sync))) { return -EFAULT; } ifr->ifr_settings.size = sizeof (sync); return 0; }
166,439
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: gplotGenCommandFile(GPLOT *gplot) { char buf[L_BUF_SIZE]; char *cmdstr, *plottitle, *dataname; l_int32 i, plotstyle, nplots; FILE *fp; PROCNAME("gplotGenCommandFile"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); /* Remove any previous command data */ sarrayClear(gplot->cmddata); /* Generate command data instructions */ if (gplot->title) { /* set title */ snprintf(buf, L_BUF_SIZE, "set title '%s'", gplot->title); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->xlabel) { /* set xlabel */ snprintf(buf, L_BUF_SIZE, "set xlabel '%s'", gplot->xlabel); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->ylabel) { /* set ylabel */ snprintf(buf, L_BUF_SIZE, "set ylabel '%s'", gplot->ylabel); sarrayAddString(gplot->cmddata, buf, L_COPY); } /* Set terminal type and output */ if (gplot->outformat == GPLOT_PNG) { snprintf(buf, L_BUF_SIZE, "set terminal png; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_PS) { snprintf(buf, L_BUF_SIZE, "set terminal postscript; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_EPS) { snprintf(buf, L_BUF_SIZE, "set terminal postscript eps; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_LATEX) { snprintf(buf, L_BUF_SIZE, "set terminal latex; set output '%s'", gplot->outname); } sarrayAddString(gplot->cmddata, buf, L_COPY); if (gplot->scaling == GPLOT_LOG_SCALE_X || gplot->scaling == GPLOT_LOG_SCALE_X_Y) { snprintf(buf, L_BUF_SIZE, "set logscale x"); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->scaling == GPLOT_LOG_SCALE_Y || gplot->scaling == GPLOT_LOG_SCALE_X_Y) { snprintf(buf, L_BUF_SIZE, "set logscale y"); sarrayAddString(gplot->cmddata, buf, L_COPY); } nplots = sarrayGetCount(gplot->datanames); for (i = 0; i < nplots; i++) { plottitle = sarrayGetString(gplot->plottitles, i, L_NOCOPY); dataname = sarrayGetString(gplot->datanames, i, L_NOCOPY); numaGetIValue(gplot->plotstyles, i, &plotstyle); if (nplots == 1) { snprintf(buf, L_BUF_SIZE, "plot '%s' title '%s' %s", dataname, plottitle, gplotstylenames[plotstyle]); } else { if (i == 0) snprintf(buf, L_BUF_SIZE, "plot '%s' title '%s' %s, \\", dataname, plottitle, gplotstylenames[plotstyle]); else if (i < nplots - 1) snprintf(buf, L_BUF_SIZE, " '%s' title '%s' %s, \\", dataname, plottitle, gplotstylenames[plotstyle]); else snprintf(buf, L_BUF_SIZE, " '%s' title '%s' %s", dataname, plottitle, gplotstylenames[plotstyle]); } sarrayAddString(gplot->cmddata, buf, L_COPY); } /* Write command data to file */ cmdstr = sarrayToString(gplot->cmddata, 1); if ((fp = fopenWriteStream(gplot->cmdname, "w")) == NULL) { LEPT_FREE(cmdstr); return ERROR_INT("cmd stream not opened", procName, 1); } fwrite(cmdstr, 1, strlen(cmdstr), fp); fclose(fp); LEPT_FREE(cmdstr); return 0; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
gplotGenCommandFile(GPLOT *gplot) { char buf[L_BUFSIZE]; char *cmdstr, *plottitle, *dataname; l_int32 i, plotstyle, nplots; FILE *fp; PROCNAME("gplotGenCommandFile"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); /* Remove any previous command data */ sarrayClear(gplot->cmddata); /* Generate command data instructions */ if (gplot->title) { /* set title */ snprintf(buf, L_BUFSIZE, "set title '%s'", gplot->title); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->xlabel) { /* set xlabel */ snprintf(buf, L_BUFSIZE, "set xlabel '%s'", gplot->xlabel); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->ylabel) { /* set ylabel */ snprintf(buf, L_BUFSIZE, "set ylabel '%s'", gplot->ylabel); sarrayAddString(gplot->cmddata, buf, L_COPY); } /* Set terminal type and output */ if (gplot->outformat == GPLOT_PNG) { snprintf(buf, L_BUFSIZE, "set terminal png; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_PS) { snprintf(buf, L_BUFSIZE, "set terminal postscript; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_EPS) { snprintf(buf, L_BUFSIZE, "set terminal postscript eps; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_LATEX) { snprintf(buf, L_BUFSIZE, "set terminal latex; set output '%s'", gplot->outname); } sarrayAddString(gplot->cmddata, buf, L_COPY); if (gplot->scaling == GPLOT_LOG_SCALE_X || gplot->scaling == GPLOT_LOG_SCALE_X_Y) { snprintf(buf, L_BUFSIZE, "set logscale x"); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->scaling == GPLOT_LOG_SCALE_Y || gplot->scaling == GPLOT_LOG_SCALE_X_Y) { snprintf(buf, L_BUFSIZE, "set logscale y"); sarrayAddString(gplot->cmddata, buf, L_COPY); } nplots = sarrayGetCount(gplot->datanames); for (i = 0; i < nplots; i++) { plottitle = sarrayGetString(gplot->plottitles, i, L_NOCOPY); dataname = sarrayGetString(gplot->datanames, i, L_NOCOPY); numaGetIValue(gplot->plotstyles, i, &plotstyle); if (nplots == 1) { snprintf(buf, L_BUFSIZE, "plot '%s' title '%s' %s", dataname, plottitle, gplotstylenames[plotstyle]); } else { if (i == 0) snprintf(buf, L_BUFSIZE, "plot '%s' title '%s' %s, \\", dataname, plottitle, gplotstylenames[plotstyle]); else if (i < nplots - 1) snprintf(buf, L_BUFSIZE, " '%s' title '%s' %s, \\", dataname, plottitle, gplotstylenames[plotstyle]); else snprintf(buf, L_BUFSIZE, " '%s' title '%s' %s", dataname, plottitle, gplotstylenames[plotstyle]); } sarrayAddString(gplot->cmddata, buf, L_COPY); } /* Write command data to file */ cmdstr = sarrayToString(gplot->cmddata, 1); if ((fp = fopenWriteStream(gplot->cmdname, "w")) == NULL) { LEPT_FREE(cmdstr); return ERROR_INT("cmd stream not opened", procName, 1); } fwrite(cmdstr, 1, strlen(cmdstr), fp); fclose(fp); LEPT_FREE(cmdstr); return 0; }
169,325
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void IndexedDBTransaction::Abort(const IndexedDBDatabaseError& error) { IDB_TRACE1("IndexedDBTransaction::Abort", "txn.id", id()); DCHECK(!processing_event_queue_); if (state_ == FINISHED) return; UMA_HISTOGRAM_ENUMERATION("WebCore.IndexedDB.TransactionAbortReason", ExceptionCodeToUmaEnum(error.code()), UmaIDBExceptionExclusiveMaxValue); timeout_timer_.Stop(); state_ = FINISHED; should_process_queue_ = false; if (backing_store_transaction_begun_) transaction_->Rollback(); while (!abort_task_stack_.empty()) abort_task_stack_.pop().Run(); preemptive_task_queue_.clear(); pending_preemptive_events_ = 0; task_queue_.clear(); CloseOpenCursors(); transaction_->Reset(); database_->transaction_coordinator().DidFinishTransaction(this); #ifndef NDEBUG DCHECK(!database_->transaction_coordinator().IsActive(this)); #endif if (callbacks_.get()) callbacks_->OnAbort(*this, error); database_->TransactionFinished(this, false); connection_->RemoveTransaction(id_); } Commit Message: [IndexedDB] Fixing early destruction of connection during forceclose Patch is as small as possible for merging. Bug: 842990 Change-Id: I9968ffee1bf3279e61e1ec13e4d541f713caf12f Reviewed-on: https://chromium-review.googlesource.com/1062935 Commit-Queue: Daniel Murphy <dmurph@chromium.org> Commit-Queue: Victor Costan <pwnall@chromium.org> Reviewed-by: Victor Costan <pwnall@chromium.org> Cr-Commit-Position: refs/heads/master@{#559383} CWE ID:
void IndexedDBTransaction::Abort(const IndexedDBDatabaseError& error) { IDB_TRACE1("IndexedDBTransaction::Abort", "txn.id", id()); DCHECK(!processing_event_queue_); if (state_ == FINISHED) return; UMA_HISTOGRAM_ENUMERATION("WebCore.IndexedDB.TransactionAbortReason", ExceptionCodeToUmaEnum(error.code()), UmaIDBExceptionExclusiveMaxValue); timeout_timer_.Stop(); state_ = FINISHED; should_process_queue_ = false; if (backing_store_transaction_begun_) transaction_->Rollback(); while (!abort_task_stack_.empty()) abort_task_stack_.pop().Run(); preemptive_task_queue_.clear(); pending_preemptive_events_ = 0; task_queue_.clear(); CloseOpenCursors(); transaction_->Reset(); database_->transaction_coordinator().DidFinishTransaction(this); #ifndef NDEBUG DCHECK(!database_->transaction_coordinator().IsActive(this)); #endif if (callbacks_.get()) callbacks_->OnAbort(*this, error); database_->TransactionFinished(this, false); // Note: During force-close situations, the connection can be destroyed during // the |IndexedDBDatabase::TransactionFinished| call if (connection_) connection_->RemoveTransaction(id_); }
173,219
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: fix_transited_encoding(krb5_context context, krb5_kdc_configuration *config, krb5_boolean check_policy, const TransitedEncoding *tr, EncTicketPart *et, const char *client_realm, const char *server_realm, const char *tgt_realm) { krb5_error_code ret = 0; char **realms, **tmp; unsigned int num_realms; size_t i; switch (tr->tr_type) { case DOMAIN_X500_COMPRESS: break; case 0: /* * Allow empty content of type 0 because that is was Microsoft * generates in their TGT. */ if (tr->contents.length == 0) break; kdc_log(context, config, 0, "Transited type 0 with non empty content"); return KRB5KDC_ERR_TRTYPE_NOSUPP; default: kdc_log(context, config, 0, "Unknown transited type: %u", tr->tr_type); return KRB5KDC_ERR_TRTYPE_NOSUPP; } ret = krb5_domain_x500_decode(context, tr->contents, &realms, &num_realms, client_realm, server_realm); if(ret){ krb5_warn(context, ret, "Decoding transited encoding"); return ret; } if(strcmp(client_realm, tgt_realm) && strcmp(server_realm, tgt_realm)) { /* not us, so add the previous realm to transited set */ if (num_realms + 1 > UINT_MAX/sizeof(*realms)) { ret = ERANGE; goto free_realms; } tmp = realloc(realms, (num_realms + 1) * sizeof(*realms)); if(tmp == NULL){ ret = ENOMEM; goto free_realms; } realms = tmp; realms[num_realms] = strdup(tgt_realm); if(realms[num_realms] == NULL){ ret = ENOMEM; goto free_realms; } num_realms++; } if(num_realms == 0) { if(strcmp(client_realm, server_realm)) kdc_log(context, config, 0, "cross-realm %s -> %s", client_realm, server_realm); } else { size_t l = 0; char *rs; for(i = 0; i < num_realms; i++) l += strlen(realms[i]) + 2; rs = malloc(l); if(rs != NULL) { *rs = '\0'; for(i = 0; i < num_realms; i++) { if(i > 0) strlcat(rs, ", ", l); strlcat(rs, realms[i], l); } kdc_log(context, config, 0, "cross-realm %s -> %s via [%s]", client_realm, server_realm, rs); free(rs); } } if(check_policy) { ret = krb5_check_transited(context, client_realm, server_realm, realms, num_realms, NULL); if(ret) { krb5_warn(context, ret, "cross-realm %s -> %s", client_realm, server_realm); goto free_realms; } et->flags.transited_policy_checked = 1; } et->transited.tr_type = DOMAIN_X500_COMPRESS; ret = krb5_domain_x500_encode(realms, num_realms, &et->transited.contents); if(ret) krb5_warn(context, ret, "Encoding transited encoding"); free_realms: for(i = 0; i < num_realms; i++) free(realms[i]); free(realms); return ret; } Commit Message: Fix transit path validation CVE-2017-6594 Commit f469fc6 (2010-10-02) inadvertently caused the previous hop realm to not be added to the transit path of issued tickets. This may, in some cases, enable bypass of capath policy in Heimdal versions 1.5 through 7.2. Note, this may break sites that rely on the bug. With the bug some incomplete [capaths] worked, that should not have. These may now break authentication in some cross-realm configurations. CWE ID: CWE-295
fix_transited_encoding(krb5_context context, krb5_kdc_configuration *config, krb5_boolean check_policy, const TransitedEncoding *tr, EncTicketPart *et, const char *client_realm, const char *server_realm, const char *tgt_realm) { krb5_error_code ret = 0; char **realms, **tmp; unsigned int num_realms; size_t i; switch (tr->tr_type) { case DOMAIN_X500_COMPRESS: break; case 0: /* * Allow empty content of type 0 because that is was Microsoft * generates in their TGT. */ if (tr->contents.length == 0) break; kdc_log(context, config, 0, "Transited type 0 with non empty content"); return KRB5KDC_ERR_TRTYPE_NOSUPP; default: kdc_log(context, config, 0, "Unknown transited type: %u", tr->tr_type); return KRB5KDC_ERR_TRTYPE_NOSUPP; } ret = krb5_domain_x500_decode(context, tr->contents, &realms, &num_realms, client_realm, server_realm); if(ret){ krb5_warn(context, ret, "Decoding transited encoding"); return ret; } /* * If the realm of the presented tgt is neither the client nor the server * realm, it is a transit realm and must be added to transited set. */ if(strcmp(client_realm, tgt_realm) && strcmp(server_realm, tgt_realm)) { if (num_realms + 1 > UINT_MAX/sizeof(*realms)) { ret = ERANGE; goto free_realms; } tmp = realloc(realms, (num_realms + 1) * sizeof(*realms)); if(tmp == NULL){ ret = ENOMEM; goto free_realms; } realms = tmp; realms[num_realms] = strdup(tgt_realm); if(realms[num_realms] == NULL){ ret = ENOMEM; goto free_realms; } num_realms++; } if(num_realms == 0) { if(strcmp(client_realm, server_realm)) kdc_log(context, config, 0, "cross-realm %s -> %s", client_realm, server_realm); } else { size_t l = 0; char *rs; for(i = 0; i < num_realms; i++) l += strlen(realms[i]) + 2; rs = malloc(l); if(rs != NULL) { *rs = '\0'; for(i = 0; i < num_realms; i++) { if(i > 0) strlcat(rs, ", ", l); strlcat(rs, realms[i], l); } kdc_log(context, config, 0, "cross-realm %s -> %s via [%s]", client_realm, server_realm, rs); free(rs); } } if(check_policy) { ret = krb5_check_transited(context, client_realm, server_realm, realms, num_realms, NULL); if(ret) { krb5_warn(context, ret, "cross-realm %s -> %s", client_realm, server_realm); goto free_realms; } et->flags.transited_policy_checked = 1; } et->transited.tr_type = DOMAIN_X500_COMPRESS; ret = krb5_domain_x500_encode(realms, num_realms, &et->transited.contents); if(ret) krb5_warn(context, ret, "Encoding transited encoding"); free_realms: for(i = 0; i < num_realms; i++) free(realms[i]); free(realms); return ret; }
168,325
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: QuicConnectionHelperTest() : framer_(QuicDecrypter::Create(kNULL), QuicEncrypter::Create(kNULL)), creator_(guid_, &framer_), net_log_(BoundNetLog()), scheduler_(new MockScheduler()), socket_(&empty_data_, net_log_.net_log()), runner_(new TestTaskRunner(&clock_)), helper_(new TestConnectionHelper(runner_.get(), &clock_, &socket_)), connection_(guid_, IPEndPoint(), helper_), frame1_(1, false, 0, data1) { connection_.set_visitor(&visitor_); connection_.SetScheduler(scheduler_); } Commit Message: Fix uninitialized access in QuicConnectionHelperTest BUG=159928 Review URL: https://chromiumcodereview.appspot.com/11360153 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@166708 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
QuicConnectionHelperTest() : guid_(0), framer_(QuicDecrypter::Create(kNULL), QuicEncrypter::Create(kNULL)), creator_(guid_, &framer_), net_log_(BoundNetLog()), scheduler_(new MockScheduler()), socket_(&empty_data_, net_log_.net_log()), runner_(new TestTaskRunner(&clock_)), helper_(new TestConnectionHelper(runner_.get(), &clock_, &socket_)), connection_(guid_, IPEndPoint(), helper_), frame1_(1, false, 0, data1) { connection_.set_visitor(&visitor_); connection_.SetScheduler(scheduler_); }
171,411
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BaseMultipleFieldsDateAndTimeInputType::didBlurFromControl() { RefPtr<HTMLInputElement> protector(element()); element()->setFocus(false); } Commit Message: Fix reentrance of BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree. destroyShadowSubtree could dispatch 'blur' event unexpectedly because element()->focused() had incorrect information. We make sure it has correct information by checking if the UA shadow root contains the focused element. BUG=257353 Review URL: https://chromiumcodereview.appspot.com/19067004 git-svn-id: svn://svn.chromium.org/blink/trunk@154086 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void BaseMultipleFieldsDateAndTimeInputType::didBlurFromControl() { if (containsFocusedShadowElement()) return; RefPtr<HTMLInputElement> protector(element()); element()->setFocus(false); }
171,211
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jas_matrix_t *jas_matrix_create(int numrows, int numcols) { jas_matrix_t *matrix; int i; if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) { return 0; } matrix->flags_ = 0; matrix->numrows_ = numrows; matrix->numcols_ = numcols; matrix->rows_ = 0; matrix->maxrows_ = numrows; matrix->data_ = 0; matrix->datasize_ = numrows * numcols; if (matrix->maxrows_ > 0) { if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_, sizeof(jas_seqent_t *)))) { jas_matrix_destroy(matrix); return 0; } } if (matrix->datasize_ > 0) { if (!(matrix->data_ = jas_alloc2(matrix->datasize_, sizeof(jas_seqent_t)))) { jas_matrix_destroy(matrix); return 0; } } for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[i * matrix->numcols_]; } for (i = 0; i < matrix->datasize_; ++i) { matrix->data_[i] = 0; } matrix->xstart_ = 0; matrix->ystart_ = 0; matrix->xend_ = matrix->numcols_; matrix->yend_ = matrix->numrows_; return matrix; } Commit Message: Fixed a problem with a null pointer dereference in the BMP decoder. CWE ID: CWE-476
jas_matrix_t *jas_matrix_create(int numrows, int numcols) { jas_matrix_t *matrix; int i; if (numrows < 0 || numcols < 0) { return 0; } if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) { return 0; } matrix->flags_ = 0; matrix->numrows_ = numrows; matrix->numcols_ = numcols; matrix->rows_ = 0; matrix->maxrows_ = numrows; matrix->data_ = 0; matrix->datasize_ = numrows * numcols; if (matrix->maxrows_ > 0) { if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_, sizeof(jas_seqent_t *)))) { jas_matrix_destroy(matrix); return 0; } } if (matrix->datasize_ > 0) { if (!(matrix->data_ = jas_alloc2(matrix->datasize_, sizeof(jas_seqent_t)))) { jas_matrix_destroy(matrix); return 0; } } for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[i * matrix->numcols_]; } for (i = 0; i < matrix->datasize_; ++i) { matrix->data_[i] = 0; } matrix->xstart_ = 0; matrix->ystart_ = 0; matrix->xend_ = matrix->numcols_; matrix->yend_ = matrix->numrows_; return matrix; }
168,755