instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Chapters::Atom::ExpandDisplaysArray() { if (m_displays_size > m_displays_count) return true; // nothing else to do const int size = (m_displays_size == 0) ? 1 : 2 * m_displays_size; Display* const displays = new (std::nothrow) Display[size]; if (displays == NULL) return false; for (int idx = 0; idx < m_displays_count; ++idx) { m_displays[idx].ShallowCopy(displays[idx]); } delete[] m_displays; m_displays = displays; m_displays_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::Atom::ExpandDisplaysArray()
174,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PreconnectManager::FinishPreresolveJob(PreresolveJobId job_id, bool success) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); PreresolveJob* job = preresolve_jobs_.Lookup(job_id); DCHECK(job); bool need_preconnect = success && job->need_preconnect(); if (need_preconnect) { PreconnectUrl(job->url, job->num_sockets, job->allow_credentials, job->network_isolation_key); } PreresolveInfo* info = job->info; if (info) info->stats->requests_stats.emplace_back(job->url, need_preconnect); preresolve_jobs_.Remove(job_id); --inflight_preresolves_count_; if (info) { DCHECK_LE(1u, info->inflight_count); --info->inflight_count; } if (info && info->is_done()) AllPreresolvesForUrlFinished(info); TryToLaunchPreresolveJobs(); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void PreconnectManager::FinishPreresolveJob(PreresolveJobId job_id, bool success) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); PreresolveJob* job = preresolve_jobs_.Lookup(job_id); DCHECK(job); bool need_preconnect = success && job->need_preconnect(); if (need_preconnect) { PreconnectUrl(job->url, job->num_sockets, job->allow_credentials, job->network_isolation_key); } PreresolveInfo* info = job->info; if (info) { info->stats->requests_stats.emplace_back(url::Origin::Create(job->url), need_preconnect); } preresolve_jobs_.Remove(job_id); --inflight_preresolves_count_; if (info) { DCHECK_LE(1u, info->inflight_count); --info->inflight_count; } if (info && info->is_done()) AllPreresolvesForUrlFinished(info); TryToLaunchPreresolveJobs(); }
172,374
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: InputMethodLibrary* CrosLibrary::GetInputMethodLibrary() { return input_method_lib_.GetDefaultImpl(use_stub_impl_); } 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
InputMethodLibrary* CrosLibrary::GetInputMethodLibrary() {
170,623
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: v8::Local<v8::Object> V8Console::createConsole(InspectedContext* inspectedContext, bool hasMemoryAttribute) { v8::Local<v8::Context> context = inspectedContext->context(); v8::Context::Scope contextScope(context); v8::Isolate* isolate = context->GetIsolate(); v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); v8::Local<v8::Object> console = v8::Object::New(isolate); createBoundFunctionProperty(context, console, "debug", V8Console::debugCallback); createBoundFunctionProperty(context, console, "error", V8Console::errorCallback); createBoundFunctionProperty(context, console, "info", V8Console::infoCallback); createBoundFunctionProperty(context, console, "log", V8Console::logCallback); createBoundFunctionProperty(context, console, "warn", V8Console::warnCallback); createBoundFunctionProperty(context, console, "dir", V8Console::dirCallback); createBoundFunctionProperty(context, console, "dirxml", V8Console::dirxmlCallback); createBoundFunctionProperty(context, console, "table", V8Console::tableCallback); createBoundFunctionProperty(context, console, "trace", V8Console::traceCallback); createBoundFunctionProperty(context, console, "group", V8Console::groupCallback); createBoundFunctionProperty(context, console, "groupCollapsed", V8Console::groupCollapsedCallback); createBoundFunctionProperty(context, console, "groupEnd", V8Console::groupEndCallback); createBoundFunctionProperty(context, console, "clear", V8Console::clearCallback); createBoundFunctionProperty(context, console, "count", V8Console::countCallback); createBoundFunctionProperty(context, console, "assert", V8Console::assertCallback); createBoundFunctionProperty(context, console, "markTimeline", V8Console::markTimelineCallback); createBoundFunctionProperty(context, console, "profile", V8Console::profileCallback); createBoundFunctionProperty(context, console, "profileEnd", V8Console::profileEndCallback); createBoundFunctionProperty(context, console, "timeline", V8Console::timelineCallback); createBoundFunctionProperty(context, console, "timelineEnd", V8Console::timelineEndCallback); createBoundFunctionProperty(context, console, "time", V8Console::timeCallback); createBoundFunctionProperty(context, console, "timeEnd", V8Console::timeEndCallback); createBoundFunctionProperty(context, console, "timeStamp", V8Console::timeStampCallback); bool success = console->SetPrototype(context, v8::Object::New(isolate)).FromMaybe(false); DCHECK(success); if (hasMemoryAttribute) console->SetAccessorProperty(toV8StringInternalized(isolate, "memory"), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memoryGetterCallback, console, 0).ToLocalChecked(), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memorySetterCallback, v8::Local<v8::Value>(), 0).ToLocalChecked(), static_cast<v8::PropertyAttribute>(v8::None), v8::DEFAULT); console->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext)); return console; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79
v8::Local<v8::Object> V8Console::createConsole(InspectedContext* inspectedContext, bool hasMemoryAttribute) { v8::Local<v8::Context> context = inspectedContext->context(); v8::Context::Scope contextScope(context); v8::Isolate* isolate = context->GetIsolate(); v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); v8::Local<v8::Object> console = v8::Object::New(isolate); bool success = console->SetPrototype(context, v8::Object::New(isolate)).FromMaybe(false); DCHECK(success); createBoundFunctionProperty(context, console, "debug", V8Console::debugCallback); createBoundFunctionProperty(context, console, "error", V8Console::errorCallback); createBoundFunctionProperty(context, console, "info", V8Console::infoCallback); createBoundFunctionProperty(context, console, "log", V8Console::logCallback); createBoundFunctionProperty(context, console, "warn", V8Console::warnCallback); createBoundFunctionProperty(context, console, "dir", V8Console::dirCallback); createBoundFunctionProperty(context, console, "dirxml", V8Console::dirxmlCallback); createBoundFunctionProperty(context, console, "table", V8Console::tableCallback); createBoundFunctionProperty(context, console, "trace", V8Console::traceCallback); createBoundFunctionProperty(context, console, "group", V8Console::groupCallback); createBoundFunctionProperty(context, console, "groupCollapsed", V8Console::groupCollapsedCallback); createBoundFunctionProperty(context, console, "groupEnd", V8Console::groupEndCallback); createBoundFunctionProperty(context, console, "clear", V8Console::clearCallback); createBoundFunctionProperty(context, console, "count", V8Console::countCallback); createBoundFunctionProperty(context, console, "assert", V8Console::assertCallback); createBoundFunctionProperty(context, console, "markTimeline", V8Console::markTimelineCallback); createBoundFunctionProperty(context, console, "profile", V8Console::profileCallback); createBoundFunctionProperty(context, console, "profileEnd", V8Console::profileEndCallback); createBoundFunctionProperty(context, console, "timeline", V8Console::timelineCallback); createBoundFunctionProperty(context, console, "timelineEnd", V8Console::timelineEndCallback); createBoundFunctionProperty(context, console, "time", V8Console::timeCallback); createBoundFunctionProperty(context, console, "timeEnd", V8Console::timeEndCallback); createBoundFunctionProperty(context, console, "timeStamp", V8Console::timeStampCallback); if (hasMemoryAttribute) console->SetAccessorProperty(toV8StringInternalized(isolate, "memory"), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memoryGetterCallback, console, 0).ToLocalChecked(), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memorySetterCallback, v8::Local<v8::Value>(), 0).ToLocalChecked(), static_cast<v8::PropertyAttribute>(v8::None), v8::DEFAULT); console->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext)); return console; }
172,063
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram( Reference ref) { PersistentHistogramData* data = memory_allocator_->GetAsObject<PersistentHistogramData>(ref); const size_t length = memory_allocator_->GetAllocSize(ref); if (!data || data->name[0] == '\0' || reinterpret_cast<char*>(data)[length - 1] != '\0' || data->samples_metadata.id == 0 || data->logged_metadata.id == 0 || (data->logged_metadata.id != data->samples_metadata.id && data->logged_metadata.id != data->samples_metadata.id + 1) || HashMetricName(data->name) != data->samples_metadata.id) { RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_METADATA); NOTREACHED(); return nullptr; } return CreateHistogram(data); } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram( Reference ref) { PersistentHistogramData* data = memory_allocator_->GetAsObject<PersistentHistogramData>(ref); const size_t length = memory_allocator_->GetAllocSize(ref); if (!data || data->name[0] == '\0' || reinterpret_cast<char*>(data)[length - 1] != '\0' || data->samples_metadata.id == 0 || data->logged_metadata.id == 0 || (data->logged_metadata.id != data->samples_metadata.id && data->logged_metadata.id != data->samples_metadata.id + 1) || HashMetricName(data->name) != data->samples_metadata.id) { NOTREACHED(); return nullptr; } return CreateHistogram(data); }
172,134
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void fht16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { vp9_fht16x16_c(in, out, stride, tx_type); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void fht16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { void idct16x16_ref(const tran_low_t *in, uint8_t *dest, int stride, int /*tx_type*/) { vpx_idct16x16_256_add_c(in, dest, stride); } void fht16x16_ref(const int16_t *in, tran_low_t *out, int stride, int tx_type) { vp9_fht16x16_c(in, out, stride, tx_type); }
174,530
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static blink::WebScreenOrientations stringToOrientations(const AtomicString& orientationString) { DEFINE_STATIC_LOCAL(const AtomicString, portrait, ("portrait", AtomicString::ConstructFromLiteral)); DEFINE_STATIC_LOCAL(const AtomicString, landscape, ("landscape", AtomicString::ConstructFromLiteral)); if (orientationString == portrait) return blink::WebScreenOrientationPortraitPrimary | blink::WebScreenOrientationPortraitSecondary; if (orientationString == landscape) return blink::WebScreenOrientationLandscapePrimary | blink::WebScreenOrientationLandscapeSecondary; unsigned length = 0; ScreenOrientationInfo* orientationMap = orientationsMap(length); for (unsigned i = 0; i < length; ++i) { if (orientationMap[i].name == orientationString) return orientationMap[i].orientation; } return 0; } Commit Message: Screen Orientation: use OrientationLockType enum for lockOrientation(). BUG=162827 Review URL: https://codereview.chromium.org/204653002 git-svn-id: svn://svn.chromium.org/blink/trunk@169972 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
static blink::WebScreenOrientations stringToOrientations(const AtomicString& orientationString) { DEFINE_STATIC_LOCAL(const AtomicString, any, ("any", AtomicString::ConstructFromLiteral)); DEFINE_STATIC_LOCAL(const AtomicString, portrait, ("portrait", AtomicString::ConstructFromLiteral)); DEFINE_STATIC_LOCAL(const AtomicString, landscape, ("landscape", AtomicString::ConstructFromLiteral)); if (orientationString == any) { return blink::WebScreenOrientationPortraitPrimary | blink::WebScreenOrientationPortraitSecondary | blink::WebScreenOrientationLandscapePrimary | blink::WebScreenOrientationLandscapeSecondary; } if (orientationString == portrait) return blink::WebScreenOrientationPortraitPrimary | blink::WebScreenOrientationPortraitSecondary; if (orientationString == landscape) return blink::WebScreenOrientationLandscapePrimary | blink::WebScreenOrientationLandscapeSecondary; unsigned length = 0; ScreenOrientationInfo* orientationMap = orientationsMap(length); for (unsigned i = 0; i < length; ++i) { if (orientationMap[i].name == orientationString) return orientationMap[i].orientation; } return 0; }
171,440
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) { List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); notifyEmptyBufferDone(inHeader); continue; } BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } if (inHeader->nOffset == 0) { mAnchorTimeUs = inHeader->nTimeStamp; mNumSamplesOutput = 0; } const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset; int32_t numBytesRead; if (mMode == MODE_NARROW) { if (outHeader->nAllocLen < kNumSamplesPerFrameNB * sizeof(int16_t)) { ALOGE("b/27662364: NB expected output buffer %zu bytes vs %u", kNumSamplesPerFrameNB * sizeof(int16_t), outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "27662364"); notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); mSignalledError = true; return; } int16 mode = ((inputPtr[0] >> 3) & 0x0f); size_t frameSize = WmfDecBytesPerFrame[mode] + 1; if (inHeader->nFilledLen < frameSize) { ALOGE("b/27662364: expected %zu bytes vs %u", frameSize, inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL); mSignalledError = true; return; } numBytesRead = AMRDecode(mState, (Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f), (UWord8 *)&inputPtr[1], reinterpret_cast<int16_t *>(outHeader->pBuffer), MIME_IETF); if (numBytesRead == -1) { ALOGE("PV AMR decoder AMRDecode() call failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } ++numBytesRead; // Include the frame type header byte. if (static_cast<size_t>(numBytesRead) > inHeader->nFilledLen) { notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } } else { if (outHeader->nAllocLen < kNumSamplesPerFrameWB * sizeof(int16_t)) { ALOGE("b/27662364: WB expected output buffer %zu bytes vs %u", kNumSamplesPerFrameWB * sizeof(int16_t), outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "27662364"); notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); mSignalledError = true; return; } int16 mode = ((inputPtr[0] >> 3) & 0x0f); if (mode >= 10 && mode <= 13) { ALOGE("encountered illegal frame type %d in AMR WB content.", mode); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } size_t frameSize = getFrameSize(mode); if (inHeader->nFilledLen < frameSize) { ALOGE("b/27662364: expected %zu bytes vs %u", frameSize, inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL); mSignalledError = true; return; } int16_t *outPtr = (int16_t *)outHeader->pBuffer; if (mode >= 9) { memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t)); } else if (mode < 9) { int16 frameType; RX_State_wb rx_state; mime_unsorting( const_cast<uint8_t *>(&inputPtr[1]), mInputSampleBuffer, &frameType, &mode, 1, &rx_state); int16_t numSamplesOutput; pvDecoder_AmrWb( mode, mInputSampleBuffer, outPtr, &numSamplesOutput, mDecoderBuf, frameType, mDecoderCookie); CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB); for (int i = 0; i < kNumSamplesPerFrameWB; ++i) { /* Delete the 2 LSBs (14-bit output) */ outPtr[i] &= 0xfffC; } } numBytesRead = frameSize; } inHeader->nOffset += numBytesRead; inHeader->nFilledLen -= numBytesRead; outHeader->nFlags = 0; outHeader->nOffset = 0; if (mMode == MODE_NARROW) { outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateNB; mNumSamplesOutput += kNumSamplesPerFrameNB; } else { outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateWB; mNumSamplesOutput += kNumSamplesPerFrameWB; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; ++mInputBufferCount; } } Commit Message: Fix AMR decoder Previous change caused EOS to be ignored. Bug: 27843673 Related-to-bug: 27662364 Change-Id: Ia148a88abc861a9b393f42bc7cd63d8d3ae349bc CWE ID: CWE-264
void SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) { List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); notifyEmptyBufferDone(inHeader); continue; } if (inHeader->nOffset == 0) { mAnchorTimeUs = inHeader->nTimeStamp; mNumSamplesOutput = 0; } const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset; int32_t numBytesRead; if (mMode == MODE_NARROW) { if (outHeader->nAllocLen < kNumSamplesPerFrameNB * sizeof(int16_t)) { ALOGE("b/27662364: NB expected output buffer %zu bytes vs %u", kNumSamplesPerFrameNB * sizeof(int16_t), outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "27662364"); notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); mSignalledError = true; return; } int16 mode = ((inputPtr[0] >> 3) & 0x0f); size_t frameSize = WmfDecBytesPerFrame[mode] + 1; if (inHeader->nFilledLen < frameSize) { ALOGE("b/27662364: expected %zu bytes vs %u", frameSize, inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL); mSignalledError = true; return; } numBytesRead = AMRDecode(mState, (Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f), (UWord8 *)&inputPtr[1], reinterpret_cast<int16_t *>(outHeader->pBuffer), MIME_IETF); if (numBytesRead == -1) { ALOGE("PV AMR decoder AMRDecode() call failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } ++numBytesRead; // Include the frame type header byte. if (static_cast<size_t>(numBytesRead) > inHeader->nFilledLen) { notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } } else { if (outHeader->nAllocLen < kNumSamplesPerFrameWB * sizeof(int16_t)) { ALOGE("b/27662364: WB expected output buffer %zu bytes vs %u", kNumSamplesPerFrameWB * sizeof(int16_t), outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "27662364"); notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); mSignalledError = true; return; } int16 mode = ((inputPtr[0] >> 3) & 0x0f); if (mode >= 10 && mode <= 13) { ALOGE("encountered illegal frame type %d in AMR WB content.", mode); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } size_t frameSize = getFrameSize(mode); if (inHeader->nFilledLen < frameSize) { ALOGE("b/27662364: expected %zu bytes vs %u", frameSize, inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL); mSignalledError = true; return; } int16_t *outPtr = (int16_t *)outHeader->pBuffer; if (mode >= 9) { memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t)); } else if (mode < 9) { int16 frameType; RX_State_wb rx_state; mime_unsorting( const_cast<uint8_t *>(&inputPtr[1]), mInputSampleBuffer, &frameType, &mode, 1, &rx_state); int16_t numSamplesOutput; pvDecoder_AmrWb( mode, mInputSampleBuffer, outPtr, &numSamplesOutput, mDecoderBuf, frameType, mDecoderCookie); CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB); for (int i = 0; i < kNumSamplesPerFrameWB; ++i) { /* Delete the 2 LSBs (14-bit output) */ outPtr[i] &= 0xfffC; } } numBytesRead = frameSize; } inHeader->nOffset += numBytesRead; inHeader->nFilledLen -= numBytesRead; outHeader->nFlags = 0; outHeader->nOffset = 0; if (mMode == MODE_NARROW) { outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateNB; mNumSamplesOutput += kNumSamplesPerFrameNB; } else { outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateWB; mNumSamplesOutput += kNumSamplesPerFrameWB; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; ++mInputBufferCount; } }
174,230
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; Quantum index; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { PixelInfo quantum_bits; PixelPacket shift; /* Verify BMP identifier. */ if (bmp_info.ba_offset == 0) start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MagickPathExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MagickPathExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } (void) ReadBlobLSBLong(image); /* Profile data */ (void) ReadBlobLSBLong(image); /* Profile size */ (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->alpha_trait=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait : UndefinedPixelTrait; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->resolution.x=(double) bmp_info.x_pixels/100.0; image->resolution.y=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if (((MagickSizeType) length/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->alpha_trait=BlendPixelTrait; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register unsigned int sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red >= 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green >= 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue >= 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0) { shift.alpha++; if (shift.alpha >= 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.red=(MagickRealType) (sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.green=(MagickRealType) (sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.blue=(MagickRealType) (sample-shift.blue); sample=shift.alpha; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.alpha=(MagickRealType) (sample-shift.alpha); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; x++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns; x != 0; --x) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha == 8) alpha|=(alpha >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1268 CWE ID: CWE-770
static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; Quantum index; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { PixelInfo quantum_bits; PixelPacket shift; /* Verify BMP identifier. */ if (bmp_info.ba_offset == 0) start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MagickPathExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); if (bmp_info.number_colors > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MagickPathExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } (void) ReadBlobLSBLong(image); /* Profile data */ (void) ReadBlobLSBLong(image); /* Profile size */ (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->alpha_trait=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait : UndefinedPixelTrait; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->resolution.x=(double) bmp_info.x_pixels/100.0; image->resolution.y=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if (((MagickSizeType) length/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->alpha_trait=BlendPixelTrait; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register unsigned int sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red >= 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green >= 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue >= 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0) { shift.alpha++; if (shift.alpha >= 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.red=(MagickRealType) (sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.green=(MagickRealType) (sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.blue=(MagickRealType) (sample-shift.blue); sample=shift.alpha; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.alpha=(MagickRealType) (sample-shift.alpha); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; x++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns; x != 0; --x) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha == 8) alpha|=(alpha >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }
169,036
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct bpf_verifier_state *this_branch = env->cur_state; struct bpf_verifier_state *other_branch; struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; struct bpf_reg_state *dst_reg, *other_branch_regs; u8 opcode = BPF_OP(insn->code); int err; if (opcode > BPF_JSLE) { verbose(env, "invalid BPF_JMP opcode %x\n", opcode); return -EINVAL; } if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->src_reg); return -EACCES; } } else { if (insn->src_reg != BPF_REG_0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg = &regs[insn->dst_reg]; if (BPF_SRC(insn->code) == BPF_K) { int pred = is_branch_taken(dst_reg, insn->imm, opcode); if (pred == 1) { /* only follow the goto, ignore fall-through */ *insn_idx += insn->off; return 0; } else if (pred == 0) { /* only follow fall-through branch, since * that's where the program will go */ return 0; } } other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx); if (!other_branch) return -EFAULT; other_branch_regs = other_branch->frame[other_branch->curframe]->regs; /* detect if we are comparing against a constant value so we can adjust * our min/max values for our dst register. * this is only legit if both are scalars (or pointers to the same * object, I suppose, but we don't support that right now), because * otherwise the different base pointers mean the offsets aren't * comparable. */ if (BPF_SRC(insn->code) == BPF_X) { if (dst_reg->type == SCALAR_VALUE && regs[insn->src_reg].type == SCALAR_VALUE) { if (tnum_is_const(regs[insn->src_reg].var_off)) reg_set_min_max(&other_branch_regs[insn->dst_reg], dst_reg, regs[insn->src_reg].var_off.value, opcode); else if (tnum_is_const(dst_reg->var_off)) reg_set_min_max_inv(&other_branch_regs[insn->src_reg], &regs[insn->src_reg], dst_reg->var_off.value, opcode); else if (opcode == BPF_JEQ || opcode == BPF_JNE) /* Comparing for equality, we can combine knowledge */ reg_combine_min_max(&other_branch_regs[insn->src_reg], &other_branch_regs[insn->dst_reg], &regs[insn->src_reg], &regs[insn->dst_reg], opcode); } } else if (dst_reg->type == SCALAR_VALUE) { reg_set_min_max(&other_branch_regs[insn->dst_reg], dst_reg, insn->imm, opcode); } /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ if (BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && reg_type_may_be_null(dst_reg->type)) { /* Mark all identical registers in each branch as either * safe or unknown depending R == 0 or R != 0 conditional. */ mark_ptr_or_null_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); mark_ptr_or_null_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg], this_branch, other_branch) && is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->dst_reg); return -EACCES; } if (env->log.level) print_verifier_state(env, this_branch->frame[this_branch->curframe]); return 0; } Commit Message: bpf: prevent out of bounds speculation on pointer arithmetic Jann reported that the original commit back in b2157399cc98 ("bpf: prevent out-of-bounds speculation") was not sufficient to stop CPU from speculating out of bounds memory access: While b2157399cc98 only focussed on masking array map access for unprivileged users for tail calls and data access such that the user provided index gets sanitized from BPF program and syscall side, there is still a more generic form affected from BPF programs that applies to most maps that hold user data in relation to dynamic map access when dealing with unknown scalars or "slow" known scalars as access offset, for example: - Load a map value pointer into R6 - Load an index into R7 - Do a slow computation (e.g. with a memory dependency) that loads a limit into R8 (e.g. load the limit from a map for high latency, then mask it to make the verifier happy) - Exit if R7 >= R8 (mispredicted branch) - Load R0 = R6[R7] - Load R0 = R6[R0] For unknown scalars there are two options in the BPF verifier where we could derive knowledge from in order to guarantee safe access to the memory: i) While </>/<=/>= variants won't allow to derive any lower or upper bounds from the unknown scalar where it would be safe to add it to the map value pointer, it is possible through ==/!= test however. ii) another option is to transform the unknown scalar into a known scalar, for example, through ALU ops combination such as R &= <imm> followed by R |= <imm> or any similar combination where the original information from the unknown scalar would be destroyed entirely leaving R with a constant. The initial slow load still precedes the latter ALU ops on that register, so the CPU executes speculatively from that point. Once we have the known scalar, any compare operation would work then. A third option only involving registers with known scalars could be crafted as described in [0] where a CPU port (e.g. Slow Int unit) would be filled with many dependent computations such that the subsequent condition depending on its outcome has to wait for evaluation on its execution port and thereby executing speculatively if the speculated code can be scheduled on a different execution port, or any other form of mistraining as described in [1], for example. Given this is not limited to only unknown scalars, not only map but also stack access is affected since both is accessible for unprivileged users and could potentially be used for out of bounds access under speculation. In order to prevent any of these cases, the verifier is now sanitizing pointer arithmetic on the offset such that any out of bounds speculation would be masked in a way where the pointer arithmetic result in the destination register will stay unchanged, meaning offset masked into zero similar as in array_index_nospec() case. With regards to implementation, there are three options that were considered: i) new insn for sanitation, ii) push/pop insn and sanitation as inlined BPF, iii) reuse of ax register and sanitation as inlined BPF. Option i) has the downside that we end up using from reserved bits in the opcode space, but also that we would require each JIT to emit masking as native arch opcodes meaning mitigation would have slow adoption till everyone implements it eventually which is counter-productive. Option ii) and iii) have both in common that a temporary register is needed in order to implement the sanitation as inlined BPF since we are not allowed to modify the source register. While a push / pop insn in ii) would be useful to have in any case, it requires once again that every JIT needs to implement it first. While possible, amount of changes needed would also be unsuitable for a -stable patch. Therefore, the path which has fewer changes, less BPF instructions for the mitigation and does not require anything to be changed in the JITs is option iii) which this work is pursuing. The ax register is already mapped to a register in all JITs (modulo arm32 where it's mapped to stack as various other BPF registers there) and used in constant blinding for JITs-only so far. It can be reused for verifier rewrites under certain constraints. The interpreter's tmp "register" has therefore been remapped into extending the register set with hidden ax register and reusing that for a number of instructions that needed the prior temporary variable internally (e.g. div, mod). This allows for zero increase in stack space usage in the interpreter, and enables (restricted) generic use in rewrites otherwise as long as such a patchlet does not make use of these instructions. The sanitation mask is dynamic and relative to the offset the map value or stack pointer currently holds. There are various cases that need to be taken under consideration for the masking, e.g. such operation could look as follows: ptr += val or val += ptr or ptr -= val. Thus, the value to be sanitized could reside either in source or in destination register, and the limit is different depending on whether the ALU op is addition or subtraction and depending on the current known and bounded offset. The limit is derived as follows: limit := max_value_size - (smin_value + off). For subtraction: limit := umax_value + off. This holds because we do not allow any pointer arithmetic that would temporarily go out of bounds or would have an unknown value with mixed signed bounds where it is unclear at verification time whether the actual runtime value would be either negative or positive. For example, we have a derived map pointer value with constant offset and bounded one, so limit based on smin_value works because the verifier requires that statically analyzed arithmetic on the pointer must be in bounds, and thus it checks if resulting smin_value + off and umax_value + off is still within map value bounds at time of arithmetic in addition to time of access. Similarly, for the case of stack access we derive the limit as follows: MAX_BPF_STACK + off for subtraction and -off for the case of addition where off := ptr_reg->off + ptr_reg->var_off.value. Subtraction is a special case for the masking which can be in form of ptr += -val, ptr -= -val, or ptr -= val. In the first two cases where we know that the value is negative, we need to temporarily negate the value in order to do the sanitation on a positive value where we later swap the ALU op, and restore original source register if the value was in source. The sanitation of pointer arithmetic alone is still not fully sufficient as is, since a scenario like the following could happen ... PTR += 0x1000 (e.g. K-based imm) PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON PTR += 0x1000 PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON [...] ... which under speculation could end up as ... PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] [...] ... and therefore still access out of bounds. To prevent such case, the verifier is also analyzing safety for potential out of bounds access under speculative execution. Meaning, it is also simulating pointer access under truncation. We therefore "branch off" and push the current verification state after the ALU operation with known 0 to the verification stack for later analysis. Given the current path analysis succeeded it is likely that the one under speculation can be pruned. In any case, it is also subject to existing complexity limits and therefore anything beyond this point will be rejected. In terms of pruning, it needs to be ensured that the verification state from speculative execution simulation must never prune a non-speculative execution path, therefore, we mark verifier state accordingly at the time of push_stack(). If verifier detects out of bounds access under speculative execution from one of the possible paths that includes a truncation, it will reject such program. Given we mask every reg-based pointer arithmetic for unprivileged programs, we've been looking into how it could affect real-world programs in terms of size increase. As the majority of programs are targeted for privileged-only use case, we've unconditionally enabled masking (with its alu restrictions on top of it) for privileged programs for the sake of testing in order to check i) whether they get rejected in its current form, and ii) by how much the number of instructions and size will increase. We've tested this by using Katran, Cilium and test_l4lb from the kernel selftests. For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb we've used test_l4lb.o as well as test_l4lb_noinline.o. We found that none of the programs got rejected by the verifier with this change, and that impact is rather minimal to none. balancer_kern.o had 13,904 bytes (1,738 insns) xlated and 7,797 bytes JITed before and after the change. Most complex program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated and 18,538 bytes JITed before and after and none of the other tail call programs in bpf_lxc.o had any changes either. For the older bpf_lxc_opt_-DUNKNOWN.o object we found a small increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed after the change. Other programs from that object file had similar small increase. Both test_l4lb.o had no change and remained at 6,544 bytes (817 insns) xlated and 3,401 bytes JITed and for test_l4lb_noinline.o constant at 5,080 bytes (634 insns) xlated and 3,313 bytes JITed. This can be explained in that LLVM typically optimizes stack based pointer arithmetic by using K-based operations and that use of dynamic map access is not overly frequent. However, in future we may decide to optimize the algorithm further under known guarantees from branch and value speculation. Latter seems also unclear in terms of prediction heuristics that today's CPUs apply as well as whether there could be collisions in e.g. the predictor's Value History/Pattern Table for triggering out of bounds access, thus masking is performed unconditionally at this point but could be subject to relaxation later on. We were generally also brainstorming various other approaches for mitigation, but the blocker was always lack of available registers at runtime and/or overhead for runtime tracking of limits belonging to a specific pointer. Thus, we found this to be minimally intrusive under given constraints. With that in place, a simple example with sanitized access on unprivileged load at post-verification time looks as follows: # bpftool prog dump xlated id 282 [...] 28: (79) r1 = *(u64 *)(r7 +0) 29: (79) r2 = *(u64 *)(r7 +8) 30: (57) r1 &= 15 31: (79) r3 = *(u64 *)(r0 +4608) 32: (57) r3 &= 1 33: (47) r3 |= 1 34: (2d) if r2 > r3 goto pc+19 35: (b4) (u32) r11 = (u32) 20479 | 36: (1f) r11 -= r2 | Dynamic sanitation for pointer 37: (4f) r11 |= r2 | arithmetic with registers 38: (87) r11 = -r11 | containing bounded or known 39: (c7) r11 s>>= 63 | scalars in order to prevent 40: (5f) r11 &= r2 | out of bounds speculation. 41: (0f) r4 += r11 | 42: (71) r4 = *(u8 *)(r4 +0) 43: (6f) r4 <<= r1 [...] For the case where the scalar sits in the destination register as opposed to the source register, the following code is emitted for the above example: [...] 16: (b4) (u32) r11 = (u32) 20479 17: (1f) r11 -= r2 18: (4f) r11 |= r2 19: (87) r11 = -r11 20: (c7) r11 s>>= 63 21: (5f) r2 &= r11 22: (0f) r2 += r0 23: (61) r0 = *(u32 *)(r2 +0) [...] JIT blinding example with non-conflicting use of r10: [...] d5: je 0x0000000000000106 _ d7: mov 0x0(%rax),%edi | da: mov $0xf153246,%r10d | Index load from map value and e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f. e7: and %r10,%rdi |_ ea: mov $0x2f,%r10d | f0: sub %rdi,%r10 | Sanitized addition. Both use r10 f3: or %rdi,%r10 | but do not interfere with each f6: neg %r10 | other. (Neither do these instructions f9: sar $0x3f,%r10 | interfere with the use of ax as temp fd: and %r10,%rdi | in interpreter.) 100: add %rax,%rdi |_ 103: mov 0x0(%rdi),%eax [...] Tested that it fixes Jann's reproducer, and also checked that test_verifier and test_progs suite with interpreter, JIT and JIT with hardening enabled on x86-64 and arm64 runs successfully. [0] Speculose: Analyzing the Security Implications of Speculative Execution in CPUs, Giorgi Maisuradze and Christian Rossow, https://arxiv.org/pdf/1801.04084.pdf [1] A Systematic Evaluation of Transient Execution Attacks and Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz, Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens, Dmitry Evtyushkin, Daniel Gruss, https://arxiv.org/pdf/1811.05441.pdf Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> CWE ID: CWE-189
static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct bpf_verifier_state *this_branch = env->cur_state; struct bpf_verifier_state *other_branch; struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; struct bpf_reg_state *dst_reg, *other_branch_regs; u8 opcode = BPF_OP(insn->code); int err; if (opcode > BPF_JSLE) { verbose(env, "invalid BPF_JMP opcode %x\n", opcode); return -EINVAL; } if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->src_reg); return -EACCES; } } else { if (insn->src_reg != BPF_REG_0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg = &regs[insn->dst_reg]; if (BPF_SRC(insn->code) == BPF_K) { int pred = is_branch_taken(dst_reg, insn->imm, opcode); if (pred == 1) { /* only follow the goto, ignore fall-through */ *insn_idx += insn->off; return 0; } else if (pred == 0) { /* only follow fall-through branch, since * that's where the program will go */ return 0; } } other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false); if (!other_branch) return -EFAULT; other_branch_regs = other_branch->frame[other_branch->curframe]->regs; /* detect if we are comparing against a constant value so we can adjust * our min/max values for our dst register. * this is only legit if both are scalars (or pointers to the same * object, I suppose, but we don't support that right now), because * otherwise the different base pointers mean the offsets aren't * comparable. */ if (BPF_SRC(insn->code) == BPF_X) { if (dst_reg->type == SCALAR_VALUE && regs[insn->src_reg].type == SCALAR_VALUE) { if (tnum_is_const(regs[insn->src_reg].var_off)) reg_set_min_max(&other_branch_regs[insn->dst_reg], dst_reg, regs[insn->src_reg].var_off.value, opcode); else if (tnum_is_const(dst_reg->var_off)) reg_set_min_max_inv(&other_branch_regs[insn->src_reg], &regs[insn->src_reg], dst_reg->var_off.value, opcode); else if (opcode == BPF_JEQ || opcode == BPF_JNE) /* Comparing for equality, we can combine knowledge */ reg_combine_min_max(&other_branch_regs[insn->src_reg], &other_branch_regs[insn->dst_reg], &regs[insn->src_reg], &regs[insn->dst_reg], opcode); } } else if (dst_reg->type == SCALAR_VALUE) { reg_set_min_max(&other_branch_regs[insn->dst_reg], dst_reg, insn->imm, opcode); } /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ if (BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && reg_type_may_be_null(dst_reg->type)) { /* Mark all identical registers in each branch as either * safe or unknown depending R == 0 or R != 0 conditional. */ mark_ptr_or_null_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); mark_ptr_or_null_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg], this_branch, other_branch) && is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->dst_reg); return -EACCES; } if (env->log.level) print_verifier_state(env, this_branch->frame[this_branch->curframe]); return 0; }
170,240
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mif_process_cmpt(mif_hdr_t *hdr, char *buf) { jas_tvparser_t *tvp; mif_cmpt_t *cmpt; int id; cmpt = 0; tvp = 0; if (!(cmpt = mif_cmpt_create())) { goto error; } cmpt->tlx = 0; cmpt->tly = 0; cmpt->sampperx = 0; cmpt->samppery = 0; cmpt->width = 0; cmpt->height = 0; cmpt->prec = 0; cmpt->sgnd = -1; cmpt->data = 0; if (!(tvp = jas_tvparser_create(buf))) { goto error; } while (!(id = jas_tvparser_next(tvp))) { switch (jas_taginfo_nonull(jas_taginfos_lookup(mif_tags, jas_tvparser_gettag(tvp)))->id) { case MIF_TLX: cmpt->tlx = atoi(jas_tvparser_getval(tvp)); break; case MIF_TLY: cmpt->tly = atoi(jas_tvparser_getval(tvp)); break; case MIF_WIDTH: cmpt->width = atoi(jas_tvparser_getval(tvp)); break; case MIF_HEIGHT: cmpt->height = atoi(jas_tvparser_getval(tvp)); break; case MIF_HSAMP: cmpt->sampperx = atoi(jas_tvparser_getval(tvp)); break; case MIF_VSAMP: cmpt->samppery = atoi(jas_tvparser_getval(tvp)); break; case MIF_PREC: cmpt->prec = atoi(jas_tvparser_getval(tvp)); break; case MIF_SGND: cmpt->sgnd = atoi(jas_tvparser_getval(tvp)); break; case MIF_DATA: if (!(cmpt->data = jas_strdup(jas_tvparser_getval(tvp)))) { return -1; } break; } } jas_tvparser_destroy(tvp); if (!cmpt->sampperx || !cmpt->samppery) { goto error; } if (mif_hdr_addcmpt(hdr, hdr->numcmpts, cmpt)) { goto error; } return 0; error: if (cmpt) { mif_cmpt_destroy(cmpt); } if (tvp) { jas_tvparser_destroy(tvp); } return -1; } Commit Message: CVE-2015-5221 CWE ID: CWE-416
static int mif_process_cmpt(mif_hdr_t *hdr, char *buf) { jas_tvparser_t *tvp; mif_cmpt_t *cmpt; int id; cmpt = 0; tvp = 0; if (!(cmpt = mif_cmpt_create())) { goto error; } cmpt->tlx = 0; cmpt->tly = 0; cmpt->sampperx = 0; cmpt->samppery = 0; cmpt->width = 0; cmpt->height = 0; cmpt->prec = 0; cmpt->sgnd = -1; cmpt->data = 0; if (!(tvp = jas_tvparser_create(buf))) { goto error; } while (!(id = jas_tvparser_next(tvp))) { switch (jas_taginfo_nonull(jas_taginfos_lookup(mif_tags, jas_tvparser_gettag(tvp)))->id) { case MIF_TLX: cmpt->tlx = atoi(jas_tvparser_getval(tvp)); break; case MIF_TLY: cmpt->tly = atoi(jas_tvparser_getval(tvp)); break; case MIF_WIDTH: cmpt->width = atoi(jas_tvparser_getval(tvp)); break; case MIF_HEIGHT: cmpt->height = atoi(jas_tvparser_getval(tvp)); break; case MIF_HSAMP: cmpt->sampperx = atoi(jas_tvparser_getval(tvp)); break; case MIF_VSAMP: cmpt->samppery = atoi(jas_tvparser_getval(tvp)); break; case MIF_PREC: cmpt->prec = atoi(jas_tvparser_getval(tvp)); break; case MIF_SGND: cmpt->sgnd = atoi(jas_tvparser_getval(tvp)); break; case MIF_DATA: if (!(cmpt->data = jas_strdup(jas_tvparser_getval(tvp)))) { return -1; } break; } } if (!cmpt->sampperx || !cmpt->samppery) { goto error; } if (mif_hdr_addcmpt(hdr, hdr->numcmpts, cmpt)) { goto error; } jas_tvparser_destroy(tvp); return 0; error: if (cmpt) { mif_cmpt_destroy(cmpt); } if (tvp) { jas_tvparser_destroy(tvp); } return -1; }
168,874
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const char* SegmentInfo::GetMuxingAppAsUTF8() const { return m_pMuxingAppAsUTF8; } 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 char* SegmentInfo::GetMuxingAppAsUTF8() const
174,342
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: init_remote_listener(int port, gboolean encrypted) { int rc; int *ssock = NULL; struct sockaddr_in saddr; int optval; static struct mainloop_fd_callbacks remote_listen_fd_callbacks = { .dispatch = cib_remote_listen, .destroy = remote_connection_destroy, }; if (port <= 0) { /* dont start it */ return 0; } if (encrypted) { #ifndef HAVE_GNUTLS_GNUTLS_H crm_warn("TLS support is not available"); return 0; #else crm_notice("Starting a tls listener on port %d.", port); gnutls_global_init(); /* gnutls_global_set_log_level (10); */ gnutls_global_set_log_function(debug_log); gnutls_dh_params_init(&dh_params); gnutls_dh_params_generate2(dh_params, DH_BITS); gnutls_anon_allocate_server_credentials(&anon_cred_s); gnutls_anon_set_server_dh_params(anon_cred_s, dh_params); #endif } else { crm_warn("Starting a plain_text listener on port %d.", port); } #ifndef HAVE_PAM crm_warn("PAM is _not_ enabled!"); #endif /* create server socket */ ssock = malloc(sizeof(int)); *ssock = socket(AF_INET, SOCK_STREAM, 0); if (*ssock == -1) { crm_perror(LOG_ERR, "Can not create server socket." ERROR_SUFFIX); free(ssock); return -1; } /* reuse address */ optval = 1; rc = setsockopt(*ssock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if(rc < 0) { crm_perror(LOG_INFO, "Couldn't allow the reuse of local addresses by our remote listener"); } /* bind server socket */ memset(&saddr, '\0', sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = INADDR_ANY; saddr.sin_port = htons(port); if (bind(*ssock, (struct sockaddr *)&saddr, sizeof(saddr)) == -1) { crm_perror(LOG_ERR, "Can not bind server socket." ERROR_SUFFIX); close(*ssock); free(ssock); return -2; } if (listen(*ssock, 10) == -1) { crm_perror(LOG_ERR, "Can not start listen." ERROR_SUFFIX); close(*ssock); free(ssock); return -3; } mainloop_add_fd("cib-remote", G_PRIORITY_DEFAULT, *ssock, ssock, &remote_listen_fd_callbacks); return *ssock; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
init_remote_listener(int port, gboolean encrypted) { int rc; int *ssock = NULL; struct sockaddr_in saddr; int optval; static struct mainloop_fd_callbacks remote_listen_fd_callbacks = { .dispatch = cib_remote_listen, .destroy = remote_connection_destroy, }; if (port <= 0) { /* dont start it */ return 0; } if (encrypted) { #ifndef HAVE_GNUTLS_GNUTLS_H crm_warn("TLS support is not available"); return 0; #else crm_notice("Starting a tls listener on port %d.", port); gnutls_global_init(); /* gnutls_global_set_log_level (10); */ gnutls_global_set_log_function(debug_log); gnutls_dh_params_init(&dh_params); gnutls_dh_params_generate2(dh_params, DH_BITS); gnutls_anon_allocate_server_credentials(&anon_cred_s); gnutls_anon_set_server_dh_params(anon_cred_s, dh_params); #endif } else { crm_warn("Starting a plain_text listener on port %d.", port); } #ifndef HAVE_PAM crm_warn("PAM is _not_ enabled!"); #endif /* create server socket */ ssock = malloc(sizeof(int)); *ssock = socket(AF_INET, SOCK_STREAM, 0); if (*ssock == -1) { crm_perror(LOG_ERR, "Can not create server socket." ERROR_SUFFIX); free(ssock); return -1; } /* reuse address */ optval = 1; rc = setsockopt(*ssock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if(rc < 0) { crm_perror(LOG_INFO, "Couldn't allow the reuse of local addresses by our remote listener"); } /* bind server socket */ memset(&saddr, '\0', sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = INADDR_ANY; saddr.sin_port = htons(port); if (bind(*ssock, (struct sockaddr *)&saddr, sizeof(saddr)) == -1) { crm_perror(LOG_ERR, "Can not bind server socket." ERROR_SUFFIX); close(*ssock); free(ssock); return -2; } if (listen(*ssock, 10) == -1) { crm_perror(LOG_ERR, "Can not start listen." ERROR_SUFFIX); close(*ssock); free(ssock); return -3; } mainloop_add_fd("cib-remote", G_PRIORITY_DEFAULT, *ssock, ssock, &remote_listen_fd_callbacks); return *ssock; }
166,150
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite( BrowserContext* browser_context, const GURL& url) { SiteProcessMap* map = GetSiteProcessMapForBrowserContext(browser_context); std::string site = SiteInstance::GetSiteForURL(browser_context, url) .possibly_invalid_spec(); return map->FindProcess(site); } Commit Message: Check for appropriate bindings in process-per-site mode. BUG=174059 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/12188025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181386 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite( BrowserContext* browser_context, const GURL& url) { SiteProcessMap* map = GetSiteProcessMapForBrowserContext(browser_context); // See if we have an existing process with appropriate bindings for this site. // If not, the caller should create a new process and register it. std::string site = SiteInstance::GetSiteForURL(browser_context, url) .possibly_invalid_spec(); RenderProcessHost* host = map->FindProcess(site); if (host && !IsSuitableHost(host, browser_context, url)) { // The registered process does not have an appropriate set of bindings for // the url. Remove it from the map so we can register a better one. RecordAction(UserMetricsAction("BindingsMismatch_GetProcessHostPerSite")); map->RemoveProcess(host); host = NULL; } return host; }
171,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool BaseAudioContext::WouldTaintOrigin(const KURL& url) const { if (url.ProtocolIsData()) { return false; } Document* document = GetDocument(); if (document && document->GetSecurityOrigin()) { return !document->GetSecurityOrigin()->CanRequest(url); } return true; } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732
bool BaseAudioContext::WouldTaintOrigin(const KURL& url) const {
172,633
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: find_auth_end (FlatpakProxyClient *client, Buffer *buffer) { guchar *match; int i; /* First try to match any leftover at the start */ if (client->auth_end_offset > 0) { gsize left = strlen (AUTH_END_STRING) - client->auth_end_offset; gsize to_match = MIN (left, buffer->pos); /* Matched at least up to to_match */ if (memcmp (buffer->data, &AUTH_END_STRING[client->auth_end_offset], to_match) == 0) { client->auth_end_offset += to_match; /* Matched all */ if (client->auth_end_offset == strlen (AUTH_END_STRING)) return to_match; /* Matched to end of buffer */ return -1; } /* Did not actually match at start */ client->auth_end_offset = -1; } /* Look for whole match inside buffer */ match = memmem (buffer, buffer->pos, AUTH_END_STRING, strlen (AUTH_END_STRING)); if (match != NULL) return match - buffer->data + strlen (AUTH_END_STRING); /* Record longest prefix match at the end */ for (i = MIN (strlen (AUTH_END_STRING) - 1, buffer->pos); i > 0; i--) { if (memcmp (buffer->data + buffer->pos - i, AUTH_END_STRING, i) == 0) { client->auth_end_offset = i; break; } } return -1; } Commit Message: Fix vulnerability in dbus proxy During the authentication all client data is directly forwarded to the dbus daemon as is, until we detect the BEGIN command after which we start filtering the binary dbus protocol. Unfortunately the detection of the BEGIN command in the proxy did not exactly match the detection in the dbus daemon. A BEGIN followed by a space or tab was considered ok in the daemon but not by the proxy. This could be exploited to send arbitrary dbus messages to the host, which can be used to break out of the sandbox. This was noticed by Gabriel Campana of The Google Security Team. This fix makes the detection of the authentication phase end match the dbus code. In addition we duplicate the authentication line validation from dbus, which includes ensuring all data is ASCII, and limiting the size of a line to 16k. In fact, we add some extra stringent checks, disallowing ASCII control chars and requiring that auth lines start with a capital letter. CWE ID: CWE-436
find_auth_end (FlatpakProxyClient *client, Buffer *buffer) { goffset offset = 0; gsize original_size = client->auth_buffer->len; /* Add the new data to the remaining data from last iteration */ g_byte_array_append (client->auth_buffer, buffer->data, buffer->pos); while (TRUE) { guint8 *line_start = client->auth_buffer->data + offset; gsize remaining_data = client->auth_buffer->len - offset; guint8 *line_end; line_end = memmem (line_start, remaining_data, AUTH_LINE_SENTINEL, strlen (AUTH_LINE_SENTINEL)); if (line_end) /* Found end of line */ { offset = (line_end + strlen (AUTH_LINE_SENTINEL) - line_start); if (!auth_line_is_valid (line_start, line_end)) return FIND_AUTH_END_ABORT; *line_end = 0; if (auth_line_is_begin (line_start)) return offset - original_size; /* continue with next line */ } else { /* No end-of-line in this buffer */ g_byte_array_remove_range (client->auth_buffer, 0, offset); /* Abort if more than 16k before newline, similar to what dbus-daemon does */ if (client->auth_buffer->len >= 16*1024) return FIND_AUTH_END_ABORT; return FIND_AUTH_END_CONTINUE; } } }
169,340
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ext4_end_io_nolock(ext4_io_end_t *io) { struct inode *inode = io->inode; loff_t offset = io->offset; ssize_t size = io->size; int ret = 0; ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p," "list->prev 0x%p\n", io, inode->i_ino, io->list.next, io->list.prev); if (list_empty(&io->list)) return ret; if (io->flag != EXT4_IO_UNWRITTEN) return ret; if (offset + size <= i_size_read(inode)) ret = ext4_convert_unwritten_extents(inode, offset, size); if (ret < 0) { printk(KERN_EMERG "%s: failed to convert unwritten" "extents to written extents, error is %d" " io is still on inode %lu aio dio list\n", __func__, ret, inode->i_ino); return ret; } /* clear the DIO AIO unwritten flag */ io->flag = 0; return ret; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
static int ext4_end_io_nolock(ext4_io_end_t *io) { struct inode *inode = io->inode; loff_t offset = io->offset; ssize_t size = io->size; int ret = 0; ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p," "list->prev 0x%p\n", io, inode->i_ino, io->list.next, io->list.prev); if (list_empty(&io->list)) return ret; if (io->flag != EXT4_IO_UNWRITTEN) return ret; ret = ext4_convert_unwritten_extents(inode, offset, size); if (ret < 0) { printk(KERN_EMERG "%s: failed to convert unwritten" "extents to written extents, error is %d" " io is still on inode %lu aio dio list\n", __func__, ret, inode->i_ino); return ret; } /* clear the DIO AIO unwritten flag */ io->flag = 0; return ret; }
167,541
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_event_interrupt(struct pt_regs *regs) { int i; struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events); struct perf_event *event; unsigned long val; int found = 0; int nmi; if (cpuhw->n_limited) freeze_limited_counters(cpuhw, mfspr(SPRN_PMC5), mfspr(SPRN_PMC6)); perf_read_regs(regs); nmi = perf_intr_is_nmi(regs); if (nmi) nmi_enter(); else irq_enter(); for (i = 0; i < cpuhw->n_events; ++i) { event = cpuhw->event[i]; if (!event->hw.idx || is_limited_pmc(event->hw.idx)) continue; val = read_pmc(event->hw.idx); if ((int)val < 0) { /* event has overflowed */ found = 1; record_and_restart(event, val, regs, nmi); } } /* * In case we didn't find and reset the event that caused * the interrupt, scan all events and reset any that are * negative, to avoid getting continual interrupts. * Any that we processed in the previous loop will not be negative. */ if (!found) { for (i = 0; i < ppmu->n_counter; ++i) { if (is_limited_pmc(i + 1)) continue; val = read_pmc(i + 1); if ((int)val < 0) write_pmc(i + 1, 0); } } /* * Reset MMCR0 to its normal value. This will set PMXE and * clear FC (freeze counters) and PMAO (perf mon alert occurred) * and thus allow interrupts to occur again. * XXX might want to use MSR.PM to keep the events frozen until * we get back out of this interrupt. */ write_mmcr0(cpuhw, cpuhw->mmcr[0]); if (nmi) nmi_exit(); else irq_exit(); } Commit Message: perf, powerpc: Handle events that raise an exception without overflowing Events on POWER7 can roll back if a speculative event doesn't eventually complete. Unfortunately in some rare cases they will raise a performance monitor exception. We need to catch this to ensure we reset the PMC. In all cases the PMC will be 256 or less cycles from overflow. Signed-off-by: Anton Blanchard <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Cc: <[email protected]> # as far back as it applies cleanly LKML-Reference: <20110309143842.6c22845e@kryten> Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-189
static void perf_event_interrupt(struct pt_regs *regs) { int i; struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events); struct perf_event *event; unsigned long val; int found = 0; int nmi; if (cpuhw->n_limited) freeze_limited_counters(cpuhw, mfspr(SPRN_PMC5), mfspr(SPRN_PMC6)); perf_read_regs(regs); nmi = perf_intr_is_nmi(regs); if (nmi) nmi_enter(); else irq_enter(); for (i = 0; i < cpuhw->n_events; ++i) { event = cpuhw->event[i]; if (!event->hw.idx || is_limited_pmc(event->hw.idx)) continue; val = read_pmc(event->hw.idx); if ((int)val < 0) { /* event has overflowed */ found = 1; record_and_restart(event, val, regs, nmi); } } /* * In case we didn't find and reset the event that caused * the interrupt, scan all events and reset any that are * negative, to avoid getting continual interrupts. * Any that we processed in the previous loop will not be negative. */ if (!found) { for (i = 0; i < ppmu->n_counter; ++i) { if (is_limited_pmc(i + 1)) continue; val = read_pmc(i + 1); if (pmc_overflow(val)) write_pmc(i + 1, 0); } } /* * Reset MMCR0 to its normal value. This will set PMXE and * clear FC (freeze counters) and PMAO (perf mon alert occurred) * and thus allow interrupts to occur again. * XXX might want to use MSR.PM to keep the events frozen until * we get back out of this interrupt. */ write_mmcr0(cpuhw, cpuhw->mmcr[0]); if (nmi) nmi_exit(); else irq_exit(); }
165,679
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) { size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0); icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length); if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) == ustr_host.length()) diacritic_remover_.get()->transliterate(ustr_host); extra_confusable_mapper_.get()->transliterate(ustr_host); UErrorCode status = U_ZERO_ERROR; icu::UnicodeString ustr_skeleton; uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton, &status); if (U_FAILURE(status)) return false; std::string skeleton; return LookupMatchInTopDomains(ustr_skeleton.toUTF8String(skeleton)); } Commit Message: Map U+04CF to lowercase L as well. U+04CF (ӏ) has the confusability skeleton of 'i' (lowercase I), but it can be confused for 'l' (lowercase L) or '1' (digit) if rendered in some fonts. If a host name contains it, calculate the confusability skeleton twice, once with the default mapping to 'i' (lowercase I) and the 2nd time with an alternative mapping to 'l'. Mapping them to 'l' (lowercase L) also gets it treated as similar to digit 1 because the confusability skeleton of digit 1 is 'l'. Bug: 817247 Test: components_unittests --gtest_filter=*IDN* Change-Id: I7442b950c9457eea285e17f01d1f43c9acc5d79c Reviewed-on: https://chromium-review.googlesource.com/974165 Commit-Queue: Jungshik Shin <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Reviewed-by: Eric Lawrence <[email protected]> Cr-Commit-Position: refs/heads/master@{#551263} CWE ID:
bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) { size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0); icu::UnicodeString host(FALSE, hostname.data(), hostname_length); if (lgc_letters_n_ascii_.span(host, 0, USET_SPAN_CONTAINED) == host.length()) diacritic_remover_.get()->transliterate(host); extra_confusable_mapper_.get()->transliterate(host); UErrorCode status = U_ZERO_ERROR; icu::UnicodeString skeleton; // Map U+04CF (ӏ) to lowercase L in addition to what uspoof_getSkeleton does // (mapping it to lowercase I). int32_t u04cf_pos; if ((u04cf_pos = host.indexOf(0x4CF)) != -1) { icu::UnicodeString host_alt(host); size_t length = host_alt.length(); char16_t* buffer = host_alt.getBuffer(-1); for (char16_t* uc = buffer + u04cf_pos ; uc < buffer + length; ++uc) { if (*uc == 0x4CF) *uc = 0x6C; // Lowercase L } host_alt.releaseBuffer(length); uspoof_getSkeletonUnicodeString(checker_, 0, host_alt, skeleton, &status); if (U_SUCCESS(status) && LookupMatchInTopDomains(skeleton)) return true; } uspoof_getSkeletonUnicodeString(checker_, 0, host, skeleton, &status); return U_SUCCESS(status) && LookupMatchInTopDomains(skeleton); }
173,224
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long ssl3_ctrl(SSL *s, int cmd, long larg, void *parg) { int ret = 0; #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_RSA) if ( # ifndef OPENSSL_NO_RSA cmd == SSL_CTRL_SET_TMP_RSA || cmd == SSL_CTRL_SET_TMP_RSA_CB || # endif # ifndef OPENSSL_NO_DSA cmd == SSL_CTRL_SET_TMP_DH || cmd == SSL_CTRL_SET_TMP_DH_CB || # endif 0) { if (!ssl_cert_inst(&s->cert)) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_MALLOC_FAILURE); return (0); } } #endif switch (cmd) { case SSL_CTRL_GET_SESSION_REUSED: ret = s->hit; break; case SSL_CTRL_GET_CLIENT_CERT_REQUEST: break; case SSL_CTRL_GET_NUM_RENEGOTIATIONS: ret = s->s3->num_renegotiations; break; case SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS: ret = s->s3->num_renegotiations; s->s3->num_renegotiations = 0; break; case SSL_CTRL_GET_TOTAL_RENEGOTIATIONS: ret = s->s3->total_renegotiations; break; case SSL_CTRL_GET_FLAGS: ret = (int)(s->s3->flags); break; #ifndef OPENSSL_NO_RSA case SSL_CTRL_NEED_TMP_RSA: if ((s->cert != NULL) && (s->cert->rsa_tmp == NULL) && ((s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) || (EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) > (512 / 8)))) ret = 1; break; case SSL_CTRL_SET_TMP_RSA: { RSA *rsa = (RSA *)parg; if (rsa == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); return (ret); } if ((rsa = RSAPrivateKey_dup(rsa)) == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_RSA_LIB); return (ret); } if (s->cert->rsa_tmp != NULL) RSA_free(s->cert->rsa_tmp); s->cert->rsa_tmp = rsa; ret = 1; } break; case SSL_CTRL_SET_TMP_RSA_CB: { SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return (ret); } break; #endif #ifndef OPENSSL_NO_DH case SSL_CTRL_SET_TMP_DH: { DH *dh = (DH *)parg; if (dh == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); return (ret); } if ((dh = DHparams_dup(dh)) == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); return (ret); } if (!(s->options & SSL_OP_SINGLE_DH_USE)) { if (!DH_generate_key(dh)) { DH_free(dh); SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); return (ret); } } if (s->cert->dh_tmp != NULL) DH_free(s->cert->dh_tmp); s->cert->dh_tmp = dh; SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); return (ret); } } if (s->cert->dh_tmp != NULL) DH_free(s->cert->dh_tmp); s->cert->dh_tmp = dh; ret = 1; } Commit Message: CWE ID: CWE-200
long ssl3_ctrl(SSL *s, int cmd, long larg, void *parg) { int ret = 0; #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_RSA) if ( # ifndef OPENSSL_NO_RSA cmd == SSL_CTRL_SET_TMP_RSA || cmd == SSL_CTRL_SET_TMP_RSA_CB || # endif # ifndef OPENSSL_NO_DSA cmd == SSL_CTRL_SET_TMP_DH || cmd == SSL_CTRL_SET_TMP_DH_CB || # endif 0) { if (!ssl_cert_inst(&s->cert)) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_MALLOC_FAILURE); return (0); } } #endif switch (cmd) { case SSL_CTRL_GET_SESSION_REUSED: ret = s->hit; break; case SSL_CTRL_GET_CLIENT_CERT_REQUEST: break; case SSL_CTRL_GET_NUM_RENEGOTIATIONS: ret = s->s3->num_renegotiations; break; case SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS: ret = s->s3->num_renegotiations; s->s3->num_renegotiations = 0; break; case SSL_CTRL_GET_TOTAL_RENEGOTIATIONS: ret = s->s3->total_renegotiations; break; case SSL_CTRL_GET_FLAGS: ret = (int)(s->s3->flags); break; #ifndef OPENSSL_NO_RSA case SSL_CTRL_NEED_TMP_RSA: if ((s->cert != NULL) && (s->cert->rsa_tmp == NULL) && ((s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) || (EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) > (512 / 8)))) ret = 1; break; case SSL_CTRL_SET_TMP_RSA: { RSA *rsa = (RSA *)parg; if (rsa == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); return (ret); } if ((rsa = RSAPrivateKey_dup(rsa)) == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_RSA_LIB); return (ret); } if (s->cert->rsa_tmp != NULL) RSA_free(s->cert->rsa_tmp); s->cert->rsa_tmp = rsa; ret = 1; } break; case SSL_CTRL_SET_TMP_RSA_CB: { SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return (ret); } break; #endif #ifndef OPENSSL_NO_DH case SSL_CTRL_SET_TMP_DH: { DH *dh = (DH *)parg; if (dh == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); return (ret); } if ((dh = DHparams_dup(dh)) == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); return (ret); } if (s->cert->dh_tmp != NULL) DH_free(s->cert->dh_tmp); s->cert->dh_tmp = dh; SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); return (ret); } } if (s->cert->dh_tmp != NULL) DH_free(s->cert->dh_tmp); s->cert->dh_tmp = dh; ret = 1; }
165,255
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *print_string( cJSON *item ) { return print_string_ptr( item->valuestring ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static char *print_string( cJSON *item )
167,309
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static jlong Region_createFromParcel(JNIEnv* env, jobject clazz, jobject parcel) { if (parcel == NULL) { return NULL; } android::Parcel* p = android::parcelForJavaObject(env, parcel); SkRegion* region = new SkRegion; size_t size = p->readInt32(); region->readFromMemory(p->readInplace(size), size); return reinterpret_cast<jlong>(region); } Commit Message: Check that the parcel contained the expected amount of region data. DO NOT MERGE bug:20883006 Change-Id: Ib47a8ec8696dbc37e958b8dbceb43fcbabf6605b CWE ID: CWE-264
static jlong Region_createFromParcel(JNIEnv* env, jobject clazz, jobject parcel) { if (parcel == NULL) { return NULL; } android::Parcel* p = android::parcelForJavaObject(env, parcel); const size_t size = p->readInt32(); const void* regionData = p->readInplace(size); if (regionData == NULL) { return NULL; } SkRegion* region = new SkRegion; region->readFromMemory(regionData, size); return reinterpret_cast<jlong>(region); }
173,341
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ocfs2_dio_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); struct ocfs2_inode_info *oi = OCFS2_I(inode); struct ocfs2_write_ctxt *wc; struct ocfs2_write_cluster_desc *desc = NULL; struct ocfs2_dio_write_ctxt *dwc = NULL; struct buffer_head *di_bh = NULL; u64 p_blkno; loff_t pos = iblock << inode->i_sb->s_blocksize_bits; unsigned len, total_len = bh_result->b_size; int ret = 0, first_get_block = 0; len = osb->s_clustersize - (pos & (osb->s_clustersize - 1)); len = min(total_len, len); mlog(0, "get block of %lu at %llu:%u req %u\n", inode->i_ino, pos, len, total_len); /* * Because we need to change file size in ocfs2_dio_end_io_write(), or * we may need to add it to orphan dir. So can not fall to fast path * while file size will be changed. */ if (pos + total_len <= i_size_read(inode)) { down_read(&oi->ip_alloc_sem); /* This is the fast path for re-write. */ ret = ocfs2_get_block(inode, iblock, bh_result, create); up_read(&oi->ip_alloc_sem); if (buffer_mapped(bh_result) && !buffer_new(bh_result) && ret == 0) goto out; /* Clear state set by ocfs2_get_block. */ bh_result->b_state = 0; } dwc = ocfs2_dio_alloc_write_ctx(bh_result, &first_get_block); if (unlikely(dwc == NULL)) { ret = -ENOMEM; mlog_errno(ret); goto out; } if (ocfs2_clusters_for_bytes(inode->i_sb, pos + total_len) > ocfs2_clusters_for_bytes(inode->i_sb, i_size_read(inode)) && !dwc->dw_orphaned) { /* * when we are going to alloc extents beyond file size, add the * inode to orphan dir, so we can recall those spaces when * system crashed during write. */ ret = ocfs2_add_inode_to_orphan(osb, inode); if (ret < 0) { mlog_errno(ret); goto out; } dwc->dw_orphaned = 1; } ret = ocfs2_inode_lock(inode, &di_bh, 1); if (ret) { mlog_errno(ret); goto out; } down_write(&oi->ip_alloc_sem); if (first_get_block) { if (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb))) ret = ocfs2_zero_tail(inode, di_bh, pos); else ret = ocfs2_expand_nonsparse_inode(inode, di_bh, pos, total_len, NULL); if (ret < 0) { mlog_errno(ret); goto unlock; } } ret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len, OCFS2_WRITE_DIRECT, NULL, (void **)&wc, di_bh, NULL); if (ret) { mlog_errno(ret); goto unlock; } desc = &wc->w_desc[0]; p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, desc->c_phys); BUG_ON(p_blkno == 0); p_blkno += iblock & (u64)(ocfs2_clusters_to_blocks(inode->i_sb, 1) - 1); map_bh(bh_result, inode->i_sb, p_blkno); bh_result->b_size = len; if (desc->c_needs_zero) set_buffer_new(bh_result); /* May sleep in end_io. It should not happen in a irq context. So defer * it to dio work queue. */ set_buffer_defer_completion(bh_result); if (!list_empty(&wc->w_unwritten_list)) { struct ocfs2_unwritten_extent *ue = NULL; ue = list_first_entry(&wc->w_unwritten_list, struct ocfs2_unwritten_extent, ue_node); BUG_ON(ue->ue_cpos != desc->c_cpos); /* The physical address may be 0, fill it. */ ue->ue_phys = desc->c_phys; list_splice_tail_init(&wc->w_unwritten_list, &dwc->dw_zero_list); dwc->dw_zero_count++; } ret = ocfs2_write_end_nolock(inode->i_mapping, pos, len, len, wc); BUG_ON(ret != len); ret = 0; unlock: up_write(&oi->ip_alloc_sem); ocfs2_inode_unlock(inode, 1); brelse(di_bh); out: if (ret < 0) ret = -EIO; return ret; } Commit Message: ocfs2: ip_alloc_sem should be taken in ocfs2_get_block() ip_alloc_sem should be taken in ocfs2_get_block() when reading file in DIRECT mode to prevent concurrent access to extent tree with ocfs2_dio_end_io_write(), which may cause BUGON in the following situation: read file 'A' end_io of writing file 'A' vfs_read __vfs_read ocfs2_file_read_iter generic_file_read_iter ocfs2_direct_IO __blockdev_direct_IO do_blockdev_direct_IO do_direct_IO get_more_blocks ocfs2_get_block ocfs2_extent_map_get_blocks ocfs2_get_clusters ocfs2_get_clusters_nocache() ocfs2_search_extent_list return the index of record which contains the v_cluster, that is v_cluster > rec[i]->e_cpos. ocfs2_dio_end_io ocfs2_dio_end_io_write down_write(&oi->ip_alloc_sem); ocfs2_mark_extent_written ocfs2_change_extent_flag ocfs2_split_extent ... --> modify the rec[i]->e_cpos, resulting in v_cluster < rec[i]->e_cpos. BUG_ON(v_cluster < le32_to_cpu(rec->e_cpos)) [[email protected]: v3] Link: http://lkml.kernel.org/r/[email protected] Link: http://lkml.kernel.org/r/[email protected] Fixes: c15471f79506 ("ocfs2: fix sparse file & data ordering issue in direct io") Signed-off-by: Alex Chen <[email protected]> Reviewed-by: Jun Piao <[email protected]> Reviewed-by: Joseph Qi <[email protected]> Reviewed-by: Gang He <[email protected]> Acked-by: Changwei Ge <[email protected]> Cc: Mark Fasheh <[email protected]> Cc: Joel Becker <[email protected]> Cc: Junxiao Bi <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
static int ocfs2_dio_get_block(struct inode *inode, sector_t iblock, static int ocfs2_dio_wr_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); struct ocfs2_inode_info *oi = OCFS2_I(inode); struct ocfs2_write_ctxt *wc; struct ocfs2_write_cluster_desc *desc = NULL; struct ocfs2_dio_write_ctxt *dwc = NULL; struct buffer_head *di_bh = NULL; u64 p_blkno; loff_t pos = iblock << inode->i_sb->s_blocksize_bits; unsigned len, total_len = bh_result->b_size; int ret = 0, first_get_block = 0; len = osb->s_clustersize - (pos & (osb->s_clustersize - 1)); len = min(total_len, len); mlog(0, "get block of %lu at %llu:%u req %u\n", inode->i_ino, pos, len, total_len); /* * Because we need to change file size in ocfs2_dio_end_io_write(), or * we may need to add it to orphan dir. So can not fall to fast path * while file size will be changed. */ if (pos + total_len <= i_size_read(inode)) { /* This is the fast path for re-write. */ ret = ocfs2_lock_get_block(inode, iblock, bh_result, create); if (buffer_mapped(bh_result) && !buffer_new(bh_result) && ret == 0) goto out; /* Clear state set by ocfs2_get_block. */ bh_result->b_state = 0; } dwc = ocfs2_dio_alloc_write_ctx(bh_result, &first_get_block); if (unlikely(dwc == NULL)) { ret = -ENOMEM; mlog_errno(ret); goto out; } if (ocfs2_clusters_for_bytes(inode->i_sb, pos + total_len) > ocfs2_clusters_for_bytes(inode->i_sb, i_size_read(inode)) && !dwc->dw_orphaned) { /* * when we are going to alloc extents beyond file size, add the * inode to orphan dir, so we can recall those spaces when * system crashed during write. */ ret = ocfs2_add_inode_to_orphan(osb, inode); if (ret < 0) { mlog_errno(ret); goto out; } dwc->dw_orphaned = 1; } ret = ocfs2_inode_lock(inode, &di_bh, 1); if (ret) { mlog_errno(ret); goto out; } down_write(&oi->ip_alloc_sem); if (first_get_block) { if (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb))) ret = ocfs2_zero_tail(inode, di_bh, pos); else ret = ocfs2_expand_nonsparse_inode(inode, di_bh, pos, total_len, NULL); if (ret < 0) { mlog_errno(ret); goto unlock; } } ret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len, OCFS2_WRITE_DIRECT, NULL, (void **)&wc, di_bh, NULL); if (ret) { mlog_errno(ret); goto unlock; } desc = &wc->w_desc[0]; p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, desc->c_phys); BUG_ON(p_blkno == 0); p_blkno += iblock & (u64)(ocfs2_clusters_to_blocks(inode->i_sb, 1) - 1); map_bh(bh_result, inode->i_sb, p_blkno); bh_result->b_size = len; if (desc->c_needs_zero) set_buffer_new(bh_result); /* May sleep in end_io. It should not happen in a irq context. So defer * it to dio work queue. */ set_buffer_defer_completion(bh_result); if (!list_empty(&wc->w_unwritten_list)) { struct ocfs2_unwritten_extent *ue = NULL; ue = list_first_entry(&wc->w_unwritten_list, struct ocfs2_unwritten_extent, ue_node); BUG_ON(ue->ue_cpos != desc->c_cpos); /* The physical address may be 0, fill it. */ ue->ue_phys = desc->c_phys; list_splice_tail_init(&wc->w_unwritten_list, &dwc->dw_zero_list); dwc->dw_zero_count++; } ret = ocfs2_write_end_nolock(inode->i_mapping, pos, len, len, wc); BUG_ON(ret != len); ret = 0; unlock: up_write(&oi->ip_alloc_sem); ocfs2_inode_unlock(inode, 1); brelse(di_bh); out: if (ret < 0) ret = -EIO; return ret; }
169,396
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunScrollbarThumbDragLatencyTest() { #if !defined(OS_ANDROID) blink::WebFloatPoint scrollbar_thumb(795, 30); blink::WebMouseEvent mouse_down = SyntheticWebMouseEventBuilder::Build( blink::WebInputEvent::kMouseDown, scrollbar_thumb.x, scrollbar_thumb.y, 0); mouse_down.button = blink::WebMouseEvent::Button::kLeft; mouse_down.SetTimeStamp(base::TimeTicks::Now()); GetWidgetHost()->ForwardMouseEvent(mouse_down); blink::WebMouseEvent mouse_move = SyntheticWebMouseEventBuilder::Build( blink::WebInputEvent::kMouseMove, scrollbar_thumb.x, scrollbar_thumb.y + 10, 0); mouse_move.button = blink::WebMouseEvent::Button::kLeft; mouse_move.SetTimeStamp(base::TimeTicks::Now()); GetWidgetHost()->ForwardMouseEvent(mouse_move); RunUntilInputProcessed(GetWidgetHost()); mouse_move.SetPositionInWidget(scrollbar_thumb.x, scrollbar_thumb.y + 20); mouse_move.SetPositionInScreen(scrollbar_thumb.x, scrollbar_thumb.y + 20); GetWidgetHost()->ForwardMouseEvent(mouse_move); RunUntilInputProcessed(GetWidgetHost()); blink::WebMouseEvent mouse_up = SyntheticWebMouseEventBuilder::Build( blink::WebInputEvent::kMouseUp, scrollbar_thumb.x, scrollbar_thumb.y + 20, 0); mouse_up.button = blink::WebMouseEvent::Button::kLeft; mouse_up.SetTimeStamp(base::TimeTicks::Now()); GetWidgetHost()->ForwardMouseEvent(mouse_up); RunUntilInputProcessed(GetWidgetHost()); FetchHistogramsFromChildProcesses(); const std::string scroll_types[] = {"ScrollBegin", "ScrollUpdate"}; for (const std::string& scroll_type : scroll_types) { EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.TimeToScrollUpdateSwapBegin4")); EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.RendererSwapToBrowserNotified2")); EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.BrowserNotifiedToBeforeGpuSwap2")); EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.GpuSwap2")); std::string thread_name = DoesScrollbarScrollOnMainThread() ? "Main" : "Impl"; EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.TimeToHandled2_" + thread_name)); EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.HandledToRendererSwap2_" + thread_name)); } #endif // !defined(OS_ANDROID) } Commit Message: Revert "Add explicit flag for compositor scrollbar injected gestures" This reverts commit d9a56afcbdf9850bc39bb3edb56d07d11a1eb2b2. Reason for revert: Findit (https://goo.gl/kROfz5) identified CL at revision 669086 as the culprit for flakes in the build cycles as shown on: https://analysis.chromium.org/p/chromium/flake-portal/analysis/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyQwsSDEZsYWtlQ3VscHJpdCIxY2hyb21pdW0vZDlhNTZhZmNiZGY5ODUwYmMzOWJiM2VkYjU2ZDA3ZDExYTFlYjJiMgw Sample Failed Build: https://ci.chromium.org/buildbot/chromium.chromiumos/linux-chromeos-rel/25818 Sample Failed Step: content_browsertests on Ubuntu-16.04 Sample Flaky Test: ScrollLatencyScrollbarBrowserTest.ScrollbarThumbDragLatency Original change's description: > Add explicit flag for compositor scrollbar injected gestures > > The original change to enable scrollbar latency for the composited > scrollbars incorrectly used an existing member to try and determine > whether a GestureScrollUpdate was the first one in an injected sequence > or not. is_first_gesture_scroll_update_ was incorrect because it is only > updated when input is actually dispatched to InputHandlerProxy, and the > flag is cleared for all GSUs before the location where it was being > read. > > This bug was missed because of incorrect tests. The > VerifyRecordedSamplesForHistogram method doesn't actually assert or > expect anything - the return value must be inspected. > > As part of fixing up the tests, I made a few other changes to get them > passing consistently across all platforms: > - turn on main thread scrollbar injection feature (in case it's ever > turned off we don't want the tests to start failing) > - enable mock scrollbars > - disable smooth scrolling > - don't run scrollbar tests on Android > > The composited scrollbar button test is disabled due to a bug in how > the mock theme reports its button sizes, which throws off the region > detection in ScrollbarLayerImplBase::IdentifyScrollbarPart (filed > crbug.com/974063 for this issue). > > Change-Id: Ie1a762a5f6ecc264d22f0256db68f141fc76b950 > > Bug: 954007 > Change-Id: Ib258e08e083e79da90ba2e4e4216e4879cf00cf7 > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1652741 > Commit-Queue: Daniel Libby <[email protected]> > Reviewed-by: David Bokan <[email protected]> > Cr-Commit-Position: refs/heads/master@{#669086} Change-Id: Icc743e48fa740fe27f0cb0cfa21b209a696f518c No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 954007 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1660114 Cr-Commit-Position: refs/heads/master@{#669150} CWE ID: CWE-281
void RunScrollbarThumbDragLatencyTest() {
172,429
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_context_time( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, OM_uint32 *time_rec) { OM_uint32 ret; ret = gss_context_time(minor_status, context_handle, time_rec); return (ret); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
spnego_gss_context_time( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, OM_uint32 *time_rec) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); ret = gss_context_time(minor_status, sc->ctx_handle, time_rec); return (ret); }
166,653
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LaunchServiceProcessControl(bool wait) { ServiceProcessControl::GetInstance()->Launch( base::Bind(&ServiceProcessControlBrowserTest::ProcessControlLaunched, base::Unretained(this)), base::Bind( &ServiceProcessControlBrowserTest::ProcessControlLaunchFailed, base::Unretained(this))); if (wait) content::RunMessageLoop(); } Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated(). Bug: 844016 Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0 Reviewed-on: https://chromium-review.googlesource.com/1126576 Commit-Queue: Wez <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#573131} CWE ID: CWE-94
void LaunchServiceProcessControl(bool wait) { void LaunchServiceProcessControl(base::RepeatingClosure on_launched) { ServiceProcessControl::GetInstance()->Launch( base::BindOnce( &ServiceProcessControlBrowserTest::ProcessControlLaunched, base::Unretained(this), on_launched), base::BindOnce( &ServiceProcessControlBrowserTest::ProcessControlLaunchFailed,
172,051
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DevToolsAgentHostImpl::AttachClient(DevToolsAgentHostClient* client) { if (SessionByClient(client)) return; InnerAttachClient(client); } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
void DevToolsAgentHostImpl::AttachClient(DevToolsAgentHostClient* client) { if (SessionByClient(client)) return; InnerAttachClient(client, false /* restricted */); } bool DevToolsAgentHostImpl::AttachRestrictedClient( DevToolsAgentHostClient* client) { if (SessionByClient(client)) return false; return InnerAttachClient(client, true /* restricted */); }
173,242
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: FileStream::FileStream(base::File file, const scoped_refptr<base::TaskRunner>& task_runner) : context_(base::MakeUnique<Context>(std::move(file), task_runner)) {} 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 <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Bence Béky <[email protected]> Cr-Commit-Position: refs/heads/master@{#498123} CWE ID: CWE-311
FileStream::FileStream(base::File file, const scoped_refptr<base::TaskRunner>& task_runner)
173,263
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id, int do_interlace, int use_update_info) { memset(dp, 0, sizeof *dp); dp->ps = ps; dp->colour_type = COL_FROM_ID(id); dp->bit_depth = DEPTH_FROM_ID(id); if (dp->bit_depth < 1 || dp->bit_depth > 16) internal_error(ps, "internal: bad bit depth"); if (dp->colour_type == 3) dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8; else dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = dp->bit_depth; dp->interlace_type = INTERLACE_FROM_ID(id); check_interlace_type(dp->interlace_type); dp->id = id; /* All the rest are filled in after the read_info: */ dp->w = 0; dp->h = 0; dp->npasses = 0; dp->pixel_size = 0; dp->bit_width = 0; dp->cbRow = 0; dp->do_interlace = do_interlace; dp->is_transparent = 0; dp->speed = ps->speed; dp->use_update_info = use_update_info; dp->npalette = 0; /* Preset the transparent color to black: */ memset(&dp->transparent, 0, sizeof dp->transparent); /* Preset the palette to full intensity/opaque througout: */ memset(dp->palette, 0xff, sizeof dp->palette); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id, int do_interlace, int use_update_info) { memset(dp, 0, sizeof *dp); dp->ps = ps; dp->colour_type = COL_FROM_ID(id); dp->bit_depth = DEPTH_FROM_ID(id); if (dp->bit_depth < 1 || dp->bit_depth > 16) internal_error(ps, "internal: bad bit depth"); if (dp->colour_type == 3) dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8; else dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = dp->bit_depth; dp->interlace_type = INTERLACE_FROM_ID(id); check_interlace_type(dp->interlace_type); dp->id = id; /* All the rest are filled in after the read_info: */ dp->w = 0; dp->h = 0; dp->npasses = 0; dp->pixel_size = 0; dp->bit_width = 0; dp->cbRow = 0; dp->do_interlace = do_interlace; dp->littleendian = 0; dp->is_transparent = 0; dp->speed = ps->speed; dp->use_update_info = use_update_info; dp->npalette = 0; /* Preset the transparent color to black: */ memset(&dp->transparent, 0, sizeof dp->transparent); /* Preset the palette to full intensity/opaque througout: */ memset(dp->palette, 0xff, sizeof dp->palette); }
173,697
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadBGRImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *canvas_image, *image; MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); if (image_info->interlace != PartitionInterlace) { status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Create virtual canvas to support cropping (i.e. image.rgb[100x100+10+20]). */ canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse, exception); (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod); quantum_info=AcquireQuantumInfo(image_info,canvas_image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); quantum_type=BGRQuantum; if (LocaleCompare(image_info->magick,"BGRA") == 0) { quantum_type=BGRAQuantum; image->matte=MagickTrue; } if (image_info->number_scenes != 0) while (image->scene < image_info->scene) { /* Skip to next image. */ image->scene++; length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) break; } } count=0; length=0; scene=0; do { /* Read pixels to virtual canvas image then push to image. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: BGRBGRBGRBGRBGRBGR... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=QueueAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } count=ReadBlob(image,length,pixels); } break; } case LineInterlace: { static QuantumType quantum_types[4] = { BlueQuantum, GreenQuantum, RedQuantum, AlphaQuantum }; /* Line interlacing: BBB...GGG...RRR...RRR...GGG...BBB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } for (i=0; i < (ssize_t) (image->matte != MagickFalse ? 4 : 3); i++) { quantum_type=quantum_types[i]; q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { switch (quantum_type) { case RedQuantum: { SetPixelRed(q,GetPixelRed(p)); break; } case GreenQuantum: { SetPixelGreen(q,GetPixelGreen(p)); break; } case BlueQuantum: { SetPixelBlue(q,GetPixelBlue(p)); break; } case OpacityQuantum: { SetPixelOpacity(q,GetPixelOpacity(p)); break; } case AlphaQuantum: { SetPixelAlpha(q,GetPixelAlpha(p)); break; } default: break; } p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,6); if (status == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,6); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,6); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,6,6); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: BBBBBB..., GGGGGG..., RRRRRR... */ AppendImageFormat("B",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); length=GetQuantumExtent(canvas_image,quantum_info,BlueQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("G",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,GreenQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("R",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } (void) CloseBlob(image); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } } SetQuantumImageType(image,quantum_type); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (count == (ssize_t) length) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } scene++; } while (count == (ssize_t) length); quantum_info=DestroyQuantumInfo(quantum_info); InheritException(&image->exception,&canvas_image->exception); canvas_image=DestroyImage(canvas_image); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadBGRImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *canvas_image, *image; MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); if (image_info->interlace != PartitionInterlace) { status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Create virtual canvas to support cropping (i.e. image.rgb[100x100+10+20]). */ canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse, exception); (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod); quantum_info=AcquireQuantumInfo(image_info,canvas_image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); quantum_type=BGRQuantum; if (LocaleCompare(image_info->magick,"BGRA") == 0) { quantum_type=BGRAQuantum; image->matte=MagickTrue; } if (image_info->number_scenes != 0) while (image->scene < image_info->scene) { /* Skip to next image. */ image->scene++; length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) break; } } count=0; length=0; scene=0; do { /* Read pixels to virtual canvas image then push to image. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: BGRBGRBGRBGRBGRBGR... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=QueueAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } count=ReadBlob(image,length,pixels); } break; } case LineInterlace: { static QuantumType quantum_types[4] = { BlueQuantum, GreenQuantum, RedQuantum, AlphaQuantum }; /* Line interlacing: BBB...GGG...RRR...RRR...GGG...BBB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } for (i=0; i < (ssize_t) (image->matte != MagickFalse ? 4 : 3); i++) { quantum_type=quantum_types[i]; q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { switch (quantum_type) { case RedQuantum: { SetPixelRed(q,GetPixelRed(p)); break; } case GreenQuantum: { SetPixelGreen(q,GetPixelGreen(p)); break; } case BlueQuantum: { SetPixelBlue(q,GetPixelBlue(p)); break; } case OpacityQuantum: { SetPixelOpacity(q,GetPixelOpacity(p)); break; } case AlphaQuantum: { SetPixelAlpha(q,GetPixelAlpha(p)); break; } default: break; } p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,6); if (status == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,6); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,6); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,6,6); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: BBBBBB..., GGGGGG..., RRRRRR... */ AppendImageFormat("B",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); length=GetQuantumExtent(canvas_image,quantum_info,BlueQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("G",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,GreenQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("R",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } (void) CloseBlob(image); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } } SetQuantumImageType(image,quantum_type); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (count == (ssize_t) length) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } scene++; } while (count == (ssize_t) length); quantum_info=DestroyQuantumInfo(quantum_info); InheritException(&image->exception,&canvas_image->exception); canvas_image=DestroyImage(canvas_image); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,549
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void jslGetTokenString(char *str, size_t len) { if (lex->tk == LEX_ID) { strncpy(str, "ID:", len); strncat(str, jslGetTokenValueAsString(), len); } else if (lex->tk == LEX_STR) { strncpy(str, "String:'", len); strncat(str, jslGetTokenValueAsString(), len); strncat(str, "'", len); } else jslTokenAsString(lex->tk, str, len); } Commit Message: Fix strncat/cpy bounding issues (fix #1425) CWE ID: CWE-119
void jslGetTokenString(char *str, size_t len) { if (lex->tk == LEX_ID) { espruino_snprintf(str, len, "ID:%s", jslGetTokenValueAsString()); } else if (lex->tk == LEX_STR) { espruino_snprintf(str, len, "String:'%s'", jslGetTokenValueAsString()); } else jslTokenAsString(lex->tk, str, len); }
169,211
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_tRNS_to_alpha_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* We don't know yet whether there will be a tRNS chunk, but we know that * this transformation should do nothing if there already is an alpha * channel. */ return (colour_type & PNG_COLOR_MASK_ALPHA) == 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_tRNS_to_alpha_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* We don't know yet whether there will be a tRNS chunk, but we know that * this transformation should do nothing if there already is an alpha * channel. In addition, after the bug fix in 1.7.0, there is no longer * any action on a palette image. */ return # if PNG_LIBPNG_VER >= 10700 colour_type != PNG_COLOR_TYPE_PALETTE && # endif (colour_type & PNG_COLOR_MASK_ALPHA) == 0; }
173,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name) { unsigned upper_length; int len, type, optlen; char *dest, *ret; /* option points to OPT_DATA, need to go back to get OPT_LEN */ len = option[-OPT_DATA + OPT_LEN]; type = optflag->flags & OPTION_TYPE_MASK; optlen = dhcp_option_lengths[type]; upper_length = len_of_option_as_string[type] * ((unsigned)(len + optlen - 1) / (unsigned)optlen); dest = ret = xmalloc(upper_length + strlen(opt_name) + 2); dest += sprintf(ret, "%s=", opt_name); while (len >= optlen) { switch (type) { case OPTION_IP: case OPTION_IP_PAIR: dest += sprint_nip(dest, "", option); if (type == OPTION_IP) break; dest += sprint_nip(dest, "/", option + 4); break; case OPTION_U8: dest += sprintf(dest, "%u", *option); break; case OPTION_U16: { uint16_t val_u16; move_from_unaligned16(val_u16, option); dest += sprintf(dest, "%u", ntohs(val_u16)); break; } case OPTION_S32: case OPTION_U32: { uint32_t val_u32; move_from_unaligned32(val_u32, option); dest += sprintf(dest, type == OPTION_U32 ? "%lu" : "%ld", (unsigned long) ntohl(val_u32)); break; } /* Note: options which use 'return' instead of 'break' * (for example, OPTION_STRING) skip the code which handles * the case of list of options. */ case OPTION_STRING: case OPTION_STRING_HOST: memcpy(dest, option, len); dest[len] = '\0'; if (type == OPTION_STRING_HOST && !good_hostname(dest)) safe_strncpy(dest, "bad", len); return ret; case OPTION_STATIC_ROUTES: { /* Option binary format: * mask [one byte, 0..32] * ip [big endian, 0..4 bytes depending on mask] * router [big endian, 4 bytes] * may be repeated * * We convert it to a string "IP/MASK ROUTER IP2/MASK2 ROUTER2" */ const char *pfx = ""; while (len >= 1 + 4) { /* mask + 0-byte ip + router */ uint32_t nip; uint8_t *p; unsigned mask; int bytes; mask = *option++; if (mask > 32) break; len--; nip = 0; p = (void*) &nip; bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */ while (--bytes >= 0) { *p++ = *option++; len--; } if (len < 4) break; /* print ip/mask */ dest += sprint_nip(dest, pfx, (void*) &nip); pfx = " "; dest += sprintf(dest, "/%u ", mask); /* print router */ dest += sprint_nip(dest, "", option); option += 4; len -= 4; } return ret; } case OPTION_6RD: /* Option binary format (see RFC 5969): * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 6rdPrefix | * ... (16 octets) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * ... 6rdBRIPv4Address(es) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * We convert it to a string * "IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address..." * * Sanity check: ensure that our length is at least 22 bytes, that * IPv4MaskLen <= 32, * 6rdPrefixLen <= 128, * 6rdPrefixLen + (32 - IPv4MaskLen) <= 128 * (2nd condition need no check - it follows from 1st and 3rd). * Else, return envvar with empty value ("optname=") */ if (len >= (1 + 1 + 16 + 4) && option[0] <= 32 && (option[1] + 32 - option[0]) <= 128 ) { /* IPv4MaskLen */ dest += sprintf(dest, "%u ", *option++); /* 6rdPrefixLen */ dest += sprintf(dest, "%u ", *option++); /* 6rdPrefix */ dest += sprint_nip6(dest, /* "", */ option); option += 16; len -= 1 + 1 + 16 + 4; /* "+ 4" above corresponds to the length of IPv4 addr * we consume in the loop below */ while (1) { /* 6rdBRIPv4Address(es) */ dest += sprint_nip(dest, " ", option); option += 4; len -= 4; /* do we have yet another 4+ bytes? */ if (len < 0) break; /* no */ } } return ret; #if ENABLE_FEATURE_UDHCP_RFC3397 case OPTION_DNS_STRING: /* unpack option into dest; use ret for prefix (i.e., "optname=") */ dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } /* error. return "optname=" string */ return ret; case OPTION_SIP_SERVERS: /* Option binary format: * type: byte * type=0: domain names, dns-compressed * type=1: IP addrs */ option++; len--; if (option[-1] == 0) { dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } } else if (option[-1] == 1) { const char *pfx = ""; while (1) { len -= 4; if (len < 0) break; dest += sprint_nip(dest, pfx, option); pfx = " "; option += 4; } } return ret; #endif } /* switch */ /* If we are here, try to format any remaining data * in the option as another, similarly-formatted option */ option += optlen; len -= optlen; if (len < optlen /* || !(optflag->flags & OPTION_LIST) */) break; *dest++ = ' '; *dest = '\0'; } /* while */ return ret; } Commit Message: CWE ID: CWE-119
static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name) { unsigned upper_length; int len, type, optlen; char *dest, *ret; /* option points to OPT_DATA, need to go back to get OPT_LEN */ len = option[-OPT_DATA + OPT_LEN]; type = optflag->flags & OPTION_TYPE_MASK; optlen = dhcp_option_lengths[type]; upper_length = len_of_option_as_string[type] * ((unsigned)(len + optlen) / (unsigned)optlen); dest = ret = xmalloc(upper_length + strlen(opt_name) + 2); dest += sprintf(ret, "%s=", opt_name); while (len >= optlen) { switch (type) { case OPTION_IP: case OPTION_IP_PAIR: dest += sprint_nip(dest, "", option); if (type == OPTION_IP) break; dest += sprint_nip(dest, "/", option + 4); break; case OPTION_U8: dest += sprintf(dest, "%u", *option); break; case OPTION_U16: { uint16_t val_u16; move_from_unaligned16(val_u16, option); dest += sprintf(dest, "%u", ntohs(val_u16)); break; } case OPTION_S32: case OPTION_U32: { uint32_t val_u32; move_from_unaligned32(val_u32, option); dest += sprintf(dest, type == OPTION_U32 ? "%lu" : "%ld", (unsigned long) ntohl(val_u32)); break; } /* Note: options which use 'return' instead of 'break' * (for example, OPTION_STRING) skip the code which handles * the case of list of options. */ case OPTION_STRING: case OPTION_STRING_HOST: memcpy(dest, option, len); dest[len] = '\0'; if (type == OPTION_STRING_HOST && !good_hostname(dest)) safe_strncpy(dest, "bad", len); return ret; case OPTION_STATIC_ROUTES: { /* Option binary format: * mask [one byte, 0..32] * ip [big endian, 0..4 bytes depending on mask] * router [big endian, 4 bytes] * may be repeated * * We convert it to a string "IP/MASK ROUTER IP2/MASK2 ROUTER2" */ const char *pfx = ""; while (len >= 1 + 4) { /* mask + 0-byte ip + router */ uint32_t nip; uint8_t *p; unsigned mask; int bytes; mask = *option++; if (mask > 32) break; len--; nip = 0; p = (void*) &nip; bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */ while (--bytes >= 0) { *p++ = *option++; len--; } if (len < 4) break; /* print ip/mask */ dest += sprint_nip(dest, pfx, (void*) &nip); pfx = " "; dest += sprintf(dest, "/%u ", mask); /* print router */ dest += sprint_nip(dest, "", option); option += 4; len -= 4; } return ret; } case OPTION_6RD: /* Option binary format (see RFC 5969): * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 6rdPrefix | * ... (16 octets) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * ... 6rdBRIPv4Address(es) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * We convert it to a string * "IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address..." * * Sanity check: ensure that our length is at least 22 bytes, that * IPv4MaskLen <= 32, * 6rdPrefixLen <= 128, * 6rdPrefixLen + (32 - IPv4MaskLen) <= 128 * (2nd condition need no check - it follows from 1st and 3rd). * Else, return envvar with empty value ("optname=") */ if (len >= (1 + 1 + 16 + 4) && option[0] <= 32 && (option[1] + 32 - option[0]) <= 128 ) { /* IPv4MaskLen */ dest += sprintf(dest, "%u ", *option++); /* 6rdPrefixLen */ dest += sprintf(dest, "%u ", *option++); /* 6rdPrefix */ dest += sprint_nip6(dest, /* "", */ option); option += 16; len -= 1 + 1 + 16 + 4; /* "+ 4" above corresponds to the length of IPv4 addr * we consume in the loop below */ while (1) { /* 6rdBRIPv4Address(es) */ dest += sprint_nip(dest, " ", option); option += 4; len -= 4; /* do we have yet another 4+ bytes? */ if (len < 0) break; /* no */ } } return ret; #if ENABLE_FEATURE_UDHCP_RFC3397 case OPTION_DNS_STRING: /* unpack option into dest; use ret for prefix (i.e., "optname=") */ dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } /* error. return "optname=" string */ return ret; case OPTION_SIP_SERVERS: /* Option binary format: * type: byte * type=0: domain names, dns-compressed * type=1: IP addrs */ option++; len--; if (option[-1] == 0) { dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } } else if (option[-1] == 1) { const char *pfx = ""; while (1) { len -= 4; if (len < 0) break; dest += sprint_nip(dest, pfx, option); pfx = " "; option += 4; } } return ret; #endif } /* switch */ /* If we are here, try to format any remaining data * in the option as another, similarly-formatted option */ option += optlen; len -= optlen; if (len < optlen /* || !(optflag->flags & OPTION_LIST) */) break; *dest++ = ' '; *dest = '\0'; } /* while */ return ret; }
165,349
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int mp4client_main(int argc, char **argv) { char c; const char *str; int ret_val = 0; u32 i, times[100], nb_times, dump_mode; u32 simulation_time_in_ms = 0; u32 initial_service_id = 0; Bool auto_exit = GF_FALSE; Bool logs_set = GF_FALSE; Bool start_fs = GF_FALSE; Bool use_rtix = GF_FALSE; Bool pause_at_first = GF_FALSE; Bool no_cfg_save = GF_FALSE; Bool is_cfg_only = GF_FALSE; Double play_from = 0; #ifdef GPAC_MEMORY_TRACKING GF_MemTrackerType mem_track = GF_MemTrackerNone; #endif Double fps = GF_IMPORT_DEFAULT_FPS; Bool fill_ar, visible, do_uncache, has_command; char *url_arg, *out_arg, *the_cfg, *rti_file, *views, *mosaic; FILE *logfile = NULL; Float scale = 1; #ifndef WIN32 dlopen(NULL, RTLD_NOW|RTLD_GLOBAL); #endif /*by default use current dir*/ strcpy(the_url, "."); memset(&user, 0, sizeof(GF_User)); dump_mode = DUMP_NONE; fill_ar = visible = do_uncache = has_command = GF_FALSE; url_arg = out_arg = the_cfg = rti_file = views = mosaic = NULL; nb_times = 0; times[0] = 0; /*first locate config file if specified*/ for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { the_cfg = argv[i+1]; i++; } else if (!strcmp(arg, "-mem-track") || !strcmp(arg, "-mem-track-stack")) { #ifdef GPAC_MEMORY_TRACKING mem_track = !strcmp(arg, "-mem-track-stack") ? GF_MemTrackerBackTrace : GF_MemTrackerSimple; #else fprintf(stderr, "WARNING - GPAC not compiled with Memory Tracker - ignoring \"%s\"\n", arg); #endif } else if (!strcmp(arg, "-gui")) { gui_mode = 1; } else if (!strcmp(arg, "-guid")) { gui_mode = 2; } else if (!strcmp(arg, "-h") || !strcmp(arg, "-help")) { PrintUsage(); return 0; } } #ifdef GPAC_MEMORY_TRACKING gf_sys_init(mem_track); #else gf_sys_init(GF_MemTrackerNone); #endif gf_sys_set_args(argc, (const char **) argv); cfg_file = gf_cfg_init(the_cfg, NULL); if (!cfg_file) { fprintf(stderr, "Error: Configuration File not found\n"); return 1; } /*if logs are specified, use them*/ if (gf_log_set_tools_levels( gf_cfg_get_key(cfg_file, "General", "Logs") ) != GF_OK) { return 1; } if( gf_cfg_get_key(cfg_file, "General", "Logs") != NULL ) { logs_set = GF_TRUE; } if (!gui_mode) { str = gf_cfg_get_key(cfg_file, "General", "ForceGUI"); if (str && !strcmp(str, "yes")) gui_mode = 1; } for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-rti")) { rti_file = argv[i+1]; i++; } else if (!strcmp(arg, "-rtix")) { rti_file = argv[i+1]; i++; use_rtix = GF_TRUE; } else if (!stricmp(arg, "-size")) { /*usage of %ud breaks sscanf on MSVC*/ if (sscanf(argv[i+1], "%dx%d", &forced_width, &forced_height) != 2) { forced_width = forced_height = 0; } i++; } else if (!strcmp(arg, "-quiet")) { be_quiet = 1; } else if (!strcmp(arg, "-strict-error")) { gf_log_set_strict_error(1); } else if (!strcmp(arg, "-log-file") || !strcmp(arg, "-lf")) { logfile = gf_fopen(argv[i+1], "wt"); gf_log_set_callback(logfile, on_gpac_log); i++; } else if (!strcmp(arg, "-logs") ) { if (gf_log_set_tools_levels(argv[i+1]) != GF_OK) { return 1; } logs_set = GF_TRUE; i++; } else if (!strcmp(arg, "-log-clock") || !strcmp(arg, "-lc")) { log_time_start = 1; } else if (!strcmp(arg, "-log-utc") || !strcmp(arg, "-lu")) { log_utc_time = 1; } #if defined(__DARWIN__) || defined(__APPLE__) else if (!strcmp(arg, "-thread")) threading_flags = 0; #else else if (!strcmp(arg, "-no-thread")) threading_flags = GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_WINDOW_NO_THREAD; #endif else if (!strcmp(arg, "-no-cthread") || !strcmp(arg, "-no-compositor-thread")) threading_flags |= GF_TERM_NO_COMPOSITOR_THREAD; else if (!strcmp(arg, "-no-audio")) no_audio = 1; else if (!strcmp(arg, "-no-regulation")) no_regulation = 1; else if (!strcmp(arg, "-fs")) start_fs = 1; else if (!strcmp(arg, "-opt")) { set_cfg_option(argv[i+1]); i++; } else if (!strcmp(arg, "-conf")) { set_cfg_option(argv[i+1]); is_cfg_only=GF_TRUE; i++; } else if (!strcmp(arg, "-ifce")) { gf_cfg_set_key(cfg_file, "Network", "DefaultMCastInterface", argv[i+1]); i++; } else if (!stricmp(arg, "-help")) { PrintUsage(); return 1; } else if (!stricmp(arg, "-noprog")) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } else if (!stricmp(arg, "-no-save") || !stricmp(arg, "--no-save") /*old versions used --n-save ...*/) { no_cfg_save=1; } else if (!stricmp(arg, "-ntp-shift")) { s32 shift = atoi(argv[i+1]); i++; gf_net_set_ntp_shift(shift); } else if (!stricmp(arg, "-run-for")) { simulation_time_in_ms = atoi(argv[i+1]) * 1000; if (!simulation_time_in_ms) simulation_time_in_ms = 1; /*1ms*/ i++; } else if (!strcmp(arg, "-out")) { out_arg = argv[i+1]; i++; } else if (!stricmp(arg, "-fps")) { fps = atof(argv[i+1]); i++; } else if (!strcmp(arg, "-avi") || !strcmp(arg, "-sha")) { dump_mode &= 0xFFFF0000; if (!strcmp(arg, "-sha")) dump_mode |= DUMP_SHA1; else dump_mode |= DUMP_AVI; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) { if (!strcmp(arg, "-avi") && (nb_times!=2) ) { fprintf(stderr, "Only one time arg found for -avi - check usage\n"); return 1; } i++; } } else if (!strcmp(arg, "-rgbds")) { /*get dump in rgbds pixel format*/ dump_mode |= DUMP_RGB_DEPTH_SHAPE; } else if (!strcmp(arg, "-rgbd")) { /*get dump in rgbd pixel format*/ dump_mode |= DUMP_RGB_DEPTH; } else if (!strcmp(arg, "-depth")) { dump_mode |= DUMP_DEPTH_ONLY; } else if (!strcmp(arg, "-bmp")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_BMP; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-png")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_PNG; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-raw")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_RAW; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!stricmp(arg, "-scale")) { sscanf(argv[i+1], "%f", &scale); i++; } else if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { /* already parsed */ i++; } /*arguments only used in non-gui mode*/ if (!gui_mode) { if (arg[0] != '-') { if (url_arg) { fprintf(stderr, "Several input URLs provided (\"%s\", \"%s\"). Check your command-line.\n", url_arg, arg); return 1; } url_arg = arg; } else if (!strcmp(arg, "-loop")) loop_at_end = 1; else if (!strcmp(arg, "-bench")) bench_mode = 1; else if (!strcmp(arg, "-vbench")) bench_mode = 2; else if (!strcmp(arg, "-sbench")) bench_mode = 3; else if (!strcmp(arg, "-no-addon")) enable_add_ons = GF_FALSE; else if (!strcmp(arg, "-pause")) pause_at_first = 1; else if (!strcmp(arg, "-play-from")) { play_from = atof((const char *) argv[i+1]); i++; } else if (!strcmp(arg, "-speed")) { playback_speed = FLT2FIX( atof((const char *) argv[i+1]) ); if (playback_speed <= 0) playback_speed = FIX_ONE; i++; } else if (!strcmp(arg, "-no-wnd")) user.init_flags |= GF_TERM_WINDOWLESS; else if (!strcmp(arg, "-no-back")) user.init_flags |= GF_TERM_WINDOW_TRANSPARENT; else if (!strcmp(arg, "-align")) { if (argv[i+1][0]=='m') align_mode = 1; else if (argv[i+1][0]=='b') align_mode = 2; align_mode <<= 8; if (argv[i+1][1]=='m') align_mode |= 1; else if (argv[i+1][1]=='r') align_mode |= 2; i++; } else if (!strcmp(arg, "-fill")) { fill_ar = GF_TRUE; } else if (!strcmp(arg, "-show")) { visible = 1; } else if (!strcmp(arg, "-uncache")) { do_uncache = GF_TRUE; } else if (!strcmp(arg, "-exit")) auto_exit = GF_TRUE; else if (!stricmp(arg, "-views")) { views = argv[i+1]; i++; } else if (!stricmp(arg, "-mosaic")) { mosaic = argv[i+1]; i++; } else if (!stricmp(arg, "-com")) { has_command = GF_TRUE; i++; } else if (!stricmp(arg, "-service")) { initial_service_id = atoi(argv[i+1]); i++; } } } if (is_cfg_only) { gf_cfg_del(cfg_file); fprintf(stderr, "GPAC Config updated\n"); return 0; } if (do_uncache) { const char *cache_dir = gf_cfg_get_key(cfg_file, "General", "CacheDirectory"); do_flatten_cache(cache_dir); fprintf(stderr, "GPAC Cache dir %s flattened\n", cache_dir); gf_cfg_del(cfg_file); return 0; } if (dump_mode && !url_arg ) { FILE *test; url_arg = (char *)gf_cfg_get_key(cfg_file, "General", "StartupFile"); test = url_arg ? gf_fopen(url_arg, "rt") : NULL; if (!test) url_arg = NULL; else gf_fclose(test); if (!url_arg) { fprintf(stderr, "Missing argument for dump\n"); PrintUsage(); if (logfile) gf_fclose(logfile); return 1; } } if (!gui_mode && !url_arg && (gf_cfg_get_key(cfg_file, "General", "StartupFile") != NULL)) { gui_mode=1; } #ifdef WIN32 if (gui_mode==1) { const char *opt; TCHAR buffer[1024]; DWORD res = GetCurrentDirectory(1024, buffer); buffer[res] = 0; opt = gf_cfg_get_key(cfg_file, "General", "ModulesDirectory"); if (strstr(opt, buffer)) { gui_mode=1; } else { gui_mode=2; } } #endif if (gui_mode==1) { hide_shell(1); } if (gui_mode) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } if (!url_arg && simulation_time_in_ms) simulation_time_in_ms += gf_sys_clock(); #if defined(__DARWIN__) || defined(__APPLE__) carbon_init(); #endif if (dump_mode) rti_file = NULL; if (!logs_set) { gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_WARNING); } if (rti_file || logfile || log_utc_time || log_time_start) gf_log_set_callback(NULL, on_gpac_log); if (rti_file) init_rti_logs(rti_file, url_arg, use_rtix); { GF_SystemRTInfo rti; if (gf_sys_get_rti(0, &rti, 0)) fprintf(stderr, "System info: %d MB RAM - %d cores\n", (u32) (rti.physical_memory/1024/1024), rti.nb_cores); } /*setup dumping options*/ if (dump_mode) { user.init_flags |= GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_REGULATION; if (!visible) user.init_flags |= GF_TERM_INIT_HIDE; gf_cfg_set_key(cfg_file, "Audio", "DriverName", "Raw Audio Output"); no_cfg_save=GF_TRUE; } else { init_w = forced_width; init_h = forced_height; } user.modules = gf_modules_new(NULL, cfg_file); if (user.modules) i = gf_modules_get_count(user.modules); if (!i || !user.modules) { fprintf(stderr, "Error: no modules found - exiting\n"); if (user.modules) gf_modules_del(user.modules); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Modules Found : %d \n", i); str = gf_cfg_get_key(cfg_file, "General", "GPACVersion"); if (!str || strcmp(str, GPAC_FULL_VERSION)) { gf_cfg_del_section(cfg_file, "PluginsCache"); gf_cfg_set_key(cfg_file, "General", "GPACVersion", GPAC_FULL_VERSION); } user.config = cfg_file; user.EventProc = GPAC_EventProc; /*dummy in this case (global vars) but MUST be non-NULL*/ user.opaque = user.modules; if (threading_flags) user.init_flags |= threading_flags; if (no_audio) user.init_flags |= GF_TERM_NO_AUDIO; if (no_regulation) user.init_flags |= GF_TERM_NO_REGULATION; if (threading_flags & (GF_TERM_NO_DECODER_THREAD|GF_TERM_NO_COMPOSITOR_THREAD) ) term_step = GF_TRUE; if (dump_mode) user.init_flags |= GF_TERM_USE_AUDIO_HW_CLOCK; if (bench_mode) { gf_cfg_discard_changes(user.config); auto_exit = GF_TRUE; gf_cfg_set_key(user.config, "Audio", "DriverName", "Raw Audio Output"); if (bench_mode!=2) { gf_cfg_set_key(user.config, "Video", "DriverName", "Raw Video Output"); gf_cfg_set_key(user.config, "RAWVideo", "RawOutput", "null"); gf_cfg_set_key(user.config, "Compositor", "OpenGLMode", "disable"); } else { gf_cfg_set_key(user.config, "Video", "DisableVSync", "yes"); } } { char dim[50]; sprintf(dim, "%d", forced_width); gf_cfg_set_key(user.config, "Compositor", "DefaultWidth", forced_width ? dim : NULL); sprintf(dim, "%d", forced_height); gf_cfg_set_key(user.config, "Compositor", "DefaultHeight", forced_height ? dim : NULL); } fprintf(stderr, "Loading GPAC Terminal\n"); i = gf_sys_clock(); term = gf_term_new(&user); if (!term) { fprintf(stderr, "\nInit error - check you have at least one video out and one rasterizer...\nFound modules:\n"); list_modules(user.modules); gf_modules_del(user.modules); gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Terminal Loaded in %d ms\n", gf_sys_clock()-i); if (bench_mode) { display_rti = 2; gf_term_set_option(term, GF_OPT_VIDEO_BENCH, (bench_mode==3) ? 2 : 1); if (bench_mode==1) bench_mode=2; } if (dump_mode) { if (fill_ar) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); } else { /*check video output*/ str = gf_cfg_get_key(cfg_file, "Video", "DriverName"); if (!bench_mode && !strcmp(str, "Raw Video Output")) fprintf(stderr, "WARNING: using raw output video (memory only) - no display used\n"); /*check audio output*/ str = gf_cfg_get_key(cfg_file, "Audio", "DriverName"); if (!str || !strcmp(str, "No Audio Output Available")) fprintf(stderr, "WARNING: no audio output available - make sure no other program is locking the sound card\n"); str = gf_cfg_get_key(cfg_file, "General", "NoMIMETypeFetch"); no_mime_check = (str && !stricmp(str, "yes")) ? 1 : 0; } str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Enabled"); if (str && !strcmp(str, "yes")) { str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Name"); if (str) fprintf(stderr, "HTTP Proxy %s enabled\n", str); } if (rti_file) { str = gf_cfg_get_key(cfg_file, "General", "RTIRefreshPeriod"); if (str) { rti_update_time_ms = atoi(str); } else { gf_cfg_set_key(cfg_file, "General", "RTIRefreshPeriod", "200"); } UpdateRTInfo("At GPAC load time\n"); } Run = 1; if (dump_mode) { if (!nb_times) { times[0] = 0; nb_times++; } ret_val = dump_file(url_arg, out_arg, dump_mode, fps, forced_width, forced_height, scale, times, nb_times); Run = 0; } else if (views) { } /*connect if requested*/ else if (!gui_mode && url_arg) { char *ext; strcpy(the_url, url_arg); ext = strrchr(the_url, '.'); if (ext && (!stricmp(ext, ".m3u") || !stricmp(ext, ".pls"))) { GF_Err e = GF_OK; fprintf(stderr, "Opening Playlist %s\n", the_url); strcpy(pl_path, the_url); /*this is not clean, we need to have a plugin handle playlist for ourselves*/ if (!strncmp("http:", the_url, 5)) { GF_DownloadSession *sess = gf_dm_sess_new(term->downloader, the_url, GF_NETIO_SESSION_NOT_THREADED, NULL, NULL, &e); if (sess) { e = gf_dm_sess_process(sess); if (!e) strcpy(the_url, gf_dm_sess_get_cache_name(sess)); gf_dm_sess_del(sess); } } playlist = e ? NULL : gf_fopen(the_url, "rt"); readonly_playlist = 1; if (playlist) { request_next_playlist_item = GF_TRUE; } else { if (e) fprintf(stderr, "Failed to open playlist %s: %s\n", the_url, gf_error_to_string(e) ); fprintf(stderr, "Hit 'h' for help\n\n"); } } else { fprintf(stderr, "Opening URL %s\n", the_url); if (pause_at_first) fprintf(stderr, "[Status: Paused]\n"); gf_term_connect_from_time(term, the_url, (u64) (play_from*1000), pause_at_first); } } else { fprintf(stderr, "Hit 'h' for help\n\n"); str = gf_cfg_get_key(cfg_file, "General", "StartupFile"); if (str) { strcpy(the_url, "MP4Client "GPAC_FULL_VERSION); gf_term_connect(term, str); startup_file = 1; is_connected = 1; } } if (gui_mode==2) gui_mode=0; if (start_fs) gf_term_set_option(term, GF_OPT_FULLSCREEN, 1); if (views) { char szTemp[4046]; sprintf(szTemp, "views://%s", views); gf_term_connect(term, szTemp); } if (mosaic) { char szTemp[4046]; sprintf(szTemp, "mosaic://%s", mosaic); gf_term_connect(term, szTemp); } if (bench_mode) { rti_update_time_ms = 500; bench_mode_start = gf_sys_clock(); } while (Run) { /*we don't want getchar to block*/ if ((gui_mode==1) || !gf_prompt_has_input()) { if (reload) { reload = 0; gf_term_disconnect(term); gf_term_connect(term, startup_file ? gf_cfg_get_key(cfg_file, "General", "StartupFile") : the_url); } if (restart && gf_term_get_option(term, GF_OPT_IS_OVER)) { restart = 0; gf_term_play_from_time(term, 0, 0); } if (request_next_playlist_item) { c = '\n'; request_next_playlist_item = 0; goto force_input; } if (has_command && is_connected) { has_command = GF_FALSE; for (i=0; i<(u32)argc; i++) { if (!strcmp(argv[i], "-com")) { gf_term_scene_update(term, NULL, argv[i+1]); i++; } } } if (initial_service_id && is_connected) { GF_ObjectManager *root_od = gf_term_get_root_object(term); if (root_od) { gf_term_select_service(term, root_od, initial_service_id); initial_service_id = 0; } } if (!use_rtix || display_rti) UpdateRTInfo(NULL); if (term_step) { gf_term_process_step(term); } else { gf_sleep(rti_update_time_ms); } if (auto_exit && eos_seen && gf_term_get_option(term, GF_OPT_IS_OVER)) { Run = GF_FALSE; } /*sim time*/ if (simulation_time_in_ms && ( (gf_term_get_elapsed_time_in_ms(term)>simulation_time_in_ms) || (!url_arg && gf_sys_clock()>simulation_time_in_ms)) ) { Run = GF_FALSE; } continue; } c = gf_prompt_get_char(); force_input: switch (c) { case 'q': { GF_Event evt; memset(&evt, 0, sizeof(GF_Event)); evt.type = GF_EVENT_QUIT; gf_term_send_event(term, &evt); } break; case 'X': exit(0); break; case 'Q': break; case 'o': startup_file = 0; gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read absolute URL, aborting\n"); break; } if (rti_file) init_rti_logs(rti_file, the_url, use_rtix); gf_term_connect(term, the_url); break; case 'O': gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL to the playlist\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read the absolute URL, aborting.\n"); break; } playlist = gf_fopen(the_url, "rt"); if (playlist) { if (1 > fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Cannot read any URL from playlist, aborting.\n"); gf_fclose( playlist); break; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case '\n': case 'N': if (playlist) { int res; gf_term_disconnect(term); res = fscanf(playlist, "%s", the_url); if ((res == EOF) && loop_at_end) { fseek(playlist, 0, SEEK_SET); res = fscanf(playlist, "%s", the_url); } if (res == EOF) { fprintf(stderr, "No more items - exiting\n"); Run = 0; } else if (the_url[0] == '#') { request_next_playlist_item = GF_TRUE; } else { fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect_with_path(term, the_url, pl_path); } } break; case 'P': if (playlist) { u32 count; gf_term_disconnect(term); if (1 > scanf("%u", &count)) { fprintf(stderr, "Cannot read number, aborting.\n"); break; } while (count) { if (fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Failed to read line, aborting\n"); break; } count--; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case 'r': if (is_connected) reload = 1; break; case 'D': if (is_connected) gf_term_disconnect(term); break; case 'p': if (is_connected) { Bool is_pause = gf_term_get_option(term, GF_OPT_PLAY_STATE); fprintf(stderr, "[Status: %s]\n", is_pause ? "Playing" : "Paused"); gf_term_set_option(term, GF_OPT_PLAY_STATE, is_pause ? GF_STATE_PLAYING : GF_STATE_PAUSED); } break; case 's': if (is_connected) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE); fprintf(stderr, "Step time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, "\n"); } break; case 'z': case 'T': if (!CanSeek || (Duration<=2000)) { fprintf(stderr, "scene not seekable\n"); } else { Double res; s32 seekTo; fprintf(stderr, "Duration: "); PrintTime(Duration); res = gf_term_get_time_in_ms(term); if (c=='z') { res *= 100; res /= (s64)Duration; fprintf(stderr, " (current %.2f %%)\nEnter Seek percentage:\n", res); if (scanf("%d", &seekTo) == 1) { if (seekTo > 100) seekTo = 100; res = (Double)(s64)Duration; res /= 100; res *= seekTo; gf_term_play_from_time(term, (u64) (s64) res, 0); } } else { u32 r, h, m, s; fprintf(stderr, " - Current Time: "); PrintTime((u64) res); fprintf(stderr, "\nEnter seek time (Format: s, m:s or h:m:s):\n"); h = m = s = 0; r =scanf("%d:%d:%d", &h, &m, &s); if (r==2) { s = m; m = h; h = 0; } else if (r==1) { s = h; m = h = 0; } if (r && (r<=3)) { u64 time = h*3600 + m*60 + s; gf_term_play_from_time(term, time*1000, 0); } } } break; case 't': { if (is_connected) { fprintf(stderr, "Current Time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, " - Duration: "); PrintTime(Duration); fprintf(stderr, "\n"); } } break; case 'w': if (is_connected) PrintWorldInfo(term); break; case 'v': if (is_connected) PrintODList(term, NULL, 0, 0, "Root"); break; case 'i': if (is_connected) { u32 ID; fprintf(stderr, "Enter OD ID (0 for main OD): "); fflush(stderr); if (scanf("%ud", &ID) == 1) { ViewOD(term, ID, (u32)-1, NULL); } else { char str_url[GF_MAX_PATH]; if (scanf("%s", str_url) == 1) ViewOD(term, 0, (u32)-1, str_url); } } break; case 'j': if (is_connected) { u32 num; do { fprintf(stderr, "Enter OD number (0 for main OD): "); fflush(stderr); } while( 1 > scanf("%ud", &num)); ViewOD(term, (u32)-1, num, NULL); } break; case 'b': if (is_connected) ViewODs(term, 1); break; case 'm': if (is_connected) ViewODs(term, 0); break; case 'l': list_modules(user.modules); break; case 'n': if (is_connected) set_navigation(); break; case 'x': if (is_connected) gf_term_set_option(term, GF_OPT_NAVIGATION_TYPE, 0); break; case 'd': if (is_connected) { GF_ObjectManager *odm = NULL; char radname[GF_MAX_PATH], *sExt; GF_Err e; u32 i, count, odid; Bool xml_dump, std_out; radname[0] = 0; do { fprintf(stderr, "Enter Inline OD ID if any or 0 : "); fflush(stderr); } while( 1 > scanf("%ud", &odid)); if (odid) { GF_ObjectManager *root_odm = gf_term_get_root_object(term); if (!root_odm) break; count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { GF_MediaInfo info; odm = gf_term_get_object(term, root_odm, i); if (gf_term_get_object_info(term, odm, &info) == GF_OK) { if (info.od->objectDescriptorID==odid) break; } odm = NULL; } } do { fprintf(stderr, "Enter file radical name (+\'.x\' for XML dumping) - \"std\" for stderr: "); fflush(stderr); } while( 1 > scanf("%s", radname)); sExt = strrchr(radname, '.'); xml_dump = 0; if (sExt) { if (!stricmp(sExt, ".x")) xml_dump = 1; sExt[0] = 0; } std_out = strnicmp(radname, "std", 3) ? 0 : 1; e = gf_term_dump_scene(term, std_out ? NULL : radname, NULL, xml_dump, 0, odm); fprintf(stderr, "Dump done (%s)\n", gf_error_to_string(e)); } break; case 'c': PrintGPACConfig(); break; case '3': { Bool use_3d = !gf_term_get_option(term, GF_OPT_USE_OPENGL); if (gf_term_set_option(term, GF_OPT_USE_OPENGL, use_3d)==GF_OK) { fprintf(stderr, "Using %s for 2D drawing\n", use_3d ? "OpenGL" : "2D rasterizer"); } } break; case 'k': { Bool opt = gf_term_get_option(term, GF_OPT_STRESS_MODE); opt = !opt; fprintf(stderr, "Turning stress mode %s\n", opt ? "on" : "off"); gf_term_set_option(term, GF_OPT_STRESS_MODE, opt); } break; case '4': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3); break; case '5': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9); break; case '6': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); break; case '7': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP); break; case 'C': switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_DISABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_ENABLED); break; case GF_MEDIA_CACHE_ENABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_DISABLED); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache is running - please stop it first\n"); continue; } switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_ENABLED: fprintf(stderr, "Streaming Cache Enabled\n"); break; case GF_MEDIA_CACHE_DISABLED: fprintf(stderr, "Streaming Cache Disabled\n"); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache Running\n"); break; } break; case 'S': case 'A': if (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)==GF_MEDIA_CACHE_RUNNING) { gf_term_set_option(term, GF_OPT_MEDIA_CACHE, (c=='S') ? GF_MEDIA_CACHE_DISABLED : GF_MEDIA_CACHE_DISCARD); fprintf(stderr, "Streaming Cache stopped\n"); } else { fprintf(stderr, "Streaming Cache not running\n"); } break; case 'R': display_rti = !display_rti; ResetCaption(); break; case 'F': if (display_rti) display_rti = 0; else display_rti = 2; ResetCaption(); break; case 'u': { GF_Err e; char szCom[8192]; fprintf(stderr, "Enter command to send:\n"); fflush(stdin); szCom[0] = 0; if (1 > scanf("%[^\t\n]", szCom)) { fprintf(stderr, "Cannot read command to send, aborting.\n"); break; } e = gf_term_scene_update(term, NULL, szCom); if (e) fprintf(stderr, "Processing command failed: %s\n", gf_error_to_string(e)); } break; case 'e': { GF_Err e; char jsCode[8192]; fprintf(stderr, "Enter JavaScript code to evaluate:\n"); fflush(stdin); jsCode[0] = 0; if (1 > scanf("%[^\t\n]", jsCode)) { fprintf(stderr, "Cannot read code to evaluate, aborting.\n"); break; } e = gf_term_scene_update(term, "application/ecmascript", jsCode); if (e) fprintf(stderr, "Processing JS code failed: %s\n", gf_error_to_string(e)); } break; case 'L': { char szLog[1024], *cur_logs; cur_logs = gf_log_get_tools_levels(); fprintf(stderr, "Enter new log level (current tools %s):\n", cur_logs); gf_free(cur_logs); if (scanf("%s", szLog) < 1) { fprintf(stderr, "Cannot read new log level, aborting.\n"); break; } gf_log_modify_tools_levels(szLog); } break; case 'g': { GF_SystemRTInfo rti; gf_sys_get_rti(rti_update_time_ms, &rti, 0); fprintf(stderr, "GPAC allocated memory "LLD"\n", rti.gpac_memory); } break; case 'M': { u32 size; do { fprintf(stderr, "Enter new video cache memory in kBytes (current %ud):\n", gf_term_get_option(term, GF_OPT_VIDEO_CACHE_SIZE)); } while (1 > scanf("%ud", &size)); gf_term_set_option(term, GF_OPT_VIDEO_CACHE_SIZE, size); } break; case 'H': { u32 http_bitrate = gf_term_get_option(term, GF_OPT_HTTP_MAX_RATE); do { fprintf(stderr, "Enter new http bitrate in bps (0 for none) - current limit: %d\n", http_bitrate); } while (1 > scanf("%ud", &http_bitrate)); gf_term_set_option(term, GF_OPT_HTTP_MAX_RATE, http_bitrate); } break; case 'E': gf_term_set_option(term, GF_OPT_RELOAD_CONFIG, 1); break; case 'B': switch_bench(!bench_mode); break; case 'Y': { char szOpt[8192]; fprintf(stderr, "Enter option to set (Section:Name=Value):\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read option\n"); break; } set_cfg_option(szOpt); } break; /*extract to PNG*/ case 'Z': { char szFileName[100]; u32 nb_pass, nb_views, offscreen_view = 0; GF_VideoSurface fb; GF_Err e; nb_pass = 1; nb_views = gf_term_get_option(term, GF_OPT_NUM_STEREO_VIEWS); if (nb_views>1) { fprintf(stderr, "Auto-stereo mode detected - type number of view to dump (0 is main output, 1 to %d offscreen view, %d for all offscreen, %d for all offscreen and main)\n", nb_views, nb_views+1, nb_views+2); if (scanf("%d", &offscreen_view) != 1) { offscreen_view = 0; } if (offscreen_view==nb_views+1) { offscreen_view = 1; nb_pass = nb_views; } else if (offscreen_view==nb_views+2) { offscreen_view = 0; nb_pass = nb_views+1; } } while (nb_pass) { nb_pass--; if (offscreen_view) { sprintf(szFileName, "view%d_dump.png", offscreen_view); e = gf_term_get_offscreen_buffer(term, &fb, offscreen_view-1, 0); } else { sprintf(szFileName, "gpac_video_dump_"LLU".png", gf_net_get_utc() ); e = gf_term_get_screen_buffer(term, &fb); } offscreen_view++; if (e) { fprintf(stderr, "Error dumping screen buffer %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { #ifndef GPAC_DISABLE_AV_PARSERS u32 dst_size = fb.width*fb.height*4; char *dst = (char*)gf_malloc(sizeof(char)*dst_size); e = gf_img_png_enc(fb.video_buffer, fb.width, fb.height, fb.pitch_y, fb.pixel_format, dst, &dst_size); if (e) { fprintf(stderr, "Error encoding PNG %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { FILE *png = gf_fopen(szFileName, "wb"); if (!png) { fprintf(stderr, "Error writing file %s\n", szFileName); nb_pass = 0; } else { gf_fwrite(dst, dst_size, 1, png); gf_fclose(png); fprintf(stderr, "Dump to %s\n", szFileName); } } if (dst) gf_free(dst); gf_term_release_screen_buffer(term, &fb); #endif //GPAC_DISABLE_AV_PARSERS } } fprintf(stderr, "Done: %s\n", szFileName); } break; case 'G': { GF_ObjectManager *root_od, *odm; u32 index; char szOpt[8192]; fprintf(stderr, "Enter 0-based index of object to select or service ID:\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read OD ID\n"); break; } index = atoi(szOpt); odm = NULL; root_od = gf_term_get_root_object(term); if (root_od) { if ( gf_term_find_service(term, root_od, index)) { gf_term_select_service(term, root_od, index); } else { fprintf(stderr, "Cannot find service %d - trying with object index\n", index); odm = gf_term_get_object(term, root_od, index); if (odm) { gf_term_select_object(term, odm); } else { fprintf(stderr, "Cannot find object at index %d\n", index); } } } } break; case 'h': PrintHelp(); break; default: break; } } if (bench_mode) { PrintAVInfo(GF_TRUE); } /*FIXME: we have an issue in cleaning up after playing in bench mode and run-for 0 (buildbot tests). We for now disable error checks after run-for is done*/ if (simulation_time_in_ms) { gf_log_set_strict_error(0); } i = gf_sys_clock(); gf_term_disconnect(term); if (rti_file) UpdateRTInfo("Disconnected\n"); fprintf(stderr, "Deleting terminal... "); if (playlist) gf_fclose(playlist); #if defined(__DARWIN__) || defined(__APPLE__) carbon_uninit(); #endif gf_term_del(term); fprintf(stderr, "done (in %d ms) - ran for %d ms\n", gf_sys_clock() - i, gf_sys_clock()); fprintf(stderr, "GPAC cleanup ...\n"); gf_modules_del(user.modules); if (no_cfg_save) gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (rti_logs) gf_fclose(rti_logs); if (logfile) gf_fclose(logfile); if (gui_mode) { hide_shell(2); } #ifdef GPAC_MEMORY_TRACKING if (mem_track && (gf_memory_size() || gf_file_handles_count() )) { gf_log_set_tool_level(GF_LOG_MEMORY, GF_LOG_INFO); gf_memory_print(); return 2; } #endif return ret_val; } Commit Message: fix some overflows due to strcpy fixes #1184, #1186, #1187 among other things CWE ID: CWE-119
int mp4client_main(int argc, char **argv) { char c; const char *str; int ret_val = 0; u32 i, times[100], nb_times, dump_mode; u32 simulation_time_in_ms = 0; u32 initial_service_id = 0; Bool auto_exit = GF_FALSE; Bool logs_set = GF_FALSE; Bool start_fs = GF_FALSE; Bool use_rtix = GF_FALSE; Bool pause_at_first = GF_FALSE; Bool no_cfg_save = GF_FALSE; Bool is_cfg_only = GF_FALSE; Double play_from = 0; #ifdef GPAC_MEMORY_TRACKING GF_MemTrackerType mem_track = GF_MemTrackerNone; #endif Double fps = GF_IMPORT_DEFAULT_FPS; Bool fill_ar, visible, do_uncache, has_command; char *url_arg, *out_arg, *the_cfg, *rti_file, *views, *mosaic; FILE *logfile = NULL; Float scale = 1; #ifndef WIN32 dlopen(NULL, RTLD_NOW|RTLD_GLOBAL); #endif /*by default use current dir*/ strcpy(the_url, "."); memset(&user, 0, sizeof(GF_User)); dump_mode = DUMP_NONE; fill_ar = visible = do_uncache = has_command = GF_FALSE; url_arg = out_arg = the_cfg = rti_file = views = mosaic = NULL; nb_times = 0; times[0] = 0; /*first locate config file if specified*/ for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { the_cfg = argv[i+1]; i++; } else if (!strcmp(arg, "-mem-track") || !strcmp(arg, "-mem-track-stack")) { #ifdef GPAC_MEMORY_TRACKING mem_track = !strcmp(arg, "-mem-track-stack") ? GF_MemTrackerBackTrace : GF_MemTrackerSimple; #else fprintf(stderr, "WARNING - GPAC not compiled with Memory Tracker - ignoring \"%s\"\n", arg); #endif } else if (!strcmp(arg, "-gui")) { gui_mode = 1; } else if (!strcmp(arg, "-guid")) { gui_mode = 2; } else if (!strcmp(arg, "-h") || !strcmp(arg, "-help")) { PrintUsage(); return 0; } } #ifdef GPAC_MEMORY_TRACKING gf_sys_init(mem_track); #else gf_sys_init(GF_MemTrackerNone); #endif gf_sys_set_args(argc, (const char **) argv); cfg_file = gf_cfg_init(the_cfg, NULL); if (!cfg_file) { fprintf(stderr, "Error: Configuration File not found\n"); return 1; } /*if logs are specified, use them*/ if (gf_log_set_tools_levels( gf_cfg_get_key(cfg_file, "General", "Logs") ) != GF_OK) { return 1; } if( gf_cfg_get_key(cfg_file, "General", "Logs") != NULL ) { logs_set = GF_TRUE; } if (!gui_mode) { str = gf_cfg_get_key(cfg_file, "General", "ForceGUI"); if (str && !strcmp(str, "yes")) gui_mode = 1; } for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-rti")) { rti_file = argv[i+1]; i++; } else if (!strcmp(arg, "-rtix")) { rti_file = argv[i+1]; i++; use_rtix = GF_TRUE; } else if (!stricmp(arg, "-size")) { /*usage of %ud breaks sscanf on MSVC*/ if (sscanf(argv[i+1], "%dx%d", &forced_width, &forced_height) != 2) { forced_width = forced_height = 0; } i++; } else if (!strcmp(arg, "-quiet")) { be_quiet = 1; } else if (!strcmp(arg, "-strict-error")) { gf_log_set_strict_error(1); } else if (!strcmp(arg, "-log-file") || !strcmp(arg, "-lf")) { logfile = gf_fopen(argv[i+1], "wt"); gf_log_set_callback(logfile, on_gpac_log); i++; } else if (!strcmp(arg, "-logs") ) { if (gf_log_set_tools_levels(argv[i+1]) != GF_OK) { return 1; } logs_set = GF_TRUE; i++; } else if (!strcmp(arg, "-log-clock") || !strcmp(arg, "-lc")) { log_time_start = 1; } else if (!strcmp(arg, "-log-utc") || !strcmp(arg, "-lu")) { log_utc_time = 1; } #if defined(__DARWIN__) || defined(__APPLE__) else if (!strcmp(arg, "-thread")) threading_flags = 0; #else else if (!strcmp(arg, "-no-thread")) threading_flags = GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_WINDOW_NO_THREAD; #endif else if (!strcmp(arg, "-no-cthread") || !strcmp(arg, "-no-compositor-thread")) threading_flags |= GF_TERM_NO_COMPOSITOR_THREAD; else if (!strcmp(arg, "-no-audio")) no_audio = 1; else if (!strcmp(arg, "-no-regulation")) no_regulation = 1; else if (!strcmp(arg, "-fs")) start_fs = 1; else if (!strcmp(arg, "-opt")) { set_cfg_option(argv[i+1]); i++; } else if (!strcmp(arg, "-conf")) { set_cfg_option(argv[i+1]); is_cfg_only=GF_TRUE; i++; } else if (!strcmp(arg, "-ifce")) { gf_cfg_set_key(cfg_file, "Network", "DefaultMCastInterface", argv[i+1]); i++; } else if (!stricmp(arg, "-help")) { PrintUsage(); return 1; } else if (!stricmp(arg, "-noprog")) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } else if (!stricmp(arg, "-no-save") || !stricmp(arg, "--no-save") /*old versions used --n-save ...*/) { no_cfg_save=1; } else if (!stricmp(arg, "-ntp-shift")) { s32 shift = atoi(argv[i+1]); i++; gf_net_set_ntp_shift(shift); } else if (!stricmp(arg, "-run-for")) { simulation_time_in_ms = atoi(argv[i+1]) * 1000; if (!simulation_time_in_ms) simulation_time_in_ms = 1; /*1ms*/ i++; } else if (!strcmp(arg, "-out")) { out_arg = argv[i+1]; i++; } else if (!stricmp(arg, "-fps")) { fps = atof(argv[i+1]); i++; } else if (!strcmp(arg, "-avi") || !strcmp(arg, "-sha")) { dump_mode &= 0xFFFF0000; if (!strcmp(arg, "-sha")) dump_mode |= DUMP_SHA1; else dump_mode |= DUMP_AVI; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) { if (!strcmp(arg, "-avi") && (nb_times!=2) ) { fprintf(stderr, "Only one time arg found for -avi - check usage\n"); return 1; } i++; } } else if (!strcmp(arg, "-rgbds")) { /*get dump in rgbds pixel format*/ dump_mode |= DUMP_RGB_DEPTH_SHAPE; } else if (!strcmp(arg, "-rgbd")) { /*get dump in rgbd pixel format*/ dump_mode |= DUMP_RGB_DEPTH; } else if (!strcmp(arg, "-depth")) { dump_mode |= DUMP_DEPTH_ONLY; } else if (!strcmp(arg, "-bmp")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_BMP; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-png")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_PNG; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-raw")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_RAW; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!stricmp(arg, "-scale")) { sscanf(argv[i+1], "%f", &scale); i++; } else if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { /* already parsed */ i++; } /*arguments only used in non-gui mode*/ if (!gui_mode) { if (arg[0] != '-') { if (url_arg) { fprintf(stderr, "Several input URLs provided (\"%s\", \"%s\"). Check your command-line.\n", url_arg, arg); return 1; } url_arg = arg; } else if (!strcmp(arg, "-loop")) loop_at_end = 1; else if (!strcmp(arg, "-bench")) bench_mode = 1; else if (!strcmp(arg, "-vbench")) bench_mode = 2; else if (!strcmp(arg, "-sbench")) bench_mode = 3; else if (!strcmp(arg, "-no-addon")) enable_add_ons = GF_FALSE; else if (!strcmp(arg, "-pause")) pause_at_first = 1; else if (!strcmp(arg, "-play-from")) { play_from = atof((const char *) argv[i+1]); i++; } else if (!strcmp(arg, "-speed")) { playback_speed = FLT2FIX( atof((const char *) argv[i+1]) ); if (playback_speed <= 0) playback_speed = FIX_ONE; i++; } else if (!strcmp(arg, "-no-wnd")) user.init_flags |= GF_TERM_WINDOWLESS; else if (!strcmp(arg, "-no-back")) user.init_flags |= GF_TERM_WINDOW_TRANSPARENT; else if (!strcmp(arg, "-align")) { if (argv[i+1][0]=='m') align_mode = 1; else if (argv[i+1][0]=='b') align_mode = 2; align_mode <<= 8; if (argv[i+1][1]=='m') align_mode |= 1; else if (argv[i+1][1]=='r') align_mode |= 2; i++; } else if (!strcmp(arg, "-fill")) { fill_ar = GF_TRUE; } else if (!strcmp(arg, "-show")) { visible = 1; } else if (!strcmp(arg, "-uncache")) { do_uncache = GF_TRUE; } else if (!strcmp(arg, "-exit")) auto_exit = GF_TRUE; else if (!stricmp(arg, "-views")) { views = argv[i+1]; i++; } else if (!stricmp(arg, "-mosaic")) { mosaic = argv[i+1]; i++; } else if (!stricmp(arg, "-com")) { has_command = GF_TRUE; i++; } else if (!stricmp(arg, "-service")) { initial_service_id = atoi(argv[i+1]); i++; } } } if (is_cfg_only) { gf_cfg_del(cfg_file); fprintf(stderr, "GPAC Config updated\n"); return 0; } if (do_uncache) { const char *cache_dir = gf_cfg_get_key(cfg_file, "General", "CacheDirectory"); do_flatten_cache(cache_dir); fprintf(stderr, "GPAC Cache dir %s flattened\n", cache_dir); gf_cfg_del(cfg_file); return 0; } if (dump_mode && !url_arg ) { FILE *test; url_arg = (char *)gf_cfg_get_key(cfg_file, "General", "StartupFile"); test = url_arg ? gf_fopen(url_arg, "rt") : NULL; if (!test) url_arg = NULL; else gf_fclose(test); if (!url_arg) { fprintf(stderr, "Missing argument for dump\n"); PrintUsage(); if (logfile) gf_fclose(logfile); return 1; } } if (!gui_mode && !url_arg && (gf_cfg_get_key(cfg_file, "General", "StartupFile") != NULL)) { gui_mode=1; } #ifdef WIN32 if (gui_mode==1) { const char *opt; TCHAR buffer[1024]; DWORD res = GetCurrentDirectory(1024, buffer); buffer[res] = 0; opt = gf_cfg_get_key(cfg_file, "General", "ModulesDirectory"); if (strstr(opt, buffer)) { gui_mode=1; } else { gui_mode=2; } } #endif if (gui_mode==1) { hide_shell(1); } if (gui_mode) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } if (!url_arg && simulation_time_in_ms) simulation_time_in_ms += gf_sys_clock(); #if defined(__DARWIN__) || defined(__APPLE__) carbon_init(); #endif if (dump_mode) rti_file = NULL; if (!logs_set) { gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_WARNING); } if (rti_file || logfile || log_utc_time || log_time_start) gf_log_set_callback(NULL, on_gpac_log); if (rti_file) init_rti_logs(rti_file, url_arg, use_rtix); { GF_SystemRTInfo rti; if (gf_sys_get_rti(0, &rti, 0)) fprintf(stderr, "System info: %d MB RAM - %d cores\n", (u32) (rti.physical_memory/1024/1024), rti.nb_cores); } /*setup dumping options*/ if (dump_mode) { user.init_flags |= GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_REGULATION; if (!visible) user.init_flags |= GF_TERM_INIT_HIDE; gf_cfg_set_key(cfg_file, "Audio", "DriverName", "Raw Audio Output"); no_cfg_save=GF_TRUE; } else { init_w = forced_width; init_h = forced_height; } user.modules = gf_modules_new(NULL, cfg_file); if (user.modules) i = gf_modules_get_count(user.modules); if (!i || !user.modules) { fprintf(stderr, "Error: no modules found - exiting\n"); if (user.modules) gf_modules_del(user.modules); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Modules Found : %d \n", i); str = gf_cfg_get_key(cfg_file, "General", "GPACVersion"); if (!str || strcmp(str, GPAC_FULL_VERSION)) { gf_cfg_del_section(cfg_file, "PluginsCache"); gf_cfg_set_key(cfg_file, "General", "GPACVersion", GPAC_FULL_VERSION); } user.config = cfg_file; user.EventProc = GPAC_EventProc; /*dummy in this case (global vars) but MUST be non-NULL*/ user.opaque = user.modules; if (threading_flags) user.init_flags |= threading_flags; if (no_audio) user.init_flags |= GF_TERM_NO_AUDIO; if (no_regulation) user.init_flags |= GF_TERM_NO_REGULATION; if (threading_flags & (GF_TERM_NO_DECODER_THREAD|GF_TERM_NO_COMPOSITOR_THREAD) ) term_step = GF_TRUE; if (dump_mode) user.init_flags |= GF_TERM_USE_AUDIO_HW_CLOCK; if (bench_mode) { gf_cfg_discard_changes(user.config); auto_exit = GF_TRUE; gf_cfg_set_key(user.config, "Audio", "DriverName", "Raw Audio Output"); if (bench_mode!=2) { gf_cfg_set_key(user.config, "Video", "DriverName", "Raw Video Output"); gf_cfg_set_key(user.config, "RAWVideo", "RawOutput", "null"); gf_cfg_set_key(user.config, "Compositor", "OpenGLMode", "disable"); } else { gf_cfg_set_key(user.config, "Video", "DisableVSync", "yes"); } } { char dim[50]; sprintf(dim, "%d", forced_width); gf_cfg_set_key(user.config, "Compositor", "DefaultWidth", forced_width ? dim : NULL); sprintf(dim, "%d", forced_height); gf_cfg_set_key(user.config, "Compositor", "DefaultHeight", forced_height ? dim : NULL); } fprintf(stderr, "Loading GPAC Terminal\n"); i = gf_sys_clock(); term = gf_term_new(&user); if (!term) { fprintf(stderr, "\nInit error - check you have at least one video out and one rasterizer...\nFound modules:\n"); list_modules(user.modules); gf_modules_del(user.modules); gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Terminal Loaded in %d ms\n", gf_sys_clock()-i); if (bench_mode) { display_rti = 2; gf_term_set_option(term, GF_OPT_VIDEO_BENCH, (bench_mode==3) ? 2 : 1); if (bench_mode==1) bench_mode=2; } if (dump_mode) { if (fill_ar) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); } else { /*check video output*/ str = gf_cfg_get_key(cfg_file, "Video", "DriverName"); if (!bench_mode && !strcmp(str, "Raw Video Output")) fprintf(stderr, "WARNING: using raw output video (memory only) - no display used\n"); /*check audio output*/ str = gf_cfg_get_key(cfg_file, "Audio", "DriverName"); if (!str || !strcmp(str, "No Audio Output Available")) fprintf(stderr, "WARNING: no audio output available - make sure no other program is locking the sound card\n"); str = gf_cfg_get_key(cfg_file, "General", "NoMIMETypeFetch"); no_mime_check = (str && !stricmp(str, "yes")) ? 1 : 0; } str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Enabled"); if (str && !strcmp(str, "yes")) { str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Name"); if (str) fprintf(stderr, "HTTP Proxy %s enabled\n", str); } if (rti_file) { str = gf_cfg_get_key(cfg_file, "General", "RTIRefreshPeriod"); if (str) { rti_update_time_ms = atoi(str); } else { gf_cfg_set_key(cfg_file, "General", "RTIRefreshPeriod", "200"); } UpdateRTInfo("At GPAC load time\n"); } Run = 1; if (dump_mode) { if (!nb_times) { times[0] = 0; nb_times++; } ret_val = dump_file(url_arg, out_arg, dump_mode, fps, forced_width, forced_height, scale, times, nb_times); Run = 0; } else if (views) { } /*connect if requested*/ else if (!gui_mode && url_arg) { char *ext; if (strlen(url_arg) >= sizeof(the_url)) { fprintf(stderr, "Input url %s is too long, truncating to %d chars.\n", url_arg, (int)(sizeof(the_url) - 1)); strncpy(the_url, url_arg, sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; } else { strcpy(the_url, url_arg); } ext = strrchr(the_url, '.'); if (ext && (!stricmp(ext, ".m3u") || !stricmp(ext, ".pls"))) { GF_Err e = GF_OK; fprintf(stderr, "Opening Playlist %s\n", the_url); strcpy(pl_path, the_url); /*this is not clean, we need to have a plugin handle playlist for ourselves*/ if (!strncmp("http:", the_url, 5)) { GF_DownloadSession *sess = gf_dm_sess_new(term->downloader, the_url, GF_NETIO_SESSION_NOT_THREADED, NULL, NULL, &e); if (sess) { e = gf_dm_sess_process(sess); if (!e) { strncpy(the_url, gf_dm_sess_get_cache_name(sess), sizeof(the_url) - 1); the_url[sizeof(the_cfg) - 1] = 0; } gf_dm_sess_del(sess); } } playlist = e ? NULL : gf_fopen(the_url, "rt"); readonly_playlist = 1; if (playlist) { request_next_playlist_item = GF_TRUE; } else { if (e) fprintf(stderr, "Failed to open playlist %s: %s\n", the_url, gf_error_to_string(e) ); fprintf(stderr, "Hit 'h' for help\n\n"); } } else { fprintf(stderr, "Opening URL %s\n", the_url); if (pause_at_first) fprintf(stderr, "[Status: Paused]\n"); gf_term_connect_from_time(term, the_url, (u64) (play_from*1000), pause_at_first); } } else { fprintf(stderr, "Hit 'h' for help\n\n"); str = gf_cfg_get_key(cfg_file, "General", "StartupFile"); if (str) { strncpy(the_url, "MP4Client "GPAC_FULL_VERSION , sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; gf_term_connect(term, str); startup_file = 1; is_connected = 1; } } if (gui_mode==2) gui_mode=0; if (start_fs) gf_term_set_option(term, GF_OPT_FULLSCREEN, 1); if (views) { char szTemp[4046]; sprintf(szTemp, "views://%s", views); gf_term_connect(term, szTemp); } if (mosaic) { char szTemp[4046]; sprintf(szTemp, "mosaic://%s", mosaic); gf_term_connect(term, szTemp); } if (bench_mode) { rti_update_time_ms = 500; bench_mode_start = gf_sys_clock(); } while (Run) { /*we don't want getchar to block*/ if ((gui_mode==1) || !gf_prompt_has_input()) { if (reload) { reload = 0; gf_term_disconnect(term); gf_term_connect(term, startup_file ? gf_cfg_get_key(cfg_file, "General", "StartupFile") : the_url); } if (restart && gf_term_get_option(term, GF_OPT_IS_OVER)) { restart = 0; gf_term_play_from_time(term, 0, 0); } if (request_next_playlist_item) { c = '\n'; request_next_playlist_item = 0; goto force_input; } if (has_command && is_connected) { has_command = GF_FALSE; for (i=0; i<(u32)argc; i++) { if (!strcmp(argv[i], "-com")) { gf_term_scene_update(term, NULL, argv[i+1]); i++; } } } if (initial_service_id && is_connected) { GF_ObjectManager *root_od = gf_term_get_root_object(term); if (root_od) { gf_term_select_service(term, root_od, initial_service_id); initial_service_id = 0; } } if (!use_rtix || display_rti) UpdateRTInfo(NULL); if (term_step) { gf_term_process_step(term); } else { gf_sleep(rti_update_time_ms); } if (auto_exit && eos_seen && gf_term_get_option(term, GF_OPT_IS_OVER)) { Run = GF_FALSE; } /*sim time*/ if (simulation_time_in_ms && ( (gf_term_get_elapsed_time_in_ms(term)>simulation_time_in_ms) || (!url_arg && gf_sys_clock()>simulation_time_in_ms)) ) { Run = GF_FALSE; } continue; } c = gf_prompt_get_char(); force_input: switch (c) { case 'q': { GF_Event evt; memset(&evt, 0, sizeof(GF_Event)); evt.type = GF_EVENT_QUIT; gf_term_send_event(term, &evt); } break; case 'X': exit(0); break; case 'Q': break; case 'o': startup_file = 0; gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read absolute URL, aborting\n"); break; } if (rti_file) init_rti_logs(rti_file, the_url, use_rtix); gf_term_connect(term, the_url); break; case 'O': gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL to the playlist\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read the absolute URL, aborting.\n"); break; } playlist = gf_fopen(the_url, "rt"); if (playlist) { if (1 > fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Cannot read any URL from playlist, aborting.\n"); gf_fclose( playlist); break; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case '\n': case 'N': if (playlist) { int res; gf_term_disconnect(term); res = fscanf(playlist, "%s", the_url); if ((res == EOF) && loop_at_end) { fseek(playlist, 0, SEEK_SET); res = fscanf(playlist, "%s", the_url); } if (res == EOF) { fprintf(stderr, "No more items - exiting\n"); Run = 0; } else if (the_url[0] == '#') { request_next_playlist_item = GF_TRUE; } else { fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect_with_path(term, the_url, pl_path); } } break; case 'P': if (playlist) { u32 count; gf_term_disconnect(term); if (1 > scanf("%u", &count)) { fprintf(stderr, "Cannot read number, aborting.\n"); break; } while (count) { if (fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Failed to read line, aborting\n"); break; } count--; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case 'r': if (is_connected) reload = 1; break; case 'D': if (is_connected) gf_term_disconnect(term); break; case 'p': if (is_connected) { Bool is_pause = gf_term_get_option(term, GF_OPT_PLAY_STATE); fprintf(stderr, "[Status: %s]\n", is_pause ? "Playing" : "Paused"); gf_term_set_option(term, GF_OPT_PLAY_STATE, is_pause ? GF_STATE_PLAYING : GF_STATE_PAUSED); } break; case 's': if (is_connected) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE); fprintf(stderr, "Step time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, "\n"); } break; case 'z': case 'T': if (!CanSeek || (Duration<=2000)) { fprintf(stderr, "scene not seekable\n"); } else { Double res; s32 seekTo; fprintf(stderr, "Duration: "); PrintTime(Duration); res = gf_term_get_time_in_ms(term); if (c=='z') { res *= 100; res /= (s64)Duration; fprintf(stderr, " (current %.2f %%)\nEnter Seek percentage:\n", res); if (scanf("%d", &seekTo) == 1) { if (seekTo > 100) seekTo = 100; res = (Double)(s64)Duration; res /= 100; res *= seekTo; gf_term_play_from_time(term, (u64) (s64) res, 0); } } else { u32 r, h, m, s; fprintf(stderr, " - Current Time: "); PrintTime((u64) res); fprintf(stderr, "\nEnter seek time (Format: s, m:s or h:m:s):\n"); h = m = s = 0; r =scanf("%d:%d:%d", &h, &m, &s); if (r==2) { s = m; m = h; h = 0; } else if (r==1) { s = h; m = h = 0; } if (r && (r<=3)) { u64 time = h*3600 + m*60 + s; gf_term_play_from_time(term, time*1000, 0); } } } break; case 't': { if (is_connected) { fprintf(stderr, "Current Time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, " - Duration: "); PrintTime(Duration); fprintf(stderr, "\n"); } } break; case 'w': if (is_connected) PrintWorldInfo(term); break; case 'v': if (is_connected) PrintODList(term, NULL, 0, 0, "Root"); break; case 'i': if (is_connected) { u32 ID; fprintf(stderr, "Enter OD ID (0 for main OD): "); fflush(stderr); if (scanf("%ud", &ID) == 1) { ViewOD(term, ID, (u32)-1, NULL); } else { char str_url[GF_MAX_PATH]; if (scanf("%s", str_url) == 1) ViewOD(term, 0, (u32)-1, str_url); } } break; case 'j': if (is_connected) { u32 num; do { fprintf(stderr, "Enter OD number (0 for main OD): "); fflush(stderr); } while( 1 > scanf("%ud", &num)); ViewOD(term, (u32)-1, num, NULL); } break; case 'b': if (is_connected) ViewODs(term, 1); break; case 'm': if (is_connected) ViewODs(term, 0); break; case 'l': list_modules(user.modules); break; case 'n': if (is_connected) set_navigation(); break; case 'x': if (is_connected) gf_term_set_option(term, GF_OPT_NAVIGATION_TYPE, 0); break; case 'd': if (is_connected) { GF_ObjectManager *odm = NULL; char radname[GF_MAX_PATH], *sExt; GF_Err e; u32 i, count, odid; Bool xml_dump, std_out; radname[0] = 0; do { fprintf(stderr, "Enter Inline OD ID if any or 0 : "); fflush(stderr); } while( 1 > scanf("%ud", &odid)); if (odid) { GF_ObjectManager *root_odm = gf_term_get_root_object(term); if (!root_odm) break; count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { GF_MediaInfo info; odm = gf_term_get_object(term, root_odm, i); if (gf_term_get_object_info(term, odm, &info) == GF_OK) { if (info.od->objectDescriptorID==odid) break; } odm = NULL; } } do { fprintf(stderr, "Enter file radical name (+\'.x\' for XML dumping) - \"std\" for stderr: "); fflush(stderr); } while( 1 > scanf("%s", radname)); sExt = strrchr(radname, '.'); xml_dump = 0; if (sExt) { if (!stricmp(sExt, ".x")) xml_dump = 1; sExt[0] = 0; } std_out = strnicmp(radname, "std", 3) ? 0 : 1; e = gf_term_dump_scene(term, std_out ? NULL : radname, NULL, xml_dump, 0, odm); fprintf(stderr, "Dump done (%s)\n", gf_error_to_string(e)); } break; case 'c': PrintGPACConfig(); break; case '3': { Bool use_3d = !gf_term_get_option(term, GF_OPT_USE_OPENGL); if (gf_term_set_option(term, GF_OPT_USE_OPENGL, use_3d)==GF_OK) { fprintf(stderr, "Using %s for 2D drawing\n", use_3d ? "OpenGL" : "2D rasterizer"); } } break; case 'k': { Bool opt = gf_term_get_option(term, GF_OPT_STRESS_MODE); opt = !opt; fprintf(stderr, "Turning stress mode %s\n", opt ? "on" : "off"); gf_term_set_option(term, GF_OPT_STRESS_MODE, opt); } break; case '4': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3); break; case '5': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9); break; case '6': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); break; case '7': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP); break; case 'C': switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_DISABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_ENABLED); break; case GF_MEDIA_CACHE_ENABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_DISABLED); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache is running - please stop it first\n"); continue; } switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_ENABLED: fprintf(stderr, "Streaming Cache Enabled\n"); break; case GF_MEDIA_CACHE_DISABLED: fprintf(stderr, "Streaming Cache Disabled\n"); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache Running\n"); break; } break; case 'S': case 'A': if (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)==GF_MEDIA_CACHE_RUNNING) { gf_term_set_option(term, GF_OPT_MEDIA_CACHE, (c=='S') ? GF_MEDIA_CACHE_DISABLED : GF_MEDIA_CACHE_DISCARD); fprintf(stderr, "Streaming Cache stopped\n"); } else { fprintf(stderr, "Streaming Cache not running\n"); } break; case 'R': display_rti = !display_rti; ResetCaption(); break; case 'F': if (display_rti) display_rti = 0; else display_rti = 2; ResetCaption(); break; case 'u': { GF_Err e; char szCom[8192]; fprintf(stderr, "Enter command to send:\n"); fflush(stdin); szCom[0] = 0; if (1 > scanf("%[^\t\n]", szCom)) { fprintf(stderr, "Cannot read command to send, aborting.\n"); break; } e = gf_term_scene_update(term, NULL, szCom); if (e) fprintf(stderr, "Processing command failed: %s\n", gf_error_to_string(e)); } break; case 'e': { GF_Err e; char jsCode[8192]; fprintf(stderr, "Enter JavaScript code to evaluate:\n"); fflush(stdin); jsCode[0] = 0; if (1 > scanf("%[^\t\n]", jsCode)) { fprintf(stderr, "Cannot read code to evaluate, aborting.\n"); break; } e = gf_term_scene_update(term, "application/ecmascript", jsCode); if (e) fprintf(stderr, "Processing JS code failed: %s\n", gf_error_to_string(e)); } break; case 'L': { char szLog[1024], *cur_logs; cur_logs = gf_log_get_tools_levels(); fprintf(stderr, "Enter new log level (current tools %s):\n", cur_logs); gf_free(cur_logs); if (scanf("%s", szLog) < 1) { fprintf(stderr, "Cannot read new log level, aborting.\n"); break; } gf_log_modify_tools_levels(szLog); } break; case 'g': { GF_SystemRTInfo rti; gf_sys_get_rti(rti_update_time_ms, &rti, 0); fprintf(stderr, "GPAC allocated memory "LLD"\n", rti.gpac_memory); } break; case 'M': { u32 size; do { fprintf(stderr, "Enter new video cache memory in kBytes (current %ud):\n", gf_term_get_option(term, GF_OPT_VIDEO_CACHE_SIZE)); } while (1 > scanf("%ud", &size)); gf_term_set_option(term, GF_OPT_VIDEO_CACHE_SIZE, size); } break; case 'H': { u32 http_bitrate = gf_term_get_option(term, GF_OPT_HTTP_MAX_RATE); do { fprintf(stderr, "Enter new http bitrate in bps (0 for none) - current limit: %d\n", http_bitrate); } while (1 > scanf("%ud", &http_bitrate)); gf_term_set_option(term, GF_OPT_HTTP_MAX_RATE, http_bitrate); } break; case 'E': gf_term_set_option(term, GF_OPT_RELOAD_CONFIG, 1); break; case 'B': switch_bench(!bench_mode); break; case 'Y': { char szOpt[8192]; fprintf(stderr, "Enter option to set (Section:Name=Value):\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read option\n"); break; } set_cfg_option(szOpt); } break; /*extract to PNG*/ case 'Z': { char szFileName[100]; u32 nb_pass, nb_views, offscreen_view = 0; GF_VideoSurface fb; GF_Err e; nb_pass = 1; nb_views = gf_term_get_option(term, GF_OPT_NUM_STEREO_VIEWS); if (nb_views>1) { fprintf(stderr, "Auto-stereo mode detected - type number of view to dump (0 is main output, 1 to %d offscreen view, %d for all offscreen, %d for all offscreen and main)\n", nb_views, nb_views+1, nb_views+2); if (scanf("%d", &offscreen_view) != 1) { offscreen_view = 0; } if (offscreen_view==nb_views+1) { offscreen_view = 1; nb_pass = nb_views; } else if (offscreen_view==nb_views+2) { offscreen_view = 0; nb_pass = nb_views+1; } } while (nb_pass) { nb_pass--; if (offscreen_view) { sprintf(szFileName, "view%d_dump.png", offscreen_view); e = gf_term_get_offscreen_buffer(term, &fb, offscreen_view-1, 0); } else { sprintf(szFileName, "gpac_video_dump_"LLU".png", gf_net_get_utc() ); e = gf_term_get_screen_buffer(term, &fb); } offscreen_view++; if (e) { fprintf(stderr, "Error dumping screen buffer %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { #ifndef GPAC_DISABLE_AV_PARSERS u32 dst_size = fb.width*fb.height*4; char *dst = (char*)gf_malloc(sizeof(char)*dst_size); e = gf_img_png_enc(fb.video_buffer, fb.width, fb.height, fb.pitch_y, fb.pixel_format, dst, &dst_size); if (e) { fprintf(stderr, "Error encoding PNG %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { FILE *png = gf_fopen(szFileName, "wb"); if (!png) { fprintf(stderr, "Error writing file %s\n", szFileName); nb_pass = 0; } else { gf_fwrite(dst, dst_size, 1, png); gf_fclose(png); fprintf(stderr, "Dump to %s\n", szFileName); } } if (dst) gf_free(dst); gf_term_release_screen_buffer(term, &fb); #endif //GPAC_DISABLE_AV_PARSERS } } fprintf(stderr, "Done: %s\n", szFileName); } break; case 'G': { GF_ObjectManager *root_od, *odm; u32 index; char szOpt[8192]; fprintf(stderr, "Enter 0-based index of object to select or service ID:\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read OD ID\n"); break; } index = atoi(szOpt); odm = NULL; root_od = gf_term_get_root_object(term); if (root_od) { if ( gf_term_find_service(term, root_od, index)) { gf_term_select_service(term, root_od, index); } else { fprintf(stderr, "Cannot find service %d - trying with object index\n", index); odm = gf_term_get_object(term, root_od, index); if (odm) { gf_term_select_object(term, odm); } else { fprintf(stderr, "Cannot find object at index %d\n", index); } } } } break; case 'h': PrintHelp(); break; default: break; } } if (bench_mode) { PrintAVInfo(GF_TRUE); } /*FIXME: we have an issue in cleaning up after playing in bench mode and run-for 0 (buildbot tests). We for now disable error checks after run-for is done*/ if (simulation_time_in_ms) { gf_log_set_strict_error(0); } i = gf_sys_clock(); gf_term_disconnect(term); if (rti_file) UpdateRTInfo("Disconnected\n"); fprintf(stderr, "Deleting terminal... "); if (playlist) gf_fclose(playlist); #if defined(__DARWIN__) || defined(__APPLE__) carbon_uninit(); #endif gf_term_del(term); fprintf(stderr, "done (in %d ms) - ran for %d ms\n", gf_sys_clock() - i, gf_sys_clock()); fprintf(stderr, "GPAC cleanup ...\n"); gf_modules_del(user.modules); if (no_cfg_save) gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (rti_logs) gf_fclose(rti_logs); if (logfile) gf_fclose(logfile); if (gui_mode) { hide_shell(2); } #ifdef GPAC_MEMORY_TRACKING if (mem_track && (gf_memory_size() || gf_file_handles_count() )) { gf_log_set_tool_level(GF_LOG_MEMORY, GF_LOG_INFO); gf_memory_print(); return 2; } #endif return ret_val; }
169,790
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WtsConsoleSessionProcessDriver::OnChannelConnected() { DCHECK(caller_task_runner_->BelongsToCurrentThread()); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void WtsConsoleSessionProcessDriver::OnChannelConnected() { void WtsConsoleSessionProcessDriver::OnChannelConnected(int32 peer_pid) { DCHECK(caller_task_runner_->BelongsToCurrentThread()); }
171,554
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec, WORD32 num_mb_skip, UWORD8 u1_is_idr_slice, UWORD16 u2_frame_num, pocstruct_t *ps_cur_poc, WORD32 prev_slice_err) { WORD32 i2_cur_mb_addr; UWORD32 u1_num_mbs, u1_num_mbsNby2; UWORD32 u1_mb_idx = ps_dec->u1_mb_idx; UWORD32 i2_mb_skip_run; UWORD32 u1_num_mbs_next, u1_end_of_row; const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; UWORD32 u1_slice_end; UWORD32 u1_tfr_n_mb; UWORD32 u1_decode_nmb; dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; deblk_mb_t *ps_cur_deblk_mb; dec_mb_info_t *ps_cur_mb_info; parse_pmbarams_t *ps_parse_mb_data; UWORD32 u1_inter_mb_type; UWORD32 u1_deblk_mb_type; UWORD16 u2_total_mbs_coded; UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag; parse_part_params_t *ps_part_info; WORD32 ret; if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return 0; } if(prev_slice_err == 1) { /* first slice - missing/header corruption */ ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num; if(!ps_dec->u1_first_slice_in_stream) { ih264d_end_of_pic(ps_dec, u1_is_idr_slice, ps_dec->ps_cur_slice->u2_frame_num); ps_dec->s_cur_pic_poc.u2_frame_num = ps_dec->ps_cur_slice->u2_frame_num; } { WORD32 i, j, poc = 0; ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0; ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; if(ps_dec->ps_cur_pic != NULL) poc = ps_dec->ps_cur_pic->i4_poc + 2; j = 0; for(i = 0; i < MAX_NUM_PIC_PARAMS; i++) if(ps_dec->ps_pps[i].u1_is_valid == TRUE) j = i; { ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc, ps_dec->ps_cur_slice->u2_frame_num, &ps_dec->ps_pps[j]); if(ret != OK) { return ret; } } ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0; ps_dec->u4_output_present = 0; { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); /* If error code is non-zero then there is no buffer available for display, hence avoid format conversion */ if(0 != ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; } else ps_dec->u4_output_present = 1; } if(ps_dec->u1_separate_parse == 1) { if(ps_dec->u4_dec_thread_created == 0) { ithread_create(ps_dec->pv_dec_thread_handle, NULL, (void *)ih264d_decode_picture_thread, (void *)ps_dec); ps_dec->u4_dec_thread_created = 1; } if((ps_dec->u4_num_cores == 3) && ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) && (ps_dec->u4_bs_deblk_thread_created == 0)) { ps_dec->u4_start_recon_deblk = 0; ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, (void *)ih264d_recon_deblk_thread, (void *)ps_dec); ps_dec->u4_bs_deblk_thread_created = 1; } } } } else { dec_slice_struct_t *ps_parse_cur_slice; ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; if(ps_dec->u1_slice_header_done && ps_parse_cur_slice == ps_dec->ps_parse_cur_slice) { u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb; if(u1_num_mbs) { ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1; } else { if(ps_dec->u1_separate_parse) { ps_cur_mb_info = ps_dec->ps_nmb_info - 1; } else { ps_cur_mb_info = ps_dec->ps_nmb_info + ps_dec->u4_num_mbs_prev_nmb - 1; } } ps_dec->u2_mby = ps_cur_mb_info->u2_mby; ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx; ps_dec->u1_mb_ngbr_availablity = ps_cur_mb_info->u1_mb_ngbr_availablity; ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data; ps_dec->u2_cur_mb_addr--; ps_dec->i4_submb_ofst -= SUB_BLK_SIZE; if(u1_num_mbs) { if (ps_dec->u1_pr_sl_type == P_SLICE || ps_dec->u1_pr_sl_type == B_SLICE) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); ps_dec->ps_part = ps_dec->ps_parse_part_params; } u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = 1; u1_tfr_n_mb = 1; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; ps_dec->u1_mb_idx = 0; ps_dec->u4_num_mbs_cur_nmb = 0; } if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; return 0; } ps_dec->u2_cur_slice_num++; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; ps_dec->ps_parse_cur_slice++; } else { ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; } } /******************************************************/ /* Initializations to new slice */ /******************************************************/ { WORD32 num_entries; WORD32 size; UWORD8 *pu1_buf; num_entries = MAX_FRAMES; if((1 >= ps_dec->ps_cur_sps->u1_num_ref_frames) && (0 == ps_dec->i4_display_delay)) { num_entries = 1; } num_entries = ((2 * num_entries) + 1); if(BASE_PROFILE_IDC != ps_dec->ps_cur_sps->u1_profile_idc) { num_entries *= 2; } size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; pu1_buf += size * ps_dec->u2_cur_slice_num; ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf; } ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; if(ps_dec->ps_cur_slice->u1_field_pic_flag) ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num; ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd; if(ps_dec->u1_separate_parse) { ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; } else { ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; } /******************************************************/ /* Initializations specific to P slice */ /******************************************************/ u1_inter_mb_type = P_MB; u1_deblk_mb_type = D_INTER_MB; ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_parse_cur_slice->slice_type = P_SLICE; ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb; ps_dec->ps_part = ps_dec->ps_parse_part_params; /******************************************************/ /* Parsing / decoding the slice */ /******************************************************/ ps_dec->u1_slice_header_done = 2; ps_dec->u1_qp = ps_slice->u1_slice_qp; ih264d_update_qp(ps_dec, 0); u1_mb_idx = ps_dec->u1_mb_idx; ps_parse_mb_data = ps_dec->ps_parse_mb_data; u1_num_mbs = u1_mb_idx; u1_slice_end = 0; u1_tfr_n_mb = 0; u1_decode_nmb = 0; u1_num_mbsNby2 = 0; i2_cur_mb_addr = ps_dec->u2_total_mbs_coded; i2_mb_skip_run = num_mb_skip; while(!u1_slice_end) { UWORD8 u1_mb_type; if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) break; ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; ps_cur_mb_info->u1_Mux = 0; ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; ps_cur_mb_info->u1_end_of_slice = 0; /* Storing Default partition info */ ps_parse_mb_data->u1_num_part = 1; ps_parse_mb_data->u1_isI_mb = 0; /**************************************************************/ /* Get the required information for decoding of MB */ /**************************************************************/ /* mb_x, mb_y, neighbor availablity, */ if (u1_mbaff) ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); else ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); /* Set the deblocking parameters for this MB */ if(ps_dec->u4_app_disable_deblk_frm == 0) { ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, ps_dec->u1_mb_ngbr_availablity, ps_dec->u1_cur_mb_fld_dec_flag); } /* Set appropriate flags in ps_cur_mb_info and ps_dec */ ps_dec->i1_prev_mb_qp_delta = 0; ps_dec->u1_sub_mb_num = 0; ps_cur_mb_info->u1_mb_type = MB_SKIP; ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16; ps_cur_mb_info->u1_cbp = 0; /* Storing Skip partition info */ ps_part_info = ps_dec->ps_part; ps_part_info->u1_is_direct = PART_DIRECT_16x16; ps_part_info->u1_sub_mb_num = 0; ps_dec->ps_part++; /* Update Nnzs */ ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC); ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type; ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type; i2_mb_skip_run--; ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; if (u1_mbaff) { ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); } /**************************************************************/ /* Get next Macroblock address */ /**************************************************************/ i2_cur_mb_addr++; u1_num_mbs++; u1_num_mbsNby2++; ps_parse_mb_data++; /****************************************************************/ /* Check for End Of Row and other flags that determine when to */ /* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */ /* N-Mb */ /****************************************************************/ u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = !i2_mb_skip_run; u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row || u1_slice_end; u1_decode_nmb = u1_tfr_n_mb || u1_slice_end; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(u1_decode_nmb) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); u1_num_mbsNby2 = 0; ps_parse_mb_data = ps_dec->ps_parse_mb_data; ps_dec->ps_part = ps_dec->ps_parse_part_params; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; if(u1_tfr_n_mb) u1_num_mbs = 0; u1_mb_idx = u1_num_mbs; ps_dec->u1_mb_idx = u1_num_mbs; } } ps_dec->u4_num_mbs_cur_nmb = 0; ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr - ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice; H264_DEC_DEBUG_PRINT("Mbs in slice: %d\n", ps_dec->ps_cur_slice->u4_mbs_in_slice); ps_dec->u2_cur_slice_num++; /* incremented here only if first slice is inserted */ if(ps_dec->u4_first_slice_in_pic != 0) ps_dec->ps_parse_cur_slice++; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; } return 0; } Commit Message: Decoder: Initialize slice parameters before concealing error MBs Also memset ps_dec_op structure to zero. For error input, this ensures dimensions are initialized to zero Bug: 28165661 Change-Id: I66eb2ddc5e02e74b7ff04da5f749443920f37141 CWE ID: CWE-20
WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec, WORD32 num_mb_skip, UWORD8 u1_is_idr_slice, UWORD16 u2_frame_num, pocstruct_t *ps_cur_poc, WORD32 prev_slice_err) { WORD32 i2_cur_mb_addr; UWORD32 u1_num_mbs, u1_num_mbsNby2; UWORD32 u1_mb_idx = ps_dec->u1_mb_idx; UWORD32 i2_mb_skip_run; UWORD32 u1_num_mbs_next, u1_end_of_row; const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; UWORD32 u1_slice_end; UWORD32 u1_tfr_n_mb; UWORD32 u1_decode_nmb; dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; deblk_mb_t *ps_cur_deblk_mb; dec_mb_info_t *ps_cur_mb_info; parse_pmbarams_t *ps_parse_mb_data; UWORD32 u1_inter_mb_type; UWORD32 u1_deblk_mb_type; UWORD16 u2_total_mbs_coded; UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag; parse_part_params_t *ps_part_info; WORD32 ret; if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return 0; } if(prev_slice_err == 1) { /* first slice - missing/header corruption */ ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num; if(!ps_dec->u1_first_slice_in_stream) { ih264d_end_of_pic(ps_dec, u1_is_idr_slice, ps_dec->ps_cur_slice->u2_frame_num); ps_dec->s_cur_pic_poc.u2_frame_num = ps_dec->ps_cur_slice->u2_frame_num; } { WORD32 i, j, poc = 0; ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0; ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; if(ps_dec->ps_cur_pic != NULL) poc = ps_dec->ps_cur_pic->i4_poc + 2; j = 0; for(i = 0; i < MAX_NUM_PIC_PARAMS; i++) if(ps_dec->ps_pps[i].u1_is_valid == TRUE) j = i; { //initialize slice params required by ih264d_start_of_pic to valid values ps_dec->ps_cur_slice->u1_bottom_field_flag = 0; ps_dec->ps_cur_slice->u1_field_pic_flag = 0; ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_cur_slice->u1_nal_ref_idc = 1; ps_dec->ps_cur_slice->u1_nal_unit_type = 1; ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc, ps_dec->ps_cur_slice->u2_frame_num, &ps_dec->ps_pps[j]); if(ret != OK) { return ret; } } ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0; ps_dec->u4_output_present = 0; { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); /* If error code is non-zero then there is no buffer available for display, hence avoid format conversion */ if(0 != ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; } else ps_dec->u4_output_present = 1; } if(ps_dec->u1_separate_parse == 1) { if(ps_dec->u4_dec_thread_created == 0) { ithread_create(ps_dec->pv_dec_thread_handle, NULL, (void *)ih264d_decode_picture_thread, (void *)ps_dec); ps_dec->u4_dec_thread_created = 1; } if((ps_dec->u4_num_cores == 3) && ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) && (ps_dec->u4_bs_deblk_thread_created == 0)) { ps_dec->u4_start_recon_deblk = 0; ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, (void *)ih264d_recon_deblk_thread, (void *)ps_dec); ps_dec->u4_bs_deblk_thread_created = 1; } } } } else { dec_slice_struct_t *ps_parse_cur_slice; ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; if(ps_dec->u1_slice_header_done && ps_parse_cur_slice == ps_dec->ps_parse_cur_slice) { u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb; if(u1_num_mbs) { ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1; } else { if(ps_dec->u1_separate_parse) { ps_cur_mb_info = ps_dec->ps_nmb_info - 1; } else { ps_cur_mb_info = ps_dec->ps_nmb_info + ps_dec->u4_num_mbs_prev_nmb - 1; } } ps_dec->u2_mby = ps_cur_mb_info->u2_mby; ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx; ps_dec->u1_mb_ngbr_availablity = ps_cur_mb_info->u1_mb_ngbr_availablity; ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data; ps_dec->u2_cur_mb_addr--; ps_dec->i4_submb_ofst -= SUB_BLK_SIZE; if(u1_num_mbs) { if (ps_dec->u1_pr_sl_type == P_SLICE || ps_dec->u1_pr_sl_type == B_SLICE) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); ps_dec->ps_part = ps_dec->ps_parse_part_params; } u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = 1; u1_tfr_n_mb = 1; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; ps_dec->u1_mb_idx = 0; ps_dec->u4_num_mbs_cur_nmb = 0; } if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; return 0; } ps_dec->u2_cur_slice_num++; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; ps_dec->ps_parse_cur_slice++; } else { ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; } } /******************************************************/ /* Initializations to new slice */ /******************************************************/ { WORD32 num_entries; WORD32 size; UWORD8 *pu1_buf; num_entries = MAX_FRAMES; if((1 >= ps_dec->ps_cur_sps->u1_num_ref_frames) && (0 == ps_dec->i4_display_delay)) { num_entries = 1; } num_entries = ((2 * num_entries) + 1); if(BASE_PROFILE_IDC != ps_dec->ps_cur_sps->u1_profile_idc) { num_entries *= 2; } size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; pu1_buf += size * ps_dec->u2_cur_slice_num; ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf; } ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; ps_dec->ps_cur_slice->i1_slice_alpha_c0_offset = 0; ps_dec->ps_cur_slice->i1_slice_beta_offset = 0; if(ps_dec->ps_cur_slice->u1_field_pic_flag) ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num; ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd; if(ps_dec->u1_separate_parse) { ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; } else { ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; } /******************************************************/ /* Initializations specific to P slice */ /******************************************************/ u1_inter_mb_type = P_MB; u1_deblk_mb_type = D_INTER_MB; ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_parse_cur_slice->slice_type = P_SLICE; ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb; ps_dec->ps_part = ps_dec->ps_parse_part_params; /******************************************************/ /* Parsing / decoding the slice */ /******************************************************/ ps_dec->u1_slice_header_done = 2; ps_dec->u1_qp = ps_slice->u1_slice_qp; ih264d_update_qp(ps_dec, 0); u1_mb_idx = ps_dec->u1_mb_idx; ps_parse_mb_data = ps_dec->ps_parse_mb_data; u1_num_mbs = u1_mb_idx; u1_slice_end = 0; u1_tfr_n_mb = 0; u1_decode_nmb = 0; u1_num_mbsNby2 = 0; i2_cur_mb_addr = ps_dec->u2_total_mbs_coded; i2_mb_skip_run = num_mb_skip; while(!u1_slice_end) { UWORD8 u1_mb_type; if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) break; ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; ps_cur_mb_info->u1_Mux = 0; ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; ps_cur_mb_info->u1_end_of_slice = 0; /* Storing Default partition info */ ps_parse_mb_data->u1_num_part = 1; ps_parse_mb_data->u1_isI_mb = 0; /**************************************************************/ /* Get the required information for decoding of MB */ /**************************************************************/ /* mb_x, mb_y, neighbor availablity, */ if (u1_mbaff) ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); else ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); /* Set the deblocking parameters for this MB */ if(ps_dec->u4_app_disable_deblk_frm == 0) { ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, ps_dec->u1_mb_ngbr_availablity, ps_dec->u1_cur_mb_fld_dec_flag); } /* Set appropriate flags in ps_cur_mb_info and ps_dec */ ps_dec->i1_prev_mb_qp_delta = 0; ps_dec->u1_sub_mb_num = 0; ps_cur_mb_info->u1_mb_type = MB_SKIP; ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16; ps_cur_mb_info->u1_cbp = 0; /* Storing Skip partition info */ ps_part_info = ps_dec->ps_part; ps_part_info->u1_is_direct = PART_DIRECT_16x16; ps_part_info->u1_sub_mb_num = 0; ps_dec->ps_part++; /* Update Nnzs */ ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC); ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type; ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type; i2_mb_skip_run--; ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; if (u1_mbaff) { ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); } /**************************************************************/ /* Get next Macroblock address */ /**************************************************************/ i2_cur_mb_addr++; u1_num_mbs++; u1_num_mbsNby2++; ps_parse_mb_data++; /****************************************************************/ /* Check for End Of Row and other flags that determine when to */ /* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */ /* N-Mb */ /****************************************************************/ u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = !i2_mb_skip_run; u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row || u1_slice_end; u1_decode_nmb = u1_tfr_n_mb || u1_slice_end; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(u1_decode_nmb) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); u1_num_mbsNby2 = 0; ps_parse_mb_data = ps_dec->ps_parse_mb_data; ps_dec->ps_part = ps_dec->ps_parse_part_params; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; if(u1_tfr_n_mb) u1_num_mbs = 0; u1_mb_idx = u1_num_mbs; ps_dec->u1_mb_idx = u1_num_mbs; } } ps_dec->u4_num_mbs_cur_nmb = 0; ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr - ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice; H264_DEC_DEBUG_PRINT("Mbs in slice: %d\n", ps_dec->ps_cur_slice->u4_mbs_in_slice); ps_dec->u2_cur_slice_num++; /* incremented here only if first slice is inserted */ if(ps_dec->u4_first_slice_in_pic != 0) ps_dec->ps_parse_cur_slice++; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; } return 0; }
174,163
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SkCodec* SkIcoCodec::NewFromStream(SkStream* stream, Result* result) { std::unique_ptr<SkStream> inputStream(stream); static const uint32_t kIcoDirectoryBytes = 6; static const uint32_t kIcoDirEntryBytes = 16; std::unique_ptr<uint8_t[]> dirBuffer(new uint8_t[kIcoDirectoryBytes]); if (inputStream.get()->read(dirBuffer.get(), kIcoDirectoryBytes) != kIcoDirectoryBytes) { SkCodecPrintf("Error: unable to read ico directory header.\n"); *result = kIncompleteInput; return nullptr; } const uint16_t numImages = get_short(dirBuffer.get(), 4); if (0 == numImages) { SkCodecPrintf("Error: No images embedded in ico.\n"); *result = kInvalidInput; return nullptr; } struct Entry { uint32_t offset; uint32_t size; }; SkAutoFree dirEntryBuffer(sk_malloc_flags(sizeof(Entry) * numImages, SK_MALLOC_TEMP)); if (!dirEntryBuffer) { SkCodecPrintf("Error: OOM allocating ICO directory for %i images.\n", numImages); *result = kInternalError; return nullptr; } auto* directoryEntries = reinterpret_cast<Entry*>(dirEntryBuffer.get()); for (uint32_t i = 0; i < numImages; i++) { uint8_t entryBuffer[kIcoDirEntryBytes]; if (inputStream->read(entryBuffer, kIcoDirEntryBytes) != kIcoDirEntryBytes) { SkCodecPrintf("Error: Dir entries truncated in ico.\n"); *result = kIncompleteInput; return nullptr; } uint32_t size = get_int(entryBuffer, 8); uint32_t offset = get_int(entryBuffer, 12); directoryEntries[i].offset = offset; directoryEntries[i].size = size; } *result = kInvalidInput; struct EntryLessThan { bool operator() (Entry a, Entry b) const { return a.offset < b.offset; } }; EntryLessThan lessThan; SkTQSort(directoryEntries, &directoryEntries[numImages - 1], lessThan); uint32_t bytesRead = kIcoDirectoryBytes + numImages * kIcoDirEntryBytes; std::unique_ptr<SkTArray<std::unique_ptr<SkCodec>, true>> codecs( new (SkTArray<std::unique_ptr<SkCodec>, true>)(numImages)); for (uint32_t i = 0; i < numImages; i++) { uint32_t offset = directoryEntries[i].offset; uint32_t size = directoryEntries[i].size; if (offset < bytesRead) { SkCodecPrintf("Warning: invalid ico offset.\n"); continue; } if (inputStream.get()->skip(offset - bytesRead) != offset - bytesRead) { SkCodecPrintf("Warning: could not skip to ico offset.\n"); break; } bytesRead = offset; SkAutoFree buffer(sk_malloc_flags(size, 0)); if (!buffer) { SkCodecPrintf("Warning: OOM trying to create embedded stream.\n"); break; } if (inputStream->read(buffer.get(), size) != size) { SkCodecPrintf("Warning: could not create embedded stream.\n"); *result = kIncompleteInput; break; } sk_sp<SkData> data(SkData::MakeFromMalloc(buffer.release(), size)); std::unique_ptr<SkMemoryStream> embeddedStream(new SkMemoryStream(data)); bytesRead += size; SkCodec* codec = nullptr; Result dummyResult; if (SkPngCodec::IsPng((const char*) data->bytes(), data->size())) { codec = SkPngCodec::NewFromStream(embeddedStream.release(), &dummyResult); } else { codec = SkBmpCodec::NewFromIco(embeddedStream.release(), &dummyResult); } if (nullptr != codec) { codecs->push_back().reset(codec); } } if (0 == codecs->count()) { SkCodecPrintf("Error: could not find any valid embedded ico codecs.\n"); return nullptr; } size_t maxSize = 0; int maxIndex = 0; for (int i = 0; i < codecs->count(); i++) { SkImageInfo info = codecs->operator[](i)->getInfo(); size_t size = info.getSafeSize(info.minRowBytes()); if (size > maxSize) { maxSize = size; maxIndex = i; } } int width = codecs->operator[](maxIndex)->getInfo().width(); int height = codecs->operator[](maxIndex)->getInfo().height(); SkEncodedInfo info = codecs->operator[](maxIndex)->getEncodedInfo(); SkColorSpace* colorSpace = codecs->operator[](maxIndex)->getInfo().colorSpace(); *result = kSuccess; return new SkIcoCodec(width, height, info, codecs.release(), sk_ref_sp(colorSpace)); } Commit Message: RESTRICT AUTOMERGE: Cherry-pick "begin cleanup of malloc porting layer" Bug: 78354855 Test: Not feasible Original description: ======================================================================== 1. Merge some of the allocators into sk_malloc_flags by redefining a flag to mean zero-init 2. Add more private helpers to simplify our call-sites (and handle some overflow mul checks) 3. The 2-param helpers rely on the saturating SkSafeMath::Mul to pass max_size_t as the request, which should always fail. chromium: 508641 Reviewed-on: https://skia-review.googlesource.com/90940 Commit-Queue: Mike Reed <[email protected]> Reviewed-by: Robert Phillips <[email protected]> Reviewed-by: Stephan Altmueller <[email protected]> ======================================================================== Conflicts: - include/private/SkMalloc.h Simply removed the old definitions of SK_MALLOC_TEMP and SK_MALLOC_THROW. - public.bzl Copied SK_SUPPORT_LEGACY_MALLOC_PORTING_LAYER into the old defines. - src/codec/SkIcoCodec.cpp Drop a change where we were not using malloc yet. - src/codec/SkBmpBaseCodec.cpp - src/core/SkBitmapCache.cpp These files weren't yet using malloc (and SkBmpBaseCodec hadn't been factored out). - src/core/SkMallocPixelRef.cpp These were still using New rather than Make (return raw pointer). Leave them unchanged, as sk_malloc_flags is still valid. - src/lazy/SkDiscardableMemoryPool.cpp Leave this unchanged; sk_malloc_flags is still valid In addition, pull in SkSafeMath.h, which was originally introduced in https://skia-review.googlesource.com/c/skia/+/33721. This is required for the new sk_malloc calls. Also pull in SkSafeMath::Add and SkSafeMath::Mul, introduced in https://skia-review.googlesource.com/88581 Also add SK_MaxSizeT, which the above depends on, introduced in https://skia-review.googlesource.com/57084 Also, modify NewFromStream to use sk_malloc_canfail, matching pi and avoiding a build break Change-Id: Ib320484673a865460fc1efb900f611209e088edb (cherry picked from commit a12cc3e14ea6734c7efe76aa6a19239909830b28) CWE ID: CWE-787
SkCodec* SkIcoCodec::NewFromStream(SkStream* stream, Result* result) { std::unique_ptr<SkStream> inputStream(stream); static const uint32_t kIcoDirectoryBytes = 6; static const uint32_t kIcoDirEntryBytes = 16; std::unique_ptr<uint8_t[]> dirBuffer(new uint8_t[kIcoDirectoryBytes]); if (inputStream.get()->read(dirBuffer.get(), kIcoDirectoryBytes) != kIcoDirectoryBytes) { SkCodecPrintf("Error: unable to read ico directory header.\n"); *result = kIncompleteInput; return nullptr; } const uint16_t numImages = get_short(dirBuffer.get(), 4); if (0 == numImages) { SkCodecPrintf("Error: No images embedded in ico.\n"); *result = kInvalidInput; return nullptr; } struct Entry { uint32_t offset; uint32_t size; }; SkAutoFree dirEntryBuffer(sk_malloc_canfail(sizeof(Entry) * numImages)); if (!dirEntryBuffer) { SkCodecPrintf("Error: OOM allocating ICO directory for %i images.\n", numImages); *result = kInternalError; return nullptr; } auto* directoryEntries = reinterpret_cast<Entry*>(dirEntryBuffer.get()); for (uint32_t i = 0; i < numImages; i++) { uint8_t entryBuffer[kIcoDirEntryBytes]; if (inputStream->read(entryBuffer, kIcoDirEntryBytes) != kIcoDirEntryBytes) { SkCodecPrintf("Error: Dir entries truncated in ico.\n"); *result = kIncompleteInput; return nullptr; } uint32_t size = get_int(entryBuffer, 8); uint32_t offset = get_int(entryBuffer, 12); directoryEntries[i].offset = offset; directoryEntries[i].size = size; } *result = kInvalidInput; struct EntryLessThan { bool operator() (Entry a, Entry b) const { return a.offset < b.offset; } }; EntryLessThan lessThan; SkTQSort(directoryEntries, &directoryEntries[numImages - 1], lessThan); uint32_t bytesRead = kIcoDirectoryBytes + numImages * kIcoDirEntryBytes; std::unique_ptr<SkTArray<std::unique_ptr<SkCodec>, true>> codecs( new (SkTArray<std::unique_ptr<SkCodec>, true>)(numImages)); for (uint32_t i = 0; i < numImages; i++) { uint32_t offset = directoryEntries[i].offset; uint32_t size = directoryEntries[i].size; if (offset < bytesRead) { SkCodecPrintf("Warning: invalid ico offset.\n"); continue; } if (inputStream.get()->skip(offset - bytesRead) != offset - bytesRead) { SkCodecPrintf("Warning: could not skip to ico offset.\n"); break; } bytesRead = offset; SkAutoFree buffer(sk_malloc_canfail(size)); if (!buffer) { SkCodecPrintf("Warning: OOM trying to create embedded stream.\n"); break; } if (inputStream->read(buffer.get(), size) != size) { SkCodecPrintf("Warning: could not create embedded stream.\n"); *result = kIncompleteInput; break; } sk_sp<SkData> data(SkData::MakeFromMalloc(buffer.release(), size)); std::unique_ptr<SkMemoryStream> embeddedStream(new SkMemoryStream(data)); bytesRead += size; SkCodec* codec = nullptr; Result dummyResult; if (SkPngCodec::IsPng((const char*) data->bytes(), data->size())) { codec = SkPngCodec::NewFromStream(embeddedStream.release(), &dummyResult); } else { codec = SkBmpCodec::NewFromIco(embeddedStream.release(), &dummyResult); } if (nullptr != codec) { codecs->push_back().reset(codec); } } if (0 == codecs->count()) { SkCodecPrintf("Error: could not find any valid embedded ico codecs.\n"); return nullptr; } size_t maxSize = 0; int maxIndex = 0; for (int i = 0; i < codecs->count(); i++) { SkImageInfo info = codecs->operator[](i)->getInfo(); size_t size = info.getSafeSize(info.minRowBytes()); if (size > maxSize) { maxSize = size; maxIndex = i; } } int width = codecs->operator[](maxIndex)->getInfo().width(); int height = codecs->operator[](maxIndex)->getInfo().height(); SkEncodedInfo info = codecs->operator[](maxIndex)->getEncodedInfo(); SkColorSpace* colorSpace = codecs->operator[](maxIndex)->getInfo().colorSpace(); *result = kSuccess; return new SkIcoCodec(width, height, info, codecs.release(), sk_ref_sp(colorSpace)); }
174,084
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); RenderViewHostTestHarness::TearDown(); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); content::SetContentClient(old_client_); RenderViewHostTestHarness::TearDown(); }
171,016
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewUI::ClearAllPreviewData() { print_preview_data_service()->RemoveEntry(preview_ui_addr_str_); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::ClearAllPreviewData() { print_preview_data_service()->RemoveEntry(id_); }
170,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegate::State state) { DCHECK(message_loop()->BelongsToCurrentThread()); if (!stream_id_) return; if (state == AudioOutputIPCDelegate::kError) { DLOG(WARNING) << "AudioOutputDevice::OnStateChanged(kError)"; base::AutoLock auto_lock_(audio_thread_lock_); if (audio_thread_.get() && !audio_thread_->IsStopped()) callback_->OnRenderError(); } } Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call. I've kept my unit test changes intact but disabled until I get a proper fix. BUG=147499,150805 TBR=henrika Review URL: https://codereview.chromium.org/10946040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegate::State state) { DCHECK(message_loop()->BelongsToCurrentThread()); if (!stream_id_) return; if (state == AudioOutputIPCDelegate::kError) { DLOG(WARNING) << "AudioOutputDevice::OnStateChanged(kError)"; if (!audio_thread_.IsStopped()) callback_->OnRenderError(); } }
170,704
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int DetectEngineContentInspection(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, const Signature *s, const SigMatchData *smd, Flow *f, uint8_t *buffer, uint32_t buffer_len, uint32_t stream_start_offset, uint8_t inspection_mode, void *data) { SCEnter(); KEYWORD_PROFILING_START; det_ctx->inspection_recursion_counter++; if (det_ctx->inspection_recursion_counter == de_ctx->inspection_recursion_limit) { det_ctx->discontinue_matching = 1; KEYWORD_PROFILING_END(det_ctx, smd->type, 0); SCReturnInt(0); } if (smd == NULL || buffer_len == 0) { KEYWORD_PROFILING_END(det_ctx, smd->type, 0); SCReturnInt(0); } /* \todo unify this which is phase 2 of payload inspection unification */ if (smd->type == DETECT_CONTENT) { DetectContentData *cd = (DetectContentData *)smd->ctx; SCLogDebug("inspecting content %"PRIu32" buffer_len %"PRIu32, cd->id, buffer_len); /* we might have already have this content matched by the mpm. * (if there is any other reason why we'd want to avoid checking * it here, please fill it in) */ /* rule parsers should take care of this */ #ifdef DEBUG BUG_ON(cd->depth != 0 && cd->depth <= cd->offset); #endif /* search for our pattern, checking the matches recursively. * if we match we look for the next SigMatch as well */ uint8_t *found = NULL; uint32_t offset = 0; uint32_t depth = buffer_len; uint32_t prev_offset = 0; /**< used in recursive searching */ uint32_t prev_buffer_offset = det_ctx->buffer_offset; do { if ((cd->flags & DETECT_CONTENT_DISTANCE) || (cd->flags & DETECT_CONTENT_WITHIN)) { SCLogDebug("det_ctx->buffer_offset %"PRIu32, det_ctx->buffer_offset); offset = prev_buffer_offset; depth = buffer_len; int distance = cd->distance; if (cd->flags & DETECT_CONTENT_DISTANCE) { if (cd->flags & DETECT_CONTENT_DISTANCE_BE) { distance = det_ctx->bj_values[cd->distance]; } if (distance < 0 && (uint32_t)(abs(distance)) > offset) offset = 0; else offset += distance; SCLogDebug("cd->distance %"PRIi32", offset %"PRIu32", depth %"PRIu32, distance, offset, depth); } if (cd->flags & DETECT_CONTENT_WITHIN) { if (cd->flags & DETECT_CONTENT_WITHIN_BE) { if ((int32_t)depth > (int32_t)(prev_buffer_offset + det_ctx->bj_values[cd->within] + distance)) { depth = prev_buffer_offset + det_ctx->bj_values[cd->within] + distance; } } else { if ((int32_t)depth > (int32_t)(prev_buffer_offset + cd->within + distance)) { depth = prev_buffer_offset + cd->within + distance; } SCLogDebug("cd->within %"PRIi32", det_ctx->buffer_offset %"PRIu32", depth %"PRIu32, cd->within, prev_buffer_offset, depth); } if (stream_start_offset != 0 && prev_buffer_offset == 0) { if (depth <= stream_start_offset) { goto no_match; } else if (depth >= (stream_start_offset + buffer_len)) { ; } else { depth = depth - stream_start_offset; } } } if (cd->flags & DETECT_CONTENT_DEPTH_BE) { if ((det_ctx->bj_values[cd->depth] + prev_buffer_offset) < depth) { depth = prev_buffer_offset + det_ctx->bj_values[cd->depth]; } } else { if (cd->depth != 0) { if ((cd->depth + prev_buffer_offset) < depth) { depth = prev_buffer_offset + cd->depth; } SCLogDebug("cd->depth %"PRIu32", depth %"PRIu32, cd->depth, depth); } } if (cd->flags & DETECT_CONTENT_OFFSET_BE) { if (det_ctx->bj_values[cd->offset] > offset) offset = det_ctx->bj_values[cd->offset]; } else { if (cd->offset > offset) { offset = cd->offset; SCLogDebug("setting offset %"PRIu32, offset); } } } else { /* implied no relative matches */ /* set depth */ if (cd->flags & DETECT_CONTENT_DEPTH_BE) { depth = det_ctx->bj_values[cd->depth]; } else { if (cd->depth != 0) { depth = cd->depth; } } if (stream_start_offset != 0 && cd->flags & DETECT_CONTENT_DEPTH) { if (depth <= stream_start_offset) { goto no_match; } else if (depth >= (stream_start_offset + buffer_len)) { ; } else { depth = depth - stream_start_offset; } } /* set offset */ if (cd->flags & DETECT_CONTENT_OFFSET_BE) offset = det_ctx->bj_values[cd->offset]; else offset = cd->offset; prev_buffer_offset = 0; } /* update offset with prev_offset if we're searching for * matches after the first occurence. */ SCLogDebug("offset %"PRIu32", prev_offset %"PRIu32, offset, prev_offset); if (prev_offset != 0) offset = prev_offset; SCLogDebug("offset %"PRIu32", depth %"PRIu32, offset, depth); if (depth > buffer_len) depth = buffer_len; /* if offset is bigger than depth we can never match on a pattern. * We can however, "match" on a negated pattern. */ if (offset > depth || depth == 0) { if (cd->flags & DETECT_CONTENT_NEGATED) { goto match; } else { goto no_match; } } uint8_t *sbuffer = buffer + offset; uint32_t sbuffer_len = depth - offset; uint32_t match_offset = 0; SCLogDebug("sbuffer_len %"PRIu32, sbuffer_len); #ifdef DEBUG BUG_ON(sbuffer_len > buffer_len); #endif /* \todo Add another optimization here. If cd->content_len is * greater than sbuffer_len found is anyways NULL */ /* do the actual search */ found = SpmScan(cd->spm_ctx, det_ctx->spm_thread_ctx, sbuffer, sbuffer_len); /* next we evaluate the result in combination with the * negation flag. */ SCLogDebug("found %p cd negated %s", found, cd->flags & DETECT_CONTENT_NEGATED ? "true" : "false"); if (found == NULL && !(cd->flags & DETECT_CONTENT_NEGATED)) { goto no_match; } else if (found == NULL && (cd->flags & DETECT_CONTENT_NEGATED)) { goto match; } else if (found != NULL && (cd->flags & DETECT_CONTENT_NEGATED)) { SCLogDebug("content %"PRIu32" matched at offset %"PRIu32", but negated so no match", cd->id, match_offset); /* don't bother carrying recursive matches now, for preceding * relative keywords */ if (DETECT_CONTENT_IS_SINGLE(cd)) det_ctx->discontinue_matching = 1; goto no_match; } else { match_offset = (uint32_t)((found - buffer) + cd->content_len); SCLogDebug("content %"PRIu32" matched at offset %"PRIu32"", cd->id, match_offset); det_ctx->buffer_offset = match_offset; /* Match branch, add replace to the list if needed */ if (cd->flags & DETECT_CONTENT_REPLACE) { if (inspection_mode == DETECT_ENGINE_CONTENT_INSPECTION_MODE_PAYLOAD) { /* we will need to replace content if match is confirmed */ det_ctx->replist = DetectReplaceAddToList(det_ctx->replist, found, cd); } else { SCLogWarning(SC_ERR_INVALID_VALUE, "Can't modify payload without packet"); } } if (!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT)) { SCLogDebug("no relative match coming up, so this is a match"); goto match; } /* bail out if we have no next match. Technically this is an * error, as the current cd has the DETECT_CONTENT_RELATIVE_NEXT * flag set. */ if (smd->is_last) { goto no_match; } SCLogDebug("content %"PRIu32, cd->id); KEYWORD_PROFILING_END(det_ctx, smd->type, 1); /* see if the next buffer keywords match. If not, we will * search for another occurence of this content and see * if the others match then until we run out of matches */ int r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1, f, buffer, buffer_len, stream_start_offset, inspection_mode, data); if (r == 1) { SCReturnInt(1); } if (det_ctx->discontinue_matching) goto no_match; /* set the previous match offset to the start of this match + 1 */ prev_offset = (match_offset - (cd->content_len - 1)); SCLogDebug("trying to see if there is another match after prev_offset %"PRIu32, prev_offset); } } while(1); } else if (smd->type == DETECT_ISDATAAT) { SCLogDebug("inspecting isdataat"); DetectIsdataatData *id = (DetectIsdataatData *)smd->ctx; if (id->flags & ISDATAAT_RELATIVE) { if (det_ctx->buffer_offset + id->dataat > buffer_len) { SCLogDebug("det_ctx->buffer_offset + id->dataat %"PRIu32" > %"PRIu32, det_ctx->buffer_offset + id->dataat, buffer_len); if (id->flags & ISDATAAT_NEGATED) goto match; goto no_match; } else { SCLogDebug("relative isdataat match"); if (id->flags & ISDATAAT_NEGATED) goto no_match; goto match; } } else { if (id->dataat < buffer_len) { SCLogDebug("absolute isdataat match"); if (id->flags & ISDATAAT_NEGATED) goto no_match; goto match; } else { SCLogDebug("absolute isdataat mismatch, id->isdataat %"PRIu32", buffer_len %"PRIu32"", id->dataat, buffer_len); if (id->flags & ISDATAAT_NEGATED) goto match; goto no_match; } } } else if (smd->type == DETECT_PCRE) { SCLogDebug("inspecting pcre"); DetectPcreData *pe = (DetectPcreData *)smd->ctx; uint32_t prev_buffer_offset = det_ctx->buffer_offset; uint32_t prev_offset = 0; int r = 0; det_ctx->pcre_match_start_offset = 0; do { Packet *p = NULL; if (inspection_mode == DETECT_ENGINE_CONTENT_INSPECTION_MODE_PAYLOAD) p = (Packet *)data; r = DetectPcrePayloadMatch(det_ctx, s, smd, p, f, buffer, buffer_len); if (r == 0) { goto no_match; } if (!(pe->flags & DETECT_PCRE_RELATIVE_NEXT)) { SCLogDebug("no relative match coming up, so this is a match"); goto match; } KEYWORD_PROFILING_END(det_ctx, smd->type, 1); /* save it, in case we need to do a pcre match once again */ prev_offset = det_ctx->pcre_match_start_offset; /* see if the next payload keywords match. If not, we will * search for another occurence of this pcre and see * if the others match, until we run out of matches */ r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1, f, buffer, buffer_len, stream_start_offset, inspection_mode, data); if (r == 1) { SCReturnInt(1); } if (det_ctx->discontinue_matching) goto no_match; det_ctx->buffer_offset = prev_buffer_offset; det_ctx->pcre_match_start_offset = prev_offset; } while (1); } else if (smd->type == DETECT_BYTETEST) { DetectBytetestData *btd = (DetectBytetestData *)smd->ctx; uint8_t flags = btd->flags; int32_t offset = btd->offset; uint64_t value = btd->value; if (flags & DETECT_BYTETEST_OFFSET_BE) { offset = det_ctx->bj_values[offset]; } if (flags & DETECT_BYTETEST_VALUE_BE) { value = det_ctx->bj_values[value]; } /* if we have dce enabled we will have to use the endianness * specified by the dce header */ if (flags & DETECT_BYTETEST_DCE && data != NULL) { DCERPCState *dcerpc_state = (DCERPCState *)data; /* enable the endianness flag temporarily. once we are done * processing we reset the flags to the original value*/ flags |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] & 0x10) ? DETECT_BYTETEST_LITTLE: 0); } if (DetectBytetestDoMatch(det_ctx, s, smd->ctx, buffer, buffer_len, flags, offset, value) != 1) { goto no_match; } goto match; } else if (smd->type == DETECT_BYTEJUMP) { DetectBytejumpData *bjd = (DetectBytejumpData *)smd->ctx; uint8_t flags = bjd->flags; int32_t offset = bjd->offset; if (flags & DETECT_BYTEJUMP_OFFSET_BE) { offset = det_ctx->bj_values[offset]; } /* if we have dce enabled we will have to use the endianness * specified by the dce header */ if (flags & DETECT_BYTEJUMP_DCE && data != NULL) { DCERPCState *dcerpc_state = (DCERPCState *)data; /* enable the endianness flag temporarily. once we are done * processing we reset the flags to the original value*/ flags |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] & 0x10) ? DETECT_BYTEJUMP_LITTLE: 0); } if (DetectBytejumpDoMatch(det_ctx, s, smd->ctx, buffer, buffer_len, flags, offset) != 1) { goto no_match; } goto match; } else if (smd->type == DETECT_BYTE_EXTRACT) { DetectByteExtractData *bed = (DetectByteExtractData *)smd->ctx; uint8_t endian = bed->endian; /* if we have dce enabled we will have to use the endianness * specified by the dce header */ if ((bed->flags & DETECT_BYTE_EXTRACT_FLAG_ENDIAN) && endian == DETECT_BYTE_EXTRACT_ENDIAN_DCE && data != NULL) { DCERPCState *dcerpc_state = (DCERPCState *)data; /* enable the endianness flag temporarily. once we are done * processing we reset the flags to the original value*/ endian |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] == 0x10) ? DETECT_BYTE_EXTRACT_ENDIAN_LITTLE : DETECT_BYTE_EXTRACT_ENDIAN_BIG); } if (DetectByteExtractDoMatch(det_ctx, smd, s, buffer, buffer_len, &det_ctx->bj_values[bed->local_id], endian) != 1) { goto no_match; } goto match; /* we should never get here, but bail out just in case */ } else if (smd->type == DETECT_AL_URILEN) { SCLogDebug("inspecting uri len"); int r = 0; DetectUrilenData *urilend = (DetectUrilenData *) smd->ctx; switch (urilend->mode) { case DETECT_URILEN_EQ: if (buffer_len == urilend->urilen1) r = 1; break; case DETECT_URILEN_LT: if (buffer_len < urilend->urilen1) r = 1; break; case DETECT_URILEN_GT: if (buffer_len > urilend->urilen1) r = 1; break; case DETECT_URILEN_RA: if (buffer_len > urilend->urilen1 && buffer_len < urilend->urilen2) { r = 1; } break; } if (r == 1) { goto match; } det_ctx->discontinue_matching = 0; goto no_match; #ifdef HAVE_LUA } else if (smd->type == DETECT_LUA) { SCLogDebug("lua starting"); if (DetectLuaMatchBuffer(det_ctx, s, smd, buffer, buffer_len, det_ctx->buffer_offset, f) != 1) { SCLogDebug("lua no_match"); goto no_match; } SCLogDebug("lua match"); goto match; #endif /* HAVE_LUA */ } else if (smd->type == DETECT_BASE64_DECODE) { if (DetectBase64DecodeDoMatch(det_ctx, s, smd, buffer, buffer_len)) { if (s->sm_arrays[DETECT_SM_LIST_BASE64_DATA] != NULL) { KEYWORD_PROFILING_END(det_ctx, smd->type, 1); if (DetectBase64DataDoMatch(de_ctx, det_ctx, s, f)) { /* Base64 is a terminal list. */ goto final_match; } } } } else { SCLogDebug("sm->type %u", smd->type); #ifdef DEBUG BUG_ON(1); #endif } no_match: KEYWORD_PROFILING_END(det_ctx, smd->type, 0); SCReturnInt(0); match: /* this sigmatch matched, inspect the next one. If it was the last, * the buffer portion of the signature matched. */ if (!smd->is_last) { KEYWORD_PROFILING_END(det_ctx, smd->type, 1); int r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1, f, buffer, buffer_len, stream_start_offset, inspection_mode, data); SCReturnInt(r); } final_match: KEYWORD_PROFILING_END(det_ctx, smd->type, 1); SCReturnInt(1); } Commit Message: detect: avoid needless recursive scanning Don't recursively inspect a detect list if the recursion doesn't increase chance of success. CWE ID:
int DetectEngineContentInspection(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, const Signature *s, const SigMatchData *smd, Flow *f, uint8_t *buffer, uint32_t buffer_len, uint32_t stream_start_offset, uint8_t inspection_mode, void *data) { SCEnter(); KEYWORD_PROFILING_START; det_ctx->inspection_recursion_counter++; if (det_ctx->inspection_recursion_counter == de_ctx->inspection_recursion_limit) { det_ctx->discontinue_matching = 1; KEYWORD_PROFILING_END(det_ctx, smd->type, 0); SCReturnInt(0); } if (smd == NULL || buffer_len == 0) { KEYWORD_PROFILING_END(det_ctx, smd->type, 0); SCReturnInt(0); } /* \todo unify this which is phase 2 of payload inspection unification */ if (smd->type == DETECT_CONTENT) { DetectContentData *cd = (DetectContentData *)smd->ctx; SCLogDebug("inspecting content %"PRIu32" buffer_len %"PRIu32, cd->id, buffer_len); /* we might have already have this content matched by the mpm. * (if there is any other reason why we'd want to avoid checking * it here, please fill it in) */ /* rule parsers should take care of this */ #ifdef DEBUG BUG_ON(cd->depth != 0 && cd->depth <= cd->offset); #endif /* search for our pattern, checking the matches recursively. * if we match we look for the next SigMatch as well */ uint8_t *found = NULL; uint32_t offset = 0; uint32_t depth = buffer_len; uint32_t prev_offset = 0; /**< used in recursive searching */ uint32_t prev_buffer_offset = det_ctx->buffer_offset; do { if ((cd->flags & DETECT_CONTENT_DISTANCE) || (cd->flags & DETECT_CONTENT_WITHIN)) { SCLogDebug("det_ctx->buffer_offset %"PRIu32, det_ctx->buffer_offset); offset = prev_buffer_offset; depth = buffer_len; int distance = cd->distance; if (cd->flags & DETECT_CONTENT_DISTANCE) { if (cd->flags & DETECT_CONTENT_DISTANCE_BE) { distance = det_ctx->bj_values[cd->distance]; } if (distance < 0 && (uint32_t)(abs(distance)) > offset) offset = 0; else offset += distance; SCLogDebug("cd->distance %"PRIi32", offset %"PRIu32", depth %"PRIu32, distance, offset, depth); } if (cd->flags & DETECT_CONTENT_WITHIN) { if (cd->flags & DETECT_CONTENT_WITHIN_BE) { if ((int32_t)depth > (int32_t)(prev_buffer_offset + det_ctx->bj_values[cd->within] + distance)) { depth = prev_buffer_offset + det_ctx->bj_values[cd->within] + distance; } } else { if ((int32_t)depth > (int32_t)(prev_buffer_offset + cd->within + distance)) { depth = prev_buffer_offset + cd->within + distance; } SCLogDebug("cd->within %"PRIi32", det_ctx->buffer_offset %"PRIu32", depth %"PRIu32, cd->within, prev_buffer_offset, depth); } if (stream_start_offset != 0 && prev_buffer_offset == 0) { if (depth <= stream_start_offset) { goto no_match; } else if (depth >= (stream_start_offset + buffer_len)) { ; } else { depth = depth - stream_start_offset; } } } if (cd->flags & DETECT_CONTENT_DEPTH_BE) { if ((det_ctx->bj_values[cd->depth] + prev_buffer_offset) < depth) { depth = prev_buffer_offset + det_ctx->bj_values[cd->depth]; } } else { if (cd->depth != 0) { if ((cd->depth + prev_buffer_offset) < depth) { depth = prev_buffer_offset + cd->depth; } SCLogDebug("cd->depth %"PRIu32", depth %"PRIu32, cd->depth, depth); } } if (cd->flags & DETECT_CONTENT_OFFSET_BE) { if (det_ctx->bj_values[cd->offset] > offset) offset = det_ctx->bj_values[cd->offset]; } else { if (cd->offset > offset) { offset = cd->offset; SCLogDebug("setting offset %"PRIu32, offset); } } } else { /* implied no relative matches */ /* set depth */ if (cd->flags & DETECT_CONTENT_DEPTH_BE) { depth = det_ctx->bj_values[cd->depth]; } else { if (cd->depth != 0) { depth = cd->depth; } } if (stream_start_offset != 0 && cd->flags & DETECT_CONTENT_DEPTH) { if (depth <= stream_start_offset) { goto no_match; } else if (depth >= (stream_start_offset + buffer_len)) { ; } else { depth = depth - stream_start_offset; } } /* set offset */ if (cd->flags & DETECT_CONTENT_OFFSET_BE) offset = det_ctx->bj_values[cd->offset]; else offset = cd->offset; prev_buffer_offset = 0; } /* update offset with prev_offset if we're searching for * matches after the first occurence. */ SCLogDebug("offset %"PRIu32", prev_offset %"PRIu32, offset, prev_offset); if (prev_offset != 0) offset = prev_offset; SCLogDebug("offset %"PRIu32", depth %"PRIu32, offset, depth); if (depth > buffer_len) depth = buffer_len; /* if offset is bigger than depth we can never match on a pattern. * We can however, "match" on a negated pattern. */ if (offset > depth || depth == 0) { if (cd->flags & DETECT_CONTENT_NEGATED) { goto match; } else { goto no_match; } } uint8_t *sbuffer = buffer + offset; uint32_t sbuffer_len = depth - offset; uint32_t match_offset = 0; SCLogDebug("sbuffer_len %"PRIu32, sbuffer_len); #ifdef DEBUG BUG_ON(sbuffer_len > buffer_len); #endif /* \todo Add another optimization here. If cd->content_len is * greater than sbuffer_len found is anyways NULL */ /* do the actual search */ found = SpmScan(cd->spm_ctx, det_ctx->spm_thread_ctx, sbuffer, sbuffer_len); /* next we evaluate the result in combination with the * negation flag. */ SCLogDebug("found %p cd negated %s", found, cd->flags & DETECT_CONTENT_NEGATED ? "true" : "false"); if (found == NULL && !(cd->flags & DETECT_CONTENT_NEGATED)) { if ((cd->flags & (DETECT_CONTENT_DISTANCE|DETECT_CONTENT_WITHIN)) == 0) { /* independent match from previous matches, so failure is fatal */ det_ctx->discontinue_matching = 1; } goto no_match; } else if (found == NULL && (cd->flags & DETECT_CONTENT_NEGATED)) { goto match; } else if (found != NULL && (cd->flags & DETECT_CONTENT_NEGATED)) { SCLogDebug("content %"PRIu32" matched at offset %"PRIu32", but negated so no match", cd->id, match_offset); /* don't bother carrying recursive matches now, for preceding * relative keywords */ if (DETECT_CONTENT_IS_SINGLE(cd)) det_ctx->discontinue_matching = 1; goto no_match; } else { match_offset = (uint32_t)((found - buffer) + cd->content_len); SCLogDebug("content %"PRIu32" matched at offset %"PRIu32"", cd->id, match_offset); det_ctx->buffer_offset = match_offset; /* Match branch, add replace to the list if needed */ if (cd->flags & DETECT_CONTENT_REPLACE) { if (inspection_mode == DETECT_ENGINE_CONTENT_INSPECTION_MODE_PAYLOAD) { /* we will need to replace content if match is confirmed */ det_ctx->replist = DetectReplaceAddToList(det_ctx->replist, found, cd); } else { SCLogWarning(SC_ERR_INVALID_VALUE, "Can't modify payload without packet"); } } /* if this is the last match we're done */ if (smd->is_last) { goto match; } SCLogDebug("content %"PRIu32, cd->id); KEYWORD_PROFILING_END(det_ctx, smd->type, 1); /* see if the next buffer keywords match. If not, we will * search for another occurence of this content and see * if the others match then until we run out of matches */ int r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1, f, buffer, buffer_len, stream_start_offset, inspection_mode, data); if (r == 1) { SCReturnInt(1); } SCLogDebug("no match for 'next sm'"); if (det_ctx->discontinue_matching) { SCLogDebug("'next sm' said to discontinue this right now"); goto no_match; } /* no match and no reason to look for another instance */ if ((cd->flags & DETECT_CONTENT_RELATIVE_NEXT) == 0) { SCLogDebug("'next sm' does not depend on me, so we can give up"); det_ctx->discontinue_matching = 1; goto no_match; } SCLogDebug("'next sm' depends on me %p, lets see what we can do (flags %u)", cd, cd->flags); /* set the previous match offset to the start of this match + 1 */ prev_offset = (match_offset - (cd->content_len - 1)); SCLogDebug("trying to see if there is another match after prev_offset %"PRIu32, prev_offset); } } while(1); } else if (smd->type == DETECT_ISDATAAT) { SCLogDebug("inspecting isdataat"); DetectIsdataatData *id = (DetectIsdataatData *)smd->ctx; if (id->flags & ISDATAAT_RELATIVE) { if (det_ctx->buffer_offset + id->dataat > buffer_len) { SCLogDebug("det_ctx->buffer_offset + id->dataat %"PRIu32" > %"PRIu32, det_ctx->buffer_offset + id->dataat, buffer_len); if (id->flags & ISDATAAT_NEGATED) goto match; goto no_match; } else { SCLogDebug("relative isdataat match"); if (id->flags & ISDATAAT_NEGATED) goto no_match; goto match; } } else { if (id->dataat < buffer_len) { SCLogDebug("absolute isdataat match"); if (id->flags & ISDATAAT_NEGATED) goto no_match; goto match; } else { SCLogDebug("absolute isdataat mismatch, id->isdataat %"PRIu32", buffer_len %"PRIu32"", id->dataat, buffer_len); if (id->flags & ISDATAAT_NEGATED) goto match; goto no_match; } } } else if (smd->type == DETECT_PCRE) { SCLogDebug("inspecting pcre"); DetectPcreData *pe = (DetectPcreData *)smd->ctx; uint32_t prev_buffer_offset = det_ctx->buffer_offset; uint32_t prev_offset = 0; int r = 0; det_ctx->pcre_match_start_offset = 0; do { Packet *p = NULL; if (inspection_mode == DETECT_ENGINE_CONTENT_INSPECTION_MODE_PAYLOAD) p = (Packet *)data; r = DetectPcrePayloadMatch(det_ctx, s, smd, p, f, buffer, buffer_len); if (r == 0) { goto no_match; } if (!(pe->flags & DETECT_PCRE_RELATIVE_NEXT)) { SCLogDebug("no relative match coming up, so this is a match"); goto match; } KEYWORD_PROFILING_END(det_ctx, smd->type, 1); /* save it, in case we need to do a pcre match once again */ prev_offset = det_ctx->pcre_match_start_offset; /* see if the next payload keywords match. If not, we will * search for another occurence of this pcre and see * if the others match, until we run out of matches */ r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1, f, buffer, buffer_len, stream_start_offset, inspection_mode, data); if (r == 1) { SCReturnInt(1); } if (det_ctx->discontinue_matching) goto no_match; det_ctx->buffer_offset = prev_buffer_offset; det_ctx->pcre_match_start_offset = prev_offset; } while (1); } else if (smd->type == DETECT_BYTETEST) { DetectBytetestData *btd = (DetectBytetestData *)smd->ctx; uint8_t flags = btd->flags; int32_t offset = btd->offset; uint64_t value = btd->value; if (flags & DETECT_BYTETEST_OFFSET_BE) { offset = det_ctx->bj_values[offset]; } if (flags & DETECT_BYTETEST_VALUE_BE) { value = det_ctx->bj_values[value]; } /* if we have dce enabled we will have to use the endianness * specified by the dce header */ if (flags & DETECT_BYTETEST_DCE && data != NULL) { DCERPCState *dcerpc_state = (DCERPCState *)data; /* enable the endianness flag temporarily. once we are done * processing we reset the flags to the original value*/ flags |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] & 0x10) ? DETECT_BYTETEST_LITTLE: 0); } if (DetectBytetestDoMatch(det_ctx, s, smd->ctx, buffer, buffer_len, flags, offset, value) != 1) { goto no_match; } goto match; } else if (smd->type == DETECT_BYTEJUMP) { DetectBytejumpData *bjd = (DetectBytejumpData *)smd->ctx; uint8_t flags = bjd->flags; int32_t offset = bjd->offset; if (flags & DETECT_BYTEJUMP_OFFSET_BE) { offset = det_ctx->bj_values[offset]; } /* if we have dce enabled we will have to use the endianness * specified by the dce header */ if (flags & DETECT_BYTEJUMP_DCE && data != NULL) { DCERPCState *dcerpc_state = (DCERPCState *)data; /* enable the endianness flag temporarily. once we are done * processing we reset the flags to the original value*/ flags |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] & 0x10) ? DETECT_BYTEJUMP_LITTLE: 0); } if (DetectBytejumpDoMatch(det_ctx, s, smd->ctx, buffer, buffer_len, flags, offset) != 1) { goto no_match; } goto match; } else if (smd->type == DETECT_BYTE_EXTRACT) { DetectByteExtractData *bed = (DetectByteExtractData *)smd->ctx; uint8_t endian = bed->endian; /* if we have dce enabled we will have to use the endianness * specified by the dce header */ if ((bed->flags & DETECT_BYTE_EXTRACT_FLAG_ENDIAN) && endian == DETECT_BYTE_EXTRACT_ENDIAN_DCE && data != NULL) { DCERPCState *dcerpc_state = (DCERPCState *)data; /* enable the endianness flag temporarily. once we are done * processing we reset the flags to the original value*/ endian |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] == 0x10) ? DETECT_BYTE_EXTRACT_ENDIAN_LITTLE : DETECT_BYTE_EXTRACT_ENDIAN_BIG); } if (DetectByteExtractDoMatch(det_ctx, smd, s, buffer, buffer_len, &det_ctx->bj_values[bed->local_id], endian) != 1) { goto no_match; } goto match; /* we should never get here, but bail out just in case */ } else if (smd->type == DETECT_AL_URILEN) { SCLogDebug("inspecting uri len"); int r = 0; DetectUrilenData *urilend = (DetectUrilenData *) smd->ctx; switch (urilend->mode) { case DETECT_URILEN_EQ: if (buffer_len == urilend->urilen1) r = 1; break; case DETECT_URILEN_LT: if (buffer_len < urilend->urilen1) r = 1; break; case DETECT_URILEN_GT: if (buffer_len > urilend->urilen1) r = 1; break; case DETECT_URILEN_RA: if (buffer_len > urilend->urilen1 && buffer_len < urilend->urilen2) { r = 1; } break; } if (r == 1) { goto match; } det_ctx->discontinue_matching = 0; goto no_match; #ifdef HAVE_LUA } else if (smd->type == DETECT_LUA) { SCLogDebug("lua starting"); if (DetectLuaMatchBuffer(det_ctx, s, smd, buffer, buffer_len, det_ctx->buffer_offset, f) != 1) { SCLogDebug("lua no_match"); goto no_match; } SCLogDebug("lua match"); goto match; #endif /* HAVE_LUA */ } else if (smd->type == DETECT_BASE64_DECODE) { if (DetectBase64DecodeDoMatch(det_ctx, s, smd, buffer, buffer_len)) { if (s->sm_arrays[DETECT_SM_LIST_BASE64_DATA] != NULL) { KEYWORD_PROFILING_END(det_ctx, smd->type, 1); if (DetectBase64DataDoMatch(de_ctx, det_ctx, s, f)) { /* Base64 is a terminal list. */ goto final_match; } } } } else { SCLogDebug("sm->type %u", smd->type); #ifdef DEBUG BUG_ON(1); #endif } no_match: KEYWORD_PROFILING_END(det_ctx, smd->type, 0); SCReturnInt(0); match: /* this sigmatch matched, inspect the next one. If it was the last, * the buffer portion of the signature matched. */ if (!smd->is_last) { KEYWORD_PROFILING_END(det_ctx, smd->type, 1); int r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1, f, buffer, buffer_len, stream_start_offset, inspection_mode, data); SCReturnInt(r); } final_match: KEYWORD_PROFILING_END(det_ctx, smd->type, 1); SCReturnInt(1); }
167,721
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AppCacheDatabase::InsertCache(const CacheRecord* record) { if (!LazyOpen(kCreateIfNeeded)) return false; static const char kSql[] = "INSERT INTO Caches (cache_id, group_id, online_wildcard," " update_time, cache_size)" " VALUES(?, ?, ?, ?, ?)"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, record->cache_id); statement.BindInt64(1, record->group_id); statement.BindBool(2, record->online_wildcard); statement.BindInt64(3, record->update_time.ToInternalValue()); statement.BindInt64(4, record->cache_size); return statement.Run(); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
bool AppCacheDatabase::InsertCache(const CacheRecord* record) { if (!LazyOpen(kCreateIfNeeded)) return false; static const char kSql[] = "INSERT INTO Caches (cache_id, group_id, online_wildcard," " update_time, cache_size, padding_size)" " VALUES(?, ?, ?, ?, ?, ?)"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, record->cache_id); statement.BindInt64(1, record->group_id); statement.BindBool(2, record->online_wildcard); statement.BindInt64(3, record->update_time.ToInternalValue()); DCHECK_GE(record->cache_size, 0); statement.BindInt64(4, record->cache_size); DCHECK_GE(record->padding_size, 0); statement.BindInt64(5, record->padding_size); return statement.Run(); }
172,979
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int disrsi_( int stream, int *negate, unsigned *value, unsigned count) { int c; unsigned locval; unsigned ndigs; char *cp; char scratch[DIS_BUFSIZ+1]; assert(negate != NULL); assert(value != NULL); assert(count); assert(stream >= 0); assert(dis_getc != NULL); assert(dis_gets != NULL); memset(scratch, 0, DIS_BUFSIZ+1); if (dis_umaxd == 0) disiui_(); switch (c = (*dis_getc)(stream)) { case '-': case '+': *negate = c == '-'; if ((*dis_gets)(stream, scratch, count) != (int)count) { return(DIS_EOD); } if (count >= dis_umaxd) { if (count > dis_umaxd) goto overflow; if (memcmp(scratch, dis_umax, dis_umaxd) > 0) goto overflow; } cp = scratch; locval = 0; do { if (((c = *cp++) < '0') || (c > '9')) { return(DIS_NONDIGIT); } locval = 10 * locval + c - '0'; } while (--count); *value = locval; return (DIS_SUCCESS); break; case '0': return (DIS_LEADZRO); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ndigs = c - '0'; if (count > 1) { if ((*dis_gets)(stream, scratch + 1, count - 1) != (int)count - 1) { return(DIS_EOD); } cp = scratch; if (count >= dis_umaxd) { if (count > dis_umaxd) break; *cp = c; if (memcmp(scratch, dis_umax, dis_umaxd) > 0) break; } while (--count) { if (((c = *++cp) < '0') || (c > '9')) { return(DIS_NONDIGIT); } ndigs = 10 * ndigs + c - '0'; } } /* END if (count > 1) */ return(disrsi_(stream, negate, value, ndigs)); /*NOTREACHED*/ break; case - 1: return(DIS_EOD); /*NOTREACHED*/ break; case -2: return(DIS_EOF); /*NOTREACHED*/ break; default: return(DIS_NONDIGIT); /*NOTREACHED*/ break; } *negate = FALSE; overflow: *value = UINT_MAX; return(DIS_OVERFLOW); } /* END disrsi_() */ Commit Message: Merge pull request #171 into 2.5-fixes. CWE ID: CWE-119
int disrsi_( int stream, int *negate, unsigned *value, unsigned count) { int c; unsigned locval; unsigned ndigs; char *cp; char scratch[DIS_BUFSIZ+1]; assert(negate != NULL); assert(value != NULL); assert(count); assert(stream >= 0); assert(dis_getc != NULL); assert(dis_gets != NULL); memset(scratch, 0, DIS_BUFSIZ+1); if (dis_umaxd == 0) disiui_(); if (count >= dis_umaxd) { if (count > dis_umaxd) goto overflow; if (memcmp(scratch, dis_umax, dis_umaxd) > 0) goto overflow; } switch (c = (*dis_getc)(stream)) { case '-': case '+': *negate = c == '-'; if ((*dis_gets)(stream, scratch, count) != (int)count) { return(DIS_EOD); } if (count >= dis_umaxd) { if (count > dis_umaxd) goto overflow; if (memcmp(scratch, dis_umax, dis_umaxd) > 0) goto overflow; } cp = scratch; locval = 0; do { if (((c = *cp++) < '0') || (c > '9')) { return(DIS_NONDIGIT); } locval = 10 * locval + c - '0'; } while (--count); *value = locval; return (DIS_SUCCESS); break; case '0': return (DIS_LEADZRO); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ndigs = c - '0'; if (count > 1) { if ((*dis_gets)(stream, scratch + 1, count - 1) != (int)count - 1) { return(DIS_EOD); } cp = scratch; if (count >= dis_umaxd) { if (count > dis_umaxd) break; *cp = c; if (memcmp(scratch, dis_umax, dis_umaxd) > 0) break; } while (--count) { if (((c = *++cp) < '0') || (c > '9')) { return(DIS_NONDIGIT); } ndigs = 10 * ndigs + c - '0'; } } /* END if (count > 1) */ return(disrsi_(stream, negate, value, ndigs)); /*NOTREACHED*/ break; case - 1: return(DIS_EOD); /*NOTREACHED*/ break; case -2: return(DIS_EOF); /*NOTREACHED*/ break; default: return(DIS_NONDIGIT); /*NOTREACHED*/ break; } *negate = FALSE; overflow: *value = UINT_MAX; return(DIS_OVERFLOW); } /* END disrsi_() */
166,441
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadICONImage(const ImageInfo *image_info, ExceptionInfo *exception) { IconFile icon_file; IconInfo icon_info; Image *image; MagickBooleanType status; register ssize_t i, x; register Quantum *q; register unsigned char *p; size_t bit, byte, bytes_per_line, one, scanline_pad; ssize_t count, offset, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } icon_file.reserved=(short) ReadBlobLSBShort(image); icon_file.resource_type=(short) ReadBlobLSBShort(image); icon_file.count=(short) ReadBlobLSBShort(image); if ((icon_file.reserved != 0) || ((icon_file.resource_type != 1) && (icon_file.resource_type != 2)) || (icon_file.count > MaxIcons)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (i=0; i < icon_file.count; i++) { icon_file.directory[i].width=(unsigned char) ReadBlobByte(image); icon_file.directory[i].height=(unsigned char) ReadBlobByte(image); icon_file.directory[i].colors=(unsigned char) ReadBlobByte(image); icon_file.directory[i].reserved=(unsigned char) ReadBlobByte(image); icon_file.directory[i].planes=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].bits_per_pixel=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].size=ReadBlobLSBLong(image); icon_file.directory[i].offset=ReadBlobLSBLong(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } one=1; for (i=0; i < icon_file.count; i++) { /* Verify Icon identifier. */ offset=(ssize_t) SeekBlob(image,(MagickOffsetType) icon_file.directory[i].offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.size=ReadBlobLSBLong(image); icon_info.width=(unsigned char) ((int) ReadBlobLSBLong(image)); icon_info.height=(unsigned char) ((int) ReadBlobLSBLong(image)/2); icon_info.planes=ReadBlobLSBShort(image); icon_info.bits_per_pixel=ReadBlobLSBShort(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (((icon_info.planes == 18505) && (icon_info.bits_per_pixel == 21060)) || (icon_info.size == 0x474e5089)) { Image *icon_image; ImageInfo *read_info; size_t length; unsigned char *png; /* Icon image encoded as a compressed PNG image. */ length=icon_file.directory[i].size; png=(unsigned char *) AcquireQuantumMemory(length+16,sizeof(*png)); if (png == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickMemory(png,"\211PNG\r\n\032\n\000\000\000\015",12); png[12]=(unsigned char) icon_info.planes; png[13]=(unsigned char) (icon_info.planes >> 8); png[14]=(unsigned char) icon_info.bits_per_pixel; png[15]=(unsigned char) (icon_info.bits_per_pixel >> 8); count=ReadBlob(image,length-16,png+16); icon_image=(Image *) NULL; if (count > 0) { read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->magick,"PNG",MagickPathExtent); icon_image=BlobToImage(read_info,png,length+16,exception); read_info=DestroyImageInfo(read_info); } png=(unsigned char *) RelinquishMagickMemory(png); if (icon_image == (Image *) NULL) { if (count != (ssize_t) (length-16)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); image=DestroyImageList(image); return((Image *) NULL); } DestroyBlob(icon_image); icon_image->blob=ReferenceBlob(image->blob); ReplaceImageInList(&image,icon_image); } else { if (icon_info.bits_per_pixel > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.compression=ReadBlobLSBLong(image); icon_info.image_size=ReadBlobLSBLong(image); icon_info.x_pixels=ReadBlobLSBLong(image); icon_info.y_pixels=ReadBlobLSBLong(image); icon_info.number_colors=ReadBlobLSBLong(image); icon_info.colors_important=ReadBlobLSBLong(image); image->alpha_trait=BlendPixelTrait; image->columns=(size_t) icon_file.directory[i].width; if ((ssize_t) image->columns > icon_info.width) image->columns=(size_t) icon_info.width; if (image->columns == 0) image->columns=256; image->rows=(size_t) icon_file.directory[i].height; if ((ssize_t) image->rows > icon_info.height) image->rows=(size_t) icon_info.height; if (image->rows == 0) image->rows=256; image->depth=icon_info.bits_per_pixel; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene = %.20g",(double) i); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " size = %.20g",(double) icon_info.size); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width = %.20g",(double) icon_file.directory[i].width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height = %.20g",(double) icon_file.directory[i].height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " colors = %.20g",(double ) icon_info.number_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " planes = %.20g",(double) icon_info.planes); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bpp = %.20g",(double) icon_info.bits_per_pixel); } if ((icon_info.number_colors != 0) || (icon_info.bits_per_pixel <= 16U)) { image->storage_class=PseudoClass; image->colors=icon_info.number_colors; if (image->colors == 0) image->colors=one << icon_info.bits_per_pixel; } if (image->storage_class == PseudoClass) { register ssize_t i; unsigned char *icon_colormap; /* Read Icon raster colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4UL*sizeof(*icon_colormap)); if (icon_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) (4*image->colors),icon_colormap); if (count != (ssize_t) (4*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=icon_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].green=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].red=(Quantum) ScaleCharToQuantum(*p++); p++; } icon_colormap=(unsigned char *) RelinquishMagickMemory(icon_colormap); } /* Convert Icon raster image to pixel packets. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) & ~31) >> 3; (void) bytes_per_line; scanline_pad=((((image->columns*icon_info.bits_per_pixel)+31) & ~31)- (image->columns*icon_info.bits_per_pixel)) >> 3; switch (icon_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) (image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) { SetPixelIndex(image,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00),q); q+=GetPixelChannels(image); } } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) { SetPixelIndex(image,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00),q); q+=GetPixelChannels(image); } } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 4: { /* Read 4-bit Icon scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(image,((byte >> 4) & 0xf),q); q+=GetPixelChannels(image); SetPixelIndex(image,((byte) & 0xf),q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(image,((byte >> 4) & 0xf),q); q+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(image,byte,q); q+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); byte|=(size_t) (ReadBlobByte(image) << 8); SetPixelIndex(image,byte,q); q+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 24: case 32: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); if (icon_info.bits_per_pixel == 32) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); q+=GetPixelChannels(image); } if (icon_info.bits_per_pixel == 24) for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (image_info->ping == MagickFalse) (void) SyncImage(image,exception); if (icon_info.bits_per_pixel != 32) { /* Read the ICON alpha mask. */ image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) { SetPixelAlpha(image,(((byte & (0x80 >> bit)) != 0) ? TransparentAlpha : OpaqueAlpha),q); q+=GetPixelChannels(image); } } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) { SetPixelAlpha(image,(((byte & (0x80 >> bit)) != 0) ? TransparentAlpha : OpaqueAlpha),q); q+=GetPixelChannels(image); } } if ((image->columns % 32) != 0) for (x=0; x < (ssize_t) ((32-(image->columns % 32))/8); x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (i < (ssize_t) (icon_file.count-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-189
static Image *ReadICONImage(const ImageInfo *image_info, ExceptionInfo *exception) { IconFile icon_file; IconInfo icon_info; Image *image; MagickBooleanType status; register ssize_t i, x; register Quantum *q; register unsigned char *p; size_t bit, byte, bytes_per_line, one, scanline_pad; ssize_t count, offset, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } icon_file.reserved=(short) ReadBlobLSBShort(image); icon_file.resource_type=(short) ReadBlobLSBShort(image); icon_file.count=(short) ReadBlobLSBShort(image); if ((icon_file.reserved != 0) || ((icon_file.resource_type != 1) && (icon_file.resource_type != 2)) || (icon_file.count > MaxIcons)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (i=0; i < icon_file.count; i++) { icon_file.directory[i].width=(unsigned char) ReadBlobByte(image); icon_file.directory[i].height=(unsigned char) ReadBlobByte(image); icon_file.directory[i].colors=(unsigned char) ReadBlobByte(image); icon_file.directory[i].reserved=(unsigned char) ReadBlobByte(image); icon_file.directory[i].planes=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].bits_per_pixel=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].size=ReadBlobLSBLong(image); icon_file.directory[i].offset=ReadBlobLSBLong(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } one=1; for (i=0; i < icon_file.count; i++) { /* Verify Icon identifier. */ offset=(ssize_t) SeekBlob(image,(MagickOffsetType) icon_file.directory[i].offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.size=ReadBlobLSBLong(image); icon_info.width=(unsigned char) ((int) ReadBlobLSBLong(image)); icon_info.height=(unsigned char) ((int) ReadBlobLSBLong(image)/2); icon_info.planes=ReadBlobLSBShort(image); icon_info.bits_per_pixel=ReadBlobLSBShort(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (((icon_info.planes == 18505) && (icon_info.bits_per_pixel == 21060)) || (icon_info.size == 0x474e5089)) { Image *icon_image; ImageInfo *read_info; size_t length; unsigned char *png; /* Icon image encoded as a compressed PNG image. */ length=icon_file.directory[i].size; if (~length < 16) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); png=(unsigned char *) AcquireQuantumMemory(length+16,sizeof(*png)); if (png == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickMemory(png,"\211PNG\r\n\032\n\000\000\000\015",12); png[12]=(unsigned char) icon_info.planes; png[13]=(unsigned char) (icon_info.planes >> 8); png[14]=(unsigned char) icon_info.bits_per_pixel; png[15]=(unsigned char) (icon_info.bits_per_pixel >> 8); count=ReadBlob(image,length-16,png+16); icon_image=(Image *) NULL; if (count > 0) { read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->magick,"PNG",MagickPathExtent); icon_image=BlobToImage(read_info,png,length+16,exception); read_info=DestroyImageInfo(read_info); } png=(unsigned char *) RelinquishMagickMemory(png); if (icon_image == (Image *) NULL) { if (count != (ssize_t) (length-16)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); image=DestroyImageList(image); return((Image *) NULL); } DestroyBlob(icon_image); icon_image->blob=ReferenceBlob(image->blob); ReplaceImageInList(&image,icon_image); } else { if (icon_info.bits_per_pixel > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.compression=ReadBlobLSBLong(image); icon_info.image_size=ReadBlobLSBLong(image); icon_info.x_pixels=ReadBlobLSBLong(image); icon_info.y_pixels=ReadBlobLSBLong(image); icon_info.number_colors=ReadBlobLSBLong(image); icon_info.colors_important=ReadBlobLSBLong(image); image->alpha_trait=BlendPixelTrait; image->columns=(size_t) icon_file.directory[i].width; if ((ssize_t) image->columns > icon_info.width) image->columns=(size_t) icon_info.width; if (image->columns == 0) image->columns=256; image->rows=(size_t) icon_file.directory[i].height; if ((ssize_t) image->rows > icon_info.height) image->rows=(size_t) icon_info.height; if (image->rows == 0) image->rows=256; image->depth=icon_info.bits_per_pixel; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene = %.20g",(double) i); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " size = %.20g",(double) icon_info.size); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width = %.20g",(double) icon_file.directory[i].width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height = %.20g",(double) icon_file.directory[i].height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " colors = %.20g",(double ) icon_info.number_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " planes = %.20g",(double) icon_info.planes); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bpp = %.20g",(double) icon_info.bits_per_pixel); } if ((icon_info.number_colors != 0) || (icon_info.bits_per_pixel <= 16U)) { image->storage_class=PseudoClass; image->colors=icon_info.number_colors; if (image->colors == 0) image->colors=one << icon_info.bits_per_pixel; } if (image->storage_class == PseudoClass) { register ssize_t i; unsigned char *icon_colormap; /* Read Icon raster colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4UL*sizeof(*icon_colormap)); if (icon_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) (4*image->colors),icon_colormap); if (count != (ssize_t) (4*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=icon_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].green=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].red=(Quantum) ScaleCharToQuantum(*p++); p++; } icon_colormap=(unsigned char *) RelinquishMagickMemory(icon_colormap); } /* Convert Icon raster image to pixel packets. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) & ~31) >> 3; (void) bytes_per_line; scanline_pad=((((image->columns*icon_info.bits_per_pixel)+31) & ~31)- (image->columns*icon_info.bits_per_pixel)) >> 3; switch (icon_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) (image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) { SetPixelIndex(image,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00),q); q+=GetPixelChannels(image); } } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) { SetPixelIndex(image,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00),q); q+=GetPixelChannels(image); } } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 4: { /* Read 4-bit Icon scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(image,((byte >> 4) & 0xf),q); q+=GetPixelChannels(image); SetPixelIndex(image,((byte) & 0xf),q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(image,((byte >> 4) & 0xf),q); q+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(image,byte,q); q+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); byte|=(size_t) (ReadBlobByte(image) << 8); SetPixelIndex(image,byte,q); q+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 24: case 32: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); if (icon_info.bits_per_pixel == 32) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); q+=GetPixelChannels(image); } if (icon_info.bits_per_pixel == 24) for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (image_info->ping == MagickFalse) (void) SyncImage(image,exception); if (icon_info.bits_per_pixel != 32) { /* Read the ICON alpha mask. */ image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) { SetPixelAlpha(image,(((byte & (0x80 >> bit)) != 0) ? TransparentAlpha : OpaqueAlpha),q); q+=GetPixelChannels(image); } } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) { SetPixelAlpha(image,(((byte & (0x80 >> bit)) != 0) ? TransparentAlpha : OpaqueAlpha),q); q+=GetPixelChannels(image); } } if ((image->columns % 32) != 0) for (x=0; x < (ssize_t) ((32-(image->columns % 32))/8); x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (i < (ssize_t) (icon_file.count-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,863
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ext2_xattr_get(struct inode *inode, int name_index, const char *name, void *buffer, size_t buffer_size) { struct buffer_head *bh = NULL; struct ext2_xattr_entry *entry; size_t name_len, size; char *end; int error; ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld", name_index, name, buffer, (long)buffer_size); if (name == NULL) return -EINVAL; name_len = strlen(name); if (name_len > 255) return -ERANGE; down_read(&EXT2_I(inode)->xattr_sem); error = -ENODATA; if (!EXT2_I(inode)->i_file_acl) goto cleanup; ea_idebug(inode, "reading block %d", EXT2_I(inode)->i_file_acl); bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl); error = -EIO; if (!bh) goto cleanup; ea_bdebug(bh, "b_count=%d, refcount=%d", atomic_read(&(bh->b_count)), le32_to_cpu(HDR(bh)->h_refcount)); end = bh->b_data + bh->b_size; if (HDR(bh)->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) || HDR(bh)->h_blocks != cpu_to_le32(1)) { bad_block: ext2_error(inode->i_sb, "ext2_xattr_get", "inode %ld: bad block %d", inode->i_ino, EXT2_I(inode)->i_file_acl); error = -EIO; goto cleanup; } /* find named attribute */ entry = FIRST_ENTRY(bh); while (!IS_LAST_ENTRY(entry)) { struct ext2_xattr_entry *next = EXT2_XATTR_NEXT(entry); if ((char *)next >= end) goto bad_block; if (name_index == entry->e_name_index && name_len == entry->e_name_len && memcmp(name, entry->e_name, name_len) == 0) goto found; entry = next; } if (ext2_xattr_cache_insert(bh)) ea_idebug(inode, "cache insert failed"); error = -ENODATA; goto cleanup; found: /* check the buffer size */ if (entry->e_value_block != 0) goto bad_block; size = le32_to_cpu(entry->e_value_size); if (size > inode->i_sb->s_blocksize || le16_to_cpu(entry->e_value_offs) + size > inode->i_sb->s_blocksize) goto bad_block; if (ext2_xattr_cache_insert(bh)) ea_idebug(inode, "cache insert failed"); if (buffer) { error = -ERANGE; if (size > buffer_size) goto cleanup; /* return value of attribute */ memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs), size); } error = size; cleanup: brelse(bh); up_read(&EXT2_I(inode)->xattr_sem); return error; } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19
ext2_xattr_get(struct inode *inode, int name_index, const char *name, void *buffer, size_t buffer_size) { struct buffer_head *bh = NULL; struct ext2_xattr_entry *entry; size_t name_len, size; char *end; int error; struct mb2_cache *ext2_mb_cache = EXT2_SB(inode->i_sb)->s_mb_cache; ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld", name_index, name, buffer, (long)buffer_size); if (name == NULL) return -EINVAL; name_len = strlen(name); if (name_len > 255) return -ERANGE; down_read(&EXT2_I(inode)->xattr_sem); error = -ENODATA; if (!EXT2_I(inode)->i_file_acl) goto cleanup; ea_idebug(inode, "reading block %d", EXT2_I(inode)->i_file_acl); bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl); error = -EIO; if (!bh) goto cleanup; ea_bdebug(bh, "b_count=%d, refcount=%d", atomic_read(&(bh->b_count)), le32_to_cpu(HDR(bh)->h_refcount)); end = bh->b_data + bh->b_size; if (HDR(bh)->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) || HDR(bh)->h_blocks != cpu_to_le32(1)) { bad_block: ext2_error(inode->i_sb, "ext2_xattr_get", "inode %ld: bad block %d", inode->i_ino, EXT2_I(inode)->i_file_acl); error = -EIO; goto cleanup; } /* find named attribute */ entry = FIRST_ENTRY(bh); while (!IS_LAST_ENTRY(entry)) { struct ext2_xattr_entry *next = EXT2_XATTR_NEXT(entry); if ((char *)next >= end) goto bad_block; if (name_index == entry->e_name_index && name_len == entry->e_name_len && memcmp(name, entry->e_name, name_len) == 0) goto found; entry = next; } if (ext2_xattr_cache_insert(ext2_mb_cache, bh)) ea_idebug(inode, "cache insert failed"); error = -ENODATA; goto cleanup; found: /* check the buffer size */ if (entry->e_value_block != 0) goto bad_block; size = le32_to_cpu(entry->e_value_size); if (size > inode->i_sb->s_blocksize || le16_to_cpu(entry->e_value_offs) + size > inode->i_sb->s_blocksize) goto bad_block; if (ext2_xattr_cache_insert(ext2_mb_cache, bh)) ea_idebug(inode, "cache insert failed"); if (buffer) { error = -ERANGE; if (size > buffer_size) goto cleanup; /* return value of attribute */ memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs), size); } error = size; cleanup: brelse(bh); up_read(&EXT2_I(inode)->xattr_sem); return error; }
169,980
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void unix_copy_addr(struct msghdr *msg, struct sock *sk) { struct unix_sock *u = unix_sk(sk); msg->msg_namelen = 0; if (u->addr) { msg->msg_namelen = u->addr->len; memcpy(msg->msg_name, u->addr->name, u->addr->len); } } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static void unix_copy_addr(struct msghdr *msg, struct sock *sk) { struct unix_sock *u = unix_sk(sk); if (u->addr) { msg->msg_namelen = u->addr->len; memcpy(msg->msg_name, u->addr->name, u->addr->len); } }
166,519
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, unsigned char*& buf, size_t& buflen) { assert(pReader); assert(pos >= 0); long long total, available; long status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); if (status < 0) return false; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); if ((unsigned long)id != id_) return false; pos += len; // consume id const long long size_ = ReadUInt(pReader, pos, len); assert(size_ >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); pos += len; // consume length of size of payload assert((pos + size_) <= available); const long buflen_ = static_cast<long>(size_); buf = new (std::nothrow) unsigned char[buflen_]; assert(buf); // TODO status = pReader->Read(pos, buflen_, buf); assert(status == 0); // TODO buflen = buflen_; pos += size_; // consume size of payload return true; } 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
bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, bool Match(IMkvReader* pReader, long long& pos, unsigned long expected_id, unsigned char*& buf, size_t& buflen) { if (!pReader || pos < 0) return false; long long total = 0; long long available = 0; long status = pReader->Length(&total, &available); if (status < 0 || (total >= 0 && available > total)) return false; long len = 0; const long long id = ReadID(pReader, pos, len); if (id < 0 || (available - pos) > len) return false; if (static_cast<unsigned long>(id) != expected_id) return false; pos += len; // consume id const long long size = ReadUInt(pReader, pos, len); if (size < 0 || len <= 0 || len > 8 || (available - pos) > len) return false; unsigned long long rollover_check = static_cast<unsigned long long>(pos) + len; if (rollover_check > LONG_LONG_MAX) return false; pos += len; // consume length of size of payload rollover_check = static_cast<unsigned long long>(pos) + size; if (rollover_check > LONG_LONG_MAX) return false; if ((pos + size) > available) return false; if (size >= LONG_MAX) return false; const long buflen_ = static_cast<long>(size); buf = SafeArrayAlloc<unsigned char>(1, buflen_); if (!buf) return false; status = pReader->Read(pos, buflen_, buf); if (status != 0) return false; buflen = buflen_; pos += size; // consume size of payload return true; }
173,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static zval *_xml_xmlchar_zval(const XML_Char *s, int len, const XML_Char *encoding) { zval *ret; MAKE_STD_ZVAL(ret); if (s == NULL) { ZVAL_FALSE(ret); return ret; } if (len == 0) { len = _xml_xmlcharlen(s); } Z_TYPE_P(ret) = IS_STRING; Z_STRVAL_P(ret) = xml_utf8_decode(s, len, &Z_STRLEN_P(ret), encoding); return ret; } Commit Message: CWE ID: CWE-119
static zval *_xml_xmlchar_zval(const XML_Char *s, int len, const XML_Char *encoding) { zval *ret; MAKE_STD_ZVAL(ret); if (s == NULL) { ZVAL_FALSE(ret); return ret; } if (len == 0) { len = _xml_xmlcharlen(s); } Z_TYPE_P(ret) = IS_STRING; Z_STRVAL_P(ret) = xml_utf8_decode(s, len, &Z_STRLEN_P(ret), encoding); return ret; }
165,044
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned long Segment::GetCount() const { return m_clusterCount; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
unsigned long Segment::GetCount() const
174,299
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int misaligned_fpu_load(struct pt_regs *regs, __u32 opcode, int displacement_not_indexed, int width_shift, int do_paired_load) { /* Return -1 for a fault, 0 for OK */ int error; int destreg; __u64 address; error = generate_and_check_address(regs, opcode, displacement_not_indexed, width_shift, &address); if (error < 0) { return error; } perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, address); destreg = (opcode >> 4) & 0x3f; if (user_mode(regs)) { __u64 buffer; __u32 buflo, bufhi; if (!access_ok(VERIFY_READ, (unsigned long) address, 1UL<<width_shift)) { return -1; } if (__copy_user(&buffer, (const void *)(int)address, (1 << width_shift)) > 0) { return -1; /* fault */ } /* 'current' may be the current owner of the FPU state, so context switch the registers into memory so they can be indexed by register number. */ if (last_task_used_math == current) { enable_fpu(); save_fpu(current); disable_fpu(); last_task_used_math = NULL; regs->sr |= SR_FD; } buflo = *(__u32*) &buffer; bufhi = *(1 + (__u32*) &buffer); switch (width_shift) { case 2: current->thread.xstate->hardfpu.fp_regs[destreg] = buflo; break; case 3: if (do_paired_load) { current->thread.xstate->hardfpu.fp_regs[destreg] = buflo; current->thread.xstate->hardfpu.fp_regs[destreg+1] = bufhi; } else { #if defined(CONFIG_CPU_LITTLE_ENDIAN) current->thread.xstate->hardfpu.fp_regs[destreg] = bufhi; current->thread.xstate->hardfpu.fp_regs[destreg+1] = buflo; #else current->thread.xstate->hardfpu.fp_regs[destreg] = buflo; current->thread.xstate->hardfpu.fp_regs[destreg+1] = bufhi; #endif } break; default: printk("Unexpected width_shift %d in misaligned_fpu_load, PC=%08lx\n", width_shift, (unsigned long) regs->pc); break; } return 0; } else { die ("Misaligned FPU load inside kernel", regs, 0); return -1; } } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
static int misaligned_fpu_load(struct pt_regs *regs, __u32 opcode, int displacement_not_indexed, int width_shift, int do_paired_load) { /* Return -1 for a fault, 0 for OK */ int error; int destreg; __u64 address; error = generate_and_check_address(regs, opcode, displacement_not_indexed, width_shift, &address); if (error < 0) { return error; } perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, address); destreg = (opcode >> 4) & 0x3f; if (user_mode(regs)) { __u64 buffer; __u32 buflo, bufhi; if (!access_ok(VERIFY_READ, (unsigned long) address, 1UL<<width_shift)) { return -1; } if (__copy_user(&buffer, (const void *)(int)address, (1 << width_shift)) > 0) { return -1; /* fault */ } /* 'current' may be the current owner of the FPU state, so context switch the registers into memory so they can be indexed by register number. */ if (last_task_used_math == current) { enable_fpu(); save_fpu(current); disable_fpu(); last_task_used_math = NULL; regs->sr |= SR_FD; } buflo = *(__u32*) &buffer; bufhi = *(1 + (__u32*) &buffer); switch (width_shift) { case 2: current->thread.xstate->hardfpu.fp_regs[destreg] = buflo; break; case 3: if (do_paired_load) { current->thread.xstate->hardfpu.fp_regs[destreg] = buflo; current->thread.xstate->hardfpu.fp_regs[destreg+1] = bufhi; } else { #if defined(CONFIG_CPU_LITTLE_ENDIAN) current->thread.xstate->hardfpu.fp_regs[destreg] = bufhi; current->thread.xstate->hardfpu.fp_regs[destreg+1] = buflo; #else current->thread.xstate->hardfpu.fp_regs[destreg] = buflo; current->thread.xstate->hardfpu.fp_regs[destreg+1] = bufhi; #endif } break; default: printk("Unexpected width_shift %d in misaligned_fpu_load, PC=%08lx\n", width_shift, (unsigned long) regs->pc); break; } return 0; } else { die ("Misaligned FPU load inside kernel", regs, 0); return -1; } }
165,797
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int digi_startup(struct usb_serial *serial) { struct digi_serial *serial_priv; int ret; serial_priv = kzalloc(sizeof(*serial_priv), GFP_KERNEL); if (!serial_priv) return -ENOMEM; spin_lock_init(&serial_priv->ds_serial_lock); serial_priv->ds_oob_port_num = serial->type->num_ports; serial_priv->ds_oob_port = serial->port[serial_priv->ds_oob_port_num]; ret = digi_port_init(serial_priv->ds_oob_port, serial_priv->ds_oob_port_num); if (ret) { kfree(serial_priv); return ret; } usb_set_serial_data(serial, serial_priv); return 0; } Commit Message: USB: digi_acceleport: do sanity checking for the number of ports The driver can be crashed with devices that expose crafted descriptors with too few endpoints. See: http://seclists.org/bugtraq/2016/Mar/61 Signed-off-by: Oliver Neukum <[email protected]> [johan: fix OOB endpoint check and add error messages ] Cc: stable <[email protected]> Signed-off-by: Johan Hovold <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID:
static int digi_startup(struct usb_serial *serial) { struct device *dev = &serial->interface->dev; struct digi_serial *serial_priv; int ret; int i; /* check whether the device has the expected number of endpoints */ if (serial->num_port_pointers < serial->type->num_ports + 1) { dev_err(dev, "OOB endpoints missing\n"); return -ENODEV; } for (i = 0; i < serial->type->num_ports + 1 ; i++) { if (!serial->port[i]->read_urb) { dev_err(dev, "bulk-in endpoint missing\n"); return -ENODEV; } if (!serial->port[i]->write_urb) { dev_err(dev, "bulk-out endpoint missing\n"); return -ENODEV; } } serial_priv = kzalloc(sizeof(*serial_priv), GFP_KERNEL); if (!serial_priv) return -ENOMEM; spin_lock_init(&serial_priv->ds_serial_lock); serial_priv->ds_oob_port_num = serial->type->num_ports; serial_priv->ds_oob_port = serial->port[serial_priv->ds_oob_port_num]; ret = digi_port_init(serial_priv->ds_oob_port, serial_priv->ds_oob_port_num); if (ret) { kfree(serial_priv); return ret; } usb_set_serial_data(serial, serial_priv); return 0; }
167,357
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CancelHandwriting(int n_strokes) { IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } ibus_input_context_cancel_hand_writing(context, n_strokes); g_object_unref(context); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void CancelHandwriting(int n_strokes) { // IBusController override. virtual void CancelHandwriting(int n_strokes) { IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } ibus_input_context_cancel_hand_writing(context, n_strokes); g_object_unref(context); }
170,518
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int store_asoundrc(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_ASOUNDRC_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0644); fclose(fp); } if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { /* coverity[toctou] */ char* rp = realpath(src, NULL); if (!rp) { fprintf(stderr, "Error: Cannot access %s\n", src); exit(1); } if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) { fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n"); exit(1); } free(rp); } copy_file_as_user(src, dest, getuid(), getgid(), 0644); fs_logger2("clone", dest); return 1; // file copied } return 0; } Commit Message: security fix CWE ID: CWE-269
static int store_asoundrc(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_ASOUNDRC_FILE; // create an empty file as root, and change ownership to user FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0644); fclose(fp); } if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { /* coverity[toctou] */ char* rp = realpath(src, NULL); if (!rp) { fprintf(stderr, "Error: Cannot access %s\n", src); exit(1); } if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) { fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n"); exit(1); } free(rp); } copy_file_as_user(src, dest, getuid(), getgid(), 0644); fs_logger2("clone", dest); return 1; // file copied } return 0; }
168,372
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static long ioctl_file_dedupe_range(struct file *file, void __user *arg) { struct file_dedupe_range __user *argp = arg; struct file_dedupe_range *same = NULL; int ret; unsigned long size; u16 count; if (get_user(count, &argp->dest_count)) { ret = -EFAULT; goto out; } size = offsetof(struct file_dedupe_range __user, info[count]); same = memdup_user(argp, size); if (IS_ERR(same)) { ret = PTR_ERR(same); same = NULL; goto out; } ret = vfs_dedupe_file_range(file, same); if (ret) goto out; ret = copy_to_user(argp, same, size); if (ret) ret = -EFAULT; out: kfree(same); return ret; } Commit Message: vfs: ioctl: prevent double-fetch in dedupe ioctl This prevents a double-fetch from user space that can lead to to an undersized allocation and heap overflow. Fixes: 54dbc1517237 ("vfs: hoist the btrfs deduplication ioctl to the vfs") Signed-off-by: Scott Bauer <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-119
static long ioctl_file_dedupe_range(struct file *file, void __user *arg) { struct file_dedupe_range __user *argp = arg; struct file_dedupe_range *same = NULL; int ret; unsigned long size; u16 count; if (get_user(count, &argp->dest_count)) { ret = -EFAULT; goto out; } size = offsetof(struct file_dedupe_range __user, info[count]); same = memdup_user(argp, size); if (IS_ERR(same)) { ret = PTR_ERR(same); same = NULL; goto out; } same->dest_count = count; ret = vfs_dedupe_file_range(file, same); if (ret) goto out; ret = copy_to_user(argp, same, size); if (ret) ret = -EFAULT; out: kfree(same); return ret; }
166,997
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: HeapVector<NotificationAction> Notification::actions() const { HeapVector<NotificationAction> actions; actions.grow(m_data.actions.size()); for (size_t i = 0; i < m_data.actions.size(); ++i) { actions[i].setAction(m_data.actions[i].action); actions[i].setTitle(m_data.actions[i].title); } return actions; } Commit Message: Notification actions may have an icon url. This is behind a runtime flag for two reasons: * The implementation is incomplete. * We're still evaluating the API design. Intent to Implement and Ship: Notification Action Icons https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ BUG=581336 Review URL: https://codereview.chromium.org/1644573002 Cr-Commit-Position: refs/heads/master@{#374649} CWE ID:
HeapVector<NotificationAction> Notification::actions() const { HeapVector<NotificationAction> actions; actions.grow(m_data.actions.size()); for (size_t i = 0; i < m_data.actions.size(); ++i) { actions[i].setAction(m_data.actions[i].action); actions[i].setTitle(m_data.actions[i].title); actions[i].setIcon(m_data.actions[i].icon.string()); } return actions; }
171,633
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ThreadHeap::WriteBarrier(void* value) { DCHECK(thread_state_->IsIncrementalMarking()); DCHECK(value); DCHECK_NE(value, reinterpret_cast<void*>(-1)); BasePage* const page = PageFromObject(value); HeapObjectHeader* const header = page->IsLargeObjectPage() ? static_cast<LargeObjectPage*>(page)->GetHeapObjectHeader() : static_cast<NormalPage*>(page)->FindHeaderFromAddress( reinterpret_cast<Address>(const_cast<void*>(value))); if (header->IsMarked()) return; header->Mark(); marking_worklist_->Push( WorklistTaskId::MainThread, {header->Payload(), ThreadHeap::GcInfo(header->GcInfoIndex())->trace_}); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void ThreadHeap::WriteBarrier(void* value) { DCHECK(thread_state_->IsIncrementalMarking()); DCHECK(value); DCHECK_NE(value, reinterpret_cast<void*>(-1)); BasePage* const page = PageFromObject(value); HeapObjectHeader* const header = page->IsLargeObjectPage() ? static_cast<LargeObjectPage*>(page)->GetHeapObjectHeader() : static_cast<NormalPage*>(page)->FindHeaderFromAddress( reinterpret_cast<Address>(const_cast<void*>(value))); if (header->IsMarked()) return; header->Mark(); marking_worklist_->Push( WorklistTaskId::MainThread, {header->Payload(), GCInfoTable::Get().GCInfoFromIndex(header->GcInfoIndex())->trace_}); }
173,138
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MSG_WriteBits( msg_t *msg, int value, int bits ) { int i; oldsize += bits; if ( msg->maxsize - msg->cursize < 4 ) { msg->overflowed = qtrue; return; } if ( bits == 0 || bits < -31 || bits > 32 ) { Com_Error( ERR_DROP, "MSG_WriteBits: bad bits %i", bits ); } if ( bits < 0 ) { bits = -bits; } if ( msg->oob ) { if ( bits == 8 ) { msg->data[msg->cursize] = value; msg->cursize += 1; msg->bit += 8; } else if ( bits == 16 ) { short temp = value; CopyLittleShort( &msg->data[msg->cursize], &temp ); msg->cursize += 2; msg->bit += 16; } else if ( bits==32 ) { CopyLittleLong( &msg->data[msg->cursize], &value ); msg->cursize += 4; msg->bit += 32; } else { Com_Error( ERR_DROP, "can't write %d bits", bits ); } } else { value &= (0xffffffff >> (32 - bits)); if ( bits&7 ) { int nbits; nbits = bits&7; for( i = 0; i < nbits; i++ ) { Huff_putBit( (value & 1), msg->data, &msg->bit ); value = (value >> 1); } bits = bits - nbits; } if ( bits ) { for( i = 0; i < bits; i += 8 ) { Huff_offsetTransmit( &msgHuff.compressor, (value & 0xff), msg->data, &msg->bit ); value = (value >> 8); } } msg->cursize = (msg->bit >> 3) + 1; } } Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits Prevent reading past end of message in MSG_ReadBits. If read past end of msg->data buffer (16348 bytes) the engine could SEGFAULT. Make MSG_WriteBits use an exact buffer overflow check instead of possibly failing with a few bytes left. CWE ID: CWE-119
void MSG_WriteBits( msg_t *msg, int value, int bits ) { int i; oldsize += bits; if ( msg->overflowed ) { return; } if ( bits == 0 || bits < -31 || bits > 32 ) { Com_Error( ERR_DROP, "MSG_WriteBits: bad bits %i", bits ); } if ( bits < 0 ) { bits = -bits; } if ( msg->oob ) { if ( msg->cursize + ( bits >> 3 ) > msg->maxsize ) { msg->overflowed = qtrue; return; } if ( bits == 8 ) { msg->data[msg->cursize] = value; msg->cursize += 1; msg->bit += 8; } else if ( bits == 16 ) { short temp = value; CopyLittleShort( &msg->data[msg->cursize], &temp ); msg->cursize += 2; msg->bit += 16; } else if ( bits==32 ) { CopyLittleLong( &msg->data[msg->cursize], &value ); msg->cursize += 4; msg->bit += 32; } else { Com_Error( ERR_DROP, "can't write %d bits", bits ); } } else { value &= (0xffffffff >> (32 - bits)); if ( bits&7 ) { int nbits; nbits = bits&7; if ( msg->bit + nbits > msg->maxsize << 3 ) { msg->overflowed = qtrue; return; } for( i = 0; i < nbits; i++ ) { Huff_putBit( (value & 1), msg->data, &msg->bit ); value = (value >> 1); } bits = bits - nbits; } if ( bits ) { for( i = 0; i < bits; i += 8 ) { Huff_offsetTransmit( &msgHuff.compressor, (value & 0xff), msg->data, &msg->bit, msg->maxsize << 3 ); value = (value >> 8); if ( msg->bit > msg->maxsize << 3 ) { msg->overflowed = qtrue; return; } } } msg->cursize = (msg->bit >> 3) + 1; } }
167,999
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static double outlog(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535) * and so must be adjusted for low bit depth grayscale: */ if (out_depth <= 8) { if (pm->log8 == 0) /* switched off */ return 256; if (out_depth < 8) return pm->log8 / 255 * ((1<<out_depth)-1); return pm->log8; } if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) { if (pm->log16 == 0) return 65536; return pm->log16; } /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ if (pm->log8 == 0) return 65536; return pm->log8 * 257; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static double outlog(PNG_CONST png_modifier *pm, int in_depth, int out_depth) static double outlog(const png_modifier *pm, int in_depth, int out_depth) { /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535) * and so must be adjusted for low bit depth grayscale: */ if (out_depth <= 8) { if (pm->log8 == 0) /* switched off */ return 256; if (out_depth < 8) return pm->log8 / 255 * ((1<<out_depth)-1); return pm->log8; } if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) { if (pm->log16 == 0) return 65536; return pm->log16; } /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ if (pm->log8 == 0) return 65536; return pm->log8 * 257; }
173,675
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int br_mdb_fill_info(struct sk_buff *skb, struct netlink_callback *cb, struct net_device *dev) { struct net_bridge *br = netdev_priv(dev); struct net_bridge_mdb_htable *mdb; struct nlattr *nest, *nest2; int i, err = 0; int idx = 0, s_idx = cb->args[1]; if (br->multicast_disabled) return 0; mdb = rcu_dereference(br->mdb); if (!mdb) return 0; nest = nla_nest_start(skb, MDBA_MDB); if (nest == NULL) return -EMSGSIZE; for (i = 0; i < mdb->max; i++) { struct net_bridge_mdb_entry *mp; struct net_bridge_port_group *p, **pp; struct net_bridge_port *port; hlist_for_each_entry_rcu(mp, &mdb->mhash[i], hlist[mdb->ver]) { if (idx < s_idx) goto skip; nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY); if (nest2 == NULL) { err = -EMSGSIZE; goto out; } for (pp = &mp->ports; (p = rcu_dereference(*pp)) != NULL; pp = &p->next) { port = p->port; if (port) { struct br_mdb_entry e; e.ifindex = port->dev->ifindex; e.state = p->state; if (p->addr.proto == htons(ETH_P_IP)) e.addr.u.ip4 = p->addr.u.ip4; #if IS_ENABLED(CONFIG_IPV6) if (p->addr.proto == htons(ETH_P_IPV6)) e.addr.u.ip6 = p->addr.u.ip6; #endif e.addr.proto = p->addr.proto; if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(e), &e)) { nla_nest_cancel(skb, nest2); err = -EMSGSIZE; goto out; } } } nla_nest_end(skb, nest2); skip: idx++; } } out: cb->args[1] = idx; nla_nest_end(skb, nest); return err; } Commit Message: bridge: fix mdb info leaks The bridging code discloses heap and stack bytes via the RTM_GETMDB netlink interface and via the notify messages send to group RTNLGRP_MDB afer a successful add/del. Fix both cases by initializing all unset members/padding bytes with memset(0). Cc: Stephen Hemminger <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static int br_mdb_fill_info(struct sk_buff *skb, struct netlink_callback *cb, struct net_device *dev) { struct net_bridge *br = netdev_priv(dev); struct net_bridge_mdb_htable *mdb; struct nlattr *nest, *nest2; int i, err = 0; int idx = 0, s_idx = cb->args[1]; if (br->multicast_disabled) return 0; mdb = rcu_dereference(br->mdb); if (!mdb) return 0; nest = nla_nest_start(skb, MDBA_MDB); if (nest == NULL) return -EMSGSIZE; for (i = 0; i < mdb->max; i++) { struct net_bridge_mdb_entry *mp; struct net_bridge_port_group *p, **pp; struct net_bridge_port *port; hlist_for_each_entry_rcu(mp, &mdb->mhash[i], hlist[mdb->ver]) { if (idx < s_idx) goto skip; nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY); if (nest2 == NULL) { err = -EMSGSIZE; goto out; } for (pp = &mp->ports; (p = rcu_dereference(*pp)) != NULL; pp = &p->next) { port = p->port; if (port) { struct br_mdb_entry e; memset(&e, 0, sizeof(e)); e.ifindex = port->dev->ifindex; e.state = p->state; if (p->addr.proto == htons(ETH_P_IP)) e.addr.u.ip4 = p->addr.u.ip4; #if IS_ENABLED(CONFIG_IPV6) if (p->addr.proto == htons(ETH_P_IPV6)) e.addr.u.ip6 = p->addr.u.ip6; #endif e.addr.proto = p->addr.proto; if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(e), &e)) { nla_nest_cancel(skb, nest2); err = -EMSGSIZE; goto out; } } } nla_nest_end(skb, nest2); skip: idx++; } } out: cb->args[1] = idx; nla_nest_end(skb, nest); return err; }
166,053
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception) { char format[MaxTextExtent], keyword[MaxTextExtent], tag[MaxTextExtent], value[MaxTextExtent]; double gamma; Image *image; int c; MagickBooleanType status, value_expected; register Quantum *q; register ssize_t i, x; register unsigned char *p; ssize_t count, y; unsigned char *end, pixel[4], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Decode image header. */ image->columns=0; image->rows=0; *format='\0'; c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } while (isgraph(c) && (image->columns == 0) && (image->rows == 0)) { if (c == (int) '#') { char *comment; register char *p; size_t length; /* Read comment-- any text between # and end-of-line. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if ((c == EOF) || (c == (int) '\n')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) == MagickFalse) c=ReadBlobByte(image); else { register char *p; /* Determine a keyword and its value. */ p=keyword; do { if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c) || (c == '_')); *p='\0'; value_expected=MagickFalse; while ((isspace((int) ((unsigned char) c)) != 0) || (c == '=')) { if (c == '=') value_expected=MagickTrue; c=ReadBlobByte(image); } if (LocaleCompare(keyword,"Y") == 0) value_expected=MagickTrue; if (value_expected == MagickFalse) continue; p=value; while ((c != '\n') && (c != '\0')) { if ((size_t) (p-value) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"format") == 0) { (void) CopyMagickString(format,value,MaxTextExtent); break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(value,(char **) NULL); break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"primaries") == 0) { float chromaticity[6], white_point[2]; (void) sscanf(value,"%g %g %g %g %g %g %g %g", &chromaticity[0],&chromaticity[1],&chromaticity[2], &chromaticity[3],&chromaticity[4],&chromaticity[5], &white_point[0],&white_point[1]); image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; image->chromaticity.white_point.x=white_point[0], image->chromaticity.white_point.y=white_point[1]; break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'Y': case 'y': { char target[] = "Y"; if (strcmp(keyword,target) == 0) { int height, width; (void) sscanf(value,"%d +X %d",&height,&width); image->columns=(size_t) width; image->rows=(size_t) height; break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } default: { (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } } } if ((image->columns == 0) && (image->rows == 0)) while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) && (LocaleCompare(format,"32-bit_rle_xyze") != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); (void) SetImageColorspace(image,RGBColorspace,exception); if (LocaleCompare(format,"32-bit_rle_xyze") == 0) (void) SetImageColorspace(image,XYZColorspace,exception); image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ? NoCompression : RLECompression; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Read RGBE (red+green+blue+exponent) pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { if (image->compression != RLECompression) { count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels); if (count != (ssize_t) (4*image->columns*sizeof(*pixels))) break; } else { count=ReadBlob(image,4*sizeof(*pixel),pixel); if (count != 4) break; if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns) { (void) memcpy(pixels,pixel,4*sizeof(*pixel)); count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4); image->compression=NoCompression; } else { p=pixels; for (i=0; i < 4; i++) { end=&pixels[(i+1)*image->columns]; while (p < end) { count=ReadBlob(image,2*sizeof(*pixel),pixel); if (count < 1) break; if (pixel[0] > 128) { count=(ssize_t) pixel[0]-128; if ((count == 0) || (count > (ssize_t) (end-p))) break; while (count-- > 0) *p++=pixel[1]; } else { count=(ssize_t) pixel[0]; if ((count == 0) || (count > (ssize_t) (end-p))) break; *p++=pixel[1]; if (--count > 0) { count=ReadBlob(image,(size_t) count*sizeof(*p),p); if (count < 1) break; p+=count; } } } } } } q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; i=0; for (x=0; x < (ssize_t) image->columns; x++) { if (image->compression == RLECompression) { pixel[0]=pixels[x]; pixel[1]=pixels[x+image->columns]; pixel[2]=pixels[x+2*image->columns]; pixel[3]=pixels[x+3*image->columns]; } else { pixel[0]=pixels[i++]; pixel[1]=pixels[i++]; pixel[2]=pixels[i++]; pixel[3]=pixels[i++]; } SetPixelRed(image,0,q); SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); if (pixel[3] != 0) { gamma=pow(2.0,pixel[3]-(128.0+8.0)); SetPixelRed(image,ClampToQuantum(QuantumRange*gamma*pixel[0]),q); SetPixelGreen(image,ClampToQuantum(QuantumRange*gamma*pixel[1]),q); SetPixelBlue(image,ClampToQuantum(QuantumRange*gamma*pixel[2]),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: Fixed infinite loop and added checks for the sscanf result. CWE ID: CWE-20
static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception) { char format[MaxTextExtent], keyword[MaxTextExtent], tag[MaxTextExtent], value[MaxTextExtent]; double gamma; Image *image; int c; MagickBooleanType status, value_expected; register Quantum *q; register ssize_t i, x; register unsigned char *p; ssize_t count, y; unsigned char *end, pixel[4], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Decode image header. */ image->columns=0; image->rows=0; *format='\0'; c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } while (isgraph(c) && (image->columns == 0) && (image->rows == 0)) { if (c == (int) '#') { char *comment; register char *p; size_t length; /* Read comment-- any text between # and end-of-line. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if ((c == EOF) || (c == (int) '\n')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) == MagickFalse) c=ReadBlobByte(image); else { register char *p; /* Determine a keyword and its value. */ p=keyword; do { if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c) || (c == '_')); *p='\0'; value_expected=MagickFalse; while ((isspace((int) ((unsigned char) c)) != 0) || (c == '=')) { if (c == '=') value_expected=MagickTrue; c=ReadBlobByte(image); } if (LocaleCompare(keyword,"Y") == 0) value_expected=MagickTrue; if (value_expected == MagickFalse) continue; p=value; while ((c != '\n') && (c != '\0') && (c != EOF)) { if ((size_t) (p-value) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"format") == 0) { (void) CopyMagickString(format,value,MaxTextExtent); break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(value,(char **) NULL); break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"primaries") == 0) { float chromaticity[6], white_point[2]; if (sscanf(value,"%g %g %g %g %g %g %g %g",&chromaticity[0], &chromaticity[1],&chromaticity[2],&chromaticity[3], &chromaticity[4],&chromaticity[5],&white_point[0], &white_point[1]) == 8) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; image->chromaticity.white_point.x=white_point[0], image->chromaticity.white_point.y=white_point[1]; } break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'Y': case 'y': { char target[] = "Y"; if (strcmp(keyword,target) == 0) { int height, width; if (sscanf(value,"%d +X %d",&height,&width) == 2) { image->columns=(size_t) width; image->rows=(size_t) height; } break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } default: { (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } } } if ((image->columns == 0) && (image->rows == 0)) while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) && (LocaleCompare(format,"32-bit_rle_xyze") != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); (void) SetImageColorspace(image,RGBColorspace,exception); if (LocaleCompare(format,"32-bit_rle_xyze") == 0) (void) SetImageColorspace(image,XYZColorspace,exception); image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ? NoCompression : RLECompression; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Read RGBE (red+green+blue+exponent) pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { if (image->compression != RLECompression) { count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels); if (count != (ssize_t) (4*image->columns*sizeof(*pixels))) break; } else { count=ReadBlob(image,4*sizeof(*pixel),pixel); if (count != 4) break; if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns) { (void) memcpy(pixels,pixel,4*sizeof(*pixel)); count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4); image->compression=NoCompression; } else { p=pixels; for (i=0; i < 4; i++) { end=&pixels[(i+1)*image->columns]; while (p < end) { count=ReadBlob(image,2*sizeof(*pixel),pixel); if (count < 1) break; if (pixel[0] > 128) { count=(ssize_t) pixel[0]-128; if ((count == 0) || (count > (ssize_t) (end-p))) break; while (count-- > 0) *p++=pixel[1]; } else { count=(ssize_t) pixel[0]; if ((count == 0) || (count > (ssize_t) (end-p))) break; *p++=pixel[1]; if (--count > 0) { count=ReadBlob(image,(size_t) count*sizeof(*p),p); if (count < 1) break; p+=count; } } } } } } q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; i=0; for (x=0; x < (ssize_t) image->columns; x++) { if (image->compression == RLECompression) { pixel[0]=pixels[x]; pixel[1]=pixels[x+image->columns]; pixel[2]=pixels[x+2*image->columns]; pixel[3]=pixels[x+3*image->columns]; } else { pixel[0]=pixels[i++]; pixel[1]=pixels[i++]; pixel[2]=pixels[i++]; pixel[3]=pixels[i++]; } SetPixelRed(image,0,q); SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); if (pixel[3] != 0) { gamma=pow(2.0,pixel[3]-(128.0+8.0)); SetPixelRed(image,ClampToQuantum(QuantumRange*gamma*pixel[0]),q); SetPixelGreen(image,ClampToQuantum(QuantumRange*gamma*pixel[1]),q); SetPixelBlue(image,ClampToQuantum(QuantumRange*gamma*pixel[2]),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,856
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jiffies_to_compat_timeval(unsigned long jiffies, struct compat_timeval *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; long rem; value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &rem); value->tv_usec = rem / NSEC_PER_USEC; } Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189
jiffies_to_compat_timeval(unsigned long jiffies, struct compat_timeval *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; u32 rem; value->tv_sec = div_u64_rem(nsec, NSEC_PER_SEC, &rem); value->tv_usec = rem / NSEC_PER_USEC; }
165,748
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ReverbConvolverStage::ReverbConvolverStage(const float* impulseResponse, size_t, size_t reverbTotalLatency, size_t stageOffset, size_t stageLength, size_t fftSize, size_t renderPhase, size_t renderSliceSize, ReverbAccumulationBuffer* accumulationBuffer, bool directMode) : m_accumulationBuffer(accumulationBuffer) , m_accumulationReadIndex(0) , m_inputReadIndex(0) , m_directMode(directMode) { ASSERT(impulseResponse); ASSERT(accumulationBuffer); if (!m_directMode) { m_fftKernel = adoptPtr(new FFTFrame(fftSize)); m_fftKernel->doPaddedFFT(impulseResponse + stageOffset, stageLength); m_fftConvolver = adoptPtr(new FFTConvolver(fftSize)); } else { m_directKernel = adoptPtr(new AudioFloatArray(fftSize / 2)); m_directKernel->copyToRange(impulseResponse + stageOffset, 0, fftSize / 2); m_directConvolver = adoptPtr(new DirectConvolver(renderSliceSize)); } m_temporaryBuffer.allocate(renderSliceSize); size_t totalDelay = stageOffset + reverbTotalLatency; size_t halfSize = fftSize / 2; if (!m_directMode) { ASSERT(totalDelay >= halfSize); if (totalDelay >= halfSize) totalDelay -= halfSize; } int maxPreDelayLength = std::min(halfSize, totalDelay); m_preDelayLength = totalDelay > 0 ? renderPhase % maxPreDelayLength : 0; if (m_preDelayLength > totalDelay) m_preDelayLength = 0; m_postDelayLength = totalDelay - m_preDelayLength; m_preReadWriteIndex = 0; m_framesProcessed = 0; // total frames processed so far size_t delayBufferSize = m_preDelayLength < fftSize ? fftSize : m_preDelayLength; delayBufferSize = delayBufferSize < renderSliceSize ? renderSliceSize : delayBufferSize; m_preDelayBuffer.allocate(delayBufferSize); } Commit Message: Don't read past the end of the impulseResponse array BUG=281480 Review URL: https://chromiumcodereview.appspot.com/23689004 git-svn-id: svn://svn.chromium.org/blink/trunk@157007 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
ReverbConvolverStage::ReverbConvolverStage(const float* impulseResponse, size_t, size_t reverbTotalLatency, size_t stageOffset, size_t stageLength, size_t fftSize, size_t renderPhase, size_t renderSliceSize, ReverbAccumulationBuffer* accumulationBuffer, bool directMode) : m_accumulationBuffer(accumulationBuffer) , m_accumulationReadIndex(0) , m_inputReadIndex(0) , m_directMode(directMode) { ASSERT(impulseResponse); ASSERT(accumulationBuffer); if (!m_directMode) { m_fftKernel = adoptPtr(new FFTFrame(fftSize)); m_fftKernel->doPaddedFFT(impulseResponse + stageOffset, stageLength); m_fftConvolver = adoptPtr(new FFTConvolver(fftSize)); } else { ASSERT(!stageOffset); ASSERT(stageLength <= fftSize / 2); m_directKernel = adoptPtr(new AudioFloatArray(fftSize / 2)); m_directKernel->copyToRange(impulseResponse, 0, stageLength); m_directConvolver = adoptPtr(new DirectConvolver(renderSliceSize)); } m_temporaryBuffer.allocate(renderSliceSize); size_t totalDelay = stageOffset + reverbTotalLatency; size_t halfSize = fftSize / 2; if (!m_directMode) { ASSERT(totalDelay >= halfSize); if (totalDelay >= halfSize) totalDelay -= halfSize; } int maxPreDelayLength = std::min(halfSize, totalDelay); m_preDelayLength = totalDelay > 0 ? renderPhase % maxPreDelayLength : 0; if (m_preDelayLength > totalDelay) m_preDelayLength = 0; m_postDelayLength = totalDelay - m_preDelayLength; m_preReadWriteIndex = 0; m_framesProcessed = 0; // total frames processed so far size_t delayBufferSize = m_preDelayLength < fftSize ? fftSize : m_preDelayLength; delayBufferSize = delayBufferSize < renderSliceSize ? renderSliceSize : delayBufferSize; m_preDelayBuffer.allocate(delayBufferSize); }
171,191
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BackendIO::ExecuteBackendOperation() { switch (operation_) { case OP_INIT: result_ = backend_->SyncInit(); break; case OP_OPEN: { scoped_refptr<EntryImpl> entry; result_ = backend_->SyncOpenEntry(key_, &entry); *entry_ptr_ = LeakEntryImpl(std::move(entry)); break; } case OP_CREATE: { scoped_refptr<EntryImpl> entry; result_ = backend_->SyncCreateEntry(key_, &entry); *entry_ptr_ = LeakEntryImpl(std::move(entry)); break; } case OP_DOOM: result_ = backend_->SyncDoomEntry(key_); break; case OP_DOOM_ALL: result_ = backend_->SyncDoomAllEntries(); break; case OP_DOOM_BETWEEN: result_ = backend_->SyncDoomEntriesBetween(initial_time_, end_time_); break; case OP_DOOM_SINCE: result_ = backend_->SyncDoomEntriesSince(initial_time_); break; case OP_SIZE_ALL: result_ = backend_->SyncCalculateSizeOfAllEntries(); break; case OP_OPEN_NEXT: { scoped_refptr<EntryImpl> entry; result_ = backend_->SyncOpenNextEntry(iterator_, &entry); *entry_ptr_ = LeakEntryImpl(std::move(entry)); break; } case OP_END_ENUMERATION: backend_->SyncEndEnumeration(std::move(scoped_iterator_)); result_ = net::OK; break; case OP_ON_EXTERNAL_CACHE_HIT: backend_->SyncOnExternalCacheHit(key_); result_ = net::OK; break; case OP_CLOSE_ENTRY: entry_->Release(); result_ = net::OK; break; case OP_DOOM_ENTRY: entry_->DoomImpl(); result_ = net::OK; break; case OP_FLUSH_QUEUE: result_ = net::OK; break; case OP_RUN_TASK: task_.Run(); result_ = net::OK; break; default: NOTREACHED() << "Invalid Operation"; result_ = net::ERR_UNEXPECTED; } DCHECK_NE(net::ERR_IO_PENDING, result_); NotifyController(); } Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem Thanks to nedwilliamson@ (on gmail) for an alternative perspective plus a reduction to make fixing this much easier. Bug: 826626, 518908, 537063, 802886 Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f Reviewed-on: https://chromium-review.googlesource.com/985052 Reviewed-by: Matt Menke <[email protected]> Commit-Queue: Maks Orlovich <[email protected]> Cr-Commit-Position: refs/heads/master@{#547103} CWE ID: CWE-20
void BackendIO::ExecuteBackendOperation() { switch (operation_) { case OP_INIT: result_ = backend_->SyncInit(); break; case OP_OPEN: { scoped_refptr<EntryImpl> entry; result_ = backend_->SyncOpenEntry(key_, &entry); *entry_ptr_ = LeakEntryImpl(std::move(entry)); break; } case OP_CREATE: { scoped_refptr<EntryImpl> entry; result_ = backend_->SyncCreateEntry(key_, &entry); *entry_ptr_ = LeakEntryImpl(std::move(entry)); break; } case OP_DOOM: result_ = backend_->SyncDoomEntry(key_); break; case OP_DOOM_ALL: result_ = backend_->SyncDoomAllEntries(); break; case OP_DOOM_BETWEEN: result_ = backend_->SyncDoomEntriesBetween(initial_time_, end_time_); break; case OP_DOOM_SINCE: result_ = backend_->SyncDoomEntriesSince(initial_time_); break; case OP_SIZE_ALL: result_ = backend_->SyncCalculateSizeOfAllEntries(); break; case OP_OPEN_NEXT: { scoped_refptr<EntryImpl> entry; result_ = backend_->SyncOpenNextEntry(iterator_, &entry); *entry_ptr_ = LeakEntryImpl(std::move(entry)); break; } case OP_END_ENUMERATION: backend_->SyncEndEnumeration(std::move(scoped_iterator_)); result_ = net::OK; break; case OP_ON_EXTERNAL_CACHE_HIT: backend_->SyncOnExternalCacheHit(key_); result_ = net::OK; break; case OP_CLOSE_ENTRY: entry_->Release(); result_ = net::OK; break; case OP_DOOM_ENTRY: entry_->DoomImpl(); result_ = net::OK; break; case OP_FLUSH_QUEUE: result_ = net::OK; break; case OP_RUN_TASK: task_.Run(); result_ = net::OK; break; default: NOTREACHED() << "Invalid Operation"; result_ = net::ERR_UNEXPECTED; } DCHECK_NE(net::ERR_IO_PENDING, result_); NotifyController(); backend_->OnSyncBackendOpComplete(); }
172,699
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat) { struct file *file = kiocb->ki_filp; ssize_t ret = 0; switch (kiocb->ki_opcode) { case IOCB_CMD_PREAD: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf, kiocb->ki_left))) break; ret = security_file_permission(file, MAY_READ); if (unlikely(ret)) break; ret = aio_setup_single_vector(kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITE: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf, kiocb->ki_left))) break; ret = security_file_permission(file, MAY_WRITE); if (unlikely(ret)) break; ret = aio_setup_single_vector(kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PREADV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = security_file_permission(file, MAY_READ); if (unlikely(ret)) break; ret = aio_setup_vectored_rw(READ, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITEV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = security_file_permission(file, MAY_WRITE); if (unlikely(ret)) break; ret = aio_setup_vectored_rw(WRITE, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_FDSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fdsync; break; case IOCB_CMD_FSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fsync; break; default: dprintk("EINVAL: io_submit: no operation provided\n"); ret = -EINVAL; } if (!kiocb->ki_retry) return ret; return 0; } Commit Message: vfs: make AIO use the proper rw_verify_area() area helpers We had for some reason overlooked the AIO interface, and it didn't use the proper rw_verify_area() helper function that checks (for example) mandatory locking on the file, and that the size of the access doesn't cause us to overflow the provided offset limits etc. Instead, AIO did just the security_file_permission() thing (that rw_verify_area() also does) directly. This fixes it to do all the proper helper functions, which not only means that now mandatory file locking works with AIO too, we can actually remove lines of code. Reported-by: Manish Honap <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID:
static ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat) { struct file *file = kiocb->ki_filp; ssize_t ret = 0; switch (kiocb->ki_opcode) { case IOCB_CMD_PREAD: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf, kiocb->ki_left))) break; ret = aio_setup_single_vector(READ, file, kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITE: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf, kiocb->ki_left))) break; ret = aio_setup_single_vector(WRITE, file, kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PREADV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = aio_setup_vectored_rw(READ, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITEV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = aio_setup_vectored_rw(WRITE, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_FDSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fdsync; break; case IOCB_CMD_FSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fsync; break; default: dprintk("EINVAL: io_submit: no operation provided\n"); ret = -EINVAL; } if (!kiocb->ki_retry) return ret; return 0; }
167,611
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: config_monitor( config_tree *ptree ) { int_node *pfilegen_token; const char *filegen_string; const char *filegen_file; FILEGEN *filegen; filegen_node *my_node; attr_val *my_opts; int filegen_type; int filegen_flag; /* Set the statistics directory */ if (ptree->stats_dir) stats_config(STATS_STATSDIR, ptree->stats_dir); /* NOTE: * Calling filegen_get is brain dead. Doing a string * comparison to find the relavant filegen structure is * expensive. * * Through the parser, we already know which filegen is * being specified. Hence, we should either store a * pointer to the specified structure in the syntax tree * or an index into a filegen array. * * Need to change the filegen code to reflect the above. */ /* Turn on the specified statistics */ pfilegen_token = HEAD_PFIFO(ptree->stats_list); for (; pfilegen_token != NULL; pfilegen_token = pfilegen_token->link) { filegen_string = keyword(pfilegen_token->i); filegen = filegen_get(filegen_string); DPRINTF(4, ("enabling filegen for %s statistics '%s%s'\n", filegen_string, filegen->prefix, filegen->basename)); filegen->flag |= FGEN_FLAG_ENABLED; } /* Configure the statistics with the options */ my_node = HEAD_PFIFO(ptree->filegen_opts); for (; my_node != NULL; my_node = my_node->link) { filegen_file = keyword(my_node->filegen_token); filegen = filegen_get(filegen_file); /* Initialize the filegen variables to their pre-configuration states */ filegen_flag = filegen->flag; filegen_type = filegen->type; /* "filegen ... enabled" is the default (when filegen is used) */ filegen_flag |= FGEN_FLAG_ENABLED; my_opts = HEAD_PFIFO(my_node->options); for (; my_opts != NULL; my_opts = my_opts->link) { switch (my_opts->attr) { case T_File: filegen_file = my_opts->value.s; break; case T_Type: switch (my_opts->value.i) { default: NTP_INSIST(0); break; case T_None: filegen_type = FILEGEN_NONE; break; case T_Pid: filegen_type = FILEGEN_PID; break; case T_Day: filegen_type = FILEGEN_DAY; break; case T_Week: filegen_type = FILEGEN_WEEK; break; case T_Month: filegen_type = FILEGEN_MONTH; break; case T_Year: filegen_type = FILEGEN_YEAR; break; case T_Age: filegen_type = FILEGEN_AGE; break; } break; case T_Flag: switch (my_opts->value.i) { case T_Link: filegen_flag |= FGEN_FLAG_LINK; break; case T_Nolink: filegen_flag &= ~FGEN_FLAG_LINK; break; case T_Enable: filegen_flag |= FGEN_FLAG_ENABLED; break; case T_Disable: filegen_flag &= ~FGEN_FLAG_ENABLED; break; default: msyslog(LOG_ERR, "Unknown filegen flag token %d", my_opts->value.i); exit(1); } break; default: msyslog(LOG_ERR, "Unknown filegen option token %d", my_opts->attr); exit(1); } } filegen_config(filegen, filegen_file, filegen_type, filegen_flag); } } Commit Message: [Bug 1773] openssl not detected during ./configure. [Bug 1774] Segfaults if cryptostats enabled and built without OpenSSL. CWE ID: CWE-20
config_monitor( config_tree *ptree ) { int_node *pfilegen_token; const char *filegen_string; const char *filegen_file; FILEGEN *filegen; filegen_node *my_node; attr_val *my_opts; int filegen_type; int filegen_flag; /* Set the statistics directory */ if (ptree->stats_dir) stats_config(STATS_STATSDIR, ptree->stats_dir); /* NOTE: * Calling filegen_get is brain dead. Doing a string * comparison to find the relavant filegen structure is * expensive. * * Through the parser, we already know which filegen is * being specified. Hence, we should either store a * pointer to the specified structure in the syntax tree * or an index into a filegen array. * * Need to change the filegen code to reflect the above. */ /* Turn on the specified statistics */ pfilegen_token = HEAD_PFIFO(ptree->stats_list); for (; pfilegen_token != NULL; pfilegen_token = pfilegen_token->link) { filegen_string = keyword(pfilegen_token->i); filegen = filegen_get(filegen_string); if (NULL == filegen) { msyslog(LOG_ERR, "stats %s unrecognized", filegen_string); continue; } DPRINTF(4, ("enabling filegen for %s statistics '%s%s'\n", filegen_string, filegen->prefix, filegen->basename)); filegen->flag |= FGEN_FLAG_ENABLED; } /* Configure the statistics with the options */ my_node = HEAD_PFIFO(ptree->filegen_opts); for (; my_node != NULL; my_node = my_node->link) { filegen_file = keyword(my_node->filegen_token); filegen = filegen_get(filegen_file); if (NULL == filegen) { msyslog(LOG_ERR, "filegen category '%s' unrecognized", filegen_file); continue; } /* Initialize the filegen variables to their pre-configuration states */ filegen_flag = filegen->flag; filegen_type = filegen->type; /* "filegen ... enabled" is the default (when filegen is used) */ filegen_flag |= FGEN_FLAG_ENABLED; my_opts = HEAD_PFIFO(my_node->options); for (; my_opts != NULL; my_opts = my_opts->link) { switch (my_opts->attr) { case T_File: filegen_file = my_opts->value.s; break; case T_Type: switch (my_opts->value.i) { default: NTP_INSIST(0); break; case T_None: filegen_type = FILEGEN_NONE; break; case T_Pid: filegen_type = FILEGEN_PID; break; case T_Day: filegen_type = FILEGEN_DAY; break; case T_Week: filegen_type = FILEGEN_WEEK; break; case T_Month: filegen_type = FILEGEN_MONTH; break; case T_Year: filegen_type = FILEGEN_YEAR; break; case T_Age: filegen_type = FILEGEN_AGE; break; } break; case T_Flag: switch (my_opts->value.i) { case T_Link: filegen_flag |= FGEN_FLAG_LINK; break; case T_Nolink: filegen_flag &= ~FGEN_FLAG_LINK; break; case T_Enable: filegen_flag |= FGEN_FLAG_ENABLED; break; case T_Disable: filegen_flag &= ~FGEN_FLAG_ENABLED; break; default: msyslog(LOG_ERR, "Unknown filegen flag token %d", my_opts->value.i); exit(1); } break; default: msyslog(LOG_ERR, "Unknown filegen option token %d", my_opts->attr); exit(1); } } filegen_config(filegen, filegen_file, filegen_type, filegen_flag); } }
168,875
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void cJSON_Delete( cJSON *c ) { cJSON *next; while ( c ) { next = c->next; if ( ! ( c->type & cJSON_IsReference ) && c->child ) cJSON_Delete( c->child ); if ( ! ( c->type & cJSON_IsReference ) && c->valuestring ) cJSON_free( c->valuestring ); if ( c->string ) cJSON_free( c->string ); cJSON_free( c ); c = next; } } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
void cJSON_Delete( cJSON *c ) void cJSON_Delete(cJSON *c) { cJSON *next; while (c) { next=c->next; if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child); if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring); if (!(c->type&cJSON_StringIsConst) && c->string) cJSON_free(c->string); cJSON_free(c); c=next; } }
167,281
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct page *follow_pmd_mask(struct vm_area_struct *vma, unsigned long address, pud_t *pudp, unsigned int flags, struct follow_page_context *ctx) { pmd_t *pmd, pmdval; spinlock_t *ptl; struct page *page; struct mm_struct *mm = vma->vm_mm; pmd = pmd_offset(pudp, address); /* * The READ_ONCE() will stabilize the pmdval in a register or * on the stack so that it will stop changing under the code. */ pmdval = READ_ONCE(*pmd); if (pmd_none(pmdval)) return no_page_table(vma, flags); if (pmd_huge(pmdval) && vma->vm_flags & VM_HUGETLB) { page = follow_huge_pmd(mm, address, pmd, flags); if (page) return page; return no_page_table(vma, flags); } if (is_hugepd(__hugepd(pmd_val(pmdval)))) { page = follow_huge_pd(vma, address, __hugepd(pmd_val(pmdval)), flags, PMD_SHIFT); if (page) return page; return no_page_table(vma, flags); } retry: if (!pmd_present(pmdval)) { if (likely(!(flags & FOLL_MIGRATION))) return no_page_table(vma, flags); VM_BUG_ON(thp_migration_supported() && !is_pmd_migration_entry(pmdval)); if (is_pmd_migration_entry(pmdval)) pmd_migration_entry_wait(mm, pmd); pmdval = READ_ONCE(*pmd); /* * MADV_DONTNEED may convert the pmd to null because * mmap_sem is held in read mode */ if (pmd_none(pmdval)) return no_page_table(vma, flags); goto retry; } if (pmd_devmap(pmdval)) { ptl = pmd_lock(mm, pmd); page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap); spin_unlock(ptl); if (page) return page; } if (likely(!pmd_trans_huge(pmdval))) return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap); if ((flags & FOLL_NUMA) && pmd_protnone(pmdval)) return no_page_table(vma, flags); retry_locked: ptl = pmd_lock(mm, pmd); if (unlikely(pmd_none(*pmd))) { spin_unlock(ptl); return no_page_table(vma, flags); } if (unlikely(!pmd_present(*pmd))) { spin_unlock(ptl); if (likely(!(flags & FOLL_MIGRATION))) return no_page_table(vma, flags); pmd_migration_entry_wait(mm, pmd); goto retry_locked; } if (unlikely(!pmd_trans_huge(*pmd))) { spin_unlock(ptl); return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap); } if (flags & FOLL_SPLIT) { int ret; page = pmd_page(*pmd); if (is_huge_zero_page(page)) { spin_unlock(ptl); ret = 0; split_huge_pmd(vma, pmd, address); if (pmd_trans_unstable(pmd)) ret = -EBUSY; } else { get_page(page); spin_unlock(ptl); lock_page(page); ret = split_huge_page(page); unlock_page(page); put_page(page); if (pmd_none(*pmd)) return no_page_table(vma, flags); } return ret ? ERR_PTR(ret) : follow_page_pte(vma, address, pmd, flags, &ctx->pgmap); } page = follow_trans_huge_pmd(vma, address, pmd, flags); spin_unlock(ptl); ctx->page_mask = HPAGE_PMD_NR - 1; return page; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
static struct page *follow_pmd_mask(struct vm_area_struct *vma, unsigned long address, pud_t *pudp, unsigned int flags, struct follow_page_context *ctx) { pmd_t *pmd, pmdval; spinlock_t *ptl; struct page *page; struct mm_struct *mm = vma->vm_mm; pmd = pmd_offset(pudp, address); /* * The READ_ONCE() will stabilize the pmdval in a register or * on the stack so that it will stop changing under the code. */ pmdval = READ_ONCE(*pmd); if (pmd_none(pmdval)) return no_page_table(vma, flags); if (pmd_huge(pmdval) && vma->vm_flags & VM_HUGETLB) { page = follow_huge_pmd(mm, address, pmd, flags); if (page) return page; return no_page_table(vma, flags); } if (is_hugepd(__hugepd(pmd_val(pmdval)))) { page = follow_huge_pd(vma, address, __hugepd(pmd_val(pmdval)), flags, PMD_SHIFT); if (page) return page; return no_page_table(vma, flags); } retry: if (!pmd_present(pmdval)) { if (likely(!(flags & FOLL_MIGRATION))) return no_page_table(vma, flags); VM_BUG_ON(thp_migration_supported() && !is_pmd_migration_entry(pmdval)); if (is_pmd_migration_entry(pmdval)) pmd_migration_entry_wait(mm, pmd); pmdval = READ_ONCE(*pmd); /* * MADV_DONTNEED may convert the pmd to null because * mmap_sem is held in read mode */ if (pmd_none(pmdval)) return no_page_table(vma, flags); goto retry; } if (pmd_devmap(pmdval)) { ptl = pmd_lock(mm, pmd); page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap); spin_unlock(ptl); if (page) return page; } if (likely(!pmd_trans_huge(pmdval))) return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap); if ((flags & FOLL_NUMA) && pmd_protnone(pmdval)) return no_page_table(vma, flags); retry_locked: ptl = pmd_lock(mm, pmd); if (unlikely(pmd_none(*pmd))) { spin_unlock(ptl); return no_page_table(vma, flags); } if (unlikely(!pmd_present(*pmd))) { spin_unlock(ptl); if (likely(!(flags & FOLL_MIGRATION))) return no_page_table(vma, flags); pmd_migration_entry_wait(mm, pmd); goto retry_locked; } if (unlikely(!pmd_trans_huge(*pmd))) { spin_unlock(ptl); return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap); } if (flags & FOLL_SPLIT) { int ret; page = pmd_page(*pmd); if (is_huge_zero_page(page)) { spin_unlock(ptl); ret = 0; split_huge_pmd(vma, pmd, address); if (pmd_trans_unstable(pmd)) ret = -EBUSY; } else { if (unlikely(!try_get_page(page))) { spin_unlock(ptl); return ERR_PTR(-ENOMEM); } spin_unlock(ptl); lock_page(page); ret = split_huge_page(page); unlock_page(page); put_page(page); if (pmd_none(*pmd)) return no_page_table(vma, flags); } return ret ? ERR_PTR(ret) : follow_page_pte(vma, address, pmd, flags, &ctx->pgmap); } page = follow_trans_huge_pmd(vma, address, pmd, flags); spin_unlock(ptl); ctx->page_mask = HPAGE_PMD_NR - 1; return page; }
170,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: wb_id(netdissect_options *ndo, const struct pkt_id *id, u_int len) { int i; const char *cp; const struct id_off *io; char c; int nid; ND_PRINT((ndo, " wb-id:")); if (len < sizeof(*id) || !ND_TTEST(*id)) return (-1); len -= sizeof(*id); ND_PRINT((ndo, " %u/%s:%u (max %u/%s:%u) ", EXTRACT_32BITS(&id->pi_ps.slot), ipaddr_string(ndo, &id->pi_ps.page.p_sid), EXTRACT_32BITS(&id->pi_ps.page.p_uid), EXTRACT_32BITS(&id->pi_mslot), ipaddr_string(ndo, &id->pi_mpage.p_sid), EXTRACT_32BITS(&id->pi_mpage.p_uid))); nid = EXTRACT_16BITS(&id->pi_ps.nid); len -= sizeof(*io) * nid; io = (struct id_off *)(id + 1); cp = (char *)(io + nid); if (!ND_TTEST2(cp, len)) { ND_PRINT((ndo, "\"")); fn_print(ndo, (u_char *)cp, (u_char *)cp + len); ND_PRINT((ndo, "\"")); } c = '<'; for (i = 0; i < nid && ND_TTEST(*io); ++io, ++i) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } if (i >= nid) { ND_PRINT((ndo, ">")); return (0); } return (-1); } Commit Message: whiteboard: fixup a few reversed tests (GH #446) This is a follow-up to commit 3a3ec26. CWE ID: CWE-20
wb_id(netdissect_options *ndo, const struct pkt_id *id, u_int len) { int i; const char *cp; const struct id_off *io; char c; int nid; ND_PRINT((ndo, " wb-id:")); if (len < sizeof(*id) || !ND_TTEST(*id)) return (-1); len -= sizeof(*id); ND_PRINT((ndo, " %u/%s:%u (max %u/%s:%u) ", EXTRACT_32BITS(&id->pi_ps.slot), ipaddr_string(ndo, &id->pi_ps.page.p_sid), EXTRACT_32BITS(&id->pi_ps.page.p_uid), EXTRACT_32BITS(&id->pi_mslot), ipaddr_string(ndo, &id->pi_mpage.p_sid), EXTRACT_32BITS(&id->pi_mpage.p_uid))); nid = EXTRACT_16BITS(&id->pi_ps.nid); len -= sizeof(*io) * nid; io = (struct id_off *)(id + 1); cp = (char *)(io + nid); if (ND_TTEST2(cp, len)) { ND_PRINT((ndo, "\"")); fn_print(ndo, (u_char *)cp, (u_char *)cp + len); ND_PRINT((ndo, "\"")); } c = '<'; for (i = 0; i < nid && ND_TTEST(*io); ++io, ++i) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } if (i >= nid) { ND_PRINT((ndo, ">")); return (0); } return (-1); }
168,892
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: LPSTR tr_esc_str(LPCSTR arg, bool format) { LPSTR tmp = NULL; size_t cs = 0, x, ds, len; size_t s; if (NULL == arg) return NULL; s = strlen(arg); /* Find trailing whitespaces */ while ((s > 0) && isspace(arg[s - 1])) s--; /* Prepare a initial buffer with the size of the result string. */ ds = s + 1; if (s) tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not allocate string buffer.\n"); exit(-2); } /* Copy character for character and check, if it is necessary to escape. */ memset(tmp, 0, ds * sizeof(CHAR)); for (x = 0; x < s; x++) { switch (arg[x]) { case '<': len = format ? 13 : 4; ds += len - 1; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-3); } if (format) /* coverity[buffer_size] */ strncpy(&tmp[cs], "<replaceable>", len); else /* coverity[buffer_size] */ strncpy(&tmp[cs], "&lt;", len); cs += len; break; case '>': len = format ? 14 : 4; ds += len - 1; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-4); } if (format) /* coverity[buffer_size] */ strncpy(&tmp[cs], "</replaceable>", len); else /* coverity[buffer_size] */ strncpy(&tmp[cs], "&lt;", len); cs += len; break; case '\'': ds += 5; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-5); } tmp[cs++] = '&'; tmp[cs++] = 'a'; tmp[cs++] = 'p'; tmp[cs++] = 'o'; tmp[cs++] = 's'; tmp[cs++] = ';'; break; case '"': ds += 5; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-6); } tmp[cs++] = '&'; tmp[cs++] = 'q'; tmp[cs++] = 'u'; tmp[cs++] = 'o'; tmp[cs++] = 't'; tmp[cs++] = ';'; break; case '&': ds += 4; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-7); } tmp[cs++] = '&'; tmp[cs++] = 'a'; tmp[cs++] = 'm'; tmp[cs++] = 'p'; tmp[cs++] = ';'; break; default: tmp[cs++] = arg[x]; break; } /* Assure, the string is '\0' terminated. */ tmp[ds - 1] = '\0'; } return tmp; } Commit Message: Fixed #5645: realloc return handling CWE ID: CWE-772
LPSTR tr_esc_str(LPCSTR arg, bool format) { LPSTR tmp = NULL; LPSTR tmp2 = NULL; size_t cs = 0, x, ds, len; size_t s; if (NULL == arg) return NULL; s = strlen(arg); /* Find trailing whitespaces */ while ((s > 0) && isspace(arg[s - 1])) s--; /* Prepare a initial buffer with the size of the result string. */ ds = s + 1; if (s) { tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; } if (NULL == tmp) { fprintf(stderr, "Could not allocate string buffer.\n"); exit(-2); } /* Copy character for character and check, if it is necessary to escape. */ memset(tmp, 0, ds * sizeof(CHAR)); for (x = 0; x < s; x++) { switch (arg[x]) { case '<': len = format ? 13 : 4; ds += len - 1; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-3); } if (format) /* coverity[buffer_size] */ strncpy(&tmp[cs], "<replaceable>", len); else /* coverity[buffer_size] */ strncpy(&tmp[cs], "&lt;", len); cs += len; break; case '>': len = format ? 14 : 4; ds += len - 1; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-4); } if (format) /* coverity[buffer_size] */ strncpy(&tmp[cs], "</replaceable>", len); else /* coverity[buffer_size] */ strncpy(&tmp[cs], "&lt;", len); cs += len; break; case '\'': ds += 5; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-5); } tmp[cs++] = '&'; tmp[cs++] = 'a'; tmp[cs++] = 'p'; tmp[cs++] = 'o'; tmp[cs++] = 's'; tmp[cs++] = ';'; break; case '"': ds += 5; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-6); } tmp[cs++] = '&'; tmp[cs++] = 'q'; tmp[cs++] = 'u'; tmp[cs++] = 'o'; tmp[cs++] = 't'; tmp[cs++] = ';'; break; case '&': ds += 4; tmp2 = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (!tmp2) free(tmp); tmp = tmp2; if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-7); } tmp[cs++] = '&'; tmp[cs++] = 'a'; tmp[cs++] = 'm'; tmp[cs++] = 'p'; tmp[cs++] = ';'; break; default: tmp[cs++] = arg[x]; break; } /* Assure, the string is '\0' terminated. */ tmp[ds - 1] = '\0'; } return tmp; }
169,495
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadICONImage(const ImageInfo *image_info, ExceptionInfo *exception) { IconFile icon_file; IconInfo icon_info; Image *image; MagickBooleanType status; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; size_t bit, byte, bytes_per_line, one, scanline_pad; ssize_t count, offset, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } icon_file.reserved=(short) ReadBlobLSBShort(image); icon_file.resource_type=(short) ReadBlobLSBShort(image); icon_file.count=(short) ReadBlobLSBShort(image); if ((icon_file.reserved != 0) || ((icon_file.resource_type != 1) && (icon_file.resource_type != 2)) || (icon_file.count > MaxIcons)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (i=0; i < icon_file.count; i++) { icon_file.directory[i].width=(unsigned char) ReadBlobByte(image); icon_file.directory[i].height=(unsigned char) ReadBlobByte(image); icon_file.directory[i].colors=(unsigned char) ReadBlobByte(image); icon_file.directory[i].reserved=(unsigned char) ReadBlobByte(image); icon_file.directory[i].planes=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].bits_per_pixel=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].size=ReadBlobLSBLong(image); icon_file.directory[i].offset=ReadBlobLSBLong(image); } one=1; for (i=0; i < icon_file.count; i++) { /* Verify Icon identifier. */ offset=(ssize_t) SeekBlob(image,(MagickOffsetType) icon_file.directory[i].offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.size=ReadBlobLSBLong(image); icon_info.width=(unsigned char) ((int) ReadBlobLSBLong(image)); icon_info.height=(unsigned char) ((int) ReadBlobLSBLong(image)/2); icon_info.planes=ReadBlobLSBShort(image); icon_info.bits_per_pixel=ReadBlobLSBShort(image); if (((icon_info.planes == 18505) && (icon_info.bits_per_pixel == 21060)) || (icon_info.size == 0x474e5089)) { Image *icon_image; ImageInfo *read_info; size_t length; unsigned char *png; /* Icon image encoded as a compressed PNG image. */ length=icon_file.directory[i].size; png=(unsigned char *) AcquireQuantumMemory(length+16,sizeof(*png)); if (png == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickMemory(png,"\211PNG\r\n\032\n\000\000\000\015",12); png[12]=(unsigned char) icon_info.planes; png[13]=(unsigned char) (icon_info.planes >> 8); png[14]=(unsigned char) icon_info.bits_per_pixel; png[15]=(unsigned char) (icon_info.bits_per_pixel >> 8); count=ReadBlob(image,length-16,png+16); icon_image=(Image *) NULL; if (count > 0) { read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->magick,"PNG",MaxTextExtent); icon_image=BlobToImage(read_info,png,length+16,exception); read_info=DestroyImageInfo(read_info); } png=(unsigned char *) RelinquishMagickMemory(png); if (icon_image == (Image *) NULL) { if (count != (ssize_t) (length-16)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); image=DestroyImageList(image); return((Image *) NULL); } DestroyBlob(icon_image); icon_image->blob=ReferenceBlob(image->blob); ReplaceImageInList(&image,icon_image); icon_image->scene=i; } else { if (icon_info.bits_per_pixel > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.compression=ReadBlobLSBLong(image); icon_info.image_size=ReadBlobLSBLong(image); icon_info.x_pixels=ReadBlobLSBLong(image); icon_info.y_pixels=ReadBlobLSBLong(image); icon_info.number_colors=ReadBlobLSBLong(image); icon_info.colors_important=ReadBlobLSBLong(image); image->matte=MagickTrue; image->columns=(size_t) icon_file.directory[i].width; if ((ssize_t) image->columns > icon_info.width) image->columns=(size_t) icon_info.width; if (image->columns == 0) image->columns=256; image->rows=(size_t) icon_file.directory[i].height; if ((ssize_t) image->rows > icon_info.height) image->rows=(size_t) icon_info.height; if (image->rows == 0) image->rows=256; image->depth=icon_info.bits_per_pixel; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene = %.20g",(double) i); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " size = %.20g",(double) icon_info.size); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width = %.20g",(double) icon_file.directory[i].width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height = %.20g",(double) icon_file.directory[i].height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " colors = %.20g",(double ) icon_info.number_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " planes = %.20g",(double) icon_info.planes); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bpp = %.20g",(double) icon_info.bits_per_pixel); } if ((icon_info.number_colors != 0) || (icon_info.bits_per_pixel <= 16U)) { image->storage_class=PseudoClass; image->colors=icon_info.number_colors; if (image->colors == 0) image->colors=one << icon_info.bits_per_pixel; } if (image->storage_class == PseudoClass) { register ssize_t i; unsigned char *icon_colormap; /* Read Icon raster colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4UL*sizeof(*icon_colormap)); if (icon_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) (4*image->colors),icon_colormap); if (count != (ssize_t) (4*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=icon_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].green=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].red=(Quantum) ScaleCharToQuantum(*p++); p++; } icon_colormap=(unsigned char *) RelinquishMagickMemory(icon_colormap); } /* Convert Icon raster image to pixel packets. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) & ~31) >> 3; (void) bytes_per_line; scanline_pad=((((image->columns*icon_info.bits_per_pixel)+31) & ~31)- (image->columns*icon_info.bits_per_pixel)) >> 3; switch (icon_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00)); } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00)); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 4: { /* Read 4-bit Icon scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(indexes+x,((byte >> 4) & 0xf)); SetPixelIndex(indexes+x+1,((byte) & 0xf)); } if ((image->columns % 2) != 0) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(indexes+x,((byte >> 4) & 0xf)); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(indexes+x,byte); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); byte|=(size_t) (ReadBlobByte(image) << 8); SetPixelIndex(indexes+x,byte); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 24: case 32: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); if (icon_info.bits_per_pixel == 32) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); q++; } if (icon_info.bits_per_pixel == 24) for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (image_info->ping == MagickFalse) (void) SyncImage(image); if (icon_info.bits_per_pixel != 32) { /* Read the ICON alpha mask. */ image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ? TransparentOpacity : OpaqueOpacity)); } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ? TransparentOpacity : OpaqueOpacity)); } if ((image->columns % 32) != 0) for (x=0; x < (ssize_t) ((32-(image->columns % 32))/8); x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (i < (ssize_t) (icon_file.count-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadICONImage(const ImageInfo *image_info, ExceptionInfo *exception) { IconFile icon_file; IconInfo icon_info; Image *image; MagickBooleanType status; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; size_t bit, byte, bytes_per_line, one, scanline_pad; ssize_t count, offset, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } icon_file.reserved=(short) ReadBlobLSBShort(image); icon_file.resource_type=(short) ReadBlobLSBShort(image); icon_file.count=(short) ReadBlobLSBShort(image); if ((icon_file.reserved != 0) || ((icon_file.resource_type != 1) && (icon_file.resource_type != 2)) || (icon_file.count > MaxIcons)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (i=0; i < icon_file.count; i++) { icon_file.directory[i].width=(unsigned char) ReadBlobByte(image); icon_file.directory[i].height=(unsigned char) ReadBlobByte(image); icon_file.directory[i].colors=(unsigned char) ReadBlobByte(image); icon_file.directory[i].reserved=(unsigned char) ReadBlobByte(image); icon_file.directory[i].planes=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].bits_per_pixel=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].size=ReadBlobLSBLong(image); icon_file.directory[i].offset=ReadBlobLSBLong(image); } one=1; for (i=0; i < icon_file.count; i++) { /* Verify Icon identifier. */ offset=(ssize_t) SeekBlob(image,(MagickOffsetType) icon_file.directory[i].offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.size=ReadBlobLSBLong(image); icon_info.width=(unsigned char) ((int) ReadBlobLSBLong(image)); icon_info.height=(unsigned char) ((int) ReadBlobLSBLong(image)/2); icon_info.planes=ReadBlobLSBShort(image); icon_info.bits_per_pixel=ReadBlobLSBShort(image); if (((icon_info.planes == 18505) && (icon_info.bits_per_pixel == 21060)) || (icon_info.size == 0x474e5089)) { Image *icon_image; ImageInfo *read_info; size_t length; unsigned char *png; /* Icon image encoded as a compressed PNG image. */ length=icon_file.directory[i].size; png=(unsigned char *) AcquireQuantumMemory(length+16,sizeof(*png)); if (png == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickMemory(png,"\211PNG\r\n\032\n\000\000\000\015",12); png[12]=(unsigned char) icon_info.planes; png[13]=(unsigned char) (icon_info.planes >> 8); png[14]=(unsigned char) icon_info.bits_per_pixel; png[15]=(unsigned char) (icon_info.bits_per_pixel >> 8); count=ReadBlob(image,length-16,png+16); icon_image=(Image *) NULL; if (count > 0) { read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->magick,"PNG",MaxTextExtent); icon_image=BlobToImage(read_info,png,length+16,exception); read_info=DestroyImageInfo(read_info); } png=(unsigned char *) RelinquishMagickMemory(png); if (icon_image == (Image *) NULL) { if (count != (ssize_t) (length-16)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); image=DestroyImageList(image); return((Image *) NULL); } DestroyBlob(icon_image); icon_image->blob=ReferenceBlob(image->blob); ReplaceImageInList(&image,icon_image); icon_image->scene=i; } else { if (icon_info.bits_per_pixel > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.compression=ReadBlobLSBLong(image); icon_info.image_size=ReadBlobLSBLong(image); icon_info.x_pixels=ReadBlobLSBLong(image); icon_info.y_pixels=ReadBlobLSBLong(image); icon_info.number_colors=ReadBlobLSBLong(image); icon_info.colors_important=ReadBlobLSBLong(image); image->matte=MagickTrue; image->columns=(size_t) icon_file.directory[i].width; if ((ssize_t) image->columns > icon_info.width) image->columns=(size_t) icon_info.width; if (image->columns == 0) image->columns=256; image->rows=(size_t) icon_file.directory[i].height; if ((ssize_t) image->rows > icon_info.height) image->rows=(size_t) icon_info.height; if (image->rows == 0) image->rows=256; image->depth=icon_info.bits_per_pixel; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene = %.20g",(double) i); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " size = %.20g",(double) icon_info.size); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width = %.20g",(double) icon_file.directory[i].width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height = %.20g",(double) icon_file.directory[i].height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " colors = %.20g",(double ) icon_info.number_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " planes = %.20g",(double) icon_info.planes); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bpp = %.20g",(double) icon_info.bits_per_pixel); } if ((icon_info.number_colors != 0) || (icon_info.bits_per_pixel <= 16U)) { image->storage_class=PseudoClass; image->colors=icon_info.number_colors; if (image->colors == 0) image->colors=one << icon_info.bits_per_pixel; } if (image->storage_class == PseudoClass) { register ssize_t i; unsigned char *icon_colormap; /* Read Icon raster colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4UL*sizeof(*icon_colormap)); if (icon_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) (4*image->colors),icon_colormap); if (count != (ssize_t) (4*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=icon_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].green=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].red=(Quantum) ScaleCharToQuantum(*p++); p++; } icon_colormap=(unsigned char *) RelinquishMagickMemory(icon_colormap); } /* Convert Icon raster image to pixel packets. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) & ~31) >> 3; (void) bytes_per_line; scanline_pad=((((image->columns*icon_info.bits_per_pixel)+31) & ~31)- (image->columns*icon_info.bits_per_pixel)) >> 3; switch (icon_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00)); } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00)); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 4: { /* Read 4-bit Icon scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(indexes+x,((byte >> 4) & 0xf)); SetPixelIndex(indexes+x+1,((byte) & 0xf)); } if ((image->columns % 2) != 0) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(indexes+x,((byte >> 4) & 0xf)); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(indexes+x,byte); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); byte|=(size_t) (ReadBlobByte(image) << 8); SetPixelIndex(indexes+x,byte); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 24: case 32: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); if (icon_info.bits_per_pixel == 32) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); q++; } if (icon_info.bits_per_pixel == 24) for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (image_info->ping == MagickFalse) (void) SyncImage(image); if (icon_info.bits_per_pixel != 32) { /* Read the ICON alpha mask. */ image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ? TransparentOpacity : OpaqueOpacity)); } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ? TransparentOpacity : OpaqueOpacity)); } if ((image->columns % 32) != 0) for (x=0; x < (ssize_t) ((32-(image->columns % 32))/8); x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (i < (ssize_t) (icon_file.count-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,572
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _PUBLIC_ codepoint_t next_codepoint_handle_ext( struct smb_iconv_handle *ic, const char *str, charset_t src_charset, size_t *bytes_consumed) { /* it cannot occupy more than 4 bytes in UTF16 format */ smb_iconv_t descriptor; size_t ilen_orig; size_t ilen; size_t olen; char *outbuf; if ((str[0] & 0x80) == 0) { *bytes_consumed = 1; return (codepoint_t)str[0]; } /* * we assume that no multi-byte character can take more than 5 bytes. * we assume that no multi-byte character can take more than 5 bytes. * This is OK as we only support codepoints up to 1M (U+100000) */ ilen_orig = strnlen(str, 5); ilen = ilen_orig; descriptor = get_conv_handle(ic, src_charset, CH_UTF16); *bytes_consumed = 1; return INVALID_CODEPOINT; } Commit Message: CWE ID: CWE-200
_PUBLIC_ codepoint_t next_codepoint_handle_ext( struct smb_iconv_handle *ic, const char *str, size_t len, charset_t src_charset, size_t *bytes_consumed) { /* it cannot occupy more than 4 bytes in UTF16 format */ smb_iconv_t descriptor; size_t ilen_orig; size_t ilen; size_t olen; char *outbuf; if ((str[0] & 0x80) == 0) { *bytes_consumed = 1; return (codepoint_t)str[0]; } /* * we assume that no multi-byte character can take more than 5 bytes. * we assume that no multi-byte character can take more than 5 bytes. * This is OK as we only support codepoints up to 1M (U+100000) */ ilen_orig = MIN(len, 5); ilen = ilen_orig; descriptor = get_conv_handle(ic, src_charset, CH_UTF16); *bytes_consumed = 1; return INVALID_CODEPOINT; }
164,670
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MockRenderThread::AddRoute(int32 routing_id, IPC::Channel::Listener* listener) { EXPECT_EQ(routing_id_, routing_id); widget_ = listener; } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void MockRenderThread::AddRoute(int32 routing_id, IPC::Channel::Listener* listener) { // We may hear this for views created from OnMsgCreateWindow as well, // in which case we don't want to track the new widget. if (routing_id_ == routing_id) widget_ = listener; }
171,021
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jbig2_sd_list_referred(Jbig2Ctx *ctx, Jbig2Segment *segment) { int index; Jbig2Segment *rsegment; Jbig2SymbolDict **dicts; int n_dicts = jbig2_sd_count_referred(ctx, segment); int dindex = 0; dicts = jbig2_new(ctx, Jbig2SymbolDict *, n_dicts); if (dicts == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate referred list of symbol dictionaries"); return NULL; } for (index = 0; index < segment->referred_to_segment_count; index++) { rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]); if (rsegment && ((rsegment->flags & 63) == 0) && rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL)) { /* add this referred to symbol dictionary */ dicts[dindex++] = (Jbig2SymbolDict *) rsegment->result; } } if (dindex != n_dicts) { /* should never happen */ jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "counted %d symbol dictionaries but built a list with %d.\n", n_dicts, dindex); } return (dicts); } Commit Message: CWE ID: CWE-119
jbig2_sd_list_referred(Jbig2Ctx *ctx, Jbig2Segment *segment) { int index; Jbig2Segment *rsegment; Jbig2SymbolDict **dicts; uint32_t n_dicts = jbig2_sd_count_referred(ctx, segment); uint32_t dindex = 0; dicts = jbig2_new(ctx, Jbig2SymbolDict *, n_dicts); if (dicts == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate referred list of symbol dictionaries"); return NULL; } for (index = 0; index < segment->referred_to_segment_count; index++) { rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]); if (rsegment && ((rsegment->flags & 63) == 0) && rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL)) { /* add this referred to symbol dictionary */ dicts[dindex++] = (Jbig2SymbolDict *) rsegment->result; } } if (dindex != n_dicts) { /* should never happen */ jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "counted %d symbol dictionaries but built a list with %d.\n", n_dicts, dindex); } return (dicts); }
165,501
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { int fmtid; int id; char *infile; jas_stream_t *instream; jas_image_t *image; int width; int height; int depth; int numcmpts; int verbose; char *fmtname; int debug; size_t max_mem; if (jas_init()) { abort(); } cmdname = argv[0]; infile = 0; verbose = 0; debug = 0; #if defined(JAS_DEFAULT_MAX_MEM_USAGE) max_mem = JAS_DEFAULT_MAX_MEM_USAGE; #endif /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_VERBOSE: verbose = 1; break; case OPT_VERSION: printf("%s\n", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_DEBUG: debug = atoi(jas_optarg); break; case OPT_INFILE: infile = jas_optarg; break; case OPT_MAXMEM: max_mem = strtoull(jas_optarg, 0, 10); break; case OPT_HELP: default: usage(); break; } } jas_setdbglevel(debug); #if defined(JAS_DEFAULT_MAX_MEM_USAGE) jas_set_max_mem_usage(max_mem); #endif /* Open the image file. */ if (infile) { /* The image is to be read from a file. */ if (!(instream = jas_stream_fopen(infile, "rb"))) { fprintf(stderr, "cannot open input image file %s\n", infile); exit(EXIT_FAILURE); } } else { /* The image is to be read from standard input. */ if (!(instream = jas_stream_fdopen(0, "rb"))) { fprintf(stderr, "cannot open standard input\n"); exit(EXIT_FAILURE); } } if ((fmtid = jas_image_getfmt(instream)) < 0) { fprintf(stderr, "unknown image format\n"); } /* Decode the image. */ if (!(image = jas_image_decode(instream, fmtid, 0))) { jas_stream_close(instream); fprintf(stderr, "cannot load image\n"); return EXIT_FAILURE; } /* Close the image file. */ jas_stream_close(instream); if (!(numcmpts = jas_image_numcmpts(image))) { fprintf(stderr, "warning: image has no components\n"); } if (numcmpts) { width = jas_image_cmptwidth(image, 0); height = jas_image_cmptheight(image, 0); depth = jas_image_cmptprec(image, 0); } else { width = 0; height = 0; depth = 0; } if (!(fmtname = jas_image_fmttostr(fmtid))) { abort(); } printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image)); jas_image_destroy(image); jas_image_clearfmts(); return EXIT_SUCCESS; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
int main(int argc, char **argv) { int fmtid; int id; char *infile; jas_stream_t *instream; jas_image_t *image; int width; int height; int depth; int numcmpts; int verbose; char *fmtname; int debug; size_t max_mem; size_t max_samples; char optstr[32]; if (jas_init()) { abort(); } cmdname = argv[0]; max_samples = 64 * JAS_MEBI; infile = 0; verbose = 0; debug = 0; #if defined(JAS_DEFAULT_MAX_MEM_USAGE) max_mem = JAS_DEFAULT_MAX_MEM_USAGE; #endif /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_VERBOSE: verbose = 1; break; case OPT_VERSION: printf("%s\n", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_DEBUG: debug = atoi(jas_optarg); break; case OPT_INFILE: infile = jas_optarg; break; case OPT_MAXSAMPLES: max_samples = strtoull(jas_optarg, 0, 10); break; case OPT_MAXMEM: max_mem = strtoull(jas_optarg, 0, 10); break; case OPT_HELP: default: usage(); break; } } jas_setdbglevel(debug); #if defined(JAS_DEFAULT_MAX_MEM_USAGE) jas_set_max_mem_usage(max_mem); #endif /* Open the image file. */ if (infile) { /* The image is to be read from a file. */ if (!(instream = jas_stream_fopen(infile, "rb"))) { fprintf(stderr, "cannot open input image file %s\n", infile); exit(EXIT_FAILURE); } } else { /* The image is to be read from standard input. */ if (!(instream = jas_stream_fdopen(0, "rb"))) { fprintf(stderr, "cannot open standard input\n"); exit(EXIT_FAILURE); } } if ((fmtid = jas_image_getfmt(instream)) < 0) { fprintf(stderr, "unknown image format\n"); } snprintf(optstr, sizeof(optstr), "max_samples=%-zu", max_samples); /* Decode the image. */ if (!(image = jas_image_decode(instream, fmtid, optstr))) { jas_stream_close(instream); fprintf(stderr, "cannot load image\n"); return EXIT_FAILURE; } /* Close the image file. */ jas_stream_close(instream); if (!(fmtname = jas_image_fmttostr(fmtid))) { jas_eprintf("format name lookup failed\n"); return EXIT_FAILURE; } if (!(numcmpts = jas_image_numcmpts(image))) { fprintf(stderr, "warning: image has no components\n"); } if (numcmpts) { width = jas_image_cmptwidth(image, 0); height = jas_image_cmptheight(image, 0); depth = jas_image_cmptprec(image, 0); } else { width = 0; height = 0; depth = 0; } printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, JAS_CAST(long, jas_image_rawsize(image))); jas_image_destroy(image); jas_image_clearfmts(); return EXIT_SUCCESS; }
168,681
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothDeviceChromeOS::DisplayPinCode( const dbus::ObjectPath& device_path, const std::string& pincode) { DCHECK(agent_.get()); DCHECK(device_path == object_path_); VLOG(1) << object_path_.value() << ": DisplayPinCode: " << pincode; UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_DISPLAY_PINCODE, UMA_PAIRING_METHOD_COUNT); DCHECK(pairing_delegate_); pairing_delegate_->DisplayPinCode(this, pincode); pairing_delegate_used_ = true; } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::DisplayPinCode(
171,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bgp_attr_print(netdissect_options *ndo, u_int atype, const u_char *pptr, u_int len) { int i; uint16_t af; uint8_t safi, snpa, nhlen; union { /* copy buffer for bandwidth values */ float f; uint32_t i; } bw; int advance; u_int tlen; const u_char *tptr; char buf[MAXHOSTNAMELEN + 100]; int as_size; tptr = pptr; tlen=len; switch (atype) { case BGPTYPE_ORIGIN: if (len != 1) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK(*tptr); ND_PRINT((ndo, "%s", tok2str(bgp_origin_values, "Unknown Origin Typecode", tptr[0]))); } break; /* * Process AS4 byte path and AS2 byte path attributes here. */ case BGPTYPE_AS4_PATH: case BGPTYPE_AS_PATH: if (len % 2) { ND_PRINT((ndo, "invalid len")); break; } if (!len) { ND_PRINT((ndo, "empty")); break; } /* * BGP updates exchanged between New speakers that support 4 * byte AS, ASs are always encoded in 4 bytes. There is no * definitive way to find this, just by the packet's * contents. So, check for packet's TLV's sanity assuming * 2 bytes first, and it does not pass, assume that ASs are * encoded in 4 bytes format and move on. */ as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); while (tptr < pptr + len) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); for (i = 0; i < tptr[1] * as_size; i += as_size) { ND_TCHECK2(tptr[2 + i], as_size); ND_PRINT((ndo, "%s ", as_printf(ndo, astostr, sizeof(astostr), as_size == 2 ? EXTRACT_16BITS(&tptr[2 + i]) : EXTRACT_32BITS(&tptr[2 + i])))); } ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * as_size; } break; case BGPTYPE_NEXT_HOP: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); } break; case BGPTYPE_MULTI_EXIT_DISC: case BGPTYPE_LOCAL_PREF: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr))); } break; case BGPTYPE_ATOMIC_AGGREGATE: if (len != 0) ND_PRINT((ndo, "invalid len")); break; case BGPTYPE_AGGREGATOR: /* * Depending on the AS encoded is of 2 bytes or of 4 bytes, * the length of this PA can be either 6 bytes or 8 bytes. */ if (len != 6 && len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], len); if (len == 6) { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), ipaddr_string(ndo, tptr + 2))); } else { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); } break; case BGPTYPE_AGGREGATOR4: if (len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); break; case BGPTYPE_COMMUNITIES: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint32_t comm; ND_TCHECK2(tptr[0], 4); comm = EXTRACT_32BITS(tptr); switch (comm) { case BGP_COMMUNITY_NO_EXPORT: ND_PRINT((ndo, " NO_EXPORT")); break; case BGP_COMMUNITY_NO_ADVERT: ND_PRINT((ndo, " NO_ADVERTISE")); break; case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: ND_PRINT((ndo, " NO_EXPORT_SUBCONFED")); break; default: ND_PRINT((ndo, "%u:%u%s", (comm >> 16) & 0xffff, comm & 0xffff, (tlen>4) ? ", " : "")); break; } tlen -=4; tptr +=4; } break; case BGPTYPE_ORIGINATOR_ID: if (len != 4) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); break; case BGPTYPE_CLUSTER_LIST: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s%s", ipaddr_string(ndo, tptr), (tlen>4) ? ", " : "")); tlen -=4; tptr +=4; } break; case BGPTYPE_MP_REACH_NLRI: ND_TCHECK2(tptr[0], 3); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_VPLS<<8 | SAFNUM_VPLS): break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); goto done; break; } tptr +=3; ND_TCHECK(tptr[0]); nhlen = tptr[0]; tlen = nhlen; tptr++; if (tlen) { int nnh = 0; ND_PRINT((ndo, "\n\t nexthop: ")); while (tlen > 0) { if ( nnh++ > 0 ) { ND_PRINT((ndo, ", " )); } switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); tlen -= sizeof(struct in_addr); tptr += sizeof(struct in_addr); } break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): if (tlen < (int)sizeof(struct in6_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr))); tlen -= sizeof(struct in6_addr); tptr += sizeof(struct in6_addr); } break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); tlen -= (sizeof(struct in_addr)); tptr += (sizeof(struct in_addr)); } break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen))); tptr += tlen; tlen = 0; break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < BGP_VPN_RD_LEN+1) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); /* rfc986 mapped IPv4 address ? */ if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); /* rfc1888 mapped IPv6 address ? */ else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); tptr += tlen; tlen = 0; } break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); tptr += tlen; tlen = 0; goto done; break; } } } ND_PRINT((ndo, ", nh-length: %u", nhlen)); tptr += tlen; ND_TCHECK(tptr[0]); snpa = tptr[0]; tptr++; if (snpa) { ND_PRINT((ndo, "\n\t %u SNPA", snpa)); for (/*nothing*/; snpa > 0; snpa--) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "\n\t %d bytes", tptr[0])); tptr += tptr[0] + 1; } } else { ND_PRINT((ndo, ", no SNPA")); } while (tptr < pptr + len) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*tptr,tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } done: break; case BGPTYPE_MP_UNREACH_NLRI: ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); if (len == BGP_MP_NLRI_MINSIZE) ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); tptr += 3; while (tptr < pptr + len) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*(tptr-3),tlen); ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr-3, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } break; case BGPTYPE_EXTD_COMMUNITIES: if (len % 8) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint16_t extd_comm; ND_TCHECK2(tptr[0], 2); extd_comm=EXTRACT_16BITS(tptr); ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]", tok2str(bgp_extd_comm_subtype_values, "unknown extd community typecode", extd_comm), extd_comm, bittok2str(bgp_extd_comm_flag_values, "none", extd_comm))); ND_TCHECK2(*(tptr+2), 6); switch(extd_comm) { case BGP_EXT_COM_RT_0: case BGP_EXT_COM_RO_0: case BGP_EXT_COM_L2VPN_RT_0: ND_PRINT((ndo, ": %u:%u (= %s)", EXTRACT_16BITS(tptr+2), EXTRACT_32BITS(tptr+4), ipaddr_string(ndo, tptr+4))); break; case BGP_EXT_COM_RT_1: case BGP_EXT_COM_RO_1: case BGP_EXT_COM_L2VPN_RT_1: case BGP_EXT_COM_VRF_RT_IMP: ND_PRINT((ndo, ": %s:%u", ipaddr_string(ndo, tptr+2), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_RT_2: case BGP_EXT_COM_RO_2: ND_PRINT((ndo, ": %s:%u", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_LINKBAND: bw.i = EXTRACT_32BITS(tptr+2); ND_PRINT((ndo, ": bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case BGP_EXT_COM_VPN_ORIGIN: case BGP_EXT_COM_VPN_ORIGIN2: case BGP_EXT_COM_VPN_ORIGIN3: case BGP_EXT_COM_VPN_ORIGIN4: case BGP_EXT_COM_OSPF_RID: case BGP_EXT_COM_OSPF_RID2: ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2))); break; case BGP_EXT_COM_OSPF_RTYPE: case BGP_EXT_COM_OSPF_RTYPE2: ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s", ipaddr_string(ndo, tptr+2), tok2str(bgp_extd_comm_ospf_rtype_values, "unknown (0x%02x)", *(tptr+6)), (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "", ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : "")); break; case BGP_EXT_COM_L2INFO: ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u", tok2str(l2vpn_encaps_values, "unknown encaps", *(tptr+2)), *(tptr+3), EXTRACT_16BITS(tptr+4))); break; case BGP_EXT_COM_SOURCE_AS: ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2))); break; default: ND_TCHECK2(*tptr,8); print_unknown_data(ndo, tptr, "\n\t ", 8); break; } tlen -=8; tptr +=8; } break; case BGPTYPE_PMSI_TUNNEL: { uint8_t tunnel_type, flags; tunnel_type = *(tptr+1); flags = *tptr; tlen = len; ND_TCHECK2(tptr[0], 5); ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u", tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type), tunnel_type, bittok2str(bgp_pmsi_flag_values, "none", flags), EXTRACT_24BITS(tptr+2)>>4)); tptr +=5; tlen -= 5; switch (tunnel_type) { case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ case BGP_PMSI_TUNNEL_PIM_BIDIR: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Sender %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_PIM_SSM: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_INGRESS: ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s", ipaddr_string(ndo, tptr))); break; case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ case BGP_PMSI_TUNNEL_LDP_MP2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; case BGP_PMSI_TUNNEL_RSVP_P2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr, "\n\t ", tlen); } } break; } case BGPTYPE_AIGP: { uint8_t type; uint16_t length; tlen = len; while (tlen >= 3) { ND_TCHECK2(tptr[0], 3); type = *tptr; length = EXTRACT_16BITS(tptr+1); tptr += 3; tlen -= 3; ND_PRINT((ndo, "\n\t %s TLV (%u), length %u", tok2str(bgp_aigp_values, "Unknown", type), type, length)); if (length < 3) goto trunc; length -= 3; /* * Check if we can read the TLV data. */ ND_TCHECK2(tptr[3], length); switch (type) { case BGP_AIGP_TLV: if (length < 8) goto trunc; ND_PRINT((ndo, ", metric %" PRIu64, EXTRACT_64BITS(tptr))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr,"\n\t ", length); } } tptr += length; tlen -= length; } break; } case BGPTYPE_ATTR_SET: ND_TCHECK2(tptr[0], 4); if (len < 4) goto trunc; ND_PRINT((ndo, "\n\t Origin AS: %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); tptr+=4; len -=4; while (len) { u_int aflags, alenlen, alen; ND_TCHECK2(tptr[0], 2); if (len < 2) goto trunc; aflags = *tptr; atype = *(tptr + 1); tptr += 2; len -= 2; alenlen = bgp_attr_lenlen(aflags, tptr); ND_TCHECK2(tptr[0], alenlen); if (len < alenlen) goto trunc; alen = bgp_attr_len(aflags, tptr); tptr += alenlen; len -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } /* FIXME check for recursion */ if (!bgp_attr_print(ndo, atype, tptr, alen)) return 0; tptr += alen; len -= alen; } break; case BGPTYPE_LARGE_COMMUNITY: if (len == 0 || len % 12) { ND_PRINT((ndo, "invalid len")); break; } ND_PRINT((ndo, "\n\t ")); while (len > 0) { ND_TCHECK2(*tptr, 12); ND_PRINT((ndo, "%u:%u:%u%s", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), (len > 12) ? ", " : "")); tptr += 12; len -= 12; } break; default: ND_TCHECK2(*pptr,len); ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr, "\n\t ", len); break; } if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ ND_TCHECK2(*pptr,len); print_unknown_data(ndo, pptr, "\n\t ", len); } return 1; trunc: return 0; } Commit Message: CVE-2017-13046/BGP: fix an existing bounds check for PMSI Tunnel This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
bgp_attr_print(netdissect_options *ndo, u_int atype, const u_char *pptr, u_int len) { int i; uint16_t af; uint8_t safi, snpa, nhlen; union { /* copy buffer for bandwidth values */ float f; uint32_t i; } bw; int advance; u_int tlen; const u_char *tptr; char buf[MAXHOSTNAMELEN + 100]; int as_size; tptr = pptr; tlen=len; switch (atype) { case BGPTYPE_ORIGIN: if (len != 1) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK(*tptr); ND_PRINT((ndo, "%s", tok2str(bgp_origin_values, "Unknown Origin Typecode", tptr[0]))); } break; /* * Process AS4 byte path and AS2 byte path attributes here. */ case BGPTYPE_AS4_PATH: case BGPTYPE_AS_PATH: if (len % 2) { ND_PRINT((ndo, "invalid len")); break; } if (!len) { ND_PRINT((ndo, "empty")); break; } /* * BGP updates exchanged between New speakers that support 4 * byte AS, ASs are always encoded in 4 bytes. There is no * definitive way to find this, just by the packet's * contents. So, check for packet's TLV's sanity assuming * 2 bytes first, and it does not pass, assume that ASs are * encoded in 4 bytes format and move on. */ as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); while (tptr < pptr + len) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); for (i = 0; i < tptr[1] * as_size; i += as_size) { ND_TCHECK2(tptr[2 + i], as_size); ND_PRINT((ndo, "%s ", as_printf(ndo, astostr, sizeof(astostr), as_size == 2 ? EXTRACT_16BITS(&tptr[2 + i]) : EXTRACT_32BITS(&tptr[2 + i])))); } ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * as_size; } break; case BGPTYPE_NEXT_HOP: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); } break; case BGPTYPE_MULTI_EXIT_DISC: case BGPTYPE_LOCAL_PREF: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr))); } break; case BGPTYPE_ATOMIC_AGGREGATE: if (len != 0) ND_PRINT((ndo, "invalid len")); break; case BGPTYPE_AGGREGATOR: /* * Depending on the AS encoded is of 2 bytes or of 4 bytes, * the length of this PA can be either 6 bytes or 8 bytes. */ if (len != 6 && len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], len); if (len == 6) { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), ipaddr_string(ndo, tptr + 2))); } else { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); } break; case BGPTYPE_AGGREGATOR4: if (len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); break; case BGPTYPE_COMMUNITIES: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint32_t comm; ND_TCHECK2(tptr[0], 4); comm = EXTRACT_32BITS(tptr); switch (comm) { case BGP_COMMUNITY_NO_EXPORT: ND_PRINT((ndo, " NO_EXPORT")); break; case BGP_COMMUNITY_NO_ADVERT: ND_PRINT((ndo, " NO_ADVERTISE")); break; case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: ND_PRINT((ndo, " NO_EXPORT_SUBCONFED")); break; default: ND_PRINT((ndo, "%u:%u%s", (comm >> 16) & 0xffff, comm & 0xffff, (tlen>4) ? ", " : "")); break; } tlen -=4; tptr +=4; } break; case BGPTYPE_ORIGINATOR_ID: if (len != 4) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); break; case BGPTYPE_CLUSTER_LIST: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s%s", ipaddr_string(ndo, tptr), (tlen>4) ? ", " : "")); tlen -=4; tptr +=4; } break; case BGPTYPE_MP_REACH_NLRI: ND_TCHECK2(tptr[0], 3); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_VPLS<<8 | SAFNUM_VPLS): break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); goto done; break; } tptr +=3; ND_TCHECK(tptr[0]); nhlen = tptr[0]; tlen = nhlen; tptr++; if (tlen) { int nnh = 0; ND_PRINT((ndo, "\n\t nexthop: ")); while (tlen > 0) { if ( nnh++ > 0 ) { ND_PRINT((ndo, ", " )); } switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); tlen -= sizeof(struct in_addr); tptr += sizeof(struct in_addr); } break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): if (tlen < (int)sizeof(struct in6_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr))); tlen -= sizeof(struct in6_addr); tptr += sizeof(struct in6_addr); } break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); tlen -= (sizeof(struct in_addr)); tptr += (sizeof(struct in_addr)); } break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen))); tptr += tlen; tlen = 0; break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < BGP_VPN_RD_LEN+1) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); /* rfc986 mapped IPv4 address ? */ if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); /* rfc1888 mapped IPv6 address ? */ else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); tptr += tlen; tlen = 0; } break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); tptr += tlen; tlen = 0; goto done; break; } } } ND_PRINT((ndo, ", nh-length: %u", nhlen)); tptr += tlen; ND_TCHECK(tptr[0]); snpa = tptr[0]; tptr++; if (snpa) { ND_PRINT((ndo, "\n\t %u SNPA", snpa)); for (/*nothing*/; snpa > 0; snpa--) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "\n\t %d bytes", tptr[0])); tptr += tptr[0] + 1; } } else { ND_PRINT((ndo, ", no SNPA")); } while (tptr < pptr + len) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*tptr,tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } done: break; case BGPTYPE_MP_UNREACH_NLRI: ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); if (len == BGP_MP_NLRI_MINSIZE) ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); tptr += 3; while (tptr < pptr + len) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*(tptr-3),tlen); ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr-3, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } break; case BGPTYPE_EXTD_COMMUNITIES: if (len % 8) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint16_t extd_comm; ND_TCHECK2(tptr[0], 2); extd_comm=EXTRACT_16BITS(tptr); ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]", tok2str(bgp_extd_comm_subtype_values, "unknown extd community typecode", extd_comm), extd_comm, bittok2str(bgp_extd_comm_flag_values, "none", extd_comm))); ND_TCHECK2(*(tptr+2), 6); switch(extd_comm) { case BGP_EXT_COM_RT_0: case BGP_EXT_COM_RO_0: case BGP_EXT_COM_L2VPN_RT_0: ND_PRINT((ndo, ": %u:%u (= %s)", EXTRACT_16BITS(tptr+2), EXTRACT_32BITS(tptr+4), ipaddr_string(ndo, tptr+4))); break; case BGP_EXT_COM_RT_1: case BGP_EXT_COM_RO_1: case BGP_EXT_COM_L2VPN_RT_1: case BGP_EXT_COM_VRF_RT_IMP: ND_PRINT((ndo, ": %s:%u", ipaddr_string(ndo, tptr+2), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_RT_2: case BGP_EXT_COM_RO_2: ND_PRINT((ndo, ": %s:%u", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_LINKBAND: bw.i = EXTRACT_32BITS(tptr+2); ND_PRINT((ndo, ": bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case BGP_EXT_COM_VPN_ORIGIN: case BGP_EXT_COM_VPN_ORIGIN2: case BGP_EXT_COM_VPN_ORIGIN3: case BGP_EXT_COM_VPN_ORIGIN4: case BGP_EXT_COM_OSPF_RID: case BGP_EXT_COM_OSPF_RID2: ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2))); break; case BGP_EXT_COM_OSPF_RTYPE: case BGP_EXT_COM_OSPF_RTYPE2: ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s", ipaddr_string(ndo, tptr+2), tok2str(bgp_extd_comm_ospf_rtype_values, "unknown (0x%02x)", *(tptr+6)), (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "", ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : "")); break; case BGP_EXT_COM_L2INFO: ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u", tok2str(l2vpn_encaps_values, "unknown encaps", *(tptr+2)), *(tptr+3), EXTRACT_16BITS(tptr+4))); break; case BGP_EXT_COM_SOURCE_AS: ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2))); break; default: ND_TCHECK2(*tptr,8); print_unknown_data(ndo, tptr, "\n\t ", 8); break; } tlen -=8; tptr +=8; } break; case BGPTYPE_PMSI_TUNNEL: { uint8_t tunnel_type, flags; ND_TCHECK2(tptr[0], 5); tunnel_type = *(tptr+1); flags = *tptr; tlen = len; ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u", tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type), tunnel_type, bittok2str(bgp_pmsi_flag_values, "none", flags), EXTRACT_24BITS(tptr+2)>>4)); tptr +=5; tlen -= 5; switch (tunnel_type) { case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ case BGP_PMSI_TUNNEL_PIM_BIDIR: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Sender %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_PIM_SSM: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_INGRESS: ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s", ipaddr_string(ndo, tptr))); break; case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ case BGP_PMSI_TUNNEL_LDP_MP2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; case BGP_PMSI_TUNNEL_RSVP_P2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr, "\n\t ", tlen); } } break; } case BGPTYPE_AIGP: { uint8_t type; uint16_t length; tlen = len; while (tlen >= 3) { ND_TCHECK2(tptr[0], 3); type = *tptr; length = EXTRACT_16BITS(tptr+1); tptr += 3; tlen -= 3; ND_PRINT((ndo, "\n\t %s TLV (%u), length %u", tok2str(bgp_aigp_values, "Unknown", type), type, length)); if (length < 3) goto trunc; length -= 3; /* * Check if we can read the TLV data. */ ND_TCHECK2(tptr[3], length); switch (type) { case BGP_AIGP_TLV: if (length < 8) goto trunc; ND_PRINT((ndo, ", metric %" PRIu64, EXTRACT_64BITS(tptr))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr,"\n\t ", length); } } tptr += length; tlen -= length; } break; } case BGPTYPE_ATTR_SET: ND_TCHECK2(tptr[0], 4); if (len < 4) goto trunc; ND_PRINT((ndo, "\n\t Origin AS: %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); tptr+=4; len -=4; while (len) { u_int aflags, alenlen, alen; ND_TCHECK2(tptr[0], 2); if (len < 2) goto trunc; aflags = *tptr; atype = *(tptr + 1); tptr += 2; len -= 2; alenlen = bgp_attr_lenlen(aflags, tptr); ND_TCHECK2(tptr[0], alenlen); if (len < alenlen) goto trunc; alen = bgp_attr_len(aflags, tptr); tptr += alenlen; len -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } /* FIXME check for recursion */ if (!bgp_attr_print(ndo, atype, tptr, alen)) return 0; tptr += alen; len -= alen; } break; case BGPTYPE_LARGE_COMMUNITY: if (len == 0 || len % 12) { ND_PRINT((ndo, "invalid len")); break; } ND_PRINT((ndo, "\n\t ")); while (len > 0) { ND_TCHECK2(*tptr, 12); ND_PRINT((ndo, "%u:%u:%u%s", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), (len > 12) ? ", " : "")); tptr += 12; len -= 12; } break; default: ND_TCHECK2(*pptr,len); ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr, "\n\t ", len); break; } if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ ND_TCHECK2(*pptr,len); print_unknown_data(ndo, pptr, "\n\t ", len); } return 1; trunc: return 0; }
167,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DevToolsUI::DevToolsUI(content::WebUI* web_ui) : WebUIController(web_ui) { web_ui->SetBindings(0); Profile* profile = Profile::FromWebUI(web_ui); content::URLDataSource::Add( profile, new DevToolsDataSource(profile->GetRequestContext())); GURL url = web_ui->GetWebContents()->GetVisibleURL(); if (url.spec() != SanitizeFrontendURL(url).spec()) return; if (profile->IsOffTheRecord()) { GURL site = content::SiteInstance::GetSiteForURL(profile, url); content::BrowserContext::GetStoragePartitionForSite(profile, site)-> GetFileSystemContext()->EnableTemporaryFileSystemInIncognito(); } bindings_.reset(new DevToolsUIBindings(web_ui->GetWebContents())); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
DevToolsUI::DevToolsUI(content::WebUI* web_ui) : WebUIController(web_ui), bindings_(web_ui->GetWebContents()) { web_ui->SetBindings(0); Profile* profile = Profile::FromWebUI(web_ui); content::URLDataSource::Add( profile, new DevToolsDataSource(profile->GetRequestContext())); if (!profile->IsOffTheRecord()) return; GURL url = web_ui->GetWebContents()->GetVisibleURL(); GURL site = content::SiteInstance::GetSiteForURL(profile, url); content::BrowserContext::GetStoragePartitionForSite(profile, site)-> GetFileSystemContext()->EnableTemporaryFileSystemInIncognito(); }
172,456
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GLES2DecoderImpl::SimulateFixedAttribs( const char* function_name, GLuint max_vertex_accessed, bool* simulated, GLsizei primcount) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; if (!vertex_attrib_manager_->HaveFixedAttribs()) { return true; } PerformanceWarning( "GL_FIXED attributes have a signficant performance penalty"); GLuint elements_needed = 0; const VertexAttribManager::VertexAttribInfoList& infos = vertex_attrib_manager_->GetEnabledVertexAttribInfos(); for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); GLuint max_accessed = info->MaxVertexAccessed(primcount, max_vertex_accessed); GLuint num_vertices = max_accessed + 1; if (num_vertices == 0) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } if (attrib_info && info->CanAccess(max_accessed) && info->type() == GL_FIXED) { GLuint elements_used = 0; if (!SafeMultiply(num_vertices, static_cast<GLuint>(info->size()), &elements_used) || !SafeAdd(elements_needed, elements_used, &elements_needed)) { SetGLError( GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs"); return false; } } } const GLuint kSizeOfFloat = sizeof(float); // NOLINT GLuint size_needed = 0; if (!SafeMultiply(elements_needed, kSizeOfFloat, &size_needed) || size_needed > 0x7FFFFFFFU) { SetGLError(GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs"); return false; } CopyRealGLErrorsToWrapper(); glBindBuffer(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_); if (static_cast<GLsizei>(size_needed) > fixed_attrib_buffer_size_) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); GLenum error = glGetError(); if (error != GL_NO_ERROR) { SetGLError( GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs"); return false; } } GLintptr offset = 0; for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); GLuint max_accessed = info->MaxVertexAccessed(primcount, max_vertex_accessed); GLuint num_vertices = max_accessed + 1; if (num_vertices == 0) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } if (attrib_info && info->CanAccess(max_accessed) && info->type() == GL_FIXED) { int num_elements = info->size() * kSizeOfFloat; int size = num_elements * num_vertices; scoped_array<float> data(new float[size]); const int32* src = reinterpret_cast<const int32 *>( info->buffer()->GetRange(info->offset(), size)); const int32* end = src + num_elements; float* dst = data.get(); while (src != end) { *dst++ = static_cast<float>(*src++) / 65536.0f; } glBufferSubData(GL_ARRAY_BUFFER, offset, size, data.get()); glVertexAttribPointer( info->index(), info->size(), GL_FLOAT, false, 0, reinterpret_cast<GLvoid*>(offset)); offset += size; } } *simulated = true; return true; } Commit Message: Fix SafeAdd and SafeMultiply BUG=145648,145544 Review URL: https://chromiumcodereview.appspot.com/10916165 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
bool GLES2DecoderImpl::SimulateFixedAttribs( const char* function_name, GLuint max_vertex_accessed, bool* simulated, GLsizei primcount) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; if (!vertex_attrib_manager_->HaveFixedAttribs()) { return true; } PerformanceWarning( "GL_FIXED attributes have a signficant performance penalty"); GLuint elements_needed = 0; const VertexAttribManager::VertexAttribInfoList& infos = vertex_attrib_manager_->GetEnabledVertexAttribInfos(); for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); GLuint max_accessed = info->MaxVertexAccessed(primcount, max_vertex_accessed); GLuint num_vertices = max_accessed + 1; if (num_vertices == 0) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } if (attrib_info && info->CanAccess(max_accessed) && info->type() == GL_FIXED) { uint32 elements_used = 0; if (!SafeMultiplyUint32(num_vertices, info->size(), &elements_used) || !SafeAddUint32(elements_needed, elements_used, &elements_needed)) { SetGLError( GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs"); return false; } } } const uint32 kSizeOfFloat = sizeof(float); // NOLINT uint32 size_needed = 0; if (!SafeMultiplyUint32(elements_needed, kSizeOfFloat, &size_needed) || size_needed > 0x7FFFFFFFU) { SetGLError(GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs"); return false; } CopyRealGLErrorsToWrapper(); glBindBuffer(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_); if (static_cast<GLsizei>(size_needed) > fixed_attrib_buffer_size_) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); GLenum error = glGetError(); if (error != GL_NO_ERROR) { SetGLError( GL_OUT_OF_MEMORY, function_name, "simulating GL_FIXED attribs"); return false; } } GLintptr offset = 0; for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); GLuint max_accessed = info->MaxVertexAccessed(primcount, max_vertex_accessed); GLuint num_vertices = max_accessed + 1; if (num_vertices == 0) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } if (attrib_info && info->CanAccess(max_accessed) && info->type() == GL_FIXED) { int num_elements = info->size() * kSizeOfFloat; int size = num_elements * num_vertices; scoped_array<float> data(new float[size]); const int32* src = reinterpret_cast<const int32 *>( info->buffer()->GetRange(info->offset(), size)); const int32* end = src + num_elements; float* dst = data.get(); while (src != end) { *dst++ = static_cast<float>(*src++) / 65536.0f; } glBufferSubData(GL_ARRAY_BUFFER, offset, size, data.get()); glVertexAttribPointer( info->index(), info->size(), GL_FLOAT, false, 0, reinterpret_cast<GLvoid*>(offset)); offset += size; } } *simulated = true; return true; }
170,751
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GDataFileSystem::AddUploadedFileOnUIThread( UploadMode upload_mode, const FilePath& virtual_dir_path, scoped_ptr<DocumentEntry> entry, const FilePath& file_content_path, GDataCache::FileOperationType cache_operation, const base::Closure& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); base::ScopedClosureRunner callback_runner(callback); if (!entry.get()) { NOTREACHED(); return; } GDataEntry* dir_entry = directory_service_->FindEntryByPathSync( virtual_dir_path); if (!dir_entry) return; GDataDirectory* parent_dir = dir_entry->AsGDataDirectory(); if (!parent_dir) return; scoped_ptr<GDataEntry> new_entry( GDataEntry::FromDocumentEntry( NULL, entry.get(), directory_service_.get())); if (!new_entry.get()) return; if (upload_mode == UPLOAD_EXISTING_FILE) { const std::string& resource_id = new_entry->resource_id(); directory_service_->GetEntryByResourceIdAsync(resource_id, base::Bind(&RemoveStaleEntryOnUpload, resource_id, parent_dir)); } GDataFile* file = new_entry->AsGDataFile(); DCHECK(file); const std::string& resource_id = file->resource_id(); const std::string& md5 = file->file_md5(); parent_dir->AddEntry(new_entry.release()); OnDirectoryChanged(virtual_dir_path); if (upload_mode == UPLOAD_NEW_FILE) { cache_->StoreOnUIThread(resource_id, md5, file_content_path, cache_operation, base::Bind(&OnCacheUpdatedForAddUploadedFile, callback_runner.Release())); } else if (upload_mode == UPLOAD_EXISTING_FILE) { cache_->ClearDirtyOnUIThread(resource_id, md5, base::Bind(&OnCacheUpdatedForAddUploadedFile, callback_runner.Release())); } else { NOTREACHED() << "Unexpected upload mode: " << upload_mode; } } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GDataFileSystem::AddUploadedFileOnUIThread( UploadMode upload_mode, const FilePath& virtual_dir_path, scoped_ptr<DocumentEntry> entry, const FilePath& file_content_path, GDataCache::FileOperationType cache_operation, const base::Closure& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); base::ScopedClosureRunner callback_runner(callback); if (!entry.get()) { NOTREACHED(); return; } GDataEntry* dir_entry = directory_service_->FindEntryByPathSync( virtual_dir_path); if (!dir_entry) return; GDataDirectory* parent_dir = dir_entry->AsGDataDirectory(); if (!parent_dir) return; scoped_ptr<GDataEntry> new_entry( directory_service_->FromDocumentEntry(entry.get())); if (!new_entry.get()) return; if (upload_mode == UPLOAD_EXISTING_FILE) { const std::string& resource_id = new_entry->resource_id(); directory_service_->GetEntryByResourceIdAsync(resource_id, base::Bind(&RemoveStaleEntryOnUpload, resource_id, parent_dir)); } GDataFile* file = new_entry->AsGDataFile(); DCHECK(file); const std::string& resource_id = file->resource_id(); const std::string& md5 = file->file_md5(); parent_dir->AddEntry(new_entry.release()); OnDirectoryChanged(virtual_dir_path); if (upload_mode == UPLOAD_NEW_FILE) { cache_->StoreOnUIThread(resource_id, md5, file_content_path, cache_operation, base::Bind(&OnCacheUpdatedForAddUploadedFile, callback_runner.Release())); } else if (upload_mode == UPLOAD_EXISTING_FILE) { cache_->ClearDirtyOnUIThread(resource_id, md5, base::Bind(&OnCacheUpdatedForAddUploadedFile, callback_runner.Release())); } else { NOTREACHED() << "Unexpected upload mode: " << upload_mode; } }
171,480
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int check_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size) { bool strict = env->strict_alignment; const char *pointer_desc = ""; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: /* Special case, because of NET_IP_ALIGN. Given metadata sits * right in front, treat it the very same way. */ return check_pkt_ptr_alignment(env, reg, off, size, strict); case PTR_TO_MAP_VALUE: pointer_desc = "value "; break; case PTR_TO_CTX: pointer_desc = "context "; break; case PTR_TO_STACK: pointer_desc = "stack "; break; default: break; } return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, strict); } Commit Message: bpf: force strict alignment checks for stack pointers Force strict alignment checks for stack pointers because the tracking of stack spills relies on it; unaligned stack accesses can lead to corruption of spilled registers, which is exploitable. Fixes: f1174f77b50c ("bpf/verifier: rework value tracking") Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-119
static int check_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size) { bool strict = env->strict_alignment; const char *pointer_desc = ""; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: /* Special case, because of NET_IP_ALIGN. Given metadata sits * right in front, treat it the very same way. */ return check_pkt_ptr_alignment(env, reg, off, size, strict); case PTR_TO_MAP_VALUE: pointer_desc = "value "; break; case PTR_TO_CTX: pointer_desc = "context "; break; case PTR_TO_STACK: pointer_desc = "stack "; /* The stack spill tracking logic in check_stack_write() * and check_stack_read() relies on stack accesses being * aligned. */ strict = true; break; default: break; } return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, strict); }
167,641
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Encoder::EncodeFrameInternal(const VideoSource &video, const unsigned long frame_flags) { vpx_codec_err_t res; const vpx_image_t *img = video.img(); if (!encoder_.priv) { cfg_.g_w = img->d_w; cfg_.g_h = img->d_h; cfg_.g_timebase = video.timebase(); cfg_.rc_twopass_stats_in = stats_->buf(); res = vpx_codec_enc_init(&encoder_, CodecInterface(), &cfg_, init_flags_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } if (cfg_.g_w != img->d_w || cfg_.g_h != img->d_h) { cfg_.g_w = img->d_w; cfg_.g_h = img->d_h; res = vpx_codec_enc_config_set(&encoder_, &cfg_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } REGISTER_STATE_CHECK( res = vpx_codec_encode(&encoder_, video.img(), video.pts(), video.duration(), frame_flags, deadline_)); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } 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 Encoder::EncodeFrameInternal(const VideoSource &video, const unsigned long frame_flags) { vpx_codec_err_t res; const vpx_image_t *img = video.img(); if (cfg_.g_w != img->d_w || cfg_.g_h != img->d_h) { cfg_.g_w = img->d_w; cfg_.g_h = img->d_h; res = vpx_codec_enc_config_set(&encoder_, &cfg_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } API_REGISTER_STATE_CHECK( res = vpx_codec_encode(&encoder_, img, video.pts(), video.duration(), frame_flags, deadline_)); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); }
174,536
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx, struct userfaultfd_wait_queue *ewq) { if (WARN_ON_ONCE(current->flags & PF_EXITING)) goto out; ewq->ctx = ctx; init_waitqueue_entry(&ewq->wq, current); spin_lock(&ctx->event_wqh.lock); /* * After the __add_wait_queue the uwq is visible to userland * through poll/read(). */ __add_wait_queue(&ctx->event_wqh, &ewq->wq); for (;;) { set_current_state(TASK_KILLABLE); if (ewq->msg.event == 0) break; if (ACCESS_ONCE(ctx->released) || fatal_signal_pending(current)) { __remove_wait_queue(&ctx->event_wqh, &ewq->wq); if (ewq->msg.event == UFFD_EVENT_FORK) { struct userfaultfd_ctx *new; new = (struct userfaultfd_ctx *) (unsigned long) ewq->msg.arg.reserved.reserved1; userfaultfd_ctx_put(new); } break; } spin_unlock(&ctx->event_wqh.lock); wake_up_poll(&ctx->fd_wqh, POLLIN); schedule(); spin_lock(&ctx->event_wqh.lock); } __set_current_state(TASK_RUNNING); spin_unlock(&ctx->event_wqh.lock); /* * ctx may go away after this if the userfault pseudo fd is * already released. */ out: userfaultfd_ctx_put(ctx); } Commit Message: userfaultfd: non-cooperative: fix fork use after free When reading the event from the uffd, we put it on a temporary fork_event list to detect if we can still access it after releasing and retaking the event_wqh.lock. If fork aborts and removes the event from the fork_event all is fine as long as we're still in the userfault read context and fork_event head is still alive. We've to put the event allocated in the fork kernel stack, back from fork_event list-head to the event_wqh head, before returning from userfaultfd_ctx_read, because the fork_event head lifetime is limited to the userfaultfd_ctx_read stack lifetime. Forgetting to move the event back to its event_wqh place then results in __remove_wait_queue(&ctx->event_wqh, &ewq->wq); in userfaultfd_event_wait_completion to remove it from a head that has been already freed from the reader stack. This could only happen if resolve_userfault_fork failed (for example if there are no file descriptors available to allocate the fork uffd). If it succeeded it was put back correctly. Furthermore, after find_userfault_evt receives a fork event, the forked userfault context in fork_nctx and uwq->msg.arg.reserved.reserved1 can be released by the fork thread as soon as the event_wqh.lock is released. Taking a reference on the fork_nctx before dropping the lock prevents an use after free in resolve_userfault_fork(). If the fork side aborted and it already released everything, we still try to succeed resolve_userfault_fork(), if possible. Fixes: 893e26e61d04eac9 ("userfaultfd: non-cooperative: Add fork() event") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Mark Rutland <[email protected]> Tested-by: Mark Rutland <[email protected]> Cc: Pavel Emelyanov <[email protected]> Cc: Mike Rapoport <[email protected]> Cc: "Dr. David Alan Gilbert" <[email protected]> Cc: Mike Kravetz <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-416
static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx, struct userfaultfd_wait_queue *ewq) { if (WARN_ON_ONCE(current->flags & PF_EXITING)) goto out; ewq->ctx = ctx; init_waitqueue_entry(&ewq->wq, current); spin_lock(&ctx->event_wqh.lock); /* * After the __add_wait_queue the uwq is visible to userland * through poll/read(). */ __add_wait_queue(&ctx->event_wqh, &ewq->wq); for (;;) { set_current_state(TASK_KILLABLE); if (ewq->msg.event == 0) break; if (ACCESS_ONCE(ctx->released) || fatal_signal_pending(current)) { /* * &ewq->wq may be queued in fork_event, but * __remove_wait_queue ignores the head * parameter. It would be a problem if it * didn't. */ __remove_wait_queue(&ctx->event_wqh, &ewq->wq); if (ewq->msg.event == UFFD_EVENT_FORK) { struct userfaultfd_ctx *new; new = (struct userfaultfd_ctx *) (unsigned long) ewq->msg.arg.reserved.reserved1; userfaultfd_ctx_put(new); } break; } spin_unlock(&ctx->event_wqh.lock); wake_up_poll(&ctx->fd_wqh, POLLIN); schedule(); spin_lock(&ctx->event_wqh.lock); } __set_current_state(TASK_RUNNING); spin_unlock(&ctx->event_wqh.lock); /* * ctx may go away after this if the userfault pseudo fd is * already released. */ out: userfaultfd_ctx_put(ctx); }
169,431
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ImageBitmapFactories::ImageBitmapLoader::Trace(blink::Visitor* visitor) { visitor->Trace(factory_); visitor->Trace(resolver_); visitor->Trace(options_); } Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader FileReaderLoader stores its client as a raw pointer, so in cases like ImageBitmapLoader where the FileReaderLoaderClient really is garbage collected we have to make sure to destroy the FileReaderLoader when the ExecutionContext that owns it is destroyed. Bug: 913970 Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861 Reviewed-on: https://chromium-review.googlesource.com/c/1374511 Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Marijn Kruisselbrink <[email protected]> Cr-Commit-Position: refs/heads/master@{#616342} CWE ID: CWE-416
void ImageBitmapFactories::ImageBitmapLoader::Trace(blink::Visitor* visitor) { ContextLifecycleObserver::Trace(visitor); visitor->Trace(factory_); visitor->Trace(resolver_); visitor->Trace(options_); }
173,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ptaReadStream(FILE *fp) { char typestr[128]; l_int32 i, n, ix, iy, type, version; l_float32 x, y; PTA *pta; PROCNAME("ptaReadStream"); if (!fp) return (PTA *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, "\n Pta Version %d\n", &version) != 1) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (version != PTA_VERSION_NUMBER) return (PTA *)ERROR_PTR("invalid pta version", procName, NULL); if (fscanf(fp, " Number of pts = %d; format = %s\n", &n, typestr) != 2) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (!strcmp(typestr, "float")) type = 0; else /* typestr is "integer" */ type = 1; if ((pta = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("pta not made", procName, NULL); for (i = 0; i < n; i++) { if (type == 0) { /* data is float */ if (fscanf(fp, " (%f, %f)\n", &x, &y) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading floats", procName, NULL); } ptaAddPt(pta, x, y); } else { /* data is integer */ if (fscanf(fp, " (%d, %d)\n", &ix, &iy) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading ints", procName, NULL); } ptaAddPt(pta, ix, iy); } } return pta; } 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
ptaReadStream(FILE *fp) { char typestr[128]; /* hardcoded below in fscanf */ l_int32 i, n, ix, iy, type, version; l_float32 x, y; PTA *pta; PROCNAME("ptaReadStream"); if (!fp) return (PTA *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, "\n Pta Version %d\n", &version) != 1) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (version != PTA_VERSION_NUMBER) return (PTA *)ERROR_PTR("invalid pta version", procName, NULL); if (fscanf(fp, " Number of pts = %d; format = %127s\n", &n, typestr) != 2) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (!strcmp(typestr, "float")) type = 0; else /* typestr is "integer" */ type = 1; if ((pta = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("pta not made", procName, NULL); for (i = 0; i < n; i++) { if (type == 0) { /* data is float */ if (fscanf(fp, " (%f, %f)\n", &x, &y) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading floats", procName, NULL); } ptaAddPt(pta, x, y); } else { /* data is integer */ if (fscanf(fp, " (%d, %d)\n", &ix, &iy) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading ints", procName, NULL); } ptaAddPt(pta, ix, iy); } } return pta; }
169,328
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_put_le_short (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 2) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; } ; } /* header_put_le_short */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_le_short (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = x ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; } /* header_put_le_short */
170,058
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline long decode_twos_comp(ulong c, int prec) { long result; assert(prec >= 2); jas_eprintf("warning: support for signed data is untested\n"); result = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1))); return result; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
static inline long decode_twos_comp(ulong c, int prec) static inline long decode_twos_comp(jas_ulong c, int prec) { long result; assert(prec >= 2); jas_eprintf("warning: support for signed data is untested\n"); result = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1))); return result; }
168,691
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: archive_read_format_zip_cleanup(struct archive_read *a) { struct zip *zip; struct zip_entry *zip_entry, *next_zip_entry; zip = (struct zip *)(a->format->data); #ifdef HAVE_ZLIB_H if (zip->stream_valid) inflateEnd(&zip->stream); #endif #if HAVA_LZMA_H && HAVE_LIBLZMA if (zip->zipx_lzma_valid) { lzma_end(&zip->zipx_lzma_stream); } #endif #ifdef HAVE_BZLIB_H if (zip->bzstream_valid) { BZ2_bzDecompressEnd(&zip->bzstream); } #endif free(zip->uncompressed_buffer); if (zip->ppmd8_valid) __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8); if (zip->zip_entries) { zip_entry = zip->zip_entries; while (zip_entry != NULL) { next_zip_entry = zip_entry->next; archive_string_free(&zip_entry->rsrcname); free(zip_entry); zip_entry = next_zip_entry; } } free(zip->decrypted_buffer); if (zip->cctx_valid) archive_decrypto_aes_ctr_release(&zip->cctx); if (zip->hctx_valid) archive_hmac_sha1_cleanup(&zip->hctx); free(zip->iv); free(zip->erd); free(zip->v_data); archive_string_free(&zip->format_name); free(zip); (a->format->data) = NULL; return (ARCHIVE_OK); } Commit Message: Fix typo in preprocessor macro in archive_read_format_zip_cleanup() Frees lzma_stream on cleanup() Fixes #1165 CWE ID: CWE-399
archive_read_format_zip_cleanup(struct archive_read *a) { struct zip *zip; struct zip_entry *zip_entry, *next_zip_entry; zip = (struct zip *)(a->format->data); #ifdef HAVE_ZLIB_H if (zip->stream_valid) inflateEnd(&zip->stream); #endif #if HAVE_LZMA_H && HAVE_LIBLZMA if (zip->zipx_lzma_valid) { lzma_end(&zip->zipx_lzma_stream); } #endif #ifdef HAVE_BZLIB_H if (zip->bzstream_valid) { BZ2_bzDecompressEnd(&zip->bzstream); } #endif free(zip->uncompressed_buffer); if (zip->ppmd8_valid) __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8); if (zip->zip_entries) { zip_entry = zip->zip_entries; while (zip_entry != NULL) { next_zip_entry = zip_entry->next; archive_string_free(&zip_entry->rsrcname); free(zip_entry); zip_entry = next_zip_entry; } } free(zip->decrypted_buffer); if (zip->cctx_valid) archive_decrypto_aes_ctr_release(&zip->cctx); if (zip->hctx_valid) archive_hmac_sha1_cleanup(&zip->hctx); free(zip->iv); free(zip->erd); free(zip->v_data); archive_string_free(&zip->format_name); free(zip); (a->format->data) = NULL; return (ARCHIVE_OK); }
169,695
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SharedWorkerDevToolsAgentHost::WorkerRestarted( SharedWorkerHost* worker_host) { DCHECK_EQ(WORKER_TERMINATED, state_); DCHECK(!worker_host_); state_ = WORKER_NOT_READY; worker_host_ = worker_host; for (DevToolsSession* session : sessions()) session->SetRenderer(GetProcess(), nullptr); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void SharedWorkerDevToolsAgentHost::WorkerRestarted( SharedWorkerHost* worker_host) { DCHECK_EQ(WORKER_TERMINATED, state_); DCHECK(!worker_host_); state_ = WORKER_NOT_READY; worker_host_ = worker_host; for (DevToolsSession* session : sessions()) session->SetRenderer(worker_host_->process_id(), nullptr); }
172,791
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool NaClProcessHost::StartNaClExecution() { NaClBrowser* nacl_browser = NaClBrowser::GetInstance(); nacl::NaClStartParams params; params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled(); params.validation_cache_key = nacl_browser->GetValidationCacheKey(); params.version = chrome::VersionInfo().CreateVersionString(); params.enable_exception_handling = enable_exception_handling_; params.enable_debug_stub = CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableNaClDebug); params.enable_ipc_proxy = enable_ipc_proxy_; base::PlatformFile irt_file = nacl_browser->IrtFile(); CHECK_NE(irt_file, base::kInvalidPlatformFileValue); const ChildProcessData& data = process_->GetData(); for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) { if (!ShareHandleToSelLdr(data.handle, internal_->sockets_for_sel_ldr[i], true, &params.handles)) { return false; } } if (!ShareHandleToSelLdr(data.handle, irt_file, false, &params.handles)) return false; #if defined(OS_MACOSX) base::SharedMemory memory_buffer; base::SharedMemoryCreateOptions options; options.size = 1; options.executable = true; if (!memory_buffer.Create(options)) { DLOG(ERROR) << "Failed to allocate memory buffer"; return false; } nacl::FileDescriptor memory_fd; memory_fd.fd = dup(memory_buffer.handle().fd); if (memory_fd.fd < 0) { DLOG(ERROR) << "Failed to dup() a file descriptor"; return false; } memory_fd.auto_close = true; params.handles.push_back(memory_fd); #endif process_->Send(new NaClProcessMsg_Start(params)); internal_->sockets_for_sel_ldr.clear(); return true; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool NaClProcessHost::StartNaClExecution() { NaClBrowser* nacl_browser = NaClBrowser::GetInstance(); nacl::NaClStartParams params; params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled(); params.validation_cache_key = nacl_browser->GetValidationCacheKey(); params.version = chrome::VersionInfo().CreateVersionString(); params.enable_exception_handling = enable_exception_handling_; params.enable_debug_stub = CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableNaClDebug); base::PlatformFile irt_file = nacl_browser->IrtFile(); CHECK_NE(irt_file, base::kInvalidPlatformFileValue); const ChildProcessData& data = process_->GetData(); for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) { if (!ShareHandleToSelLdr(data.handle, internal_->sockets_for_sel_ldr[i], true, &params.handles)) { return false; } } if (!ShareHandleToSelLdr(data.handle, irt_file, false, &params.handles)) return false; #if defined(OS_MACOSX) base::SharedMemory memory_buffer; base::SharedMemoryCreateOptions options; options.size = 1; options.executable = true; if (!memory_buffer.Create(options)) { DLOG(ERROR) << "Failed to allocate memory buffer"; return false; } nacl::FileDescriptor memory_fd; memory_fd.fd = dup(memory_buffer.handle().fd); if (memory_fd.fd < 0) { DLOG(ERROR) << "Failed to dup() a file descriptor"; return false; } memory_fd.auto_close = true; params.handles.push_back(memory_fd); #endif process_->Send(new NaClProcessMsg_Start(params)); internal_->sockets_for_sel_ldr.clear(); return true; }
170,729
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long Segment::GetDuration() const { assert(m_pInfo); return m_pInfo->GetDuration(); } 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 Segment::GetDuration() const
174,306
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HistoryController::UpdateForCommit(RenderFrameImpl* frame, const WebHistoryItem& item, WebHistoryCommitType commit_type, bool navigation_within_page) { switch (commit_type) { case blink::WebBackForwardCommit: if (!provisional_entry_) return; current_entry_.reset(provisional_entry_.release()); if (HistoryEntry::HistoryNode* node = current_entry_->GetHistoryNodeForFrame(frame)) { node->set_item(item); } break; case blink::WebStandardCommit: CreateNewBackForwardItem(frame, item, navigation_within_page); break; case blink::WebInitialCommitInChildFrame: UpdateForInitialLoadInChildFrame(frame, item); break; case blink::WebHistoryInertCommit: if (current_entry_) { if (HistoryEntry::HistoryNode* node = current_entry_->GetHistoryNodeForFrame(frame)) { if (!navigation_within_page) node->RemoveChildren(); node->set_item(item); } } break; default: NOTREACHED() << "Invalid commit type: " << commit_type; } } Commit Message: Fix HistoryEntry corruption when commit isn't for provisional entry. BUG=597322 TEST=See bug for repro steps. Review URL: https://codereview.chromium.org/1848103004 Cr-Commit-Position: refs/heads/master@{#384659} CWE ID: CWE-254
void HistoryController::UpdateForCommit(RenderFrameImpl* frame, const WebHistoryItem& item, WebHistoryCommitType commit_type, bool navigation_within_page) { switch (commit_type) { case blink::WebBackForwardCommit: if (!provisional_entry_) return; // Commit the provisional entry, but only if this back/forward item // matches it. Otherwise it could be a commit from an earlier attempt to // go back/forward, and we should leave the provisional entry in place. if (HistoryEntry::HistoryNode* node = provisional_entry_->GetHistoryNodeForFrame(frame)) { if (node->item().itemSequenceNumber() == item.itemSequenceNumber()) current_entry_.reset(provisional_entry_.release()); } if (HistoryEntry::HistoryNode* node = current_entry_->GetHistoryNodeForFrame(frame)) { node->set_item(item); } break; case blink::WebStandardCommit: CreateNewBackForwardItem(frame, item, navigation_within_page); break; case blink::WebInitialCommitInChildFrame: UpdateForInitialLoadInChildFrame(frame, item); break; case blink::WebHistoryInertCommit: if (current_entry_) { if (HistoryEntry::HistoryNode* node = current_entry_->GetHistoryNodeForFrame(frame)) { if (!navigation_within_page) node->RemoveChildren(); node->set_item(item); } } break; default: NOTREACHED() << "Invalid commit type: " << commit_type; } }
172,565
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK"); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace); TIFFGetProfiles(tiff,image,image_info->ping); TIFFGetProperties(tiff,image); option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) TIFFGetEXIFProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5); image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING, &horizontal,&vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } if (image->matte == MagickFalse) image->depth=GetImageDepth(image,exception); } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) { quantum_info=DestroyQuantumInfo(quantum_info); break; } goto next_tiff_frame; } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); } if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG)) method=ReadRGBAMethod; if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; pixels=GetQuantumPixels(quantum_info); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register IndexPacket *indexes; register PixelPacket *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p)))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p)))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p)))); if (image->matte != MagickFalse) SetPixelOpacity(q,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p)))); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; size_t number_pixels; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass); number_pixels=columns*rows; tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels, sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { PixelPacket *tile; register ssize_t x; register PixelPacket *magick_restrict q; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+(image->columns*(rows_remaining-1)+x); for (row=rows_remaining; row > 0; row--) { if (image->matte != MagickFalse) for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); q++; p++; } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); q++; p++; } p+=columns-columns_remaining; q-=(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t) (number_pixels*sizeof(uint32)))) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } SetQuantumImageType(image,quantum_type); next_tiff_frame: quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if (image_info->number_scenes != 0) { if (image_info->scene >= GetImageListLength(image)) { /* Subimage was not found in the Photoshop layer */ image = DestroyImageList(image); return((Image *)NULL); } } return(GetFirstImageInList(image)); } Commit Message: ... CWE ID: CWE-119
static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK"); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace); TIFFGetProfiles(tiff,image,image_info->ping); TIFFGetProperties(tiff,image); option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) TIFFGetEXIFProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5); image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING, &horizontal,&vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } if (image->matte == MagickFalse) image->depth=GetImageDepth(image,exception); } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) { quantum_info=DestroyQuantumInfo(quantum_info); break; } goto next_tiff_frame; } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); } if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG)) method=ReadRGBAMethod; if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; pixels=GetQuantumPixels(quantum_info); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register IndexPacket *indexes; register PixelPacket *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p)))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p)))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p)))); if (image->matte != MagickFalse) SetPixelOpacity(q,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p)))); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass); number_pixels=(MagickSizeType) columns*rows; if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t) (number_pixels*sizeof(uint32)))) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels, sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { PixelPacket *tile; register ssize_t x; register PixelPacket *magick_restrict q; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+(image->columns*(rows_remaining-1)+x); for (row=rows_remaining; row > 0; row--) { if (image->matte != MagickFalse) for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); q++; p++; } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); q++; p++; } p+=columns-columns_remaining; q-=(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t) (number_pixels*sizeof(uint32)))) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } SetQuantumImageType(image,quantum_type); next_tiff_frame: quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if (image_info->number_scenes != 0) { if (image_info->scene >= GetImageListLength(image)) { /* Subimage was not found in the Photoshop layer */ image = DestroyImageList(image); return((Image *)NULL); } } return(GetFirstImageInList(image)); }
168,630
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int hash_recvmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)); int err; if (len > ds) len = ds; else if (len < ds) msg->msg_flags |= MSG_TRUNC; lock_sock(sk); if (ctx->more) { ctx->more = 0; ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); if (err) goto unlock; } err = memcpy_toiovec(msg->msg_iov, ctx->result, len); unlock: release_sock(sk); return err ?: len; } Commit Message: crypto: algif - suppress sending source address information in recvmsg The current code does not set the msg_namelen member to 0 and therefore makes net/socket.c leak the local sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix that. Cc: <[email protected]> # 2.6.38 Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-200
static int hash_recvmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)); int err; if (len > ds) len = ds; else if (len < ds) msg->msg_flags |= MSG_TRUNC; msg->msg_namelen = 0; lock_sock(sk); if (ctx->more) { ctx->more = 0; ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); if (err) goto unlock; } err = memcpy_toiovec(msg->msg_iov, ctx->result, len); unlock: release_sock(sk); return err ?: len; }
166,046
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int board_early_init_r(void) { int ret = 0; /* Flush d-cache and invalidate i-cache of any FLASH data */ flush_dcache(); invalidate_icache(); set_liodns(); setup_qbman_portals(); ret = trigger_fpga_config(); if (ret) printf("error triggering PCIe FPGA config\n"); /* enable the Unit LED (red) & Boot LED (on) */ qrio_set_leds(); /* enable Application Buffer */ qrio_enable_app_buffer(); return ret; } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
int board_early_init_r(void) { int ret = 0; /* Flush d-cache and invalidate i-cache of any FLASH data */ flush_dcache(); invalidate_icache(); set_liodns(); setup_qbman_portals(); ret = trigger_fpga_config(); if (ret) printf("error triggering PCIe FPGA config\n"); /* enable the Unit LED (red) & Boot LED (on) */ qrio_set_leds(); /* enable Application Buffer */ qrio_enable_app_buffer(); return 0; }
169,628
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PrintWebViewHelper::UpdatePrintSettings( const DictionaryValue& job_settings, bool is_preview) { PrintMsg_PrintPages_Params settings; Send(new PrintHostMsg_UpdatePrintSettings(routing_id(), print_pages_params_->params.document_cookie, job_settings, &settings)); if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) { print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS); return false; } if (is_preview) { if (!job_settings.GetString(printing::kPreviewUIAddr, &(settings.params.preview_ui_addr)) || !job_settings.GetInteger(printing::kPreviewRequestID, &(settings.params.preview_request_id)) || !job_settings.GetBoolean(printing::kIsFirstRequest, &(settings.params.is_first_request))) { NOTREACHED(); print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING); return false; } if (settings.params.is_first_request && !print_preview_context_.IsModifiable()) { settings.params.display_header_footer = false; } PageSizeMargins default_page_layout; GetPageSizeAndMarginsInPoints(NULL, -1, settings.params, &default_page_layout); if (!old_print_pages_params_.get() || !PageLayoutIsEqual(*old_print_pages_params_, settings)) { Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(), default_page_layout)); } SetCustomMarginsIfSelected(job_settings, &settings); if (settings.params.display_header_footer) { header_footer_info_.reset(new DictionaryValue()); header_footer_info_->SetString(printing::kSettingHeaderFooterDate, settings.params.date); header_footer_info_->SetString(printing::kSettingHeaderFooterURL, settings.params.url); header_footer_info_->SetString(printing::kSettingHeaderFooterTitle, settings.params.title); } } print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(), settings.params.document_cookie)); return true; } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool PrintWebViewHelper::UpdatePrintSettings( const DictionaryValue& job_settings, bool is_preview) { if (job_settings.empty()) { if (is_preview) print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING); return false; } // Send the cookie so that UpdatePrintSettings can reuse PrinterQuery when // possible. int cookie = print_pages_params_.get() ? print_pages_params_->params.document_cookie : 0; PrintMsg_PrintPages_Params settings; Send(new PrintHostMsg_UpdatePrintSettings(routing_id(), cookie, job_settings, &settings)); print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); if (PrintMsg_Print_Params_IsEmpty(settings.params)) { if (is_preview) { print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS); } else { WebKit::WebFrame* frame = print_preview_context_.frame(); if (!frame) { GetPrintFrame(&frame); } if (frame) { render_view()->runModalAlertDialog( frame, l10n_util::GetStringUTF16( IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS)); } } return false; } if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) { print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS); return false; } if (is_preview) { if (!job_settings.GetString(printing::kPreviewUIAddr, &(settings.params.preview_ui_addr)) || !job_settings.GetInteger(printing::kPreviewRequestID, &(settings.params.preview_request_id)) || !job_settings.GetBoolean(printing::kIsFirstRequest, &(settings.params.is_first_request))) { NOTREACHED(); print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING); return false; } if (settings.params.is_first_request && !print_preview_context_.IsModifiable()) { settings.params.display_header_footer = false; } PageSizeMargins default_page_layout; GetPageSizeAndMarginsInPoints(NULL, -1, settings.params, &default_page_layout); if (!old_print_pages_params_.get() || !PageLayoutIsEqual(*old_print_pages_params_, settings)) { Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(), default_page_layout)); } SetCustomMarginsIfSelected(job_settings, &settings); if (settings.params.display_header_footer) { header_footer_info_.reset(new DictionaryValue()); header_footer_info_->SetString(printing::kSettingHeaderFooterDate, settings.params.date); header_footer_info_->SetString(printing::kSettingHeaderFooterURL, settings.params.url); header_footer_info_->SetString(printing::kSettingHeaderFooterTitle, settings.params.title); } } print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(), settings.params.document_cookie)); return true; }
170,264
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment) { int i, length; segment->nb_index_entries = avio_rb32(pb); length = avio_rb32(pb); if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) || !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) || !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries)))) { av_freep(&segment->temporal_offset_entries); av_freep(&segment->flag_entries); return AVERROR(ENOMEM); } for (i = 0; i < segment->nb_index_entries; i++) { segment->temporal_offset_entries[i] = avio_r8(pb); avio_r8(pb); /* KeyFrameOffset */ segment->flag_entries[i] = avio_r8(pb); segment->stream_offset_entries[i] = avio_rb64(pb); avio_skip(pb, length - 11); } return 0; } Commit Message: avformat/mxfdec: Fix DoS issues in mxf_read_index_entry_array() Fixes: 20170829A.mxf Co-Author: 张洪亮(望初)" <[email protected]> Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834
static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment) { int i, length; segment->nb_index_entries = avio_rb32(pb); length = avio_rb32(pb); if(segment->nb_index_entries && length < 11) return AVERROR_INVALIDDATA; if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) || !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) || !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries)))) { av_freep(&segment->temporal_offset_entries); av_freep(&segment->flag_entries); return AVERROR(ENOMEM); } for (i = 0; i < segment->nb_index_entries; i++) { if(avio_feof(pb)) return AVERROR_INVALIDDATA; segment->temporal_offset_entries[i] = avio_r8(pb); avio_r8(pb); /* KeyFrameOffset */ segment->flag_entries[i] = avio_r8(pb); segment->stream_offset_entries[i] = avio_rb64(pb); avio_skip(pb, length - 11); } return 0; }
167,765
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool TabLifecycleUnitSource::TabLifecycleUnit::CanDiscard( DiscardReason reason, DecisionDetails* decision_details) const { DCHECK(decision_details->reasons().empty()); if (!tab_strip_model_) return false; const LifecycleUnitState target_state = reason == DiscardReason::kProactive && GetState() != LifecycleUnitState::FROZEN ? LifecycleUnitState::PENDING_DISCARD : LifecycleUnitState::DISCARDED; if (!IsValidStateChange(GetState(), target_state, DiscardReasonToStateChangeReason(reason))) { return false; } if (GetWebContents()->IsCrashed()) return false; if (!GetWebContents()->GetLastCommittedURL().is_valid() || GetWebContents()->GetLastCommittedURL().is_empty()) { return false; } if (discard_count_ > 0) { #if defined(OS_CHROMEOS) if (reason != DiscardReason::kUrgent) return false; #else return false; #endif // defined(OS_CHROMEOS) } #if defined(OS_CHROMEOS) if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #else if (tab_strip_model_->GetActiveWebContents() == GetWebContents()) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #endif // defined(OS_CHROMEOS) if (GetWebContents()->GetPageImportanceSignals().had_form_interaction) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_FORM_ENTRY); IsMediaTabImpl(decision_details); if (GetWebContents()->GetContentsMimeType() == "application/pdf") decision_details->AddReason(DecisionFailureReason::LIVE_STATE_IS_PDF); if (!IsAutoDiscardable()) { decision_details->AddReason( DecisionFailureReason::LIVE_STATE_EXTENSION_DISALLOWED); } if (decision_details->reasons().empty()) { decision_details->AddReason( DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE); DCHECK(decision_details->IsPositive()); } return decision_details->IsPositive(); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
bool TabLifecycleUnitSource::TabLifecycleUnit::CanDiscard( DiscardReason reason, DecisionDetails* decision_details) const { DCHECK(decision_details->reasons().empty()); if (!tab_strip_model_) return false; const LifecycleUnitState target_state = reason == DiscardReason::kProactive && GetState() != LifecycleUnitState::FROZEN ? LifecycleUnitState::PENDING_DISCARD : LifecycleUnitState::DISCARDED; if (!IsValidStateChange(GetState(), target_state, DiscardReasonToStateChangeReason(reason))) { return false; } if (GetWebContents()->IsCrashed()) return false; if (!GetWebContents()->GetLastCommittedURL().is_valid() || GetWebContents()->GetLastCommittedURL().is_empty()) { return false; } if (discard_count_ > 0) { #if defined(OS_CHROMEOS) if (reason != DiscardReason::kUrgent) return false; #else return false; #endif // defined(OS_CHROMEOS) } #if defined(OS_CHROMEOS) if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #else if (tab_strip_model_->GetActiveWebContents() == GetWebContents()) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #endif // defined(OS_CHROMEOS) if (GetWebContents()->GetPageImportanceSignals().had_form_interaction) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_FORM_ENTRY); IsMediaTabImpl(decision_details); if (GetWebContents()->GetContentsMimeType() == "application/pdf") decision_details->AddReason(DecisionFailureReason::LIVE_STATE_IS_PDF); if (!IsAutoDiscardable()) { decision_details->AddReason( DecisionFailureReason::LIVE_STATE_EXTENSION_DISALLOWED); } // Consult the local database to see if this tab could try to communicate with // the user while in background (don't check for the visibility here as // there's already a check for that above). if (reason != DiscardReason::kUrgent) { CheckIfTabCanCommunicateWithUserWhileInBackground(GetWebContents(), decision_details); } if (decision_details->reasons().empty()) { decision_details->AddReason( DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE); DCHECK(decision_details->IsPositive()); } return decision_details->IsPositive(); }
172,218
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if((ps_dec->ps_out_buffer->u4_num_bufs == 0) || (ps_dec->ps_out_buffer->u4_num_bufs > IVD_VIDDEC_MAX_IO_BUFFERS)) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm) { if(ps_dec->u1_init_dec_flag == 0) { /*Come out of flush mode and return*/ ps_dec->u1_flushfrm = 0; return (IV_FAIL); } ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { /* check output buffer size given by the application */ if(check_app_out_buf_size(ps_dec) != IV_SUCCESS) { ps_dec_op->u4_error_code= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return (IV_FAIL); } ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 1; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; ps_dec->u4_sps_cnt_in_process = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { WORD32 buf_size; pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; /* If dynamic bitstream buffer is not allocated and * header decode is done, then allocate dynamic bitstream buffer */ if((NULL == ps_dec->pu1_bits_buf_dynamic) && (ps_dec->i4_header_decoded & 1)) { WORD32 size; void *pv_buf; void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size); RETURN_IF((NULL == pv_buf), IV_FAIL); ps_dec->pu1_bits_buf_dynamic = pv_buf; ps_dec->u4_dynamic_bits_buf_size = size; } if(ps_dec->pu1_bits_buf_dynamic) { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; buf_size = ps_dec->u4_dynamic_bits_buf_size; } else { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; buf_size = ps_dec->u4_static_bits_buf_size; } u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ /* Since 8 bytes are read ahead, ensure 8 bytes are free at the end of the buffer, which will be memset to 0 after emulation prevention */ buflen = MIN(buflen, buf_size - 8); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); /* Decoder may read extra 8 bytes near end of the frame */ if((buflen + 8) < buf_size) { memset(pu1_bitstrm_buf + buflen, 0, 8); } u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; header_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T) || (ret == IVD_DISP_FRM_ZERO_OP_BUF_SIZE)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_pic_buf_got == 1) && (ret != IVD_MEM_ALLOC_FAILED) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; WORD32 ht_in_mbs; ht_in_mbs = ps_dec->u2_pic_ht >> (4 + ps_dec->ps_cur_slice->u1_field_pic_flag); num_mb_skipped = (ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0)) prev_slice_err = 1; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T) || (ret1 == ERROR_INV_SPS_PPS_T)) { ret = ret1; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_pic_buf_got == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } else { ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY; } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if ((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } /*--------------------------------------------------------------------*/ /* Do End of Pic processing. */ /* Should be called only if frame was decoded in previous process call*/ /*--------------------------------------------------------------------*/ if(ps_dec->u4_pic_buf_got == 1) { if(1 == ps_dec->u1_last_pic_not_decoded) { ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec); if(ret != OK) return ret; ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } else { ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; } Commit Message: Decoder: Increased allocation and added checks in sei parsing. This prevents heap overflow while parsing sei_message. Bug: 63122634 Test: ran PoC on unpatched/patched Change-Id: I61c1ff4ac053a060be8c24da4671db985cac628c (cherry picked from commit f2b70d353768af8d4ead7f32497be05f197925ef) CWE ID: CWE-200
WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if((ps_dec->ps_out_buffer->u4_num_bufs == 0) || (ps_dec->ps_out_buffer->u4_num_bufs > IVD_VIDDEC_MAX_IO_BUFFERS)) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm) { if(ps_dec->u1_init_dec_flag == 0) { /*Come out of flush mode and return*/ ps_dec->u1_flushfrm = 0; return (IV_FAIL); } ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { /* check output buffer size given by the application */ if(check_app_out_buf_size(ps_dec) != IV_SUCCESS) { ps_dec_op->u4_error_code= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return (IV_FAIL); } ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 1; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; ps_dec->u4_sps_cnt_in_process = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { WORD32 buf_size; pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; /* If dynamic bitstream buffer is not allocated and * header decode is done, then allocate dynamic bitstream buffer */ if((NULL == ps_dec->pu1_bits_buf_dynamic) && (ps_dec->i4_header_decoded & 1)) { WORD32 size; void *pv_buf; void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size + EXTRA_BS_OFFSET); RETURN_IF((NULL == pv_buf), IV_FAIL); ps_dec->pu1_bits_buf_dynamic = pv_buf; ps_dec->u4_dynamic_bits_buf_size = size; } if(ps_dec->pu1_bits_buf_dynamic) { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; buf_size = ps_dec->u4_dynamic_bits_buf_size; } else { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; buf_size = ps_dec->u4_static_bits_buf_size; } u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ /* Since 8 bytes are read ahead, ensure 8 bytes are free at the end of the buffer, which will be memset to 0 after emulation prevention */ buflen = MIN(buflen, buf_size - 8); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); /* Decoder may read extra 8 bytes near end of the frame */ if((buflen + 8) < buf_size) { memset(pu1_bitstrm_buf + buflen, 0, 8); } u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; header_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T) || (ret == IVD_DISP_FRM_ZERO_OP_BUF_SIZE)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_pic_buf_got == 1) && (ret != IVD_MEM_ALLOC_FAILED) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; WORD32 ht_in_mbs; ht_in_mbs = ps_dec->u2_pic_ht >> (4 + ps_dec->ps_cur_slice->u1_field_pic_flag); num_mb_skipped = (ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0)) prev_slice_err = 1; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T) || (ret1 == ERROR_INV_SPS_PPS_T)) { ret = ret1; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_pic_buf_got == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } else { ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY; } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if ((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } /*--------------------------------------------------------------------*/ /* Do End of Pic processing. */ /* Should be called only if frame was decoded in previous process call*/ /*--------------------------------------------------------------------*/ if(ps_dec->u4_pic_buf_got == 1) { if(1 == ps_dec->u1_last_pic_not_decoded) { ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec); if(ret != OK) return ret; ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } else { ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; }
174,106
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: getftp (struct url *u, wgint passed_expected_bytes, wgint *qtyread, wgint restval, ccon *con, int count, wgint *last_expected_bytes, FILE *warc_tmp) { int csock, dtsock, local_sock, res; uerr_t err = RETROK; /* appease the compiler */ FILE *fp; char *respline, *tms; const char *user, *passwd, *tmrate; int cmd = con->cmd; bool pasv_mode_open = false; wgint expected_bytes = 0; bool got_expected_bytes = false; bool rest_failed = false; bool rest_failed = false; int flags; wgint rd_size, previous_rd_size = 0; char type_char; bool try_again; bool list_a_used = false; assert (con != NULL); assert (con->target != NULL); /* Debug-check of the sanity of the request by making sure that LIST and RETR are never both requested (since we can handle only one at a time. */ assert (!((cmd & DO_LIST) && (cmd & DO_RETR))); /* Make sure that at least *something* is requested. */ assert ((cmd & (DO_LIST | DO_CWD | DO_RETR | DO_LOGIN)) != 0); *qtyread = restval; user = u->user; passwd = u->passwd; search_netrc (u->host, (const char **)&user, (const char **)&passwd, 1); user = user ? user : (opt.ftp_user ? opt.ftp_user : opt.user); if (!user) user = "anonymous"; passwd = passwd ? passwd : (opt.ftp_passwd ? opt.ftp_passwd : opt.passwd); if (!passwd) passwd = "-wget@"; dtsock = -1; local_sock = -1; con->dltime = 0; if (!(cmd & DO_LOGIN)) csock = con->csock; else /* cmd & DO_LOGIN */ { char *host = con->proxy ? con->proxy->host : u->host; int port = con->proxy ? con->proxy->port : u->port; /* Login to the server: */ /* First: Establish the control connection. */ csock = connect_to_host (host, port); if (csock == E_HOST) return HOSTERR; else if (csock < 0) return (retryable_socket_connect_error (errno) ? CONERROR : CONIMPOSSIBLE); if (cmd & LEAVE_PENDING) con->csock = csock; else con->csock = -1; /* Second: Login with proper USER/PASS sequence. */ logprintf (LOG_VERBOSE, _("Logging in as %s ... "), quotearg_style (escape_quoting_style, user)); if (opt.server_response) logputs (LOG_ALWAYS, "\n"); if (con->proxy) { /* If proxy is in use, log in as username@target-site. */ char *logname = concat_strings (user, "@", u->host, (char *) 0); err = ftp_login (csock, logname, passwd); xfree (logname); } else err = ftp_login (csock, user, passwd); /* FTPRERR, FTPSRVERR, WRITEFAILED, FTPLOGREFUSED, FTPLOGINC */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPSRVERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Error in server greeting.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPLOGREFUSED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("The server refuses login.\n")); fd_close (csock); con->csock = -1; return FTPLOGREFUSED; case FTPLOGINC: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Login incorrect.\n")); fd_close (csock); con->csock = -1; return FTPLOGINC; case FTPOK: if (!opt.server_response) logputs (LOG_VERBOSE, _("Logged in!\n")); break; default: abort (); } /* Third: Get the system type */ if (!opt.server_response) logprintf (LOG_VERBOSE, "==> SYST ... "); err = ftp_syst (csock, &con->rs, &con->rsu); /* FTPRERR */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPSRVERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Server error, can't determine system type.\n")); break; case FTPOK: /* Everything is OK. */ break; default: abort (); } if (!opt.server_response && err != FTPSRVERR) logputs (LOG_VERBOSE, _("done. ")); /* 2013-10-17 Andrea Urbani (matfanjol) According to the system type I choose which list command will be used. If I don't know that system, I will try, the first time of each session, "LIST -a" and "LIST". (see __LIST_A_EXPLANATION__ below) */ switch (con->rs) { case ST_VMS: /* About ST_VMS there is an old note: 2008-01-29 SMS. For a VMS FTP server, where "LIST -a" may not fail, but will never do what is desired here, skip directly to the simple "LIST" command (assumed to be the last one in the list). */ DEBUGP (("\nVMS: I know it and I will use \"LIST\" as standard list command\n")); con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST_A; break; case ST_UNIX: if (con->rsu == UST_MULTINET) { DEBUGP (("\nUNIX MultiNet: I know it and I will use \"LIST\" " "as standard list command\n")); con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST_A; } else if (con->rsu == UST_TYPE_L8) { DEBUGP (("\nUNIX TYPE L8: I know it and I will use \"LIST -a\" " "as standard list command\n")); con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST; } break; default: break; } /* Fourth: Find the initial ftp directory */ if (!opt.server_response) logprintf (LOG_VERBOSE, "==> PWD ... "); err = ftp_pwd (csock, &con->id); /* FTPRERR */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPSRVERR : /* PWD unsupported -- assume "/". */ xfree (con->id); con->id = xstrdup ("/"); break; case FTPOK: /* Everything is OK. */ break; default: abort (); } #if 0 /* 2004-09-17 SMS. Don't help me out. Please. A reasonably recent VMS FTP server will cope just fine with UNIX file specifications. This code just spoils things. Discarding the device name, for example, is not a wise move. This code was disabled but left in as an example of what not to do. */ /* VMS will report something like "PUB$DEVICE:[INITIAL.FOLDER]". Convert it to "/INITIAL/FOLDER" */ if (con->rs == ST_VMS) { char *path = strchr (con->id, '['); char *pathend = path ? strchr (path + 1, ']') : NULL; if (!path || !pathend) DEBUGP (("Initial VMS directory not in the form [...]!\n")); else { char *idir = con->id; DEBUGP (("Preprocessing the initial VMS directory\n")); DEBUGP ((" old = '%s'\n", con->id)); /* We do the conversion in-place by copying the stuff between [ and ] to the beginning, and changing dots to slashes at the same time. */ *idir++ = '/'; for (++path; path < pathend; path++, idir++) *idir = *path == '.' ? '/' : *path; *idir = '\0'; DEBUGP ((" new = '%s'\n\n", con->id)); } } #endif /* 0 */ if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); /* Fifth: Set the FTP type. */ type_char = ftp_process_type (u->params); if (!opt.server_response) logprintf (LOG_VERBOSE, "==> TYPE %c ... ", type_char); err = ftp_type (csock, type_char); /* FTPRERR, WRITEFAILED, FTPUNKNOWNTYPE */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPUNKNOWNTYPE: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Unknown type `%c', closing control connection.\n"), type_char); fd_close (csock); con->csock = -1; return err; case FTPOK: /* Everything is OK. */ break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* do login */ if (cmd & DO_CWD) { if (!*u->dir) logputs (LOG_VERBOSE, _("==> CWD not needed.\n")); else { const char *targ = NULL; int cwd_count; int cwd_end; int cwd_start; char *target = u->dir; DEBUGP (("changing working directory\n")); /* Change working directory. To change to a non-absolute Unix directory, we need to prepend initial directory (con->id) to it. Absolute directories "just work". A relative directory is one that does not begin with '/' and, on non-Unix OS'es, one that doesn't begin with "[a-z]:". This is not done for OS400, which doesn't use "/"-delimited directories, nor does it support directory hierarchies. "CWD foo" followed by "CWD bar" leaves us in "bar", not in "foo/bar", as would be customary elsewhere. */ /* 2004-09-20 SMS. Why is this wise even on UNIX? It certainly fouls VMS. See below for a more reliable, more universal method. */ /* 2008-04-22 MJC. I'm not crazy about it either. I'm informed it's useful for misconfigured servers that have some dirs in the path with +x but -r, but this method is not RFC-conformant. I understand the need to deal with crappy server configurations, but it's far better to use the canonical method first, and fall back to kludges second. */ if (target[0] != '/' && !(con->rs != ST_UNIX && c_isalpha (target[0]) && target[1] == ':') && (con->rs != ST_OS400) && (con->rs != ST_VMS)) { int idlen = strlen (con->id); char *ntarget, *p; /* Strip trailing slash(es) from con->id. */ while (idlen > 0 && con->id[idlen - 1] == '/') --idlen; p = ntarget = (char *)alloca (idlen + 1 + strlen (u->dir) + 1); memcpy (p, con->id, idlen); p += idlen; *p++ = '/'; strcpy (p, target); DEBUGP (("Prepended initial PWD to relative path:\n")); DEBUGP ((" pwd: '%s'\n old: '%s'\n new: '%s'\n", con->id, target, ntarget)); target = ntarget; } #if 0 /* 2004-09-17 SMS. Don't help me out. Please. A reasonably recent VMS FTP server will cope just fine with UNIX file specifications. This code just spoils things. Discarding the device name, for example, is not a wise move. This code was disabled but left in as an example of what not to do. */ /* If the FTP host runs VMS, we will have to convert the absolute directory path in UNIX notation to absolute directory path in VMS notation as VMS FTP servers do not like UNIX notation of absolute paths. "VMS notation" is [dir.subdir.subsubdir]. */ if (con->rs == ST_VMS) { char *tmpp; char *ntarget = (char *)alloca (strlen (target) + 2); /* We use a converted initial dir, so directories in TARGET will be separated with slashes, something like "/INITIAL/FOLDER/DIR/SUBDIR". Convert that to "[INITIAL.FOLDER.DIR.SUBDIR]". */ strcpy (ntarget, target); assert (*ntarget == '/'); *ntarget = '['; for (tmpp = ntarget + 1; *tmpp; tmpp++) if (*tmpp == '/') *tmpp = '.'; *tmpp++ = ']'; *tmpp = '\0'; DEBUGP (("Changed file name to VMS syntax:\n")); DEBUGP ((" Unix: '%s'\n VMS: '%s'\n", target, ntarget)); target = ntarget; } #endif /* 0 */ /* 2004-09-20 SMS. A relative directory is relative to the initial directory. Thus, what _is_ useful on VMS (and probably elsewhere) is to CWD to the initial directory (ideally, whatever the server reports, _exactly_, NOT badly UNIX-ixed), and then CWD to the (new) relative directory. This should probably be restructured as a function, called once or twice, but I'm lazy enough to take the badly indented loop short-cut for now. */ /* Decide on one pass (absolute) or two (relative). The VMS restriction may be relaxed when the squirrely code above is reformed. */ if ((con->rs == ST_VMS) && (target[0] != '/')) { cwd_start = 0; DEBUGP (("Using two-step CWD for relative path.\n")); } else { /* Go straight to the target. */ cwd_start = 1; } /* At least one VMS FTP server (TCPware V5.6-2) can switch to a UNIX emulation mode when given a UNIX-like directory specification (like "a/b/c"). If allowed to continue this way, LIST interpretation will be confused, because the system type (SYST response) will not be re-checked, and future UNIX-format directory listings (for multiple URLs or "-r") will be horribly misinterpreted. The cheap and nasty work-around is to do a "CWD []" after a UNIX-like directory specification is used. (A single-level directory is harmless.) This puts the TCPware server back into VMS mode, and does no harm on other servers. Unlike the rest of this block, this particular behavior _is_ VMS-specific, so it gets its own VMS test. */ if ((con->rs == ST_VMS) && (strchr( target, '/') != NULL)) { cwd_end = 3; DEBUGP (("Using extra \"CWD []\" step for VMS server.\n")); } else { cwd_end = 2; } /* 2004-09-20 SMS. */ /* Sorry about the deviant indenting. Laziness. */ for (cwd_count = cwd_start; cwd_count < cwd_end; cwd_count++) { switch (cwd_count) { case 0: /* Step one (optional): Go to the initial directory, exactly as reported by the server. */ targ = con->id; break; case 1: /* Step two: Go to the target directory. (Absolute or relative will work now.) */ targ = target; break; case 2: /* Step three (optional): "CWD []" to restore server VMS-ness. */ targ = "[]"; break; default: logprintf (LOG_ALWAYS, _("Logically impossible section reached in getftp()")); logprintf (LOG_ALWAYS, _("cwd_count: %d\ncwd_start: %d\ncwd_end: %d\n"), cwd_count, cwd_start, cwd_end); abort (); } if (!opt.server_response) logprintf (LOG_VERBOSE, "==> CWD (%d) %s ... ", cwd_count, quotearg_style (escape_quoting_style, target)); err = ftp_cwd (csock, targ); /* FTPRERR, WRITEFAILED, FTPNSFOD */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPNSFOD: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such directory %s.\n\n"), quote (u->dir)); fd_close (csock); con->csock = -1; return err; case FTPOK: break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); } /* for */ /* 2004-09-20 SMS. */ } /* else */ } else /* do not CWD */ logputs (LOG_VERBOSE, _("==> CWD not required.\n")); if ((cmd & DO_RETR) && passed_expected_bytes == 0) { if (opt.verbose) { if (!opt.server_response) logprintf (LOG_VERBOSE, "==> SIZE %s ... ", quotearg_style (escape_quoting_style, u->file)); } err = ftp_size (csock, u->file, &expected_bytes); /* FTPRERR */ switch (err) { case FTPRERR: case FTPSRVERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPOK: got_expected_bytes = true; /* Everything is OK. */ break; default: abort (); } if (!opt.server_response) { logprintf (LOG_VERBOSE, "%s\n", expected_bytes ? number_to_static_string (expected_bytes) : _("done.\n")); } } if (cmd & DO_RETR && restval > 0 && restval == expected_bytes) { /* Server confirms that file has length restval. We should stop now. Some servers (f.e. NcFTPd) return error when receive REST 0 */ logputs (LOG_VERBOSE, _("File has already been retrieved.\n")); fd_close (csock); con->csock = -1; return RETRFINISHED; } do { try_again = false; /* If anything is to be retrieved, PORT (or PASV) must be sent. */ if (cmd & (DO_LIST | DO_RETR)) { if (opt.ftp_pasv) { ip_address passive_addr; int passive_port; err = ftp_do_pasv (csock, &passive_addr, &passive_port); /* FTPRERR, WRITEFAILED, FTPNOPASV, FTPINVPASV */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPNOPASV: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Cannot initiate PASV transfer.\n")); break; case FTPINVPASV: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Cannot parse PASV response.\n")); break; case FTPOK: break; default: abort (); } /* switch (err) */ if (err==FTPOK) { DEBUGP (("trying to connect to %s port %d\n", print_address (&passive_addr), passive_port)); dtsock = connect_to_ip (&passive_addr, passive_port, NULL); if (dtsock < 0) { int save_errno = errno; fd_close (csock); con->csock = -1; logprintf (LOG_VERBOSE, _("couldn't connect to %s port %d: %s\n"), print_address (&passive_addr), passive_port, strerror (save_errno)); ? CONERROR : CONIMPOSSIBLE); } pasv_mode_open = true; /* Flag to avoid accept port */ if (!opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* err==FTP_OK */ } if (!pasv_mode_open) /* Try to use a port command if PASV failed */ { err = ftp_do_port (csock, &local_sock); /* FTPRERR, WRITEFAILED, bindport (FTPSYSERR), HOSTERR, logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case CONSOCKERR: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno)); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPSYSERR: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Bind error (%s).\n"), strerror (errno)); fd_close (dtsock); return err; case FTPPORTERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Invalid PORT.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPOK: break; default: abort (); } /* port switch */ if (!opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* dtsock == -1 */ } /* cmd & (DO_LIST | DO_RETR) */ /* Restart if needed. */ if (restval && (cmd & DO_RETR)) { if (!opt.server_response) logprintf (LOG_VERBOSE, "==> REST %s ... ", number_to_static_string (restval)); err = ftp_rest (csock, restval); /* FTPRERR, WRITEFAILED, FTPRESTFAIL */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPRESTFAIL: logputs (LOG_VERBOSE, _("\nREST failed, starting from scratch.\n")); rest_failed = true; break; case FTPOK: break; default: abort (); } if (err != FTPRESTFAIL && !opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* restval && cmd & DO_RETR */ if (cmd & DO_RETR) { /* If we're in spider mode, don't really retrieve anything except the directory listing and verify whether the given "file" exists. */ if (opt.spider) { bool exists = false; struct fileinfo *f; uerr_t _res = ftp_get_listing (u, con, &f); /* Set the DO_RETR command flag again, because it gets unset when calling ftp_get_listing() and would otherwise cause an assertion failure earlier on when this function gets repeatedly called (e.g., when recursing). */ con->cmd |= DO_RETR; if (_res == RETROK) { while (f) { if (!strcmp (f->name, u->file)) { exists = true; break; } f = f->next; } if (exists) { logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("File %s exists.\n"), quote (u->file)); } else { logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such file %s.\n"), quote (u->file)); } } fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return RETRFINISHED; } if (opt.verbose) { if (!opt.server_response) { if (restval) logputs (LOG_VERBOSE, "\n"); logprintf (LOG_VERBOSE, "==> RETR %s ... ", quotearg_style (escape_quoting_style, u->file)); } } err = ftp_retr (csock, u->file); /* FTPRERR, WRITEFAILED, FTPNSFOD */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPNSFOD: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such file %s.\n\n"), quote (u->file)); fd_close (dtsock); fd_close (local_sock); return err; case FTPOK: break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); if (! got_expected_bytes) expected_bytes = *last_expected_bytes; } /* do retrieve */ if (cmd & DO_LIST) { if (!opt.server_response) logputs (LOG_VERBOSE, "==> LIST ... "); /* As Maciej W. Rozycki ([email protected]) says, `LIST' without arguments is better than `LIST .'; confirmed by RFC959. */ err = ftp_list (csock, NULL, con->st&AVOID_LIST_A, con->st&AVOID_LIST, &list_a_used); /* FTPRERR, WRITEFAILED */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPNSFOD: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such file or directory %s.\n\n"), quote (".")); fd_close (dtsock); fd_close (local_sock); return err; case FTPOK: break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); if (! got_expected_bytes) expected_bytes = *last_expected_bytes; } /* cmd & DO_LIST */ if (!(cmd & (DO_LIST | DO_RETR)) || (opt.spider && !(cmd & DO_LIST))) return RETRFINISHED; /* Some FTP servers return the total length of file after REST command, others just return the remaining size. */ if (passed_expected_bytes && restval && expected_bytes && (expected_bytes == passed_expected_bytes - restval)) { DEBUGP (("Lying FTP server found, adjusting.\n")); expected_bytes = passed_expected_bytes; } /* If no transmission was required, then everything is OK. */ if (!pasv_mode_open) /* we are not using pasive mode so we need to accept */ } Commit Message: CWE ID: CWE-200
getftp (struct url *u, wgint passed_expected_bytes, wgint *qtyread, wgint restval, ccon *con, int count, wgint *last_expected_bytes, FILE *warc_tmp) { int csock, dtsock, local_sock, res; uerr_t err = RETROK; /* appease the compiler */ FILE *fp; char *respline, *tms; const char *user, *passwd, *tmrate; int cmd = con->cmd; wgint expected_bytes = 0; bool got_expected_bytes = false; bool rest_failed = false; bool rest_failed = false; int flags; wgint rd_size, previous_rd_size = 0; char type_char; bool try_again; bool list_a_used = false; assert (con != NULL); assert (con->target != NULL); /* Debug-check of the sanity of the request by making sure that LIST and RETR are never both requested (since we can handle only one at a time. */ assert (!((cmd & DO_LIST) && (cmd & DO_RETR))); /* Make sure that at least *something* is requested. */ assert ((cmd & (DO_LIST | DO_CWD | DO_RETR | DO_LOGIN)) != 0); *qtyread = restval; user = u->user; passwd = u->passwd; search_netrc (u->host, (const char **)&user, (const char **)&passwd, 1); user = user ? user : (opt.ftp_user ? opt.ftp_user : opt.user); if (!user) user = "anonymous"; passwd = passwd ? passwd : (opt.ftp_passwd ? opt.ftp_passwd : opt.passwd); if (!passwd) passwd = "-wget@"; dtsock = -1; local_sock = -1; con->dltime = 0; if (!(cmd & DO_LOGIN)) csock = con->csock; else /* cmd & DO_LOGIN */ { char *host = con->proxy ? con->proxy->host : u->host; int port = con->proxy ? con->proxy->port : u->port; /* Login to the server: */ /* First: Establish the control connection. */ csock = connect_to_host (host, port); if (csock == E_HOST) return HOSTERR; else if (csock < 0) return (retryable_socket_connect_error (errno) ? CONERROR : CONIMPOSSIBLE); if (cmd & LEAVE_PENDING) con->csock = csock; else con->csock = -1; /* Second: Login with proper USER/PASS sequence. */ logprintf (LOG_VERBOSE, _("Logging in as %s ... "), quotearg_style (escape_quoting_style, user)); if (opt.server_response) logputs (LOG_ALWAYS, "\n"); if (con->proxy) { /* If proxy is in use, log in as username@target-site. */ char *logname = concat_strings (user, "@", u->host, (char *) 0); err = ftp_login (csock, logname, passwd); xfree (logname); } else err = ftp_login (csock, user, passwd); /* FTPRERR, FTPSRVERR, WRITEFAILED, FTPLOGREFUSED, FTPLOGINC */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPSRVERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Error in server greeting.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPLOGREFUSED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("The server refuses login.\n")); fd_close (csock); con->csock = -1; return FTPLOGREFUSED; case FTPLOGINC: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Login incorrect.\n")); fd_close (csock); con->csock = -1; return FTPLOGINC; case FTPOK: if (!opt.server_response) logputs (LOG_VERBOSE, _("Logged in!\n")); break; default: abort (); } /* Third: Get the system type */ if (!opt.server_response) logprintf (LOG_VERBOSE, "==> SYST ... "); err = ftp_syst (csock, &con->rs, &con->rsu); /* FTPRERR */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPSRVERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Server error, can't determine system type.\n")); break; case FTPOK: /* Everything is OK. */ break; default: abort (); } if (!opt.server_response && err != FTPSRVERR) logputs (LOG_VERBOSE, _("done. ")); /* 2013-10-17 Andrea Urbani (matfanjol) According to the system type I choose which list command will be used. If I don't know that system, I will try, the first time of each session, "LIST -a" and "LIST". (see __LIST_A_EXPLANATION__ below) */ switch (con->rs) { case ST_VMS: /* About ST_VMS there is an old note: 2008-01-29 SMS. For a VMS FTP server, where "LIST -a" may not fail, but will never do what is desired here, skip directly to the simple "LIST" command (assumed to be the last one in the list). */ DEBUGP (("\nVMS: I know it and I will use \"LIST\" as standard list command\n")); con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST_A; break; case ST_UNIX: if (con->rsu == UST_MULTINET) { DEBUGP (("\nUNIX MultiNet: I know it and I will use \"LIST\" " "as standard list command\n")); con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST_A; } else if (con->rsu == UST_TYPE_L8) { DEBUGP (("\nUNIX TYPE L8: I know it and I will use \"LIST -a\" " "as standard list command\n")); con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST; } break; default: break; } /* Fourth: Find the initial ftp directory */ if (!opt.server_response) logprintf (LOG_VERBOSE, "==> PWD ... "); err = ftp_pwd (csock, &con->id); /* FTPRERR */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPSRVERR : /* PWD unsupported -- assume "/". */ xfree (con->id); con->id = xstrdup ("/"); break; case FTPOK: /* Everything is OK. */ break; default: abort (); } #if 0 /* 2004-09-17 SMS. Don't help me out. Please. A reasonably recent VMS FTP server will cope just fine with UNIX file specifications. This code just spoils things. Discarding the device name, for example, is not a wise move. This code was disabled but left in as an example of what not to do. */ /* VMS will report something like "PUB$DEVICE:[INITIAL.FOLDER]". Convert it to "/INITIAL/FOLDER" */ if (con->rs == ST_VMS) { char *path = strchr (con->id, '['); char *pathend = path ? strchr (path + 1, ']') : NULL; if (!path || !pathend) DEBUGP (("Initial VMS directory not in the form [...]!\n")); else { char *idir = con->id; DEBUGP (("Preprocessing the initial VMS directory\n")); DEBUGP ((" old = '%s'\n", con->id)); /* We do the conversion in-place by copying the stuff between [ and ] to the beginning, and changing dots to slashes at the same time. */ *idir++ = '/'; for (++path; path < pathend; path++, idir++) *idir = *path == '.' ? '/' : *path; *idir = '\0'; DEBUGP ((" new = '%s'\n\n", con->id)); } } #endif /* 0 */ if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); /* Fifth: Set the FTP type. */ type_char = ftp_process_type (u->params); if (!opt.server_response) logprintf (LOG_VERBOSE, "==> TYPE %c ... ", type_char); err = ftp_type (csock, type_char); /* FTPRERR, WRITEFAILED, FTPUNKNOWNTYPE */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPUNKNOWNTYPE: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Unknown type `%c', closing control connection.\n"), type_char); fd_close (csock); con->csock = -1; return err; case FTPOK: /* Everything is OK. */ break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* do login */ if (cmd & DO_CWD) { if (!*u->dir) logputs (LOG_VERBOSE, _("==> CWD not needed.\n")); else { const char *targ = NULL; int cwd_count; int cwd_end; int cwd_start; char *target = u->dir; DEBUGP (("changing working directory\n")); /* Change working directory. To change to a non-absolute Unix directory, we need to prepend initial directory (con->id) to it. Absolute directories "just work". A relative directory is one that does not begin with '/' and, on non-Unix OS'es, one that doesn't begin with "[a-z]:". This is not done for OS400, which doesn't use "/"-delimited directories, nor does it support directory hierarchies. "CWD foo" followed by "CWD bar" leaves us in "bar", not in "foo/bar", as would be customary elsewhere. */ /* 2004-09-20 SMS. Why is this wise even on UNIX? It certainly fouls VMS. See below for a more reliable, more universal method. */ /* 2008-04-22 MJC. I'm not crazy about it either. I'm informed it's useful for misconfigured servers that have some dirs in the path with +x but -r, but this method is not RFC-conformant. I understand the need to deal with crappy server configurations, but it's far better to use the canonical method first, and fall back to kludges second. */ if (target[0] != '/' && !(con->rs != ST_UNIX && c_isalpha (target[0]) && target[1] == ':') && (con->rs != ST_OS400) && (con->rs != ST_VMS)) { int idlen = strlen (con->id); char *ntarget, *p; /* Strip trailing slash(es) from con->id. */ while (idlen > 0 && con->id[idlen - 1] == '/') --idlen; p = ntarget = (char *)alloca (idlen + 1 + strlen (u->dir) + 1); memcpy (p, con->id, idlen); p += idlen; *p++ = '/'; strcpy (p, target); DEBUGP (("Prepended initial PWD to relative path:\n")); DEBUGP ((" pwd: '%s'\n old: '%s'\n new: '%s'\n", con->id, target, ntarget)); target = ntarget; } #if 0 /* 2004-09-17 SMS. Don't help me out. Please. A reasonably recent VMS FTP server will cope just fine with UNIX file specifications. This code just spoils things. Discarding the device name, for example, is not a wise move. This code was disabled but left in as an example of what not to do. */ /* If the FTP host runs VMS, we will have to convert the absolute directory path in UNIX notation to absolute directory path in VMS notation as VMS FTP servers do not like UNIX notation of absolute paths. "VMS notation" is [dir.subdir.subsubdir]. */ if (con->rs == ST_VMS) { char *tmpp; char *ntarget = (char *)alloca (strlen (target) + 2); /* We use a converted initial dir, so directories in TARGET will be separated with slashes, something like "/INITIAL/FOLDER/DIR/SUBDIR". Convert that to "[INITIAL.FOLDER.DIR.SUBDIR]". */ strcpy (ntarget, target); assert (*ntarget == '/'); *ntarget = '['; for (tmpp = ntarget + 1; *tmpp; tmpp++) if (*tmpp == '/') *tmpp = '.'; *tmpp++ = ']'; *tmpp = '\0'; DEBUGP (("Changed file name to VMS syntax:\n")); DEBUGP ((" Unix: '%s'\n VMS: '%s'\n", target, ntarget)); target = ntarget; } #endif /* 0 */ /* 2004-09-20 SMS. A relative directory is relative to the initial directory. Thus, what _is_ useful on VMS (and probably elsewhere) is to CWD to the initial directory (ideally, whatever the server reports, _exactly_, NOT badly UNIX-ixed), and then CWD to the (new) relative directory. This should probably be restructured as a function, called once or twice, but I'm lazy enough to take the badly indented loop short-cut for now. */ /* Decide on one pass (absolute) or two (relative). The VMS restriction may be relaxed when the squirrely code above is reformed. */ if ((con->rs == ST_VMS) && (target[0] != '/')) { cwd_start = 0; DEBUGP (("Using two-step CWD for relative path.\n")); } else { /* Go straight to the target. */ cwd_start = 1; } /* At least one VMS FTP server (TCPware V5.6-2) can switch to a UNIX emulation mode when given a UNIX-like directory specification (like "a/b/c"). If allowed to continue this way, LIST interpretation will be confused, because the system type (SYST response) will not be re-checked, and future UNIX-format directory listings (for multiple URLs or "-r") will be horribly misinterpreted. The cheap and nasty work-around is to do a "CWD []" after a UNIX-like directory specification is used. (A single-level directory is harmless.) This puts the TCPware server back into VMS mode, and does no harm on other servers. Unlike the rest of this block, this particular behavior _is_ VMS-specific, so it gets its own VMS test. */ if ((con->rs == ST_VMS) && (strchr( target, '/') != NULL)) { cwd_end = 3; DEBUGP (("Using extra \"CWD []\" step for VMS server.\n")); } else { cwd_end = 2; } /* 2004-09-20 SMS. */ /* Sorry about the deviant indenting. Laziness. */ for (cwd_count = cwd_start; cwd_count < cwd_end; cwd_count++) { switch (cwd_count) { case 0: /* Step one (optional): Go to the initial directory, exactly as reported by the server. */ targ = con->id; break; case 1: /* Step two: Go to the target directory. (Absolute or relative will work now.) */ targ = target; break; case 2: /* Step three (optional): "CWD []" to restore server VMS-ness. */ targ = "[]"; break; default: logprintf (LOG_ALWAYS, _("Logically impossible section reached in getftp()")); logprintf (LOG_ALWAYS, _("cwd_count: %d\ncwd_start: %d\ncwd_end: %d\n"), cwd_count, cwd_start, cwd_end); abort (); } if (!opt.server_response) logprintf (LOG_VERBOSE, "==> CWD (%d) %s ... ", cwd_count, quotearg_style (escape_quoting_style, target)); err = ftp_cwd (csock, targ); /* FTPRERR, WRITEFAILED, FTPNSFOD */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPNSFOD: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such directory %s.\n\n"), quote (u->dir)); fd_close (csock); con->csock = -1; return err; case FTPOK: break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); } /* for */ /* 2004-09-20 SMS. */ } /* else */ } else /* do not CWD */ logputs (LOG_VERBOSE, _("==> CWD not required.\n")); if ((cmd & DO_RETR) && passed_expected_bytes == 0) { if (opt.verbose) { if (!opt.server_response) logprintf (LOG_VERBOSE, "==> SIZE %s ... ", quotearg_style (escape_quoting_style, u->file)); } err = ftp_size (csock, u->file, &expected_bytes); /* FTPRERR */ switch (err) { case FTPRERR: case FTPSRVERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPOK: got_expected_bytes = true; /* Everything is OK. */ break; default: abort (); } if (!opt.server_response) { logprintf (LOG_VERBOSE, "%s\n", expected_bytes ? number_to_static_string (expected_bytes) : _("done.\n")); } } if (cmd & DO_RETR && restval > 0 && restval == expected_bytes) { /* Server confirms that file has length restval. We should stop now. Some servers (f.e. NcFTPd) return error when receive REST 0 */ logputs (LOG_VERBOSE, _("File has already been retrieved.\n")); fd_close (csock); con->csock = -1; return RETRFINISHED; } do { try_again = false; /* If anything is to be retrieved, PORT (or PASV) must be sent. */ if (cmd & (DO_LIST | DO_RETR)) { if (opt.ftp_pasv) { ip_address passive_addr; int passive_port; err = ftp_do_pasv (csock, &passive_addr, &passive_port); /* FTPRERR, WRITEFAILED, FTPNOPASV, FTPINVPASV */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPNOPASV: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Cannot initiate PASV transfer.\n")); break; case FTPINVPASV: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Cannot parse PASV response.\n")); break; case FTPOK: break; default: abort (); } /* switch (err) */ if (err==FTPOK) { DEBUGP (("trying to connect to %s port %d\n", print_address (&passive_addr), passive_port)); dtsock = connect_to_ip (&passive_addr, passive_port, NULL); if (dtsock < 0) { int save_errno = errno; fd_close (csock); con->csock = -1; logprintf (LOG_VERBOSE, _("couldn't connect to %s port %d: %s\n"), print_address (&passive_addr), passive_port, strerror (save_errno)); ? CONERROR : CONIMPOSSIBLE); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } else return err; /* * We do not want to fall back from PASSIVE mode to ACTIVE mode ! * The reason is the PORT command exposes the client's real IP address * to the server. Bad for someone who relies on privacy via a ftp proxy. */ } else { err = ftp_do_port (csock, &local_sock); /* FTPRERR, WRITEFAILED, bindport (FTPSYSERR), HOSTERR, logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case CONSOCKERR: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno)); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPSYSERR: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Bind error (%s).\n"), strerror (errno)); fd_close (dtsock); return err; case FTPPORTERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Invalid PORT.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPOK: break; default: abort (); } /* port switch */ if (!opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* dtsock == -1 */ } /* cmd & (DO_LIST | DO_RETR) */ /* Restart if needed. */ if (restval && (cmd & DO_RETR)) { if (!opt.server_response) logprintf (LOG_VERBOSE, "==> REST %s ... ", number_to_static_string (restval)); err = ftp_rest (csock, restval); /* FTPRERR, WRITEFAILED, FTPRESTFAIL */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPRESTFAIL: logputs (LOG_VERBOSE, _("\nREST failed, starting from scratch.\n")); rest_failed = true; break; case FTPOK: break; default: abort (); } if (err != FTPRESTFAIL && !opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* restval && cmd & DO_RETR */ if (cmd & DO_RETR) { /* If we're in spider mode, don't really retrieve anything except the directory listing and verify whether the given "file" exists. */ if (opt.spider) { bool exists = false; struct fileinfo *f; uerr_t _res = ftp_get_listing (u, con, &f); /* Set the DO_RETR command flag again, because it gets unset when calling ftp_get_listing() and would otherwise cause an assertion failure earlier on when this function gets repeatedly called (e.g., when recursing). */ con->cmd |= DO_RETR; if (_res == RETROK) { while (f) { if (!strcmp (f->name, u->file)) { exists = true; break; } f = f->next; } if (exists) { logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("File %s exists.\n"), quote (u->file)); } else { logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such file %s.\n"), quote (u->file)); } } fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return RETRFINISHED; } if (opt.verbose) { if (!opt.server_response) { if (restval) logputs (LOG_VERBOSE, "\n"); logprintf (LOG_VERBOSE, "==> RETR %s ... ", quotearg_style (escape_quoting_style, u->file)); } } err = ftp_retr (csock, u->file); /* FTPRERR, WRITEFAILED, FTPNSFOD */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPNSFOD: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such file %s.\n\n"), quote (u->file)); fd_close (dtsock); fd_close (local_sock); return err; case FTPOK: break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); if (! got_expected_bytes) expected_bytes = *last_expected_bytes; } /* do retrieve */ if (cmd & DO_LIST) { if (!opt.server_response) logputs (LOG_VERBOSE, "==> LIST ... "); /* As Maciej W. Rozycki ([email protected]) says, `LIST' without arguments is better than `LIST .'; confirmed by RFC959. */ err = ftp_list (csock, NULL, con->st&AVOID_LIST_A, con->st&AVOID_LIST, &list_a_used); /* FTPRERR, WRITEFAILED */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPNSFOD: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such file or directory %s.\n\n"), quote (".")); fd_close (dtsock); fd_close (local_sock); return err; case FTPOK: break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); if (! got_expected_bytes) expected_bytes = *last_expected_bytes; } /* cmd & DO_LIST */ if (!(cmd & (DO_LIST | DO_RETR)) || (opt.spider && !(cmd & DO_LIST))) return RETRFINISHED; /* Some FTP servers return the total length of file after REST command, others just return the remaining size. */ if (passed_expected_bytes && restval && expected_bytes && (expected_bytes == passed_expected_bytes - restval)) { DEBUGP (("Lying FTP server found, adjusting.\n")); expected_bytes = passed_expected_bytes; } /* If no transmission was required, then everything is OK. */ if (!pasv_mode_open) /* we are not using pasive mode so we need to accept */ }
164,574
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CoordinatorImpl::UnregisterClientProcess( mojom::ClientProcess* client_process) { QueuedRequest* request = GetCurrentRequest(); if (request != nullptr) { auto it = request->pending_responses.begin(); while (it != request->pending_responses.end()) { std::set<QueuedRequest::PendingResponse>::iterator current = it++; if (current->client != client_process) continue; RemovePendingResponse(client_process, current->type); request->failed_memory_dump_count++; } FinalizeGlobalMemoryDumpIfAllManagersReplied(); } for (auto& pair : in_progress_vm_region_requests_) { QueuedVmRegionRequest* request = pair.second.get(); auto it = request->pending_responses.begin(); while (it != request->pending_responses.end()) { auto current = it++; if (*current == client_process) { request->pending_responses.erase(current); } } } for (auto& pair : in_progress_vm_region_requests_) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( &CoordinatorImpl::FinalizeVmRegionDumpIfAllManagersReplied, base::Unretained(this), pair.second->dump_guid)); } size_t num_deleted = clients_.erase(client_process); DCHECK(num_deleted == 1); } Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained Bug: 856578 Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9 Reviewed-on: https://chromium-review.googlesource.com/1114617 Reviewed-by: Hector Dearman <[email protected]> Commit-Queue: Hector Dearman <[email protected]> Cr-Commit-Position: refs/heads/master@{#571528} CWE ID: CWE-416
void CoordinatorImpl::UnregisterClientProcess( mojom::ClientProcess* client_process) { QueuedRequest* request = GetCurrentRequest(); if (request != nullptr) { auto it = request->pending_responses.begin(); while (it != request->pending_responses.end()) { std::set<QueuedRequest::PendingResponse>::iterator current = it++; if (current->client != client_process) continue; RemovePendingResponse(client_process, current->type); request->failed_memory_dump_count++; } FinalizeGlobalMemoryDumpIfAllManagersReplied(); } for (auto& pair : in_progress_vm_region_requests_) { QueuedVmRegionRequest* request = pair.second.get(); auto it = request->pending_responses.begin(); while (it != request->pending_responses.end()) { auto current = it++; if (*current == client_process) { request->pending_responses.erase(current); } } } for (auto& pair : in_progress_vm_region_requests_) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( &CoordinatorImpl::FinalizeVmRegionDumpIfAllManagersReplied, weak_ptr_factory_.GetWeakPtr(), pair.second->dump_guid)); } size_t num_deleted = clients_.erase(client_process); DCHECK(num_deleted == 1); }
173,216