{"project": "Chrome", "commit_id": "327585cb0eab0859518643a2d00917081f7e7645", "target": 1, "func": "WebGraphicsContext3DDefaultImpl::WebGraphicsContext3DDefaultImpl()\n : m_initialized(false)\n , m_renderDirectlyToWebView(false)\n , m_texture(0)\n , m_fbo(0)\n , m_depthStencilBuffer(0)\n , m_multisampleFBO(0)\n , m_multisampleDepthStencilBuffer(0)\n , m_multisampleColorBuffer(0)\n , m_boundFBO(0)\n#ifdef FLIP_FRAMEBUFFER_VERTICALLY\n , m_scanline(0)\n#endif\n , m_boundArrayBuffer(0)\n , m_fragmentCompiler(0)\n , m_vertexCompiler(0)\n{\n}\n", "cwe": "", "big_vul_idx": 183491, "idx": 4575, "hash": 78432407338258014397826864332755560960} {"project": "Chrome", "commit_id": "327585cb0eab0859518643a2d00917081f7e7645", "target": 0, "func": "WebGraphicsContext3DDefaultImpl::WebGraphicsContext3DDefaultImpl()\n : m_initialized(false)\n , m_renderDirectlyToWebView(false)\n , m_texture(0)\n , m_fbo(0)\n , m_depthStencilBuffer(0)\n , m_cachedWidth(0)\n , m_cachedHeight(0)\n , m_multisampleFBO(0)\n , m_multisampleDepthStencilBuffer(0)\n , m_multisampleColorBuffer(0)\n , m_boundFBO(0)\n#ifdef FLIP_FRAMEBUFFER_VERTICALLY\n , m_scanline(0)\n#endif\n , m_boundArrayBuffer(0)\n , m_fragmentCompiler(0)\n , m_vertexCompiler(0)\n{\n}\n", "cwe": "", "big_vul_idx": 183491, "idx": 161720, "hash": 170893231026076192607745221635147409815} {"project": "Chrome", "commit_id": "123e68f88fd0ed4f7447ba81148f9b619b947c47", "target": 1, "func": "File* DataObjectItem::GetAsFile() const {\n if (Kind() != kFileKind)\n return nullptr;\n\n if (source_ == kInternalSource) {\n if (file_)\n return file_.Get();\n DCHECK(shared_buffer_);\n return nullptr;\n }\n\n DCHECK_EQ(source_, kClipboardSource);\n if (GetType() == kMimeTypeImagePng) {\n SkBitmap bitmap = SystemClipboard::GetInstance().ReadImage(\n mojom::ClipboardBuffer::kStandard);\n\n SkPixmap pixmap;\n bitmap.peekPixels(&pixmap);\n \n Vector png_data;\n SkPngEncoder::Options options;\n options.fZLibLevel = 1; // Fastest compression.\n if (!ImageEncoder::Encode(&png_data, pixmap, options))\n return nullptr;\n \n auto data = std::make_unique();\n data->SetContentType(kMimeTypeImagePng);\n data->AppendBytes(png_data.data(), png_data.size());\n const uint64_t length = data->length();\n auto blob = BlobDataHandle::Create(std::move(data), length);\n return File::Create(\"image.png\", base::Time::Now().ToDoubleT() * 1000.0,\n std::move(blob));\n }\n\n return nullptr;\n}\n", "cwe": "", "big_vul_idx": 183613, "idx": 4678, "hash": 302659875351380439224615645999140556334} {"project": "Chrome", "commit_id": "123e68f88fd0ed4f7447ba81148f9b619b947c47", "target": 0, "func": "File* DataObjectItem::GetAsFile() const {\n if (Kind() != kFileKind)\n return nullptr;\n\n if (source_ == kInternalSource) {\n if (file_)\n return file_.Get();\n DCHECK(shared_buffer_);\n return nullptr;\n }\n\n DCHECK_EQ(source_, kClipboardSource);\n if (GetType() == kMimeTypeImagePng) {\n SkBitmap bitmap = SystemClipboard::GetInstance().ReadImage(\n mojom::ClipboardBuffer::kStandard);\n\n SkPixmap pixmap;\n bitmap.peekPixels(&pixmap);\n \n // Set encoding options to favor speed over size.\n SkPngEncoder::Options options;\n options.fZLibLevel = 1;\n options.fFilterFlags = SkPngEncoder::FilterFlag::kNone;\n\n Vector png_data;\n if (!ImageEncoder::Encode(&png_data, pixmap, options))\n return nullptr;\n \n auto data = std::make_unique();\n data->SetContentType(kMimeTypeImagePng);\n data->AppendBytes(png_data.data(), png_data.size());\n const uint64_t length = data->length();\n auto blob = BlobDataHandle::Create(std::move(data), length);\n return File::Create(\"image.png\", base::Time::Now().ToDoubleT() * 1000.0,\n std::move(blob));\n }\n\n return nullptr;\n}\n", "cwe": "", "big_vul_idx": 183613, "idx": 161816, "hash": 99565885850033950966117426207956082917} {"project": "Chrome", "commit_id": "1da0daecc540238cb473f0d6322da51d3a544244", "target": 1, "func": " void VideoRendererBase::FrameReady(VideoDecoder::DecoderStatus status,\n scoped_refptr frame) {\n base::AutoLock auto_lock(lock_);\n DCHECK_NE(state_, kUninitialized);\n \n CHECK(pending_read_);\n pending_read_ = false;\n\n if (status != VideoDecoder::kOk) {\n DCHECK(!frame);\n PipelineStatus error = PIPELINE_ERROR_DECODE;\n if (status == VideoDecoder::kDecryptError)\n error = PIPELINE_ERROR_DECRYPT;\n\n if (!seek_cb_.is_null()) {\n base::ResetAndReturn(&seek_cb_).Run(error);\n return;\n }\n\n host()->SetError(error);\n return;\n }\n\n if (state_ == kStopped || state_ == kError || state_ == kFlushed ||\n state_ == kFlushingDecoder)\n return;\n\n if (state_ == kFlushing) {\n AttemptFlush_Locked();\n return;\n }\n\n if (!frame) {\n if (state_ != kSeeking)\n return;\n\n state_ = kPrerolled;\n base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);\n return;\n }\n\n if (state_ == kSeeking && !frame->IsEndOfStream() &&\n (frame->GetTimestamp() + frame->GetDuration()) <= seek_timestamp_) {\n AttemptRead_Locked();\n return;\n }\n\n if (!frame->IsEndOfStream()) {\n if (frame->GetTimestamp() > host()->GetDuration())\n frame->SetTimestamp(host()->GetDuration());\n if ((frame->GetTimestamp() + frame->GetDuration()) > host()->GetDuration())\n frame->SetDuration(host()->GetDuration() - frame->GetTimestamp());\n }\n\n ready_frames_.push_back(frame);\n DCHECK_LE(NumFrames_Locked(), limits::kMaxVideoFrames);\n if (!frame->IsEndOfStream())\n time_cb_.Run(frame->GetTimestamp() + frame->GetDuration());\n frame_available_.Signal();\n\n PipelineStatistics statistics;\n statistics.video_frames_decoded = 1;\n statistics_cb_.Run(statistics);\n\n if (NumFrames_Locked() < limits::kMaxVideoFrames && !frame->IsEndOfStream()) {\n AttemptRead_Locked();\n return;\n }\n\n if (state_ == kSeeking) {\n DCHECK(!current_frame_);\n state_ = kPrerolled;\n\n if (!ready_frames_.front()->IsEndOfStream()) {\n current_frame_ = ready_frames_.front();\n ready_frames_.pop_front();\n }\n\n DCHECK(!seek_cb_.is_null());\n base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);\n\n base::AutoUnlock ul(lock_);\n paint_cb_.Run();\n }\n}\n", "cwe": "", "big_vul_idx": 184481, "idx": 5439, "hash": 58467890702351424416835303863183847864} {"project": "Chrome", "commit_id": "1da0daecc540238cb473f0d6322da51d3a544244", "target": 0, "func": " void VideoRendererBase::FrameReady(VideoDecoder::DecoderStatus status,\n const scoped_refptr& frame) {\n base::AutoLock auto_lock(lock_);\n DCHECK_NE(state_, kUninitialized);\n \n CHECK(pending_read_);\n pending_read_ = false;\n\n if (status != VideoDecoder::kOk) {\n DCHECK(!frame);\n PipelineStatus error = PIPELINE_ERROR_DECODE;\n if (status == VideoDecoder::kDecryptError)\n error = PIPELINE_ERROR_DECRYPT;\n\n if (!seek_cb_.is_null()) {\n base::ResetAndReturn(&seek_cb_).Run(error);\n return;\n }\n\n host()->SetError(error);\n return;\n }\n\n if (state_ == kStopped || state_ == kError || state_ == kFlushed ||\n state_ == kFlushingDecoder)\n return;\n\n if (state_ == kFlushing) {\n AttemptFlush_Locked();\n return;\n }\n\n if (!frame) {\n if (state_ != kSeeking)\n return;\n\n state_ = kPrerolled;\n base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);\n return;\n }\n\n if (state_ == kSeeking && !frame->IsEndOfStream() &&\n (frame->GetTimestamp() + frame->GetDuration()) <= seek_timestamp_) {\n AttemptRead_Locked();\n return;\n }\n\n if (!frame->IsEndOfStream()) {\n if (frame->GetTimestamp() > host()->GetDuration())\n frame->SetTimestamp(host()->GetDuration());\n if ((frame->GetTimestamp() + frame->GetDuration()) > host()->GetDuration())\n frame->SetDuration(host()->GetDuration() - frame->GetTimestamp());\n }\n\n ready_frames_.push_back(frame);\n DCHECK_LE(NumFrames_Locked(), limits::kMaxVideoFrames);\n if (!frame->IsEndOfStream())\n time_cb_.Run(frame->GetTimestamp() + frame->GetDuration());\n frame_available_.Signal();\n\n PipelineStatistics statistics;\n statistics.video_frames_decoded = 1;\n statistics_cb_.Run(statistics);\n\n if (NumFrames_Locked() < limits::kMaxVideoFrames && !frame->IsEndOfStream()) {\n AttemptRead_Locked();\n return;\n }\n\n if (state_ == kSeeking) {\n DCHECK(!current_frame_);\n state_ = kPrerolled;\n\n if (!ready_frames_.front()->IsEndOfStream()) {\n current_frame_ = ready_frames_.front();\n ready_frames_.pop_front();\n }\n\n DCHECK(!seek_cb_.is_null());\n base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);\n\n base::AutoUnlock ul(lock_);\n paint_cb_.Run();\n }\n}\n", "cwe": "", "big_vul_idx": 184481, "idx": 162555, "hash": 27375883205547855814872471618190506441} {"project": "Chrome", "commit_id": "1a113d35a19c0ed6500fb5c0acdc35730617fb3f", "target": 1, "func": "void ContentSettingsStore::ClearContentSettingsForExtension(\n const std::string& ext_id,\n ExtensionPrefsScope scope) {\n bool notify = false;\n {\n base::AutoLock lock(lock_);\n OriginIdentifierValueMap* map = GetValueMap(ext_id, scope);\n char ext_id_buffer[33];\n base::strlcpy(ext_id_buffer, ext_id.c_str(), sizeof(ext_id_buffer));\n base::debug::Alias(ext_id_buffer);\n CHECK(false);\n }\n notify = !map->empty();\n map->clear();\n }\n if (notify) {\n NotifyOfContentSettingChanged(ext_id, scope != kExtensionPrefsScopeRegular);\n }\n}\n", "cwe": "", "big_vul_idx": 184504, "idx": 5458, "hash": 265797374762752738816496693872000415093} {"project": "Chrome", "commit_id": "1a113d35a19c0ed6500fb5c0acdc35730617fb3f", "target": 0, "func": "void ContentSettingsStore::ClearContentSettingsForExtension(\n const std::string& ext_id,\n ExtensionPrefsScope scope) {\n bool notify = false;\n {\n base::AutoLock lock(lock_);\n OriginIdentifierValueMap* map = GetValueMap(ext_id, scope);\n // Fail gracefully in Release builds.\n NOTREACHED();\n return;\n }\n notify = !map->empty();\n map->clear();\n }\n if (notify) {\n NotifyOfContentSettingChanged(ext_id, scope != kExtensionPrefsScopeRegular);\n }\n}\n", "cwe": "", "big_vul_idx": 184504, "idx": 162573, "hash": 12967184921243506354797539177835054040} {"project": "Chrome", "commit_id": "87190165c55bcf3eecd8824dd8d083f5e3236552", "target": 1, "func": "AudioOutputStream* AudioManagerBase::MakeAudioOutputStreamProxy(\n const AudioParameters& params) {\n DCHECK(GetMessageLoop()->BelongsToCurrentThread());\n\n scoped_refptr& dispatcher =\n output_dispatchers_[params];\n if (!dispatcher) {\n base::TimeDelta close_delay =\n base::TimeDelta::FromSeconds(kStreamCloseDelaySeconds);\n#if defined(OS_WIN) || defined(OS_MACOSX)\n const CommandLine* cmd_line = CommandLine::ForCurrentProcess();\n if (!cmd_line->HasSwitch(switches::kDisableAudioMixer)) {\n dispatcher = new AudioOutputMixer(this, params, close_delay);\n } else\n#endif\n {\n dispatcher = new AudioOutputDispatcherImpl(this, params, close_delay);\n }\n }\n return new AudioOutputProxy(dispatcher);\n}\n", "cwe": "", "big_vul_idx": 184505, "idx": 5459, "hash": 22383497495526524382736548714282288020} {"project": "Chrome", "commit_id": "87190165c55bcf3eecd8824dd8d083f5e3236552", "target": 0, "func": "AudioOutputStream* AudioManagerBase::MakeAudioOutputStreamProxy(\n const AudioParameters& params) {\n DCHECK(GetMessageLoop()->BelongsToCurrentThread());\n\n scoped_refptr& dispatcher =\n output_dispatchers_[params];\n if (!dispatcher) {\n base::TimeDelta close_delay =\n base::TimeDelta::FromSeconds(kStreamCloseDelaySeconds);\n const CommandLine* cmd_line = CommandLine::ForCurrentProcess();\n // TODO(dalecurtis): Browser side mixing has a couple issues that must be\n // fixed before it can be turned on by default: http://crbug.com/138098 and\n // http://crbug.com/140247\n if (cmd_line->HasSwitch(switches::kEnableAudioMixer)) {\n dispatcher = new AudioOutputMixer(this, params, close_delay);\n } else {\n dispatcher = new AudioOutputDispatcherImpl(this, params, close_delay);\n }\n }\n return new AudioOutputProxy(dispatcher);\n}\n", "cwe": "", "big_vul_idx": 184505, "idx": 162574, "hash": 163384496782536430146812673574056017632} {"project": "Chrome", "commit_id": "a5333583f14284a411abac2fef7caed889a8bba3", "target": 1, "func": " void ServiceWorkerScriptContext::OnInstallEvent(\n int active_version_embedded_worker_id) {\n DidHandleInstallEvent(current_request_id_);\n }\n", "cwe": "", "big_vul_idx": 185011, "idx": 5909, "hash": 199087988793021330181873049420535142766} {"project": "Chrome", "commit_id": "a5333583f14284a411abac2fef7caed889a8bba3", "target": 0, "func": " void ServiceWorkerScriptContext::OnInstallEvent(\n int active_version_embedded_worker_id) {\n proxy_->dispatchInstallEvent(current_request_id_);\n }\n", "cwe": "", "big_vul_idx": 185011, "idx": 162999, "hash": 294367026305307966881882708988400529093} {"project": "Chrome", "commit_id": "9a3dbf43f97aa7cb6b4399f9b11ce1de20f0680f", "target": 1, "func": "void SpeechSynthesis::handleSpeakingCompleted(SpeechSynthesisUtterance* utterance, bool errorOccurred)\n {\n ASSERT(utterance);\n \n bool didJustFinishCurrentUtterance = false;\n if (utterance == currentSpeechUtterance()) {\n m_utteranceQueue.removeFirst();\n didJustFinishCurrentUtterance = true;\n }\n\n fireEvent(errorOccurred ? EventTypeNames::error : EventTypeNames::end, utterance, 0, String());\n\n if (didJustFinishCurrentUtterance && !m_utteranceQueue.isEmpty())\n startSpeakingImmediately();\n}\n", "cwe": "", "big_vul_idx": 185386, "idx": 6244, "hash": 51064366369637881630682008748783014232} {"project": "Chrome", "commit_id": "9a3dbf43f97aa7cb6b4399f9b11ce1de20f0680f", "target": 0, "func": "void SpeechSynthesis::handleSpeakingCompleted(SpeechSynthesisUtterance* utterance, bool errorOccurred)\n {\n ASSERT(utterance);\n \n // Keep the utterance around long enough to fire an event on it in case m_utteranceQueue\n // is holding the last reference to it.\n RefPtrWillBeRawPtr protect(utterance);\n\n bool didJustFinishCurrentUtterance = false;\n if (utterance == currentSpeechUtterance()) {\n m_utteranceQueue.removeFirst();\n didJustFinishCurrentUtterance = true;\n }\n\n fireEvent(errorOccurred ? EventTypeNames::error : EventTypeNames::end, utterance, 0, String());\n\n if (didJustFinishCurrentUtterance && !m_utteranceQueue.isEmpty())\n startSpeakingImmediately();\n}\n", "cwe": "", "big_vul_idx": 185386, "idx": 163331, "hash": 23380105532145118333362184433256570897} {"project": "Chrome", "commit_id": "ea994548ed483e234a6fadd0cbdfa10d58b75cef", "target": 1, "func": "bool SoftwareFrameManager::SwapToNewFrame(\n uint32 output_surface_id,\n const cc::SoftwareFrameData* frame_data,\n float frame_device_scale_factor,\n base::ProcessHandle process_handle) {\n\n#ifdef OS_WIN\n scoped_ptr shared_memory(\n new base::SharedMemory(frame_data->handle, true,\n process_handle));\n#else\n scoped_ptr shared_memory(\n new base::SharedMemory(frame_data->handle, true));\n#endif\n \n if (base::SharedMemory::IsHandleValid(shared_memory->handle())) {\n const size_t size_in_bytes = 4 * frame_data->size.GetArea();\n #ifdef OS_WIN\n if (!shared_memory->Map(0)) {\n DLOG(ERROR) << \"Unable to map renderer memory.\";\n RecordAction(\n base::UserMetricsAction(\"BadMessageTerminate_SharedMemoryManager1\"));\n return false;\n }\n\n if (shared_memory->mapped_size() < size_in_bytes) {\n DLOG(ERROR) << \"Shared memory too small for given rectangle\";\n RecordAction(\n base::UserMetricsAction(\"BadMessageTerminate_SharedMemoryManager2\"));\n return false;\n }\n#else\n if (!shared_memory->Map(size_in_bytes)) {\n DLOG(ERROR) << \"Unable to map renderer memory.\";\n RecordAction(\n base::UserMetricsAction(\"BadMessageTerminate_SharedMemoryManager1\"));\n return false;\n }\n#endif\n }\n\n scoped_refptr next_frame(new SoftwareFrame(\n client_,\n output_surface_id,\n frame_data->id,\n frame_device_scale_factor,\n frame_data->size,\n shared_memory.Pass()));\n current_frame_.swap(next_frame);\n return true;\n}\n", "cwe": "", "big_vul_idx": 185417, "idx": 6270, "hash": 116003027451590305936545199542467169705} {"project": "Chrome", "commit_id": "ea994548ed483e234a6fadd0cbdfa10d58b75cef", "target": 0, "func": "bool SoftwareFrameManager::SwapToNewFrame(\n uint32 output_surface_id,\n const cc::SoftwareFrameData* frame_data,\n float frame_device_scale_factor,\n base::ProcessHandle process_handle) {\n\n#ifdef OS_WIN\n scoped_ptr shared_memory(\n new base::SharedMemory(frame_data->handle, true,\n process_handle));\n#else\n scoped_ptr shared_memory(\n new base::SharedMemory(frame_data->handle, true));\n#endif\n \n if (base::SharedMemory::IsHandleValid(shared_memory->handle())) {\n base::CheckedNumeric size_in_bytes_checked =\n base::CheckedNumeric(4) *\n base::CheckedNumeric(frame_data->size.width()) *\n base::CheckedNumeric(frame_data->size.height());\n if (!size_in_bytes_checked.IsValid()) {\n DLOG(ERROR) << \"Integer overflow when computing bytes to map.\";\n return false;\n }\n size_t size_in_bytes = size_in_bytes_checked.ValueOrDie();\n #ifdef OS_WIN\n if (!shared_memory->Map(0)) {\n DLOG(ERROR) << \"Unable to map renderer memory.\";\n RecordAction(\n base::UserMetricsAction(\"BadMessageTerminate_SharedMemoryManager1\"));\n return false;\n }\n\n if (shared_memory->mapped_size() < size_in_bytes) {\n DLOG(ERROR) << \"Shared memory too small for given rectangle\";\n RecordAction(\n base::UserMetricsAction(\"BadMessageTerminate_SharedMemoryManager2\"));\n return false;\n }\n#else\n if (!shared_memory->Map(size_in_bytes)) {\n DLOG(ERROR) << \"Unable to map renderer memory.\";\n RecordAction(\n base::UserMetricsAction(\"BadMessageTerminate_SharedMemoryManager1\"));\n return false;\n }\n#endif\n }\n\n scoped_refptr next_frame(new SoftwareFrame(\n client_,\n output_surface_id,\n frame_data->id,\n frame_device_scale_factor,\n frame_data->size,\n shared_memory.Pass()));\n current_frame_.swap(next_frame);\n return true;\n}\n", "cwe": "", "big_vul_idx": 185417, "idx": 163357, "hash": 38030128573621593790463547507154903710} {"project": "Chrome", "commit_id": "3454ed7b88318dcd4539c6e1a50d27b0ca535686", "target": 1, "func": "base::string16 GenerateKeywordFromNavigationEntry(\n const NavigationEntry* entry,\n const std::string& accept_languages) {\n if (IsFormSubmit(entry))\n return base::string16();\n\n GURL url = entry->GetUserTypedURL();\n if (!url.is_valid()) {\n url = entry->GetURL();\n if (!url.is_valid())\n return base::string16();\n }\n \n if (!url.SchemeIs(url::kHttpScheme) || (url.path().length() > 1))\n return base::string16();\n \n return TemplateURL::GenerateKeyword(url, accept_languages);\n }\n", "cwe": "", "big_vul_idx": 185451, "idx": 6302, "hash": 186236423855654680462739638936218281309} {"project": "Chrome", "commit_id": "3454ed7b88318dcd4539c6e1a50d27b0ca535686", "target": 0, "func": "base::string16 GenerateKeywordFromNavigationEntry(\n const NavigationEntry* entry,\n const std::string& accept_languages) {\n if (IsFormSubmit(entry))\n return base::string16();\n\n GURL url = entry->GetUserTypedURL();\n if (!url.is_valid()) {\n url = entry->GetURL();\n if (!url.is_valid())\n return base::string16();\n }\n \n // Don't autogenerate keywords for referrers that\n // a) are anything other than HTTP/HTTPS or\n // b) have a path.\n if (!(url.SchemeIs(url::kHttpScheme) || url.SchemeIs(url::kHttpsScheme)) ||\n (url.path().length() > 1)) {\n return base::string16();\n }\n \n return TemplateURL::GenerateKeyword(url, accept_languages);\n }\n", "cwe": "", "big_vul_idx": 185451, "idx": 163389, "hash": 215967538991632573956354911036881851299} {"project": "Chrome", "commit_id": "6834289784ed45b5524de0fb7ef43ae283b0d6d3", "target": 1, "func": "void MediaElementAudioSourceNode::process(size_t numberOfFrames)\n{\n AudioBus* outputBus = output(0)->bus();\n\n if (!mediaElement() || !m_sourceNumberOfChannels || !m_sourceSampleRate) {\n outputBus->zero();\n return;\n }\n\n MutexTryLocker tryLocker(m_processLock);\n if (tryLocker.locked()) {\n if (AudioSourceProvider* provider = mediaElement()->audioSourceProvider()) {\n if (m_multiChannelResampler.get()) {\n ASSERT(m_sourceSampleRate != sampleRate());\n m_multiChannelResampler->process(provider, outputBus, numberOfFrames);\n } else {\n ASSERT(m_sourceSampleRate == sampleRate());\n provider->provideInput(outputBus, numberOfFrames);\n }\n } else {\n outputBus->zero();\n }\n } else {\n outputBus->zero();\n }\n}\n", "cwe": "", "big_vul_idx": 185901, "idx": 6705, "hash": 214516605251072031911924399596715967965} {"project": "Chrome", "commit_id": "6834289784ed45b5524de0fb7ef43ae283b0d6d3", "target": 0, "func": "void MediaElementAudioSourceNode::process(size_t numberOfFrames)\n{\n AudioBus* outputBus = output(0)->bus();\n\n if (!mediaElement() || !m_sourceNumberOfChannels || !m_sourceSampleRate) {\n outputBus->zero();\n return;\n }\n\n MutexTryLocker tryLocker(m_processLock);\n if (tryLocker.locked()) {\n if (AudioSourceProvider* provider = mediaElement()->audioSourceProvider()) {\n // Grab data from the provider so that the element continues to make progress, even if\n // we're going to output silence anyway.\n if (m_multiChannelResampler.get()) {\n ASSERT(m_sourceSampleRate != sampleRate());\n m_multiChannelResampler->process(provider, outputBus, numberOfFrames);\n } else {\n ASSERT(m_sourceSampleRate == sampleRate());\n provider->provideInput(outputBus, numberOfFrames);\n }\n // Output silence if we don't have access to the element.\n if (!(mediaElement()->webMediaPlayer()->didPassCORSAccessCheck()\n || context()->securityOrigin()->canRequest(mediaElement()->currentSrc()))) {\n outputBus->zero();\n }\n } else {\n outputBus->zero();\n }\n } else {\n outputBus->zero();\n }\n}\n", "cwe": "", "big_vul_idx": 185901, "idx": 163787, "hash": 144288665457382459246238377147852566025} {"func": "String preg_quote(const String& str,\n const String& delimiter /* = null_string */) {\n const char* in_str = str.data();\n const char* in_str_end = in_str + str.size();\n\n /* Nothing to do if we got an empty string */\n if (in_str == in_str_end) {\n return str;\n }\n\n char delim_char = 0; /* Delimiter character to be quoted */\n bool quote_delim = false; /* Whether to quote additional delim char */\n if (!delimiter.empty()) {\n delim_char = delimiter.charAt(0);\n quote_delim = true;\n }\n\n /* Allocate enough memory so that even if each character\n is quoted, we won't run out of room */\n String ret(4 * str.size() + 1, ReserveString);\n char* out_str = ret.mutableData();\n\n /* Go through the string and quote necessary characters */\n const char* p;\n char* q;\n for (p = in_str, q = out_str; p != in_str_end; p++) {\n char c = *p;\n switch (c) {\n case '.': case '\\\\': case '+': case '*': case '?':\n case '[': case '^': case ']': case '$': case '(':\n case ')': case '{': case '}': case '=': case '!':\n case '>': case '<': case '|': case ':': case '-':\n case '#':\n *q++ = '\\\\';\n *q++ = c;\n break;\n\n case '\\0':\n *q++ = '\\\\';\n *q++ = '0';\n *q++ = '0';\n *q++ = '0';\n break;\n\n default:\n if (quote_delim && c == delim_char)\n *q++ = '\\\\';\n *q++ = c;\n break;\n }\n }\n *q = '\\0';\n\n return ret.setSize(q - out_str);\n}", "project": "hhvm", "hash": 189278878836233230295539538309071035452, "size": 55, "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "target": 1, "dataset": "other", "idx": 194999} {"func": "String preg_quote(const String& str,\n const String& delimiter /* = null_string */) {\n const char* in_str = str.data();\n const char* in_str_end = in_str + str.size();\n\n /* Nothing to do if we got an empty string */\n if (in_str == in_str_end) {\n return str;\n }\n\n char delim_char = 0; /* Delimiter character to be quoted */\n bool quote_delim = false; /* Whether to quote additional delim char */\n if (!delimiter.empty()) {\n delim_char = delimiter.charAt(0);\n quote_delim = true;\n }\n\n /* Allocate enough memory so that even if each character\n is quoted, we won't run out of room */\n static_assert(\n (StringData::MaxSize * 4 + 1) < std::numeric_limits::max()\n );\n String ret(4 * str.size() + 1, ReserveString);\n char* out_str = ret.mutableData();\n\n /* Go through the string and quote necessary characters */\n const char* p;\n char* q;\n for (p = in_str, q = out_str; p != in_str_end; p++) {\n char c = *p;\n switch (c) {\n case '.': case '\\\\': case '+': case '*': case '?':\n case '[': case '^': case ']': case '$': case '(':\n case ')': case '{': case '}': case '=': case '!':\n case '>': case '<': case '|': case ':': case '-':\n case '#':\n *q++ = '\\\\';\n *q++ = c;\n break;\n\n case '\\0':\n *q++ = '\\\\';\n *q++ = '0';\n *q++ = '0';\n *q++ = '0';\n break;\n\n default:\n if (quote_delim && c == delim_char)\n *q++ = '\\\\';\n *q++ = c;\n break;\n }\n }\n *q = '\\0';\n\n return ret.setSize(q - out_str);\n}", "project": "hhvm", "hash": 220981898952866903098305403168592775003, "size": 58, "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "target": 0, "dataset": "other", "idx": 219542} {"func": "static int xbuf_format_converter(char **outbuf, const char *fmt, va_list ap)\n{\n register char *s = nullptr;\n char *q;\n int s_len;\n\n register int min_width = 0;\n int precision = 0;\n enum {\n LEFT, RIGHT\n } adjust;\n char pad_char;\n char prefix_char;\n\n double fp_num;\n wide_int i_num = (wide_int) 0;\n u_wide_int ui_num;\n\n char num_buf[NUM_BUF_SIZE];\n char char_buf[2]; /* for printing %% and % */\n\n#ifdef HAVE_LOCALE_H\n struct lconv *lconv = nullptr;\n#endif\n\n /*\n * Flag variables\n */\n length_modifier_e modifier;\n boolean_e alternate_form;\n boolean_e print_sign;\n boolean_e print_blank;\n boolean_e adjust_precision;\n boolean_e adjust_width;\n int is_negative;\n\n int size = 240;\n char *result = (char *)malloc(size);\n int outpos = 0;\n\n while (*fmt) {\n if (*fmt != '%') {\n appendchar(&result, &outpos, &size, *fmt);\n } else {\n /*\n * Default variable settings\n */\n adjust = RIGHT;\n alternate_form = print_sign = print_blank = NO;\n pad_char = ' ';\n prefix_char = NUL;\n\n fmt++;\n\n /*\n * Try to avoid checking for flags, width or precision\n */\n if (isascii((int)*fmt) && !islower((int)*fmt)) {\n /*\n * Recognize flags: -, #, BLANK, +\n */\n for (;; fmt++) {\n if (*fmt == '-')\n adjust = LEFT;\n else if (*fmt == '+')\n print_sign = YES;\n else if (*fmt == '#')\n alternate_form = YES;\n else if (*fmt == ' ')\n print_blank = YES;\n else if (*fmt == '0')\n pad_char = '0';\n else\n break;\n }\n\n /*\n * Check if a width was specified\n */\n if (isdigit((int)*fmt)) {\n STR_TO_DEC(fmt, min_width);\n adjust_width = YES;\n } else if (*fmt == '*') {\n min_width = va_arg(ap, int);\n fmt++;\n adjust_width = YES;\n if (min_width < 0) {\n adjust = LEFT;\n min_width = -min_width;\n }\n } else\n adjust_width = NO;\n\n /*\n * Check if a precision was specified\n *\n * XXX: an unreasonable amount of precision may be specified\n * resulting in overflow of num_buf. Currently we\n * ignore this possibility.\n */\n if (*fmt == '.') {\n adjust_precision = YES;\n fmt++;\n if (isdigit((int)*fmt)) {\n STR_TO_DEC(fmt, precision);\n } else if (*fmt == '*') {\n precision = va_arg(ap, int);\n fmt++;\n if (precision < 0)\n precision = 0;\n } else\n precision = 0;\n } else\n adjust_precision = NO;\n } else\n adjust_precision = adjust_width = NO;\n\n /*\n * Modifier check\n */\n switch (*fmt) {\n case 'L':\n fmt++;\n modifier = LM_LONG_DOUBLE;\n break;\n case 'I':\n fmt++;\n#if SIZEOF_LONG_LONG\n if (*fmt == '6' && *(fmt+1) == '4') {\n fmt += 2;\n modifier = LM_LONG_LONG;\n } else\n#endif\n if (*fmt == '3' && *(fmt+1) == '2') {\n fmt += 2;\n modifier = LM_LONG;\n } else {\n#ifdef _WIN64\n modifier = LM_LONG_LONG;\n#else\n modifier = LM_LONG;\n#endif\n }\n break;\n case 'l':\n fmt++;\n#if SIZEOF_LONG_LONG\n if (*fmt == 'l') {\n fmt++;\n modifier = LM_LONG_LONG;\n } else\n#endif\n modifier = LM_LONG;\n break;\n case 'z':\n fmt++;\n modifier = LM_SIZE_T;\n break;\n case 'j':\n fmt++;\n#if SIZEOF_INTMAX_T\n modifier = LM_INTMAX_T;\n#else\n modifier = LM_SIZE_T;\n#endif\n break;\n case 't':\n fmt++;\n#if SIZEOF_PTRDIFF_T\n modifier = LM_PTRDIFF_T;\n#else\n modifier = LM_SIZE_T;\n#endif\n break;\n case 'h':\n fmt++;\n if (*fmt == 'h') {\n fmt++;\n }\n /* these are promoted to int, so no break */\n default:\n modifier = LM_STD;\n break;\n }\n\n /*\n * Argument extraction and printing.\n * First we determine the argument type.\n * Then, we convert the argument to a string.\n * On exit from the switch, s points to the string that\n * must be printed, s_len has the length of the string\n * The precision requirements, if any, are reflected in s_len.\n *\n * NOTE: pad_char may be set to '0' because of the 0 flag.\n * It is reset to ' ' by non-numeric formats\n */\n switch (*fmt) {\n case 'u':\n switch(modifier) {\n default:\n i_num = (wide_int) va_arg(ap, unsigned int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n i_num = (wide_int) va_arg(ap, unsigned long int);\n break;\n case LM_SIZE_T:\n i_num = (wide_int) va_arg(ap, size_t);\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n i_num = (wide_int) va_arg(ap, u_wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n i_num = (wide_int) va_arg(ap, uintmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n i_num = (wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n /*\n * The rest also applies to other integer formats, so fall\n * into that case.\n */\n case 'd':\n case 'i':\n /*\n * Get the arg if we haven't already.\n */\n if ((*fmt) != 'u') {\n switch(modifier) {\n default:\n i_num = (wide_int) va_arg(ap, int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n i_num = (wide_int) va_arg(ap, long int);\n break;\n case LM_SIZE_T:\n#if SIZEOF_SSIZE_T\n i_num = (wide_int) va_arg(ap, ssize_t);\n#else\n i_num = (wide_int) va_arg(ap, size_t);\n#endif\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n i_num = (wide_int) va_arg(ap, wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n i_num = (wide_int) va_arg(ap, intmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n i_num = (wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n }\n s = ap_php_conv_10(i_num, (*fmt) == 'u', &is_negative,\n &num_buf[NUM_BUF_SIZE], &s_len);\n FIX_PRECISION(adjust_precision, precision, s, s_len);\n\n if (*fmt != 'u') {\n if (is_negative)\n prefix_char = '-';\n else if (print_sign)\n prefix_char = '+';\n else if (print_blank)\n prefix_char = ' ';\n }\n break;\n\n\n case 'o':\n switch(modifier) {\n default:\n ui_num = (u_wide_int) va_arg(ap, unsigned int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n ui_num = (u_wide_int) va_arg(ap, unsigned long int);\n break;\n case LM_SIZE_T:\n ui_num = (u_wide_int) va_arg(ap, size_t);\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n ui_num = (u_wide_int) va_arg(ap, u_wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n ui_num = (u_wide_int) va_arg(ap, uintmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n s = ap_php_conv_p2(ui_num, 3, *fmt,\n &num_buf[NUM_BUF_SIZE], &s_len);\n FIX_PRECISION(adjust_precision, precision, s, s_len);\n if (alternate_form && *s != '0') {\n *--s = '0';\n s_len++;\n }\n break;\n\n\n case 'x':\n case 'X':\n switch(modifier) {\n default:\n ui_num = (u_wide_int) va_arg(ap, unsigned int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n ui_num = (u_wide_int) va_arg(ap, unsigned long int);\n break;\n case LM_SIZE_T:\n ui_num = (u_wide_int) va_arg(ap, size_t);\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n ui_num = (u_wide_int) va_arg(ap, u_wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n ui_num = (u_wide_int) va_arg(ap, uintmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n s = ap_php_conv_p2(ui_num, 4, *fmt,\n &num_buf[NUM_BUF_SIZE], &s_len);\n FIX_PRECISION(adjust_precision, precision, s, s_len);\n if (alternate_form && i_num != 0) {\n *--s = *fmt; /* 'x' or 'X' */\n *--s = '0';\n s_len += 2;\n }\n break;\n\n\n case 's':\n case 'v':\n s = va_arg(ap, char *);\n if (s != nullptr) {\n s_len = strlen(s);\n if (adjust_precision && precision < s_len)\n s_len = precision;\n } else {\n s = const_cast(s_null);\n s_len = S_NULL_LEN;\n }\n pad_char = ' ';\n break;\n\n\n case 'f':\n case 'F':\n case 'e':\n case 'E':\n switch(modifier) {\n case LM_LONG_DOUBLE:\n fp_num = (double) va_arg(ap, long double);\n break;\n case LM_STD:\n fp_num = va_arg(ap, double);\n break;\n default:\n goto fmt_error;\n }\n\n if (std::isnan(fp_num)) {\n s = const_cast(\"nan\");\n s_len = 3;\n } else if (std::isinf(fp_num)) {\n s = const_cast(\"inf\");\n s_len = 3;\n } else {\n#ifdef HAVE_LOCALE_H\n if (!lconv) {\n lconv = localeconv();\n }\n#endif\n s = php_conv_fp((*fmt == 'f')?'F':*fmt, fp_num, alternate_form,\n (adjust_precision == NO) ? FLOAT_DIGITS : precision,\n (*fmt == 'f')?LCONV_DECIMAL_POINT:'.',\n &is_negative, &num_buf[1], &s_len);\n if (is_negative)\n prefix_char = '-';\n else if (print_sign)\n prefix_char = '+';\n else if (print_blank)\n prefix_char = ' ';\n }\n break;\n\n\n case 'g':\n case 'k':\n case 'G':\n case 'H':\n switch(modifier) {\n case LM_LONG_DOUBLE:\n fp_num = (double) va_arg(ap, long double);\n break;\n case LM_STD:\n fp_num = va_arg(ap, double);\n break;\n default:\n goto fmt_error;\n }\n\n if (std::isnan(fp_num)) {\n s = const_cast(\"NAN\");\n s_len = 3;\n break;\n } else if (std::isinf(fp_num)) {\n if (fp_num > 0) {\n s = const_cast(\"INF\");\n s_len = 3;\n } else {\n s = const_cast(\"-INF\");\n s_len = 4;\n }\n break;\n }\n\n if (adjust_precision == NO)\n precision = FLOAT_DIGITS;\n else if (precision == 0)\n precision = 1;\n /*\n * * We use &num_buf[ 1 ], so that we have room for the sign\n */\n#ifdef HAVE_LOCALE_H\n if (!lconv) {\n lconv = localeconv();\n }\n#endif\n s = php_gcvt(fp_num, precision,\n (*fmt=='H' || *fmt == 'k') ? '.' : LCONV_DECIMAL_POINT,\n (*fmt == 'G' || *fmt == 'H')?'E':'e', &num_buf[1]);\n if (*s == '-')\n prefix_char = *s++;\n else if (print_sign)\n prefix_char = '+';\n else if (print_blank)\n prefix_char = ' ';\n\n s_len = strlen(s);\n\n if (alternate_form && (q = strchr(s, '.')) == nullptr)\n s[s_len++] = '.';\n break;\n\n\n case 'c':\n char_buf[0] = (char) (va_arg(ap, int));\n s = &char_buf[0];\n s_len = 1;\n pad_char = ' ';\n break;\n\n\n case '%':\n char_buf[0] = '%';\n s = &char_buf[0];\n s_len = 1;\n pad_char = ' ';\n break;\n\n\n case 'n':\n *(va_arg(ap, int *)) = outpos;\n goto skip_output;\n\n /*\n * Always extract the argument as a \"char *\" pointer. We\n * should be using \"void *\" but there are still machines\n * that don't understand it.\n * If the pointer size is equal to the size of an unsigned\n * integer we convert the pointer to a hex number, otherwise\n * we print \"%p\" to indicate that we don't handle \"%p\".\n */\n case 'p':\n if (sizeof(char *) <= sizeof(u_wide_int)) {\n ui_num = (u_wide_int)((size_t) va_arg(ap, char *));\n s = ap_php_conv_p2(ui_num, 4, 'x',\n &num_buf[NUM_BUF_SIZE], &s_len);\n if (ui_num != 0) {\n *--s = 'x';\n *--s = '0';\n s_len += 2;\n }\n } else {\n s = const_cast(\"%p\");\n s_len = 2;\n }\n pad_char = ' ';\n break;\n\n\n case NUL:\n /*\n * The last character of the format string was %.\n * We ignore it.\n */\n continue;\n\n\nfmt_error:\n throw Exception(\"Illegal length modifier specified '%c'\", *fmt);\n\n /*\n * The default case is for unrecognized %'s.\n * We print % to help the user identify what\n * option is not understood.\n * This is also useful in case the user wants to pass\n * the output of format_converter to another function\n * that understands some other % (like syslog).\n * Note that we can't point s inside fmt because the\n * unknown could be preceded by width etc.\n */\n default:\n char_buf[0] = '%';\n char_buf[1] = *fmt;\n s = char_buf;\n s_len = 2;\n pad_char = ' ';\n break;\n }\n\n if (prefix_char != NUL) {\n *--s = prefix_char;\n s_len++;\n }\n if (adjust_width && adjust == RIGHT && min_width > s_len) {\n if (pad_char == '0' && prefix_char != NUL) {\n appendchar(&result, &outpos, &size, *s);\n s++;\n s_len--;\n min_width--;\n }\n for (int i = 0; i < min_width - s_len; i++) {\n appendchar(&result, &outpos, &size, pad_char);\n }\n }\n /*\n * Print the (for now) non-null terminated string s.\n */\n appendsimplestring(&result, &outpos, &size, s, s_len);\n\n if (adjust_width && adjust == LEFT && min_width > s_len) {\n for (int i = 0; i < min_width - s_len; i++) {\n appendchar(&result, &outpos, &size, pad_char);\n }\n }\n }\nskip_output:\n fmt++;\n }\n /*\n * Add the terminating null here since it wasn't added incrementally above\n * once the whole string has been composed.\n */\n result[outpos] = NUL;\n *outbuf = result;\n return outpos;\n}", "project": "hhvm", "hash": 262008690145899457289472739326596420497, "size": 592, "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "target": 1, "dataset": "other", "idx": 195007} {"func": "static int xbuf_format_converter(char **outbuf, const char *fmt, va_list ap)\n{\n register char *s = nullptr;\n char *q;\n int s_len;\n\n register int min_width = 0;\n int precision = 0;\n enum {\n LEFT, RIGHT\n } adjust;\n char pad_char;\n char prefix_char;\n\n double fp_num;\n wide_int i_num = (wide_int) 0;\n u_wide_int ui_num;\n\n char num_buf[NUM_BUF_SIZE];\n char char_buf[2]; /* for printing %% and % */\n\n#ifdef HAVE_LOCALE_H\n struct lconv *lconv = nullptr;\n#endif\n\n /*\n * Flag variables\n */\n length_modifier_e modifier;\n boolean_e alternate_form;\n boolean_e print_sign;\n boolean_e print_blank;\n boolean_e adjust_precision;\n boolean_e adjust_width;\n int is_negative;\n\n int size = 240;\n char *result = (char *)malloc(size);\n int outpos = 0;\n\n while (*fmt) {\n if (*fmt != '%') {\n appendchar(&result, &outpos, &size, *fmt);\n } else {\n /*\n * Default variable settings\n */\n adjust = RIGHT;\n alternate_form = print_sign = print_blank = NO;\n pad_char = ' ';\n prefix_char = NUL;\n\n fmt++;\n\n /*\n * Try to avoid checking for flags, width or precision\n */\n if (isascii((int)*fmt) && !islower((int)*fmt)) {\n /*\n * Recognize flags: -, #, BLANK, +\n */\n for (;; fmt++) {\n if (*fmt == '-')\n adjust = LEFT;\n else if (*fmt == '+')\n print_sign = YES;\n else if (*fmt == '#')\n alternate_form = YES;\n else if (*fmt == ' ')\n print_blank = YES;\n else if (*fmt == '0')\n pad_char = '0';\n else\n break;\n }\n\n /*\n * Check if a width was specified\n */\n if (isdigit((int)*fmt)) {\n STR_TO_DEC(fmt, min_width);\n adjust_width = YES;\n } else if (*fmt == '*') {\n min_width = va_arg(ap, int);\n fmt++;\n adjust_width = YES;\n if (min_width < 0) {\n adjust = LEFT;\n min_width = -min_width;\n }\n } else\n adjust_width = NO;\n\n /*\n * Check if a precision was specified\n *\n * XXX: an unreasonable amount of precision may be specified\n * resulting in overflow of num_buf. Currently we\n * ignore this possibility.\n */\n if (*fmt == '.') {\n adjust_precision = YES;\n fmt++;\n if (isdigit((int)*fmt)) {\n STR_TO_DEC(fmt, precision);\n } else if (*fmt == '*') {\n precision = va_arg(ap, int);\n fmt++;\n if (precision < 0)\n precision = 0;\n } else\n precision = 0;\n } else\n adjust_precision = NO;\n } else\n adjust_precision = adjust_width = NO;\n\n /*\n * Modifier check\n */\n switch (*fmt) {\n case 'L':\n fmt++;\n modifier = LM_LONG_DOUBLE;\n break;\n case 'I':\n fmt++;\n#if SIZEOF_LONG_LONG\n if (*fmt == '6' && *(fmt+1) == '4') {\n fmt += 2;\n modifier = LM_LONG_LONG;\n } else\n#endif\n if (*fmt == '3' && *(fmt+1) == '2') {\n fmt += 2;\n modifier = LM_LONG;\n } else {\n#ifdef _WIN64\n modifier = LM_LONG_LONG;\n#else\n modifier = LM_LONG;\n#endif\n }\n break;\n case 'l':\n fmt++;\n#if SIZEOF_LONG_LONG\n if (*fmt == 'l') {\n fmt++;\n modifier = LM_LONG_LONG;\n } else\n#endif\n modifier = LM_LONG;\n break;\n case 'z':\n fmt++;\n modifier = LM_SIZE_T;\n break;\n case 'j':\n fmt++;\n#if SIZEOF_INTMAX_T\n modifier = LM_INTMAX_T;\n#else\n modifier = LM_SIZE_T;\n#endif\n break;\n case 't':\n fmt++;\n#if SIZEOF_PTRDIFF_T\n modifier = LM_PTRDIFF_T;\n#else\n modifier = LM_SIZE_T;\n#endif\n break;\n case 'h':\n fmt++;\n if (*fmt == 'h') {\n fmt++;\n }\n /* these are promoted to int, so no break */\n default:\n modifier = LM_STD;\n break;\n }\n\n /*\n * Argument extraction and printing.\n * First we determine the argument type.\n * Then, we convert the argument to a string.\n * On exit from the switch, s points to the string that\n * must be printed, s_len has the length of the string\n * The precision requirements, if any, are reflected in s_len.\n *\n * NOTE: pad_char may be set to '0' because of the 0 flag.\n * It is reset to ' ' by non-numeric formats\n */\n switch (*fmt) {\n case 'u':\n switch(modifier) {\n default:\n i_num = (wide_int) va_arg(ap, unsigned int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n i_num = (wide_int) va_arg(ap, unsigned long int);\n break;\n case LM_SIZE_T:\n i_num = (wide_int) va_arg(ap, size_t);\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n i_num = (wide_int) va_arg(ap, u_wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n i_num = (wide_int) va_arg(ap, uintmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n i_num = (wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n /*\n * The rest also applies to other integer formats, so fall\n * into that case.\n */\n case 'd':\n case 'i':\n /*\n * Get the arg if we haven't already.\n */\n if ((*fmt) != 'u') {\n switch(modifier) {\n default:\n i_num = (wide_int) va_arg(ap, int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n i_num = (wide_int) va_arg(ap, long int);\n break;\n case LM_SIZE_T:\n#if SIZEOF_SSIZE_T\n i_num = (wide_int) va_arg(ap, ssize_t);\n#else\n i_num = (wide_int) va_arg(ap, size_t);\n#endif\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n i_num = (wide_int) va_arg(ap, wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n i_num = (wide_int) va_arg(ap, intmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n i_num = (wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n }\n s = ap_php_conv_10(i_num, (*fmt) == 'u', &is_negative,\n &num_buf[NUM_BUF_SIZE], &s_len);\n FIX_PRECISION(adjust_precision, precision, s, s_len);\n\n if (*fmt != 'u') {\n if (is_negative)\n prefix_char = '-';\n else if (print_sign)\n prefix_char = '+';\n else if (print_blank)\n prefix_char = ' ';\n }\n break;\n\n\n case 'o':\n switch(modifier) {\n default:\n ui_num = (u_wide_int) va_arg(ap, unsigned int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n ui_num = (u_wide_int) va_arg(ap, unsigned long int);\n break;\n case LM_SIZE_T:\n ui_num = (u_wide_int) va_arg(ap, size_t);\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n ui_num = (u_wide_int) va_arg(ap, u_wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n ui_num = (u_wide_int) va_arg(ap, uintmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n s = ap_php_conv_p2(ui_num, 3, *fmt,\n &num_buf[NUM_BUF_SIZE], &s_len);\n FIX_PRECISION(adjust_precision, precision, s, s_len);\n if (alternate_form && *s != '0') {\n *--s = '0';\n s_len++;\n }\n break;\n\n\n case 'x':\n case 'X':\n switch(modifier) {\n default:\n ui_num = (u_wide_int) va_arg(ap, unsigned int);\n break;\n case LM_LONG_DOUBLE:\n goto fmt_error;\n case LM_LONG:\n ui_num = (u_wide_int) va_arg(ap, unsigned long int);\n break;\n case LM_SIZE_T:\n ui_num = (u_wide_int) va_arg(ap, size_t);\n break;\n#if SIZEOF_LONG_LONG\n case LM_LONG_LONG:\n ui_num = (u_wide_int) va_arg(ap, u_wide_int);\n break;\n#endif\n#if SIZEOF_INTMAX_T\n case LM_INTMAX_T:\n ui_num = (u_wide_int) va_arg(ap, uintmax_t);\n break;\n#endif\n#if SIZEOF_PTRDIFF_T\n case LM_PTRDIFF_T:\n ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);\n break;\n#endif\n }\n s = ap_php_conv_p2(ui_num, 4, *fmt,\n &num_buf[NUM_BUF_SIZE], &s_len);\n FIX_PRECISION(adjust_precision, precision, s, s_len);\n if (alternate_form && i_num != 0) {\n *--s = *fmt; /* 'x' or 'X' */\n *--s = '0';\n s_len += 2;\n }\n break;\n\n\n case 's':\n case 'v':\n s = va_arg(ap, char *);\n if (s != nullptr) {\n s_len = strlen(s);\n if (adjust_precision && precision < s_len)\n s_len = precision;\n } else {\n s = const_cast(s_null);\n s_len = S_NULL_LEN;\n }\n pad_char = ' ';\n break;\n\n\n case 'f':\n case 'F':\n case 'e':\n case 'E':\n switch(modifier) {\n case LM_LONG_DOUBLE:\n fp_num = (double) va_arg(ap, long double);\n break;\n case LM_STD:\n fp_num = va_arg(ap, double);\n break;\n default:\n goto fmt_error;\n }\n\n if (std::isnan(fp_num)) {\n s = const_cast(\"nan\");\n s_len = 3;\n } else if (std::isinf(fp_num)) {\n s = const_cast(\"inf\");\n s_len = 3;\n } else {\n#ifdef HAVE_LOCALE_H\n if (!lconv) {\n lconv = localeconv();\n }\n#endif\n s = php_conv_fp((*fmt == 'f')?'F':*fmt, fp_num, alternate_form,\n (adjust_precision == NO) ? FLOAT_DIGITS : precision,\n (*fmt == 'f')?LCONV_DECIMAL_POINT:'.',\n &is_negative, &num_buf[1], &s_len);\n if (is_negative)\n prefix_char = '-';\n else if (print_sign)\n prefix_char = '+';\n else if (print_blank)\n prefix_char = ' ';\n }\n break;\n\n\n case 'g':\n case 'k':\n case 'G':\n case 'H':\n switch(modifier) {\n case LM_LONG_DOUBLE:\n fp_num = (double) va_arg(ap, long double);\n break;\n case LM_STD:\n fp_num = va_arg(ap, double);\n break;\n default:\n goto fmt_error;\n }\n\n if (std::isnan(fp_num)) {\n s = const_cast(\"NAN\");\n s_len = 3;\n break;\n } else if (std::isinf(fp_num)) {\n if (fp_num > 0) {\n s = const_cast(\"INF\");\n s_len = 3;\n } else {\n s = const_cast(\"-INF\");\n s_len = 4;\n }\n break;\n }\n\n if (adjust_precision == NO)\n precision = FLOAT_DIGITS;\n else if (precision == 0)\n precision = 1;\n /*\n * * We use &num_buf[ 1 ], so that we have room for the sign\n */\n#ifdef HAVE_LOCALE_H\n if (!lconv) {\n lconv = localeconv();\n }\n#endif\n s = php_gcvt(fp_num, precision,\n (*fmt=='H' || *fmt == 'k') ? '.' : LCONV_DECIMAL_POINT,\n (*fmt == 'G' || *fmt == 'H')?'E':'e', &num_buf[1]);\n if (*s == '-')\n prefix_char = *s++;\n else if (print_sign)\n prefix_char = '+';\n else if (print_blank)\n prefix_char = ' ';\n\n s_len = strlen(s);\n\n if (alternate_form && (q = strchr(s, '.')) == nullptr)\n s[s_len++] = '.';\n break;\n\n\n case 'c':\n char_buf[0] = (char) (va_arg(ap, int));\n s = &char_buf[0];\n s_len = 1;\n pad_char = ' ';\n break;\n\n\n case '%':\n char_buf[0] = '%';\n s = &char_buf[0];\n s_len = 1;\n pad_char = ' ';\n break;\n\n\n case 'n':\n *(va_arg(ap, int *)) = outpos;\n goto skip_output;\n\n /*\n * Always extract the argument as a \"char *\" pointer. We\n * should be using \"void *\" but there are still machines\n * that don't understand it.\n * If the pointer size is equal to the size of an unsigned\n * integer we convert the pointer to a hex number, otherwise\n * we print \"%p\" to indicate that we don't handle \"%p\".\n */\n case 'p':\n if (sizeof(char *) <= sizeof(u_wide_int)) {\n ui_num = (u_wide_int)((size_t) va_arg(ap, char *));\n s = ap_php_conv_p2(ui_num, 4, 'x',\n &num_buf[NUM_BUF_SIZE], &s_len);\n if (ui_num != 0) {\n *--s = 'x';\n *--s = '0';\n s_len += 2;\n }\n } else {\n s = const_cast(\"%p\");\n s_len = 2;\n }\n pad_char = ' ';\n break;\n\n\n case NUL:\n /*\n * The last character of the format string was %.\n * We ignore it.\n */\n continue;\n\n\nfmt_error:\n throw Exception(\"Illegal length modifier specified '%c'\", *fmt);\n\n /*\n * The default case is for unrecognized %'s.\n * We print % to help the user identify what\n * option is not understood.\n * This is also useful in case the user wants to pass\n * the output of format_converter to another function\n * that understands some other % (like syslog).\n * Note that we can't point s inside fmt because the\n * unknown could be preceded by width etc.\n */\n default:\n char_buf[0] = '%';\n char_buf[1] = *fmt;\n s = char_buf;\n s_len = 2;\n pad_char = ' ';\n break;\n }\n\n if (prefix_char != NUL) {\n *--s = prefix_char;\n s_len++;\n }\n if (adjust_width && adjust == RIGHT && min_width > s_len) {\n if (pad_char == '0' && prefix_char != NUL) {\n appendchar(&result, &outpos, &size, *s);\n s++;\n s_len--;\n min_width--;\n }\n for (int i = 0; i < min_width - s_len; i++) {\n appendchar(&result, &outpos, &size, pad_char);\n }\n }\n /*\n * Print the (for now) non-null terminated string s.\n */\n appendsimplestring(&result, &outpos, &size, s, s_len);\n\n if (adjust_width && adjust == LEFT && min_width > s_len) {\n for (int i = 0; i < min_width - s_len; i++) {\n appendchar(&result, &outpos, &size, pad_char);\n }\n }\n }\nskip_output:\n fmt++;\n }\n /*\n * Add the terminating null here since it wasn't added incrementally above\n * once the whole string has been composed.\n */\n appendchar(&result, &outpos, &size, NUL);\n *outbuf = result;\n return outpos - 1;\n}", "project": "hhvm", "hash": 85852174078948997591369954532322878743, "size": 592, "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "target": 0, "dataset": "other", "idx": 219451} {"func": "bool CPlayListASX::LoadData(std::istream& stream)\n{\n CLog::Log(LOGINFO, \"Parsing ASX\");\n\n if(stream.peek() == '[')\n {\n return LoadAsxIniInfo(stream);\n }\n else\n {\n CXBMCTinyXML xmlDoc;\n stream >> xmlDoc;\n\n if (xmlDoc.Error())\n {\n CLog::Log(LOGERROR, \"Unable to parse ASX info Error: {}\", xmlDoc.ErrorDesc());\n return false;\n }\n\n TiXmlElement *pRootElement = xmlDoc.RootElement();\n\n // lowercase every element\n TiXmlNode *pNode = pRootElement;\n TiXmlNode *pChild = NULL;\n std::string value;\n value = pNode->Value();\n StringUtils::ToLower(value);\n pNode->SetValue(value);\n while(pNode)\n {\n pChild = pNode->IterateChildren(pChild);\n if(pChild)\n {\n if (pChild->Type() == TiXmlNode::TINYXML_ELEMENT)\n {\n value = pChild->Value();\n StringUtils::ToLower(value);\n pChild->SetValue(value);\n\n TiXmlAttribute* pAttr = pChild->ToElement()->FirstAttribute();\n while(pAttr)\n {\n value = pAttr->Name();\n StringUtils::ToLower(value);\n pAttr->SetName(value);\n pAttr = pAttr->Next();\n }\n }\n\n pNode = pChild;\n pChild = NULL;\n continue;\n }\n\n pChild = pNode;\n pNode = pNode->Parent();\n }\n std::string roottitle;\n TiXmlElement *pElement = pRootElement->FirstChildElement();\n while (pElement)\n {\n value = pElement->Value();\n if (value == \"title\" && !pElement->NoChildren())\n {\n roottitle = pElement->FirstChild()->ValueStr();\n }\n else if (value == \"entry\")\n {\n std::string title(roottitle);\n\n TiXmlElement *pRef = pElement->FirstChildElement(\"ref\");\n TiXmlElement *pTitle = pElement->FirstChildElement(\"title\");\n\n if(pTitle && !pTitle->NoChildren())\n title = pTitle->FirstChild()->ValueStr();\n\n while (pRef)\n { // multiple references may appear for one entry\n // duration may exist on this level too\n value = XMLUtils::GetAttribute(pRef, \"href\");\n if (!value.empty())\n {\n if(title.empty())\n title = value;\n\n CLog::Log(LOGINFO, \"Adding element {}, {}\", title, value);\n CFileItemPtr newItem(new CFileItem(title));\n newItem->SetPath(value);\n Add(newItem);\n }\n pRef = pRef->NextSiblingElement(\"ref\");\n }\n }\n else if (value == \"entryref\")\n {\n value = XMLUtils::GetAttribute(pElement, \"href\");\n if (!value.empty())\n { // found an entryref, let's try loading that url\n std::unique_ptr playlist(CPlayListFactory::Create(value));\n if (nullptr != playlist)\n if (playlist->Load(value))\n Add(*playlist);\n }\n }\n pElement = pElement->NextSiblingElement();\n }\n }\n\n return true;\n}", "project": "xbmc", "hash": 328153551345565129880768466980342348853, "size": 110, "commit_id": "80c8138c09598e88b4ddb6dbb279fa193bbb3237", "message": "[Playlist] dont use istream directly to a tinyxml structure\n\nTurn istream into a std::string to handle large buffers (#20305)", "target": 1, "dataset": "other", "idx": 195020} {"func": "bool CPlayListASX::LoadData(std::istream& stream)\n{\n CLog::Log(LOGINFO, \"Parsing ASX\");\n\n if(stream.peek() == '[')\n {\n return LoadAsxIniInfo(stream);\n }\n else\n {\n std::string asxstream(std::istreambuf_iterator(stream), {});\n CXBMCTinyXML xmlDoc;\n xmlDoc.Parse(asxstream, TIXML_DEFAULT_ENCODING);\n\n if (xmlDoc.Error())\n {\n CLog::Log(LOGERROR, \"Unable to parse ASX info Error: {}\", xmlDoc.ErrorDesc());\n return false;\n }\n\n TiXmlElement *pRootElement = xmlDoc.RootElement();\n\n if (!pRootElement)\n return false;\n\n // lowercase every element\n TiXmlNode *pNode = pRootElement;\n TiXmlNode *pChild = NULL;\n std::string value;\n value = pNode->Value();\n StringUtils::ToLower(value);\n pNode->SetValue(value);\n while(pNode)\n {\n pChild = pNode->IterateChildren(pChild);\n if(pChild)\n {\n if (pChild->Type() == TiXmlNode::TINYXML_ELEMENT)\n {\n value = pChild->Value();\n StringUtils::ToLower(value);\n pChild->SetValue(value);\n\n TiXmlAttribute* pAttr = pChild->ToElement()->FirstAttribute();\n while(pAttr)\n {\n value = pAttr->Name();\n StringUtils::ToLower(value);\n pAttr->SetName(value);\n pAttr = pAttr->Next();\n }\n }\n\n pNode = pChild;\n pChild = NULL;\n continue;\n }\n\n pChild = pNode;\n pNode = pNode->Parent();\n }\n std::string roottitle;\n TiXmlElement *pElement = pRootElement->FirstChildElement();\n while (pElement)\n {\n value = pElement->Value();\n if (value == \"title\" && !pElement->NoChildren())\n {\n roottitle = pElement->FirstChild()->ValueStr();\n }\n else if (value == \"entry\")\n {\n std::string title(roottitle);\n\n TiXmlElement *pRef = pElement->FirstChildElement(\"ref\");\n TiXmlElement *pTitle = pElement->FirstChildElement(\"title\");\n\n if(pTitle && !pTitle->NoChildren())\n title = pTitle->FirstChild()->ValueStr();\n\n while (pRef)\n { // multiple references may appear for one entry\n // duration may exist on this level too\n value = XMLUtils::GetAttribute(pRef, \"href\");\n if (!value.empty())\n {\n if(title.empty())\n title = value;\n\n CLog::Log(LOGINFO, \"Adding element {}, {}\", title, value);\n CFileItemPtr newItem(new CFileItem(title));\n newItem->SetPath(value);\n Add(newItem);\n }\n pRef = pRef->NextSiblingElement(\"ref\");\n }\n }\n else if (value == \"entryref\")\n {\n value = XMLUtils::GetAttribute(pElement, \"href\");\n if (!value.empty())\n { // found an entryref, let's try loading that url\n std::unique_ptr playlist(CPlayListFactory::Create(value));\n if (nullptr != playlist)\n if (playlist->Load(value))\n Add(*playlist);\n }\n }\n pElement = pElement->NextSiblingElement();\n }\n }\n\n return true;\n}", "project": "xbmc", "hash": 48091596250511939083384668842890615241, "size": 114, "commit_id": "80c8138c09598e88b4ddb6dbb279fa193bbb3237", "message": "[Playlist] dont use istream directly to a tinyxml structure\n\nTurn istream into a std::string to handle large buffers (#20305)", "target": 0, "dataset": "other", "idx": 219934} {"func": "TfLiteStatus EvalFloat(TfLiteContext* context, TfLiteNode* node,\n TfLiteFullyConnectedParams* params, OpData* data,\n const TfLiteTensor* input, const TfLiteTensor* filter,\n const TfLiteTensor* bias, TfLiteTensor* output) {\n float output_activation_min, output_activation_max;\n CalculateActivationRange(params->activation, &output_activation_min,\n &output_activation_max);\n if (kernel_type == kReference) {\n FullyConnectedParams op_params;\n op_params.float_activation_min = output_activation_min;\n op_params.float_activation_max = output_activation_max;\n if (filter->sparsity != nullptr) {\n const auto& sparsity = *filter->sparsity;\n reference_ops::FullyConnectedSparseWeight(\n sparsity, op_params, GetTensorShape(input),\n GetTensorData(input), GetTensorShape(filter),\n GetTensorData(filter), GetTensorShape(bias),\n GetTensorData(bias), GetTensorShape(output),\n GetTensorData(output));\n } else {\n reference_ops::FullyConnected(\n op_params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(filter), GetTensorData(filter),\n GetTensorShape(bias), GetTensorData(bias),\n GetTensorShape(output), GetTensorData(output));\n }\n } else if (kernel_type == kLegacyPie) {\n return EvalPie(context, node, params, data, input, filter, bias, output);\n } else {\n FullyConnectedParams op_params;\n op_params.float_activation_min = output_activation_min;\n op_params.float_activation_max = output_activation_max;\n if (filter->sparsity != nullptr) {\n const auto& sparsity = *filter->sparsity;\n if (!SupportedSparsityFormat(sparsity)) {\n TF_LITE_KERNEL_LOG(context,\n \"Unsupported sparse fully-connected weight format.\");\n return kTfLiteError;\n }\n\n if (sparsity.dim_metadata_size == kDimMetadataSizeRandomSparse) {\n // Random sparse.\n optimized_ops::FullyConnectedSparseWeight(\n sparsity, op_params, GetTensorShape(input),\n GetTensorData(input), GetTensorShape(filter),\n GetTensorData(filter), GetTensorShape(bias),\n GetTensorData(bias), GetTensorShape(output),\n GetTensorData(output));\n } else if (sparsity.dim_metadata_size == kDimMetadataSizeBlockSparse &&\n sparsity.dim_metadata[2].dense_size == 4) {\n // Block sparse with block size of 1x4.\n optimized_ops::FullyConnectedSparseWeight1x4(\n sparsity, op_params, GetTensorShape(input),\n GetTensorData(input), GetTensorShape(filter),\n GetTensorData(filter), GetTensorShape(bias),\n GetTensorData(bias), GetTensorShape(output),\n GetTensorData(output),\n CpuBackendContext::GetFromContext(context));\n } else {\n TF_LITE_KERNEL_LOG(context,\n \"Unsupported sparse fully-connected weight format.\");\n return kTfLiteError;\n }\n\n } else {\n op_params.lhs_cacheable = IsConstantTensor(filter);\n op_params.rhs_cacheable = IsConstantTensor(input);\n optimized_ops::FullyConnected(\n op_params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(filter), GetTensorData(filter),\n GetTensorShape(bias), GetTensorData(bias),\n GetTensorShape(output), GetTensorData(output),\n CpuBackendContext::GetFromContext(context));\n }\n }\n\n return kTfLiteOk;\n}", "project": "tensorflow", "hash": 44351393402196759229206049448766479746, "size": 78, "commit_id": "6c0b2b70eeee588591680f5b7d5d38175fd7cdf6", "message": "[lite] add validation check for sparse fully connected\n\nPiperOrigin-RevId: 417629354\nChange-Id: If96171c4bd4f5fdb01d6368d6deab19d1c9beca7", "target": 1, "dataset": "other", "idx": 195042} {"func": "TfLiteStatus EvalFloat(TfLiteContext* context, TfLiteNode* node,\n TfLiteFullyConnectedParams* params, OpData* data,\n const TfLiteTensor* input, const TfLiteTensor* filter,\n const TfLiteTensor* bias, TfLiteTensor* output) {\n float output_activation_min, output_activation_max;\n CalculateActivationRange(params->activation, &output_activation_min,\n &output_activation_max);\n if (kernel_type == kReference) {\n FullyConnectedParams op_params;\n op_params.float_activation_min = output_activation_min;\n op_params.float_activation_max = output_activation_max;\n if (filter->sparsity != nullptr) {\n const auto& sparsity = *filter->sparsity;\n reference_ops::FullyConnectedSparseWeight(\n sparsity, op_params, GetTensorShape(input),\n GetTensorData(input), GetTensorShape(filter),\n GetTensorData(filter), GetTensorShape(bias),\n GetTensorData(bias), GetTensorShape(output),\n GetTensorData(output));\n } else {\n reference_ops::FullyConnected(\n op_params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(filter), GetTensorData(filter),\n GetTensorShape(bias), GetTensorData(bias),\n GetTensorShape(output), GetTensorData(output));\n }\n } else if (kernel_type == kLegacyPie) {\n return EvalPie(context, node, params, data, input, filter, bias, output);\n } else {\n FullyConnectedParams op_params;\n op_params.float_activation_min = output_activation_min;\n op_params.float_activation_max = output_activation_max;\n if (filter->sparsity != nullptr) {\n const auto& sparsity = *filter->sparsity;\n if (!SupportedSparsityFormat(sparsity)) {\n TF_LITE_KERNEL_LOG(context,\n \"Unsupported sparse fully-connected weight format.\");\n return kTfLiteError;\n }\n const auto& input_shape = GetTensorShape(input);\n const auto& filter_shape = GetTensorShape(filter);\n const auto& output_shape = GetTensorShape(output);\n const auto& bias_shape = GetTensorShape(bias);\n if (!VerifySparsity(filter_shape, input_shape, output_shape, &sparsity)) {\n TF_LITE_KERNEL_LOG(context, \"Invalid sparse fully-connected format.\");\n return kTfLiteError;\n }\n\n if (sparsity.dim_metadata_size == kDimMetadataSizeRandomSparse) {\n // Random sparse.\n optimized_ops::FullyConnectedSparseWeight(\n sparsity, op_params, // Disable formatting\n input_shape, GetTensorData(input), // Disable formatting\n filter_shape, GetTensorData(filter), // Disable formatting\n bias_shape, GetTensorData(bias), // Disable formatting\n output_shape, GetTensorData(output));\n } else if (sparsity.dim_metadata_size == kDimMetadataSizeBlockSparse &&\n sparsity.dim_metadata[2].dense_size == 4) {\n // Block sparse with block size of 1x4.\n optimized_ops::FullyConnectedSparseWeight1x4(\n sparsity, op_params, // Disable formatting\n input_shape, GetTensorData(input), // Disable formatting\n filter_shape, GetTensorData(filter), // Disable formatting\n bias_shape, GetTensorData(bias), // Disable formatting\n output_shape, GetTensorData(output),\n CpuBackendContext::GetFromContext(context));\n } else {\n TF_LITE_KERNEL_LOG(context,\n \"Unsupported sparse fully-connected weight format.\");\n return kTfLiteError;\n }\n\n } else {\n op_params.lhs_cacheable = IsConstantTensor(filter);\n op_params.rhs_cacheable = IsConstantTensor(input);\n optimized_ops::FullyConnected(\n op_params, GetTensorShape(input), GetTensorData(input),\n GetTensorShape(filter), GetTensorData(filter),\n GetTensorShape(bias), GetTensorData(bias),\n GetTensorShape(output), GetTensorData(output),\n CpuBackendContext::GetFromContext(context));\n }\n }\n\n return kTfLiteOk;\n}", "project": "tensorflow", "hash": 296480280703228258350511532286684008579, "size": 86, "commit_id": "6c0b2b70eeee588591680f5b7d5d38175fd7cdf6", "message": "[lite] add validation check for sparse fully connected\n\nPiperOrigin-RevId: 417629354\nChange-Id: If96171c4bd4f5fdb01d6368d6deab19d1c9beca7", "target": 0, "dataset": "other", "idx": 220473} {"func": "uint8_t ethereum_extractThorchainData(const EthereumSignTx *msg,\n char *buffer) {\n // Swap data begins 164 chars into data buffer:\n // offset = deposit function hash + address + address + uint256\n uint16_t offset = 4 + (5 * 32);\n int16_t len = msg->data_length - offset;\n if (msg->has_data_length && len > 0) {\n memcpy(buffer, msg->data_initial_chunk.bytes + offset, len);\n // String length must be < 255 characters\n return len < 256 ? (uint8_t)len : 0;\n }\n return 0;\n}", "project": "keepkey-firmware", "hash": 30009078677497671388353724048438003192, "size": 13, "commit_id": "e49d45594002d4d3fbc1f03488e6dfc0a0a65836", "message": "710 merge", "target": 1, "dataset": "other", "idx": 195057} {"func": "uint8_t ethereum_extractThorchainData(const EthereumSignTx *msg,\n char *buffer) {\n // Swap data begins 164 chars into data buffer:\n // offset = deposit function hash + address + address + uint256\n uint16_t offset = 4 + (5 * 32);\n int16_t len = msg->data_length - offset;\n if (msg->has_data_length && len > 0 && len < 256) {\n memcpy(buffer, msg->data_initial_chunk.bytes + offset, len);\n // String length must be < 255 characters\n return (uint8_t)len;\n }\n return 0;\n}", "project": "keepkey-firmware", "hash": 31658134530975392085648913239261058010, "size": 13, "commit_id": "e49d45594002d4d3fbc1f03488e6dfc0a0a65836", "message": "710 merge", "target": 0, "dataset": "other", "idx": 220894} {"func": "static int stszin(int size)\n{\n int cnt;\n uint32_t ofs;\n\n // version/flags\n u32in();\n // Sample size\n u32in();\n // Number of entries\n mp4config.frame.ents = u32in();\n // fixme: check atom size\n mp4config.frame.data = malloc(sizeof(*mp4config.frame.data)\n * (mp4config.frame.ents + 1));\n\n if (!mp4config.frame.data)\n return ERR_FAIL;\n\n ofs = 0;\n mp4config.frame.data[0] = ofs;\n for (cnt = 0; cnt < mp4config.frame.ents; cnt++)\n {\n uint32_t fsize = u32in();\n\n ofs += fsize;\n if (mp4config.frame.maxsize < fsize)\n mp4config.frame.maxsize = fsize;\n\n mp4config.frame.data[cnt + 1] = ofs;\n\n if (ofs < mp4config.frame.data[cnt])\n return ERR_FAIL;\n }\n\n return size;\n}", "project": "faad2", "hash": 162931728092633650703368658690852714538, "size": 36, "commit_id": "1b71a6ba963d131375f5e489b3b25e36f19f3f24", "message": "fix heap-buffer-overflow in mp4read.c\n\nThis originated from an integer overflow: If mp4config.frame.ents\nwould be read-in with a value of (uint32t)(-1), it would overflow to 0\nin the size calculation for the allocation in the next line. The\nmalloc() function would then successfully return a pointer to a memory\nregion of size 0, which will cause a segfault when written to.\n\nFixes #57.", "target": 1, "dataset": "other", "idx": 195084} {"func": "static int stszin(int size)\n{\n int cnt;\n uint32_t ofs;\n\n // version/flags\n u32in();\n // Sample size\n u32in();\n // Number of entries\n mp4config.frame.ents = u32in();\n\n if (!(mp4config.frame.ents + 1))\n return ERR_FAIL;\n\n mp4config.frame.data = malloc(sizeof(*mp4config.frame.data)\n * (mp4config.frame.ents + 1));\n\n if (!mp4config.frame.data)\n return ERR_FAIL;\n\n ofs = 0;\n mp4config.frame.data[0] = ofs;\n for (cnt = 0; cnt < mp4config.frame.ents; cnt++)\n {\n uint32_t fsize = u32in();\n\n ofs += fsize;\n if (mp4config.frame.maxsize < fsize)\n mp4config.frame.maxsize = fsize;\n\n mp4config.frame.data[cnt + 1] = ofs;\n\n if (ofs < mp4config.frame.data[cnt])\n return ERR_FAIL;\n }\n\n return size;\n}", "project": "faad2", "hash": 128822819783274424928244029461541937327, "size": 39, "commit_id": "1b71a6ba963d131375f5e489b3b25e36f19f3f24", "message": "fix heap-buffer-overflow in mp4read.c\n\nThis originated from an integer overflow: If mp4config.frame.ents\nwould be read-in with a value of (uint32t)(-1), it would overflow to 0\nin the size calculation for the allocation in the next line. The\nmalloc() function would then successfully return a pointer to a memory\nregion of size 0, which will cause a segfault when written to.\n\nFixes #57.", "target": 0, "dataset": "other", "idx": 221432} {"func": "mrb_proc_copy(mrb_state *mrb, struct RProc *a, struct RProc *b)\n{\n if (a->body.irep) {\n /* already initialized proc */\n return;\n }\n a->flags = b->flags;\n a->body = b->body;\n a->upper = b->upper;\n if (!MRB_PROC_CFUNC_P(a) && a->body.irep) {\n mrb_irep_incref(mrb, (mrb_irep*)a->body.irep);\n }\n a->e.env = b->e.env;\n /* a->e.target_class = a->e.target_class; */\n}", "project": "mruby", "hash": 244789115000433749131120833427639242199, "size": 15, "commit_id": "28ccc664e5dcd3f9d55173e9afde77c4705a9ab6", "message": "proc.c: should not reference `irep` when copying failed.\n\nIt may cause broken reference count numbers.", "target": 1, "dataset": "other", "idx": 195217} {"func": "mrb_proc_copy(mrb_state *mrb, struct RProc *a, struct RProc *b)\n{\n if (a->body.irep) {\n /* already initialized proc */\n return;\n }\n if (!MRB_PROC_CFUNC_P(b) && b->body.irep) {\n mrb_irep_incref(mrb, (mrb_irep*)b->body.irep);\n }\n a->flags = b->flags;\n a->body = b->body;\n a->upper = b->upper;\n a->e.env = b->e.env;\n /* a->e.target_class = a->e.target_class; */\n}", "project": "mruby", "hash": 178869132473237542289873957189130108512, "size": 15, "commit_id": "28ccc664e5dcd3f9d55173e9afde77c4705a9ab6", "message": "proc.c: should not reference `irep` when copying failed.\n\nIt may cause broken reference count numbers.", "target": 0, "dataset": "other", "idx": 222586} {"func": "int64_t TensorByteSize(const TensorProto& t) {\n // num_elements returns -1 if shape is not fully defined.\n int64_t num_elems = TensorShape(t.tensor_shape()).num_elements();\n return num_elems < 0 ? -1 : num_elems * DataTypeSize(t.dtype());\n}", "project": "tensorflow", "hash": 12987503072502364739383952943830392043, "size": 5, "commit_id": "c2426bba00a01de6913738df8fa78e0215fcce02", "message": "Use `PartialTensorShape` instead of `TensorShape`.\n\n`TensorShape` constructor throws a CHECK-fail if shape is partial/overflows which the other doesn't. We are only determining the number of elements in the shape and partial shape should be used as it returns negative number when needed.\n\nPiperOrigin-RevId: 409205384\nChange-Id: Ia56542ff9ec758f2c9ffc7e4dcc9fa7eecd86e7b", "target": 1, "dataset": "other", "idx": 195244} {"func": "int64_t TensorByteSize(const TensorProto& t) {\n // num_elements returns -1 if shape is not fully defined.\n int64_t num_elems = PartialTensorShape(t.tensor_shape()).num_elements();\n return num_elems < 0 ? -1 : num_elems * DataTypeSize(t.dtype());\n}", "project": "tensorflow", "hash": 57172409333461341216253559449273971, "size": 5, "commit_id": "c2426bba00a01de6913738df8fa78e0215fcce02", "message": "Use `PartialTensorShape` instead of `TensorShape`.\n\n`TensorShape` constructor throws a CHECK-fail if shape is partial/overflows which the other doesn't. We are only determining the number of elements in the shape and partial shape should be used as it returns negative number when needed.\n\nPiperOrigin-RevId: 409205384\nChange-Id: Ia56542ff9ec758f2c9ffc7e4dcc9fa7eecd86e7b", "target": 0, "dataset": "other", "idx": 223149} {"func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n bool has_bias = NumInputs(node) == 3;\n\n TF_LITE_ENSURE(context, has_bias || NumInputs(node) == 2);\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n const TfLiteTensor* filter;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kFilterTensor, &filter));\n const TfLiteTensor* bias = nullptr;\n\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n TF_LITE_ENSURE_EQ(context, NumDimensions(filter), 4);\n\n const TfLiteType data_type = input->type;\n\n const TfLiteType filter_type = filter->type;\n const bool is_hybrid =\n data_type == kTfLiteFloat32 && filter_type == kTfLiteInt8;\n TF_LITE_ENSURE(context,\n data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||\n data_type == kTfLiteInt8 || data_type == kTfLiteInt16);\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, data_type);\n if (!is_hybrid) {\n TF_LITE_ENSURE(context,\n filter->type == data_type || data_type == kTfLiteInt16);\n }\n\n if (data_type == kTfLiteInt16) {\n TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0);\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);\n }\n\n // Filter in DepthwiseConv is expected to be [1, H, W, O].\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(filter, 0), 1);\n\n if (has_bias) {\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kBiasTensor, &bias));\n if (data_type == kTfLiteUInt8 || data_type == kTfLiteInt8) {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);\n } else if (data_type == kTfLiteInt16) {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, kTfLiteInt64);\n TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);\n } else {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, data_type);\n }\n TF_LITE_ENSURE_EQ(context, NumDimensions(bias), 1);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(filter, 3),\n SizeOfDimension(bias, 0));\n }\n\n int channels_out = SizeOfDimension(filter, 3);\n int width = SizeOfDimension(input, 2);\n int height = SizeOfDimension(input, 1);\n int filter_width = SizeOfDimension(filter, 2);\n int filter_height = SizeOfDimension(filter, 1);\n int batches = SizeOfDimension(input, 0);\n\n // Matching GetWindowedOutputSize in TensorFlow.\n auto padding = params->padding;\n int out_width, out_height;\n\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width,\n params->dilation_height_factor, params->dilation_width_factor, height,\n width, filter_height, filter_width, padding, &out_height, &out_width);\n\n // Note that quantized inference requires that all tensors have their\n // parameters set. This is usually done during quantized training or\n // calibration.\n if (data_type != kTfLiteFloat32) {\n TF_LITE_ENSURE_EQ(context, filter->quantization.type,\n kTfLiteAffineQuantization);\n TF_LITE_ENSURE(context, filter->quantization.type != kTfLiteNoQuantization);\n const auto* affine_quantization =\n reinterpret_cast(\n filter->quantization.params);\n TF_LITE_ENSURE(context, affine_quantization);\n TF_LITE_ENSURE(context, affine_quantization->scale);\n TF_LITE_ENSURE(context, (affine_quantization->scale->size == 1 ||\n affine_quantization->scale->size == channels_out));\n\n data->per_channel_output_multiplier.resize(channels_out);\n data->per_channel_output_shift.resize(channels_out);\n TF_LITE_ENSURE_STATUS(tflite::PopulateConvolutionQuantizationParams(\n context, input, filter, bias, output, params->activation,\n &data->output_multiplier, &data->output_shift,\n &data->output_activation_min, &data->output_activation_max,\n data->per_channel_output_multiplier.data(),\n data->per_channel_output_shift.data(), channels_out));\n }\n\n if (is_hybrid) {\n TF_LITE_ENSURE(context, filter->quantization.type != kTfLiteNoQuantization);\n const auto* affine_quantization =\n reinterpret_cast(\n filter->quantization.params);\n TF_LITE_ENSURE(context, affine_quantization);\n TF_LITE_ENSURE(context, affine_quantization->scale);\n TF_LITE_ENSURE_EQ(\n context, affine_quantization->scale->size,\n filter->dims->data[affine_quantization->quantized_dimension]);\n\n int temporaries_count = 0;\n data->input_quantized_index = temporaries_count;\n if (data->input_quantized_id == kTensorNotAllocated) {\n TF_LITE_ENSURE_OK(\n context, context->AddTensors(context, 1, &data->input_quantized_id));\n }\n ++temporaries_count;\n data->scaling_factors_index = temporaries_count;\n if (data->scaling_factors_id == kTensorNotAllocated) {\n TF_LITE_ENSURE_OK(\n context, context->AddTensors(context, 1, &data->scaling_factors_id));\n }\n ++temporaries_count;\n data->input_offset_index = temporaries_count;\n if (data->input_offset_id == kTensorNotAllocated) {\n TF_LITE_ENSURE_OK(\n context, context->AddTensors(context, 1, &data->input_offset_id));\n }\n ++temporaries_count;\n\n TfLiteIntArrayFree(node->temporaries);\n node->temporaries = TfLiteIntArrayCreate(temporaries_count);\n\n node->temporaries->data[data->input_quantized_index] =\n data->input_quantized_id;\n TfLiteTensor* input_quantized;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->input_quantized_index,\n &input_quantized));\n input_quantized->type = kTfLiteInt8;\n input_quantized->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqual(input_quantized->dims, input->dims)) {\n TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,\n input_quantized_size));\n }\n node->temporaries->data[data->scaling_factors_index] =\n data->scaling_factors_id;\n TfLiteTensor* scaling_factors;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scaling_factors_index,\n &scaling_factors));\n scaling_factors->type = kTfLiteFloat32;\n scaling_factors->allocation_type = kTfLiteArenaRw;\n const int batch_size = SizeOfDimension(input, 0);\n int scaling_dims[1] = {batch_size};\n if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {\n TfLiteIntArray* scaling_factors_size = TfLiteIntArrayCreate(1);\n scaling_factors_size->data[0] = batch_size;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scaling_factors,\n scaling_factors_size));\n }\n node->temporaries->data[data->input_offset_index] = data->input_offset_id;\n TfLiteTensor* input_offsets;\n TF_LITE_ENSURE_OK(context,\n GetTemporarySafe(context, node, data->input_offset_index,\n &input_offsets));\n input_offsets->type = kTfLiteInt32;\n input_offsets->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqualsArray(input_offsets->dims, 1, scaling_dims)) {\n TfLiteIntArray* input_offsets_size = TfLiteIntArrayCreate(1);\n input_offsets_size->data[0] = batch_size;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_offsets,\n input_offsets_size));\n }\n }\n\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(4);\n outputSize->data[0] = batches;\n outputSize->data[1] = out_height;\n outputSize->data[2] = out_width;\n outputSize->data[3] = channels_out;\n return context->ResizeTensor(context, output, outputSize);\n}", "project": "tensorflow", "hash": 195314963762430554293071564484057477345, "size": 187, "commit_id": "e5b0eec199c2d03de54fd6a7fd9275692218e2bc", "message": "[lite] Add validation check for dilation height/width to be positive integers.\n\nPiperOrigin-RevId: 416429178\nChange-Id: If7cdcddca54486434d9b2f06e7e2b401d7c3ee25", "target": 1, "dataset": "other", "idx": 195247} {"func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n OpData* data = reinterpret_cast(node->user_data);\n\n bool has_bias = NumInputs(node) == 3;\n\n TF_LITE_ENSURE(context, has_bias || NumInputs(node) == 2);\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n const TfLiteTensor* filter;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kFilterTensor, &filter));\n const TfLiteTensor* bias = nullptr;\n\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n TF_LITE_ENSURE_EQ(context, NumDimensions(filter), 4);\n TF_LITE_ENSURE(context, params->dilation_height_factor > 0);\n TF_LITE_ENSURE(context, params->dilation_width_factor > 0);\n\n const TfLiteType data_type = input->type;\n\n const TfLiteType filter_type = filter->type;\n const bool is_hybrid =\n data_type == kTfLiteFloat32 && filter_type == kTfLiteInt8;\n TF_LITE_ENSURE(context,\n data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||\n data_type == kTfLiteInt8 || data_type == kTfLiteInt16);\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, data_type);\n if (!is_hybrid) {\n TF_LITE_ENSURE(context,\n filter->type == data_type || data_type == kTfLiteInt16);\n }\n\n if (data_type == kTfLiteInt16) {\n TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0);\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);\n }\n\n // Filter in DepthwiseConv is expected to be [1, H, W, O].\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(filter, 0), 1);\n\n if (has_bias) {\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kBiasTensor, &bias));\n if (data_type == kTfLiteUInt8 || data_type == kTfLiteInt8) {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);\n } else if (data_type == kTfLiteInt16) {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, kTfLiteInt64);\n TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0);\n } else {\n TF_LITE_ENSURE_TYPES_EQ(context, bias->type, data_type);\n }\n TF_LITE_ENSURE_EQ(context, NumDimensions(bias), 1);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(filter, 3),\n SizeOfDimension(bias, 0));\n }\n\n int channels_out = SizeOfDimension(filter, 3);\n int width = SizeOfDimension(input, 2);\n int height = SizeOfDimension(input, 1);\n int filter_width = SizeOfDimension(filter, 2);\n int filter_height = SizeOfDimension(filter, 1);\n int batches = SizeOfDimension(input, 0);\n\n // Matching GetWindowedOutputSize in TensorFlow.\n auto padding = params->padding;\n int out_width, out_height;\n\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width,\n params->dilation_height_factor, params->dilation_width_factor, height,\n width, filter_height, filter_width, padding, &out_height, &out_width);\n\n // Note that quantized inference requires that all tensors have their\n // parameters set. This is usually done during quantized training or\n // calibration.\n if (data_type != kTfLiteFloat32) {\n TF_LITE_ENSURE_EQ(context, filter->quantization.type,\n kTfLiteAffineQuantization);\n TF_LITE_ENSURE(context, filter->quantization.type != kTfLiteNoQuantization);\n const auto* affine_quantization =\n reinterpret_cast(\n filter->quantization.params);\n TF_LITE_ENSURE(context, affine_quantization);\n TF_LITE_ENSURE(context, affine_quantization->scale);\n TF_LITE_ENSURE(context, (affine_quantization->scale->size == 1 ||\n affine_quantization->scale->size == channels_out));\n\n data->per_channel_output_multiplier.resize(channels_out);\n data->per_channel_output_shift.resize(channels_out);\n TF_LITE_ENSURE_STATUS(tflite::PopulateConvolutionQuantizationParams(\n context, input, filter, bias, output, params->activation,\n &data->output_multiplier, &data->output_shift,\n &data->output_activation_min, &data->output_activation_max,\n data->per_channel_output_multiplier.data(),\n data->per_channel_output_shift.data(), channels_out));\n }\n\n if (is_hybrid) {\n TF_LITE_ENSURE(context, filter->quantization.type != kTfLiteNoQuantization);\n const auto* affine_quantization =\n reinterpret_cast(\n filter->quantization.params);\n TF_LITE_ENSURE(context, affine_quantization);\n TF_LITE_ENSURE(context, affine_quantization->scale);\n TF_LITE_ENSURE_EQ(\n context, affine_quantization->scale->size,\n filter->dims->data[affine_quantization->quantized_dimension]);\n\n int temporaries_count = 0;\n data->input_quantized_index = temporaries_count;\n if (data->input_quantized_id == kTensorNotAllocated) {\n TF_LITE_ENSURE_OK(\n context, context->AddTensors(context, 1, &data->input_quantized_id));\n }\n ++temporaries_count;\n data->scaling_factors_index = temporaries_count;\n if (data->scaling_factors_id == kTensorNotAllocated) {\n TF_LITE_ENSURE_OK(\n context, context->AddTensors(context, 1, &data->scaling_factors_id));\n }\n ++temporaries_count;\n data->input_offset_index = temporaries_count;\n if (data->input_offset_id == kTensorNotAllocated) {\n TF_LITE_ENSURE_OK(\n context, context->AddTensors(context, 1, &data->input_offset_id));\n }\n ++temporaries_count;\n\n TfLiteIntArrayFree(node->temporaries);\n node->temporaries = TfLiteIntArrayCreate(temporaries_count);\n\n node->temporaries->data[data->input_quantized_index] =\n data->input_quantized_id;\n TfLiteTensor* input_quantized;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->input_quantized_index,\n &input_quantized));\n input_quantized->type = kTfLiteInt8;\n input_quantized->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqual(input_quantized->dims, input->dims)) {\n TfLiteIntArray* input_quantized_size = TfLiteIntArrayCopy(input->dims);\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_quantized,\n input_quantized_size));\n }\n node->temporaries->data[data->scaling_factors_index] =\n data->scaling_factors_id;\n TfLiteTensor* scaling_factors;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scaling_factors_index,\n &scaling_factors));\n scaling_factors->type = kTfLiteFloat32;\n scaling_factors->allocation_type = kTfLiteArenaRw;\n const int batch_size = SizeOfDimension(input, 0);\n int scaling_dims[1] = {batch_size};\n if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {\n TfLiteIntArray* scaling_factors_size = TfLiteIntArrayCreate(1);\n scaling_factors_size->data[0] = batch_size;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, scaling_factors,\n scaling_factors_size));\n }\n node->temporaries->data[data->input_offset_index] = data->input_offset_id;\n TfLiteTensor* input_offsets;\n TF_LITE_ENSURE_OK(context,\n GetTemporarySafe(context, node, data->input_offset_index,\n &input_offsets));\n input_offsets->type = kTfLiteInt32;\n input_offsets->allocation_type = kTfLiteArenaRw;\n if (!TfLiteIntArrayEqualsArray(input_offsets->dims, 1, scaling_dims)) {\n TfLiteIntArray* input_offsets_size = TfLiteIntArrayCreate(1);\n input_offsets_size->data[0] = batch_size;\n TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, input_offsets,\n input_offsets_size));\n }\n }\n\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(4);\n outputSize->data[0] = batches;\n outputSize->data[1] = out_height;\n outputSize->data[2] = out_width;\n outputSize->data[3] = channels_out;\n return context->ResizeTensor(context, output, outputSize);\n}", "project": "tensorflow", "hash": 67839353802325440041115603135108378593, "size": 189, "commit_id": "e5b0eec199c2d03de54fd6a7fd9275692218e2bc", "message": "[lite] Add validation check for dilation height/width to be positive integers.\n\nPiperOrigin-RevId: 416429178\nChange-Id: If7cdcddca54486434d9b2f06e7e2b401d7c3ee25", "target": 0, "dataset": "other", "idx": 223174} {"func": "static struct sock *pep_sock_accept(struct sock *sk, int flags, int *errp,\n\t\t\t\t bool kern)\n{\n\tstruct pep_sock *pn = pep_sk(sk), *newpn;\n\tstruct sock *newsk = NULL;\n\tstruct sk_buff *skb;\n\tstruct pnpipehdr *hdr;\n\tstruct sockaddr_pn dst, src;\n\tint err;\n\tu16 peer_type;\n\tu8 pipe_handle, enabled, n_sb;\n\tu8 aligned = 0;\n\n\tskb = skb_recv_datagram(sk, 0, flags & O_NONBLOCK, errp);\n\tif (!skb)\n\t\treturn NULL;\n\n\tlock_sock(sk);\n\tif (sk->sk_state != TCP_LISTEN) {\n\t\terr = -EINVAL;\n\t\tgoto drop;\n\t}\n\tsk_acceptq_removed(sk);\n\n\terr = -EPROTO;\n\tif (!pskb_may_pull(skb, sizeof(*hdr) + 4))\n\t\tgoto drop;\n\n\thdr = pnp_hdr(skb);\n\tpipe_handle = hdr->pipe_handle;\n\tswitch (hdr->state_after_connect) {\n\tcase PN_PIPE_DISABLE:\n\t\tenabled = 0;\n\t\tbreak;\n\tcase PN_PIPE_ENABLE:\n\t\tenabled = 1;\n\t\tbreak;\n\tdefault:\n\t\tpep_reject_conn(sk, skb, PN_PIPE_ERR_INVALID_PARAM,\n\t\t\t\tGFP_KERNEL);\n\t\tgoto drop;\n\t}\n\tpeer_type = hdr->other_pep_type << 8;\n\n\t/* Parse sub-blocks (options) */\n\tn_sb = hdr->data[3];\n\twhile (n_sb > 0) {\n\t\tu8 type, buf[1], len = sizeof(buf);\n\t\tconst u8 *data = pep_get_sb(skb, &type, &len, buf);\n\n\t\tif (data == NULL)\n\t\t\tgoto drop;\n\t\tswitch (type) {\n\t\tcase PN_PIPE_SB_CONNECT_REQ_PEP_SUB_TYPE:\n\t\t\tif (len < 1)\n\t\t\t\tgoto drop;\n\t\t\tpeer_type = (peer_type & 0xff00) | data[0];\n\t\t\tbreak;\n\t\tcase PN_PIPE_SB_ALIGNED_DATA:\n\t\t\taligned = data[0] != 0;\n\t\t\tbreak;\n\t\t}\n\t\tn_sb--;\n\t}\n\n\t/* Check for duplicate pipe handle */\n\tnewsk = pep_find_pipe(&pn->hlist, &dst, pipe_handle);\n\tif (unlikely(newsk)) {\n\t\t__sock_put(newsk);\n\t\tnewsk = NULL;\n\t\tpep_reject_conn(sk, skb, PN_PIPE_ERR_PEP_IN_USE, GFP_KERNEL);\n\t\tgoto drop;\n\t}\n\n\t/* Create a new to-be-accepted sock */\n\tnewsk = sk_alloc(sock_net(sk), PF_PHONET, GFP_KERNEL, sk->sk_prot,\n\t\t\t kern);\n\tif (!newsk) {\n\t\tpep_reject_conn(sk, skb, PN_PIPE_ERR_OVERLOAD, GFP_KERNEL);\n\t\terr = -ENOBUFS;\n\t\tgoto drop;\n\t}\n\n\tsock_init_data(NULL, newsk);\n\tnewsk->sk_state = TCP_SYN_RECV;\n\tnewsk->sk_backlog_rcv = pipe_do_rcv;\n\tnewsk->sk_protocol = sk->sk_protocol;\n\tnewsk->sk_destruct = pipe_destruct;\n\n\tnewpn = pep_sk(newsk);\n\tpn_skb_get_dst_sockaddr(skb, &dst);\n\tpn_skb_get_src_sockaddr(skb, &src);\n\tnewpn->pn_sk.sobject = pn_sockaddr_get_object(&dst);\n\tnewpn->pn_sk.dobject = pn_sockaddr_get_object(&src);\n\tnewpn->pn_sk.resource = pn_sockaddr_get_resource(&dst);\n\tsock_hold(sk);\n\tnewpn->listener = sk;\n\tskb_queue_head_init(&newpn->ctrlreq_queue);\n\tnewpn->pipe_handle = pipe_handle;\n\tatomic_set(&newpn->tx_credits, 0);\n\tnewpn->ifindex = 0;\n\tnewpn->peer_type = peer_type;\n\tnewpn->rx_credits = 0;\n\tnewpn->rx_fc = newpn->tx_fc = PN_LEGACY_FLOW_CONTROL;\n\tnewpn->init_enable = enabled;\n\tnewpn->aligned = aligned;\n\n\terr = pep_accept_conn(newsk, skb);\n\tif (err) {\n\t\tsock_put(newsk);\n\t\tnewsk = NULL;\n\t\tgoto drop;\n\t}\n\tsk_add_node(newsk, &pn->hlist);\ndrop:\n\trelease_sock(sk);\n\tkfree_skb(skb);\n\t*errp = err;\n\treturn newsk;\n}", "project": "linux", "hash": 179235263739189663934709119365050162181, "size": 120, "commit_id": "bcd0f93353326954817a4f9fa55ec57fb38acbb0", "message": "phonet: refcount leak in pep_sock_accep\n\nsock_hold(sk) is invoked in pep_sock_accept(), but __sock_put(sk) is not\ninvoked in subsequent failure branches(pep_accept_conn() != 0).\n\nSigned-off-by: Hangyu Hua \nLink: https://lore.kernel.org/r/20211209082839.33985-1-hbh25y@gmail.com\nSigned-off-by: Jakub Kicinski ", "target": 1, "dataset": "other", "idx": 195337} {"func": "static struct sock *pep_sock_accept(struct sock *sk, int flags, int *errp,\n\t\t\t\t bool kern)\n{\n\tstruct pep_sock *pn = pep_sk(sk), *newpn;\n\tstruct sock *newsk = NULL;\n\tstruct sk_buff *skb;\n\tstruct pnpipehdr *hdr;\n\tstruct sockaddr_pn dst, src;\n\tint err;\n\tu16 peer_type;\n\tu8 pipe_handle, enabled, n_sb;\n\tu8 aligned = 0;\n\n\tskb = skb_recv_datagram(sk, 0, flags & O_NONBLOCK, errp);\n\tif (!skb)\n\t\treturn NULL;\n\n\tlock_sock(sk);\n\tif (sk->sk_state != TCP_LISTEN) {\n\t\terr = -EINVAL;\n\t\tgoto drop;\n\t}\n\tsk_acceptq_removed(sk);\n\n\terr = -EPROTO;\n\tif (!pskb_may_pull(skb, sizeof(*hdr) + 4))\n\t\tgoto drop;\n\n\thdr = pnp_hdr(skb);\n\tpipe_handle = hdr->pipe_handle;\n\tswitch (hdr->state_after_connect) {\n\tcase PN_PIPE_DISABLE:\n\t\tenabled = 0;\n\t\tbreak;\n\tcase PN_PIPE_ENABLE:\n\t\tenabled = 1;\n\t\tbreak;\n\tdefault:\n\t\tpep_reject_conn(sk, skb, PN_PIPE_ERR_INVALID_PARAM,\n\t\t\t\tGFP_KERNEL);\n\t\tgoto drop;\n\t}\n\tpeer_type = hdr->other_pep_type << 8;\n\n\t/* Parse sub-blocks (options) */\n\tn_sb = hdr->data[3];\n\twhile (n_sb > 0) {\n\t\tu8 type, buf[1], len = sizeof(buf);\n\t\tconst u8 *data = pep_get_sb(skb, &type, &len, buf);\n\n\t\tif (data == NULL)\n\t\t\tgoto drop;\n\t\tswitch (type) {\n\t\tcase PN_PIPE_SB_CONNECT_REQ_PEP_SUB_TYPE:\n\t\t\tif (len < 1)\n\t\t\t\tgoto drop;\n\t\t\tpeer_type = (peer_type & 0xff00) | data[0];\n\t\t\tbreak;\n\t\tcase PN_PIPE_SB_ALIGNED_DATA:\n\t\t\taligned = data[0] != 0;\n\t\t\tbreak;\n\t\t}\n\t\tn_sb--;\n\t}\n\n\t/* Check for duplicate pipe handle */\n\tnewsk = pep_find_pipe(&pn->hlist, &dst, pipe_handle);\n\tif (unlikely(newsk)) {\n\t\t__sock_put(newsk);\n\t\tnewsk = NULL;\n\t\tpep_reject_conn(sk, skb, PN_PIPE_ERR_PEP_IN_USE, GFP_KERNEL);\n\t\tgoto drop;\n\t}\n\n\t/* Create a new to-be-accepted sock */\n\tnewsk = sk_alloc(sock_net(sk), PF_PHONET, GFP_KERNEL, sk->sk_prot,\n\t\t\t kern);\n\tif (!newsk) {\n\t\tpep_reject_conn(sk, skb, PN_PIPE_ERR_OVERLOAD, GFP_KERNEL);\n\t\terr = -ENOBUFS;\n\t\tgoto drop;\n\t}\n\n\tsock_init_data(NULL, newsk);\n\tnewsk->sk_state = TCP_SYN_RECV;\n\tnewsk->sk_backlog_rcv = pipe_do_rcv;\n\tnewsk->sk_protocol = sk->sk_protocol;\n\tnewsk->sk_destruct = pipe_destruct;\n\n\tnewpn = pep_sk(newsk);\n\tpn_skb_get_dst_sockaddr(skb, &dst);\n\tpn_skb_get_src_sockaddr(skb, &src);\n\tnewpn->pn_sk.sobject = pn_sockaddr_get_object(&dst);\n\tnewpn->pn_sk.dobject = pn_sockaddr_get_object(&src);\n\tnewpn->pn_sk.resource = pn_sockaddr_get_resource(&dst);\n\tsock_hold(sk);\n\tnewpn->listener = sk;\n\tskb_queue_head_init(&newpn->ctrlreq_queue);\n\tnewpn->pipe_handle = pipe_handle;\n\tatomic_set(&newpn->tx_credits, 0);\n\tnewpn->ifindex = 0;\n\tnewpn->peer_type = peer_type;\n\tnewpn->rx_credits = 0;\n\tnewpn->rx_fc = newpn->tx_fc = PN_LEGACY_FLOW_CONTROL;\n\tnewpn->init_enable = enabled;\n\tnewpn->aligned = aligned;\n\n\terr = pep_accept_conn(newsk, skb);\n\tif (err) {\n\t\t__sock_put(sk);\n\t\tsock_put(newsk);\n\t\tnewsk = NULL;\n\t\tgoto drop;\n\t}\n\tsk_add_node(newsk, &pn->hlist);\ndrop:\n\trelease_sock(sk);\n\tkfree_skb(skb);\n\t*errp = err;\n\treturn newsk;\n}", "project": "linux", "hash": 89449369873513891205913064355633457403, "size": 121, "commit_id": "bcd0f93353326954817a4f9fa55ec57fb38acbb0", "message": "phonet: refcount leak in pep_sock_accep\n\nsock_hold(sk) is invoked in pep_sock_accept(), but __sock_put(sk) is not\ninvoked in subsequent failure branches(pep_accept_conn() != 0).\n\nSigned-off-by: Hangyu Hua \nLink: https://lore.kernel.org/r/20211209082839.33985-1-hbh25y@gmail.com\nSigned-off-by: Jakub Kicinski ", "target": 0, "dataset": "other", "idx": 224826} {"func": "GF_Err gf_isom_box_parse_ex(GF_Box **outBox, GF_BitStream *bs, u32 parent_type, Bool is_root_box)\n{\n\tu32 type, uuid_type, hdr_size;\n\tu64 size, start, payload_start, end;\n\tchar uuid[16];\n\tGF_Err e;\n\tGF_Box *newBox;\n\tBool skip_logs = gf_bs_get_cookie(bs) ? GF_TRUE : GF_FALSE;\n\tBool is_special = GF_TRUE;\n\n\tif ((bs == NULL) || (outBox == NULL) ) return GF_BAD_PARAM;\n\t*outBox = NULL;\n\tif (gf_bs_available(bs) < 8) {\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\n\tstart = gf_bs_get_position(bs);\n\n\tuuid_type = 0;\n\tsize = (u64) gf_bs_read_u32(bs);\n\thdr_size = 4;\n\t/*fix for some boxes found in some old hinted files*/\n\tif ((size >= 2) && (size <= 4)) {\n\t\tsize = 4;\n\t\ttype = GF_ISOM_BOX_TYPE_VOID;\n\t} else {\n\t\ttype = gf_bs_read_u32(bs);\n\t\thdr_size += 4;\n\t\t/*no size means till end of file - EXCEPT FOR some old QuickTime boxes...*/\n\t\tif (type == GF_ISOM_BOX_TYPE_TOTL)\n\t\t\tsize = 12;\n\t\tif (!size) {\n\t\t\tif (is_root_box) {\n\t\t\t\tif (!skip_logs) {\n\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Warning Read Box type %s (0x%08X) size 0 reading till the end of file\\n\", gf_4cc_to_str(type), type));\n\t\t\t\t}\n\t\t\t\tsize = gf_bs_available(bs) + 8;\n\t\t\t} else {\n\t\t\t\tif (!skip_logs) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Read Box type %s (0x%08X) at position \"LLU\" has size 0 but is not at root/file level, skipping\\n\", gf_4cc_to_str(type), type, start));\n\t\t\t\t}\n\t\t\t\treturn GF_OK;\n//\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t}\n\t}\n\t/*handle uuid*/\n\tmemset(uuid, 0, 16);\n\tif (type == GF_ISOM_BOX_TYPE_UUID ) {\n\t\tif (gf_bs_available(bs) < 16) {\n\t\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t\t}\n\t\tgf_bs_read_data(bs, uuid, 16);\n\t\thdr_size += 16;\n\t\tuuid_type = gf_isom_solve_uuid_box(uuid);\n\t}\n\n\t//handle large box\n\tif (size == 1) {\n\t\tif (gf_bs_available(bs) < 8) {\n\t\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t\t}\n\t\tsize = gf_bs_read_u64(bs);\n\t\thdr_size += 8;\n\t}\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Read Box type %s size \"LLD\" start \"LLD\"\\n\", gf_4cc_to_str(type), LLD_CAST size, LLD_CAST start));\n\n\tif ( size < hdr_size ) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Box size \"LLD\" less than box header size %d\\n\", LLD_CAST size, hdr_size));\n\t\treturn GF_ISOM_INVALID_FILE;\n\t}\n\n\t//some special boxes (references and track groups) are handled by a single generic box with an associated ref/group type\n\tif (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TREF)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_TrackReferenceTypeBox*)newBox)->reference_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_IREF)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFI);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_ItemReferenceTypeBox*)newBox)->reference_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TRGR)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_TRGT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_TrackGroupTypeBox*)newBox)->group_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_GRPL)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_GRPT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_EntityToGroupTypeBox*)newBox)->grouping_type = type;\n\t} else {\n\t\t//OK, create the box based on the type\n\t\tis_special = GF_FALSE;\n\t\tnewBox = gf_isom_box_new_ex(uuid_type ? uuid_type : type, parent_type, skip_logs, is_root_box);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t}\n\n\t//OK, init and read this box\n\tif (type==GF_ISOM_BOX_TYPE_UUID && !is_special) {\n\t\tmemcpy(((GF_UUIDBox *)newBox)->uuid, uuid, 16);\n\t\t((GF_UUIDBox *)newBox)->internal_4cc = uuid_type;\n\t}\n\n\tif (!newBox->type) newBox->type = type;\n\tpayload_start = gf_bs_get_position(bs);\n\nretry_unknown_box:\n\n\tend = gf_bs_available(bs);\n\tif (size - hdr_size > end ) {\n\t\tnewBox->size = size - hdr_size - end;\n\t\t*outBox = newBox;\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\n\tnewBox->size = size - hdr_size;\n\n\tif (newBox->size) {\n\t\te = gf_isom_full_box_read(newBox, bs);\n\t\tif (!e) e = gf_isom_box_read(newBox, bs);\n\t\tnewBox->size = size;\n\t\tend = gf_bs_get_position(bs);\n\t} else {\n\t\tnewBox->size = size;\n\t\t//empty box\n\t\te = GF_OK;\n\t\tend = gf_bs_get_position(bs);\n\t}\n\n\tif (e && (e != GF_ISOM_INCOMPLETE_FILE)) {\n\t\tgf_isom_box_del(newBox);\n\t\t*outBox = NULL;\n\n\t\tif (parent_type==GF_ISOM_BOX_TYPE_STSD) {\n\t\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_UNKNOWN);\n\t\t\t((GF_UnknownBox *)newBox)->original_4cc = type;\n\t\t\tnewBox->size = size;\n\t\t\tgf_bs_seek(bs, payload_start);\n\t\t\tgoto retry_unknown_box;\n\t\t}\n\t\tif (!skip_logs) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Read Box \\\"%s\\\" (start \"LLU\") failed (%s) - skipping\\n\", gf_4cc_to_str(type), start, gf_error_to_string(e)));\n\t\t}\n\t\t//we don't try to reparse known boxes that have been failing (too dangerous)\n\t\treturn e;\n\t}\n\n\tif (end-start > size) {\n\t\tif (!skip_logs) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Box \\\"%s\\\" size \"LLU\" (start \"LLU\") invalid (read \"LLU\")\\n\", gf_4cc_to_str(type), LLU_CAST size, start, LLU_CAST (end-start) ));\n\t\t}\n\t\t/*let's still try to load the file since no error was notified*/\n\t\tgf_bs_seek(bs, start+size);\n\t} else if (end-start < size) {\n\t\tu32 to_skip = (u32) (size-(end-start));\n\t\tif (!skip_logs) {\n\t\t\tif ((to_skip!=4) || gf_bs_peek_bits(bs, 32, 0)) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Box \\\"%s\\\" (start \"LLU\") has %u extra bytes\\n\", gf_4cc_to_str(type), start, to_skip));\n\t\t\t}\n\t\t}\n\t\tgf_bs_skip_bytes(bs, to_skip);\n\t}\n\t*outBox = newBox;\n\n\treturn e;\n}", "project": "gpac", "hash": 63019188358498749414838156609255855956, "size": 165, "commit_id": "8e585e623b1d666b4ef736ed609264639cb27701", "message": "fixed potential crash - cf #1406", "target": 1, "dataset": "other", "idx": 195345} {"func": "GF_Err gf_isom_box_parse_ex(GF_Box **outBox, GF_BitStream *bs, u32 parent_type, Bool is_root_box)\n{\n\tu32 type, uuid_type, hdr_size;\n\tu64 size, start, payload_start, end;\n\tchar uuid[16];\n\tGF_Err e;\n\tGF_Box *newBox;\n\tBool skip_logs = gf_bs_get_cookie(bs) ? GF_TRUE : GF_FALSE;\n\tBool is_special = GF_TRUE;\n\n\tif ((bs == NULL) || (outBox == NULL) ) return GF_BAD_PARAM;\n\t*outBox = NULL;\n\tif (gf_bs_available(bs) < 8) {\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\n\tstart = gf_bs_get_position(bs);\n\n\tuuid_type = 0;\n\tsize = (u64) gf_bs_read_u32(bs);\n\thdr_size = 4;\n\t/*fix for some boxes found in some old hinted files*/\n\tif ((size >= 2) && (size <= 4)) {\n\t\tsize = 4;\n\t\ttype = GF_ISOM_BOX_TYPE_VOID;\n\t} else {\n\t\ttype = gf_bs_read_u32(bs);\n\t\thdr_size += 4;\n\t\t/*no size means till end of file - EXCEPT FOR some old QuickTime boxes...*/\n\t\tif (type == GF_ISOM_BOX_TYPE_TOTL)\n\t\t\tsize = 12;\n\t\tif (!size) {\n\t\t\tif (is_root_box) {\n\t\t\t\tif (!skip_logs) {\n\t\t\t\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Warning Read Box type %s (0x%08X) size 0 reading till the end of file\\n\", gf_4cc_to_str(type), type));\n\t\t\t\t}\n\t\t\t\tsize = gf_bs_available(bs) + 8;\n\t\t\t} else {\n\t\t\t\tif (!skip_logs) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Read Box type %s (0x%08X) at position \"LLU\" has size 0 but is not at root/file level, skipping\\n\", gf_4cc_to_str(type), type, start));\n\t\t\t\t}\n\t\t\t\treturn GF_OK;\n//\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t}\n\t}\n\t/*handle uuid*/\n\tmemset(uuid, 0, 16);\n\tif (type == GF_ISOM_BOX_TYPE_UUID ) {\n\t\tif (gf_bs_available(bs) < 16) {\n\t\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t\t}\n\t\tgf_bs_read_data(bs, uuid, 16);\n\t\thdr_size += 16;\n\t\tuuid_type = gf_isom_solve_uuid_box(uuid);\n\t}\n\n\t//handle large box\n\tif (size == 1) {\n\t\tif (gf_bs_available(bs) < 8) {\n\t\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t\t}\n\t\tsize = gf_bs_read_u64(bs);\n\t\thdr_size += 8;\n\t}\n\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Read Box type %s size \"LLD\" start \"LLD\"\\n\", gf_4cc_to_str(type), LLD_CAST size, LLD_CAST start));\n\n\tif ( size < hdr_size ) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Box size \"LLD\" less than box header size %d\\n\", LLD_CAST size, hdr_size));\n\t\treturn GF_ISOM_INVALID_FILE;\n\t}\n\n\t//some special boxes (references and track groups) are handled by a single generic box with an associated ref/group type\n\tif (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TREF)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_TrackReferenceTypeBox*)newBox)->reference_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_IREF)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFI);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_ItemReferenceTypeBox*)newBox)->reference_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TRGR)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_TRGT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_TrackGroupTypeBox*)newBox)->group_type = type;\n\t} else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_GRPL)) {\n\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_GRPT);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t\t((GF_EntityToGroupTypeBox*)newBox)->grouping_type = type;\n\t} else {\n\t\t//OK, create the box based on the type\n\t\tis_special = GF_FALSE;\n\t\tnewBox = gf_isom_box_new_ex(uuid_type ? uuid_type : type, parent_type, skip_logs, is_root_box);\n\t\tif (!newBox) return GF_OUT_OF_MEM;\n\t}\n\n\t//OK, init and read this box\n\tif (type==GF_ISOM_BOX_TYPE_UUID && !is_special) {\n\t\tmemcpy(((GF_UUIDBox *)newBox)->uuid, uuid, 16);\n\t\t((GF_UUIDBox *)newBox)->internal_4cc = uuid_type;\n\t}\n\n\tif (!newBox->type) newBox->type = type;\n\tpayload_start = gf_bs_get_position(bs);\n\nretry_unknown_box:\n\n\tend = gf_bs_available(bs);\n\tif (size - hdr_size > end ) {\n\t\tnewBox->size = size - hdr_size - end;\n\t\t*outBox = newBox;\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\n\tnewBox->size = size - hdr_size;\n\n\t//parse even if size is 0 - this makes sure that we perform box parsing (usually in box->read)\n\te = gf_isom_full_box_read(newBox, bs);\n\tif (!e) e = gf_isom_box_read(newBox, bs);\n\tnewBox->size = size;\n\tend = gf_bs_get_position(bs);\n\n\tif (e && (e != GF_ISOM_INCOMPLETE_FILE)) {\n\t\tgf_isom_box_del(newBox);\n\t\t*outBox = NULL;\n\n\t\tif (parent_type==GF_ISOM_BOX_TYPE_STSD) {\n\t\t\tnewBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_UNKNOWN);\n\t\t\t((GF_UnknownBox *)newBox)->original_4cc = type;\n\t\t\tnewBox->size = size;\n\t\t\tgf_bs_seek(bs, payload_start);\n\t\t\tgoto retry_unknown_box;\n\t\t}\n\t\tif (!skip_logs) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Read Box \\\"%s\\\" (start \"LLU\") failed (%s) - skipping\\n\", gf_4cc_to_str(type), start, gf_error_to_string(e)));\n\t\t}\n\t\t//we don't try to reparse known boxes that have been failing (too dangerous)\n\t\treturn e;\n\t}\n\n\tif (end-start > size) {\n\t\tif (!skip_logs) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Box \\\"%s\\\" size \"LLU\" (start \"LLU\") invalid (read \"LLU\")\\n\", gf_4cc_to_str(type), LLU_CAST size, start, LLU_CAST (end-start) ));\n\t\t}\n\t\t/*let's still try to load the file since no error was notified*/\n\t\tgf_bs_seek(bs, start+size);\n\t} else if (end-start < size) {\n\t\tu32 to_skip = (u32) (size-(end-start));\n\t\tif (!skip_logs) {\n\t\t\tif ((to_skip!=4) || gf_bs_peek_bits(bs, 32, 0)) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Box \\\"%s\\\" (start \"LLU\") has %u extra bytes\\n\", gf_4cc_to_str(type), start, to_skip));\n\t\t\t}\n\t\t}\n\t\tgf_bs_skip_bytes(bs, to_skip);\n\t}\n\t*outBox = newBox;\n\n\treturn e;\n}", "project": "gpac", "hash": 267073801759882457635850212143910860248, "size": 159, "commit_id": "8e585e623b1d666b4ef736ed609264639cb27701", "message": "fixed potential crash - cf #1406", "target": 0, "dataset": "other", "idx": 224922} {"func": "snmp_ber_decode_string_len_buffer(unsigned char *buf, uint32_t *buff_len, const char **str, uint32_t *length)\n{\n uint8_t type, i, length_bytes;\n\n buf = snmp_ber_decode_type(buf, buff_len, &type);\n\n if(buf == NULL || type != BER_DATA_TYPE_OCTET_STRING) {\n /*\n * Sanity check\n * Invalid type in buffer\n */\n return NULL;\n }\n\n if((*buf & 0x80) == 0) {\n *length = (uint32_t)*buf++;\n (*buff_len)--;\n } else {\n\n length_bytes = (uint8_t)(*buf++ & 0x7F);\n (*buff_len)--;\n if(length_bytes > 4) {\n /*\n * Sanity check\n * It will not fit in the uint32_t\n */\n return NULL;\n }\n\n *length = (uint32_t)*buf++;\n (*buff_len)--;\n for(i = 1; i < length_bytes; ++i) {\n *length <<= 8;\n *length |= *buf++;\n (*buff_len)--;\n }\n }\n\n *str = (const char *)buf;\n *buff_len -= *length;\n\n return buf + *length;\n}", "project": "contiki-ng", "hash": 245878712235324239686057305671224454457, "size": 43, "commit_id": "12c824386ab60de757de5001974d73b32e19ad71", "message": "Refactored SNMP engine after vulnerabilities", "target": 1, "dataset": "other", "idx": 195362} {"func": "snmp_ber_decode_string_len_buffer(snmp_packet_t *snmp_packet, const char **str, uint32_t *length)\n{\n uint8_t type, i, length_bytes;\n\n if(!snmp_ber_decode_type(snmp_packet, &type)) {\n return 0;\n }\n\n if(type != BER_DATA_TYPE_OCTET_STRING) {\n /*\n * Sanity check\n * Invalid type in buffer\n */\n return 0;\n }\n\n if((*snmp_packet->in & 0x80) == 0) {\n\n if(snmp_packet->used == 0) {\n return 0;\n }\n\n *length = (uint32_t)*snmp_packet->in++;\n snmp_packet->used--;\n } else {\n\n if(snmp_packet->used == 0) {\n return 0;\n }\n\n length_bytes = (uint8_t)(*snmp_packet->in++ & 0x7F);\n snmp_packet->used--;\n\n if(length_bytes > 4) {\n /*\n * Sanity check\n * It will not fit in the uint32_t\n */\n return 0;\n }\n\n if(snmp_packet->used == 0) {\n return 0;\n }\n\n *length = (uint32_t)*snmp_packet->in++;\n snmp_packet->used--;\n\n for(i = 1; i < length_bytes; ++i) {\n *length <<= 8;\n\n if(snmp_packet->used == 0) {\n return 0;\n }\n\n *length |= *snmp_packet->in++;\n snmp_packet->used--;\n }\n }\n\n *str = (const char *)snmp_packet->in;\n\n if(snmp_packet->used == 0 || snmp_packet->used - *length <= 0) {\n return 0;\n }\n\n snmp_packet->used -= *length;\n snmp_packet->in += *length;\n\n return 1;\n}", "project": "contiki-ng", "hash": 41319319420355179801852466083422626714, "size": 71, "commit_id": "12c824386ab60de757de5001974d73b32e19ad71", "message": "Refactored SNMP engine after vulnerabilities", "target": 0, "dataset": "other", "idx": 224950} {"func": " bool handleBackslash(signed char& out) {\n char ch = *p++;\n switch (ch) {\n case 0: return false;\n case '\"': out = ch; return true;\n case '\\\\': out = ch; return true;\n case '/': out = ch; return true;\n case 'b': out = '\\b'; return true;\n case 'f': out = '\\f'; return true;\n case 'n': out = '\\n'; return true;\n case 'r': out = '\\r'; return true;\n case 't': out = '\\t'; return true;\n case 'u': {\n if (UNLIKELY(is_tsimplejson)) {\n auto const ch1 = *p++;\n auto const ch2 = *p++;\n auto const dch3 = dehexchar(*p++);\n auto const dch4 = dehexchar(*p++);\n if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) {\n return false;\n }\n out = (dch3 << 4) | dch4;\n return true;\n } else {\n uint16_t u16cp = 0;\n for (int i = 0; i < 4; i++) {\n auto const hexv = dehexchar(*p++);\n if (hexv < 0) return false; // includes check for end of string\n u16cp <<= 4;\n u16cp |= hexv;\n }\n if (u16cp > 0x7f) {\n return false;\n } else {\n out = u16cp;\n return true;\n }\n }\n }\n default: return false;\n }\n }", "project": "hhvm", "hash": 222661936735492214340109696360679833540, "size": 42, "commit_id": "b3679121bb3c7017ff04b4c08402ffff5cf59b13", "message": "Fix buffer overrun in SimpleParser::handleBackslash\n\nSummary:\nIt read 4 chars, then checked for validity, but any of them could have\nbeen the end of the string, so check after each one instead.\n\nReviewed By: oulgen\n\nDifferential Revision: D19611163\n\nfbshipit-source-id: 3da0a39555cb85a93f4fd98048368f17cf37e2e4", "target": 1, "dataset": "other", "idx": 195486} {"func": " bool handleBackslash(signed char& out) {\n char ch = *p++;\n switch (ch) {\n case 0: return false;\n case '\"': out = ch; return true;\n case '\\\\': out = ch; return true;\n case '/': out = ch; return true;\n case 'b': out = '\\b'; return true;\n case 'f': out = '\\f'; return true;\n case 'n': out = '\\n'; return true;\n case 'r': out = '\\r'; return true;\n case 't': out = '\\t'; return true;\n case 'u': {\n if (UNLIKELY(is_tsimplejson)) {\n auto const ch1 = *p++;\n if (UNLIKELY(ch1 != '0')) return false;\n auto const ch2 = *p++;\n if (UNLIKELY(ch2 != '0')) return false;\n auto const dch3 = dehexchar(*p++);\n if (UNLIKELY(dch3 < 0)) return false;\n auto const dch4 = dehexchar(*p++);\n if (UNLIKELY(dch4 < 0)) return false;\n out = (dch3 << 4) | dch4;\n return true;\n } else {\n uint16_t u16cp = 0;\n for (int i = 0; i < 4; i++) {\n auto const hexv = dehexchar(*p++);\n if (hexv < 0) return false; // includes check for end of string\n u16cp <<= 4;\n u16cp |= hexv;\n }\n if (u16cp > 0x7f) {\n return false;\n } else {\n out = u16cp;\n return true;\n }\n }\n }\n default: return false;\n }\n }", "project": "hhvm", "hash": 144019738520182441880919167101542852402, "size": 43, "commit_id": "b3679121bb3c7017ff04b4c08402ffff5cf59b13", "message": "Fix buffer overrun in SimpleParser::handleBackslash\n\nSummary:\nIt read 4 chars, then checked for validity, but any of them could have\nbeen the end of the string, so check after each one instead.\n\nReviewed By: oulgen\n\nDifferential Revision: D19611163\n\nfbshipit-source-id: 3da0a39555cb85a93f4fd98048368f17cf37e2e4", "target": 0, "dataset": "other", "idx": 227282} {"func": "void LanLinkProvider::addLink(const QString& deviceId, QSslSocket* socket, NetworkPacket* receivedPacket, LanDeviceLink::ConnectionStarted connectionOrigin)\n{\n // Socket disconnection will now be handled by LanDeviceLink\n disconnect(socket, &QAbstractSocket::disconnected, socket, &QObject::deleteLater);\n\n LanDeviceLink* deviceLink;\n //Do we have a link for this device already?\n QMap< QString, LanDeviceLink* >::iterator linkIterator = m_links.find(deviceId);\n if (linkIterator != m_links.end()) {\n //qCDebug(KDECONNECT_CORE) << \"Reusing link to\" << deviceId;\n deviceLink = linkIterator.value();\n deviceLink->reset(socket, connectionOrigin);\n } else {\n deviceLink = new LanDeviceLink(deviceId, this, socket, connectionOrigin);\n connect(deviceLink, &QObject::destroyed, this, &LanLinkProvider::deviceLinkDestroyed);\n m_links[deviceId] = deviceLink;\n if (m_pairingHandlers.contains(deviceId)) {\n //We shouldn't have a pairinghandler if we didn't have a link.\n //Crash if debug, recover if release (by setting the new devicelink to the old pairinghandler)\n Q_ASSERT(m_pairingHandlers.contains(deviceId));\n m_pairingHandlers[deviceId]->setDeviceLink(deviceLink);\n }\n }\n Q_EMIT onConnectionReceived(*receivedPacket, deviceLink);\n}", "project": "kdeconnect-kde", "hash": 173422384228019084279107414716208706323, "size": 25, "commit_id": "542d94a70c56aa386c8d4d793481ce181b0422e8", "message": "Limit number of connected sockets from unpaired devices\n\nThanks Matthias Gerstner for reporting this.", "target": 1, "dataset": "other", "idx": 195488} {"func": "void LanLinkProvider::addLink(const QString& deviceId, QSslSocket* socket, NetworkPacket* receivedPacket, LanDeviceLink::ConnectionStarted connectionOrigin)\n{\n // Socket disconnection will now be handled by LanDeviceLink\n disconnect(socket, &QAbstractSocket::disconnected, socket, &QObject::deleteLater);\n\n LanDeviceLink* deviceLink;\n //Do we have a link for this device already?\n QMap< QString, LanDeviceLink* >::iterator linkIterator = m_links.find(deviceId);\n if (linkIterator != m_links.end()) {\n //qCDebug(KDECONNECT_CORE) << \"Reusing link to\" << deviceId;\n deviceLink = linkIterator.value();\n deviceLink->reset(socket, connectionOrigin);\n } else {\n deviceLink = new LanDeviceLink(deviceId, this, socket, connectionOrigin);\n // Socket disconnection will now be handled by LanDeviceLink\n disconnect(socket, &QAbstractSocket::disconnected, socket, &QObject::deleteLater);\n bool isDeviceTrusted = KdeConnectConfig::instance().trustedDevices().contains(deviceId);\n if (!isDeviceTrusted && m_links.size() > MAX_UNPAIRED_CONNECTIONS) {\n qCWarning(KDECONNECT_CORE) << \"Too many unpaired devices to remember them all. Ignoring \" << deviceId;\n socket->disconnectFromHost();\n socket->deleteLater();\n return;\n }\n connect(deviceLink, &QObject::destroyed, this, &LanLinkProvider::deviceLinkDestroyed);\n m_links[deviceId] = deviceLink;\n if (m_pairingHandlers.contains(deviceId)) {\n //We shouldn't have a pairinghandler if we didn't have a link.\n //Crash if debug, recover if release (by setting the new devicelink to the old pairinghandler)\n Q_ASSERT(m_pairingHandlers.contains(deviceId));\n m_pairingHandlers[deviceId]->setDeviceLink(deviceLink);\n }\n }\n Q_EMIT onConnectionReceived(*receivedPacket, deviceLink);\n}", "project": "kdeconnect-kde", "hash": 240980444615899412189553804947186003078, "size": 34, "commit_id": "542d94a70c56aa386c8d4d793481ce181b0422e8", "message": "Limit number of connected sockets from unpaired devices\n\nThanks Matthias Gerstner for reporting this.", "target": 0, "dataset": "other", "idx": 227355} {"func": "_libssh2_packet_add(LIBSSH2_SESSION * session, unsigned char *data,\n size_t datalen, int macstate)\n{\n int rc = 0;\n char *message = NULL;\n char *language = NULL;\n size_t message_len = 0;\n size_t language_len = 0;\n LIBSSH2_CHANNEL *channelp = NULL;\n size_t data_head = 0;\n unsigned char msg = data[0];\n\n switch(session->packAdd_state) {\n case libssh2_NB_state_idle:\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS,\n \"Packet type %d received, length=%d\",\n (int) msg, (int) datalen);\n\n if((macstate == LIBSSH2_MAC_INVALID) &&\n (!session->macerror ||\n LIBSSH2_MACERROR(session, (char *) data, datalen))) {\n /* Bad MAC input, but no callback set or non-zero return from the\n callback */\n\n LIBSSH2_FREE(session, data);\n return _libssh2_error(session, LIBSSH2_ERROR_INVALID_MAC,\n \"Invalid MAC received\");\n }\n session->packAdd_state = libssh2_NB_state_allocated;\n break;\n case libssh2_NB_state_jump1:\n goto libssh2_packet_add_jump_point1;\n case libssh2_NB_state_jump2:\n goto libssh2_packet_add_jump_point2;\n case libssh2_NB_state_jump3:\n goto libssh2_packet_add_jump_point3;\n case libssh2_NB_state_jump4:\n goto libssh2_packet_add_jump_point4;\n case libssh2_NB_state_jump5:\n goto libssh2_packet_add_jump_point5;\n default: /* nothing to do */\n break;\n }\n\n if(session->packAdd_state == libssh2_NB_state_allocated) {\n /* A couple exceptions to the packet adding rule: */\n switch(msg) {\n\n /*\n byte SSH_MSG_DISCONNECT\n uint32 reason code\n string description in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n\n case SSH_MSG_DISCONNECT:\n if(datalen >= 5) {\n size_t reason = _libssh2_ntohu32(data + 1);\n\n if(datalen >= 9) {\n message_len = _libssh2_ntohu32(data + 5);\n\n if(message_len < datalen-13) {\n /* 9 = packet_type(1) + reason(4) + message_len(4) */\n message = (char *) data + 9;\n\n language_len =\n _libssh2_ntohu32(data + 9 + message_len);\n language = (char *) data + 9 + message_len + 4;\n\n if(language_len > (datalen-13-message_len)) {\n /* bad input, clear info */\n language = message = NULL;\n language_len = message_len = 0;\n }\n }\n else\n /* bad size, clear it */\n message_len = 0;\n }\n if(session->ssh_msg_disconnect) {\n LIBSSH2_DISCONNECT(session, reason, message,\n message_len, language, language_len);\n }\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS,\n \"Disconnect(%d): %s(%s)\", reason,\n message, language);\n }\n\n LIBSSH2_FREE(session, data);\n session->socket_state = LIBSSH2_SOCKET_DISCONNECTED;\n session->packAdd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_DISCONNECT,\n \"socket disconnect\");\n /*\n byte SSH_MSG_IGNORE\n string data\n */\n\n case SSH_MSG_IGNORE:\n if(datalen >= 2) {\n if(session->ssh_msg_ignore) {\n LIBSSH2_IGNORE(session, (char *) data + 1, datalen - 1);\n }\n }\n else if(session->ssh_msg_ignore) {\n LIBSSH2_IGNORE(session, \"\", 0);\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_DEBUG\n boolean always_display\n string message in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n\n case SSH_MSG_DEBUG:\n if(datalen >= 2) {\n int always_display = data[1];\n\n if(datalen >= 6) {\n message_len = _libssh2_ntohu32(data + 2);\n\n if(message_len <= (datalen - 10)) {\n /* 6 = packet_type(1) + display(1) + message_len(4) */\n message = (char *) data + 6;\n language_len = _libssh2_ntohu32(data + 6 +\n message_len);\n\n if(language_len <= (datalen - 10 - message_len))\n language = (char *) data + 10 + message_len;\n }\n }\n\n if(session->ssh_msg_debug) {\n LIBSSH2_DEBUG(session, always_display, message,\n message_len, language, language_len);\n }\n }\n /*\n * _libssh2_debug will actually truncate this for us so\n * that it's not an inordinate about of data\n */\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS,\n \"Debug Packet: %s\", message);\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_GLOBAL_REQUEST\n string request name in US-ASCII only\n boolean want reply\n .... request-specific data follows\n */\n\n case SSH_MSG_GLOBAL_REQUEST:\n if(datalen >= 5) {\n uint32_t len = 0;\n unsigned char want_reply = 0;\n len = _libssh2_ntohu32(data + 1);\n if(datalen >= (6 + len)) {\n want_reply = data[5 + len];\n _libssh2_debug(session,\n LIBSSH2_TRACE_CONN,\n \"Received global request type %.*s (wr %X)\",\n len, data + 5, want_reply);\n }\n\n\n if(want_reply) {\n static const unsigned char packet =\n SSH_MSG_REQUEST_FAILURE;\n libssh2_packet_add_jump_point5:\n session->packAdd_state = libssh2_NB_state_jump5;\n rc = _libssh2_transport_send(session, &packet, 1, NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_CHANNEL_EXTENDED_DATA\n uint32 recipient channel\n uint32 data_type_code\n string data\n */\n\n case SSH_MSG_CHANNEL_EXTENDED_DATA:\n /* streamid(4) */\n data_head += 4;\n\n /* fall-through */\n\n /*\n byte SSH_MSG_CHANNEL_DATA\n uint32 recipient channel\n string data\n */\n\n case SSH_MSG_CHANNEL_DATA:\n /* packet_type(1) + channelno(4) + datalen(4) */\n data_head += 9;\n\n if(datalen >= data_head)\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n\n if(!channelp) {\n _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_UNKNOWN,\n \"Packet received for unknown channel\");\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n#ifdef LIBSSH2DEBUG\n {\n uint32_t stream_id = 0;\n if(msg == SSH_MSG_CHANNEL_EXTENDED_DATA)\n stream_id = _libssh2_ntohu32(data + 5);\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"%d bytes packet_add() for %lu/%lu/%lu\",\n (int) (datalen - data_head),\n channelp->local.id,\n channelp->remote.id,\n stream_id);\n }\n#endif\n if((channelp->remote.extended_data_ignore_mode ==\n LIBSSH2_CHANNEL_EXTENDED_DATA_IGNORE) &&\n (msg == SSH_MSG_CHANNEL_EXTENDED_DATA)) {\n /* Pretend we didn't receive this */\n LIBSSH2_FREE(session, data);\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Ignoring extended data and refunding %d bytes\",\n (int) (datalen - 13));\n if(channelp->read_avail + datalen - data_head >=\n channelp->remote.window_size)\n datalen = channelp->remote.window_size -\n channelp->read_avail + data_head;\n\n channelp->remote.window_size -= datalen - data_head;\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"shrinking window size by %lu bytes to %lu, \"\n \"read_avail %lu\",\n datalen - data_head,\n channelp->remote.window_size,\n channelp->read_avail);\n\n session->packAdd_channelp = channelp;\n\n /* Adjust the window based on the block we just freed */\n libssh2_packet_add_jump_point1:\n session->packAdd_state = libssh2_NB_state_jump1;\n rc = _libssh2_channel_receive_window_adjust(session->\n packAdd_channelp,\n datalen - 13,\n 1, NULL);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n\n /*\n * REMEMBER! remote means remote as source of data,\n * NOT remote window!\n */\n if(channelp->remote.packet_size < (datalen - data_head)) {\n /*\n * Spec says we MAY ignore bytes sent beyond\n * packet_size\n */\n _libssh2_error(session,\n LIBSSH2_ERROR_CHANNEL_PACKET_EXCEEDED,\n \"Packet contains more data than we offered\"\n \" to receive, truncating\");\n datalen = channelp->remote.packet_size + data_head;\n }\n if(channelp->remote.window_size <= channelp->read_avail) {\n /*\n * Spec says we MAY ignore bytes sent beyond\n * window_size\n */\n _libssh2_error(session,\n LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED,\n \"The current receive window is full,\"\n \" data ignored\");\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n /* Reset EOF status */\n channelp->remote.eof = 0;\n\n if(channelp->read_avail + datalen - data_head >\n channelp->remote.window_size) {\n _libssh2_error(session,\n LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED,\n \"Remote sent more data than current \"\n \"window allows, truncating\");\n datalen = channelp->remote.window_size -\n channelp->read_avail + data_head;\n }\n\n /* Update the read_avail counter. The window size will be\n * updated once the data is actually read from the queue\n * from an upper layer */\n channelp->read_avail += datalen - data_head;\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"increasing read_avail by %lu bytes to %lu/%lu\",\n (long)(datalen - data_head),\n (long)channelp->read_avail,\n (long)channelp->remote.window_size);\n\n break;\n\n /*\n byte SSH_MSG_CHANNEL_EOF\n uint32 recipient channel\n */\n\n case SSH_MSG_CHANNEL_EOF:\n if(datalen >= 5)\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n if(!channelp)\n /* We may have freed already, just quietly ignore this... */\n ;\n else {\n _libssh2_debug(session,\n LIBSSH2_TRACE_CONN,\n \"EOF received for channel %lu/%lu\",\n channelp->local.id,\n channelp->remote.id);\n channelp->remote.eof = 1;\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_CHANNEL_REQUEST\n uint32 recipient channel\n string request type in US-ASCII characters only\n boolean want reply\n .... type-specific data follows\n */\n\n case SSH_MSG_CHANNEL_REQUEST:\n if(datalen >= 9) {\n uint32_t channel = _libssh2_ntohu32(data + 1);\n uint32_t len = _libssh2_ntohu32(data + 5);\n unsigned char want_reply = 1;\n\n if((len + 9) < datalen)\n want_reply = data[len + 9];\n\n _libssh2_debug(session,\n LIBSSH2_TRACE_CONN,\n \"Channel %d received request type %.*s (wr %X)\",\n channel, len, data + 9, want_reply);\n\n if(len == sizeof(\"exit-status\") - 1\n && (sizeof(\"exit-status\") - 1 + 9) <= datalen\n && !memcmp(\"exit-status\", data + 9,\n sizeof(\"exit-status\") - 1)) {\n\n /* we've got \"exit-status\" packet. Set the session value */\n if(datalen >= 20)\n channelp =\n _libssh2_channel_locate(session, channel);\n\n if(channelp && (sizeof(\"exit-status\") + 13) <= datalen) {\n channelp->exit_status =\n _libssh2_ntohu32(data + 9 + sizeof(\"exit-status\"));\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Exit status %lu received for \"\n \"channel %lu/%lu\",\n channelp->exit_status,\n channelp->local.id,\n channelp->remote.id);\n }\n\n }\n else if(len == sizeof(\"exit-signal\") - 1\n && (sizeof(\"exit-signal\") - 1 + 9) <= datalen\n && !memcmp(\"exit-signal\", data + 9,\n sizeof(\"exit-signal\") - 1)) {\n /* command terminated due to signal */\n if(datalen >= 20)\n channelp = _libssh2_channel_locate(session, channel);\n\n if(channelp && (sizeof(\"exit-signal\") + 13) <= datalen) {\n /* set signal name (without SIG prefix) */\n uint32_t namelen =\n _libssh2_ntohu32(data + 9 + sizeof(\"exit-signal\"));\n\n if(namelen <= UINT_MAX - 1) {\n channelp->exit_signal =\n LIBSSH2_ALLOC(session, namelen + 1);\n }\n else {\n channelp->exit_signal = NULL;\n }\n\n if(!channelp->exit_signal)\n rc = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"memory for signal name\");\n else if((sizeof(\"exit-signal\") + 13 + namelen <=\n datalen)) {\n memcpy(channelp->exit_signal,\n data + 13 + sizeof(\"exit-signal\"), namelen);\n channelp->exit_signal[namelen] = '\\0';\n /* TODO: save error message and language tag */\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Exit signal %s received for \"\n \"channel %lu/%lu\",\n channelp->exit_signal,\n channelp->local.id,\n channelp->remote.id);\n }\n }\n }\n\n\n if(want_reply) {\n unsigned char packet[5];\n libssh2_packet_add_jump_point4:\n session->packAdd_state = libssh2_NB_state_jump4;\n packet[0] = SSH_MSG_CHANNEL_FAILURE;\n memcpy(&packet[1], data + 1, 4);\n rc = _libssh2_transport_send(session, packet, 5, NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return rc;\n\n /*\n byte SSH_MSG_CHANNEL_CLOSE\n uint32 recipient channel\n */\n\n case SSH_MSG_CHANNEL_CLOSE:\n if(datalen >= 5)\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n if(!channelp) {\n /* We may have freed already, just quietly ignore this... */\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Close received for channel %lu/%lu\",\n channelp->local.id,\n channelp->remote.id);\n\n channelp->remote.close = 1;\n channelp->remote.eof = 1;\n\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_CHANNEL_OPEN\n string \"session\"\n uint32 sender channel\n uint32 initial window size\n uint32 maximum packet size\n */\n\n case SSH_MSG_CHANNEL_OPEN:\n if(datalen < 17)\n ;\n else if((datalen >= (sizeof(\"forwarded-tcpip\") + 4)) &&\n ((sizeof(\"forwarded-tcpip\") - 1) ==\n _libssh2_ntohu32(data + 1))\n &&\n (memcmp(data + 5, \"forwarded-tcpip\",\n sizeof(\"forwarded-tcpip\") - 1) == 0)) {\n\n /* init the state struct */\n memset(&session->packAdd_Qlstn_state, 0,\n sizeof(session->packAdd_Qlstn_state));\n\n libssh2_packet_add_jump_point2:\n session->packAdd_state = libssh2_NB_state_jump2;\n rc = packet_queue_listener(session, data, datalen,\n &session->packAdd_Qlstn_state);\n }\n else if((datalen >= (sizeof(\"x11\") + 4)) &&\n ((sizeof(\"x11\") - 1) == _libssh2_ntohu32(data + 1)) &&\n (memcmp(data + 5, \"x11\", sizeof(\"x11\") - 1) == 0)) {\n\n /* init the state struct */\n memset(&session->packAdd_x11open_state, 0,\n sizeof(session->packAdd_x11open_state));\n\n libssh2_packet_add_jump_point3:\n session->packAdd_state = libssh2_NB_state_jump3;\n rc = packet_x11_open(session, data, datalen,\n &session->packAdd_x11open_state);\n }\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return rc;\n\n /*\n byte SSH_MSG_CHANNEL_WINDOW_ADJUST\n uint32 recipient channel\n uint32 bytes to add\n */\n case SSH_MSG_CHANNEL_WINDOW_ADJUST:\n if(datalen < 9)\n ;\n else {\n uint32_t bytestoadd = _libssh2_ntohu32(data + 5);\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n if(channelp) {\n channelp->local.window_size += bytestoadd;\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Window adjust for channel %lu/%lu, \"\n \"adding %lu bytes, new window_size=%lu\",\n channelp->local.id,\n channelp->remote.id,\n bytestoadd,\n channelp->local.window_size);\n }\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n default:\n break;\n }\n\n session->packAdd_state = libssh2_NB_state_sent;\n }\n\n if(session->packAdd_state == libssh2_NB_state_sent) {\n LIBSSH2_PACKET *packetp =\n LIBSSH2_ALLOC(session, sizeof(LIBSSH2_PACKET));\n if(!packetp) {\n _libssh2_debug(session, LIBSSH2_ERROR_ALLOC,\n \"memory for packet\");\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return LIBSSH2_ERROR_ALLOC;\n }\n packetp->data = data;\n packetp->data_len = datalen;\n packetp->data_head = data_head;\n\n _libssh2_list_add(&session->packets, &packetp->node);\n\n session->packAdd_state = libssh2_NB_state_sent1;\n }\n\n if((msg == SSH_MSG_KEXINIT &&\n !(session->state & LIBSSH2_STATE_EXCHANGING_KEYS)) ||\n (session->packAdd_state == libssh2_NB_state_sent2)) {\n if(session->packAdd_state == libssh2_NB_state_sent1) {\n /*\n * Remote wants new keys\n * Well, it's already in the brigade,\n * let's just call back into ourselves\n */\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS, \"Renegotiating Keys\");\n\n session->packAdd_state = libssh2_NB_state_sent2;\n }\n\n /*\n * The KEXINIT message has been added to the queue. The packAdd and\n * readPack states need to be reset because _libssh2_kex_exchange\n * (eventually) calls upon _libssh2_transport_read to read the rest of\n * the key exchange conversation.\n */\n session->readPack_state = libssh2_NB_state_idle;\n session->packet.total_num = 0;\n session->packAdd_state = libssh2_NB_state_idle;\n session->fullpacket_state = libssh2_NB_state_idle;\n\n memset(&session->startup_key_state, 0, sizeof(key_exchange_state_t));\n\n /*\n * If there was a key reexchange failure, let's just hope we didn't\n * send NEWKEYS yet, otherwise remote will drop us like a rock\n */\n rc = _libssh2_kex_exchange(session, 1, &session->startup_key_state);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n}", "project": "libssh2", "hash": 1170263160591633863198263904436599036, "size": 621, "commit_id": "dedcbd106f8e52d5586b0205bc7677e4c9868f9c", "message": "packet.c: improve message parsing (#402)\n\n* packet.c: improve parsing of packets\r\n\r\nfile: packet.c\r\n\r\nnotes:\r\nUse _libssh2_get_string API in SSH_MSG_DEBUG/SSH_MSG_DISCONNECT. Additional uint32 bounds check in SSH_MSG_GLOBAL_REQUEST.", "target": 1, "dataset": "other", "idx": 195648} {"func": "_libssh2_packet_add(LIBSSH2_SESSION * session, unsigned char *data,\n size_t datalen, int macstate)\n{\n int rc = 0;\n unsigned char *message = NULL;\n unsigned char *language = NULL;\n size_t message_len = 0;\n size_t language_len = 0;\n LIBSSH2_CHANNEL *channelp = NULL;\n size_t data_head = 0;\n unsigned char msg = data[0];\n\n switch(session->packAdd_state) {\n case libssh2_NB_state_idle:\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS,\n \"Packet type %d received, length=%d\",\n (int) msg, (int) datalen);\n\n if((macstate == LIBSSH2_MAC_INVALID) &&\n (!session->macerror ||\n LIBSSH2_MACERROR(session, (char *) data, datalen))) {\n /* Bad MAC input, but no callback set or non-zero return from the\n callback */\n\n LIBSSH2_FREE(session, data);\n return _libssh2_error(session, LIBSSH2_ERROR_INVALID_MAC,\n \"Invalid MAC received\");\n }\n session->packAdd_state = libssh2_NB_state_allocated;\n break;\n case libssh2_NB_state_jump1:\n goto libssh2_packet_add_jump_point1;\n case libssh2_NB_state_jump2:\n goto libssh2_packet_add_jump_point2;\n case libssh2_NB_state_jump3:\n goto libssh2_packet_add_jump_point3;\n case libssh2_NB_state_jump4:\n goto libssh2_packet_add_jump_point4;\n case libssh2_NB_state_jump5:\n goto libssh2_packet_add_jump_point5;\n default: /* nothing to do */\n break;\n }\n\n if(session->packAdd_state == libssh2_NB_state_allocated) {\n /* A couple exceptions to the packet adding rule: */\n switch(msg) {\n\n /*\n byte SSH_MSG_DISCONNECT\n uint32 reason code\n string description in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n\n case SSH_MSG_DISCONNECT:\n if(datalen >= 5) {\n uint32_t reason = 0;\n struct string_buf buf;\n buf.data = (unsigned char *)data;\n buf.dataptr = buf.data;\n buf.len = datalen;\n buf.dataptr++; /* advance past type */\n\n _libssh2_get_u32(&buf, &reason);\n _libssh2_get_string(&buf, &message, &message_len);\n _libssh2_get_string(&buf, &language, &language_len);\n\n if(session->ssh_msg_disconnect) {\n LIBSSH2_DISCONNECT(session, reason, (const char *)message,\n message_len, (const char *)language,\n language_len);\n }\n\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS,\n \"Disconnect(%d): %s(%s)\", reason,\n message, language);\n }\n\n LIBSSH2_FREE(session, data);\n session->socket_state = LIBSSH2_SOCKET_DISCONNECTED;\n session->packAdd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_DISCONNECT,\n \"socket disconnect\");\n /*\n byte SSH_MSG_IGNORE\n string data\n */\n\n case SSH_MSG_IGNORE:\n if(datalen >= 2) {\n if(session->ssh_msg_ignore) {\n LIBSSH2_IGNORE(session, (char *) data + 1, datalen - 1);\n }\n }\n else if(session->ssh_msg_ignore) {\n LIBSSH2_IGNORE(session, \"\", 0);\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_DEBUG\n boolean always_display\n string message in ISO-10646 UTF-8 encoding [RFC3629]\n string language tag [RFC3066]\n */\n\n case SSH_MSG_DEBUG:\n if(datalen >= 2) {\n int always_display = data[1];\n\n if(datalen >= 6) {\n struct string_buf buf;\n buf.data = (unsigned char *)data;\n buf.dataptr = buf.data;\n buf.len = datalen;\n buf.dataptr += 2; /* advance past type & always display */\n\n _libssh2_get_string(&buf, &message, &message_len);\n _libssh2_get_string(&buf, &language, &language_len);\n }\n\n if(session->ssh_msg_debug) {\n LIBSSH2_DEBUG(session, always_display,\n (const char *)message,\n message_len, (const char *)language,\n language_len);\n }\n }\n\n /*\n * _libssh2_debug will actually truncate this for us so\n * that it's not an inordinate about of data\n */\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS,\n \"Debug Packet: %s\", message);\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_GLOBAL_REQUEST\n string request name in US-ASCII only\n boolean want reply\n .... request-specific data follows\n */\n\n case SSH_MSG_GLOBAL_REQUEST:\n if(datalen >= 5) {\n uint32_t len = 0;\n unsigned char want_reply = 0;\n len = _libssh2_ntohu32(data + 1);\n if((len <= (UINT_MAX - 6)) && (datalen >= (6 + len))) {\n want_reply = data[5 + len];\n _libssh2_debug(session,\n LIBSSH2_TRACE_CONN,\n \"Received global request type %.*s (wr %X)\",\n len, data + 5, want_reply);\n }\n\n\n if(want_reply) {\n static const unsigned char packet =\n SSH_MSG_REQUEST_FAILURE;\n libssh2_packet_add_jump_point5:\n session->packAdd_state = libssh2_NB_state_jump5;\n rc = _libssh2_transport_send(session, &packet, 1, NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_CHANNEL_EXTENDED_DATA\n uint32 recipient channel\n uint32 data_type_code\n string data\n */\n\n case SSH_MSG_CHANNEL_EXTENDED_DATA:\n /* streamid(4) */\n data_head += 4;\n\n /* fall-through */\n\n /*\n byte SSH_MSG_CHANNEL_DATA\n uint32 recipient channel\n string data\n */\n\n case SSH_MSG_CHANNEL_DATA:\n /* packet_type(1) + channelno(4) + datalen(4) */\n data_head += 9;\n\n if(datalen >= data_head)\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n\n if(!channelp) {\n _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_UNKNOWN,\n \"Packet received for unknown channel\");\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n#ifdef LIBSSH2DEBUG\n {\n uint32_t stream_id = 0;\n if(msg == SSH_MSG_CHANNEL_EXTENDED_DATA)\n stream_id = _libssh2_ntohu32(data + 5);\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"%d bytes packet_add() for %lu/%lu/%lu\",\n (int) (datalen - data_head),\n channelp->local.id,\n channelp->remote.id,\n stream_id);\n }\n#endif\n if((channelp->remote.extended_data_ignore_mode ==\n LIBSSH2_CHANNEL_EXTENDED_DATA_IGNORE) &&\n (msg == SSH_MSG_CHANNEL_EXTENDED_DATA)) {\n /* Pretend we didn't receive this */\n LIBSSH2_FREE(session, data);\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Ignoring extended data and refunding %d bytes\",\n (int) (datalen - 13));\n if(channelp->read_avail + datalen - data_head >=\n channelp->remote.window_size)\n datalen = channelp->remote.window_size -\n channelp->read_avail + data_head;\n\n channelp->remote.window_size -= datalen - data_head;\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"shrinking window size by %lu bytes to %lu, \"\n \"read_avail %lu\",\n datalen - data_head,\n channelp->remote.window_size,\n channelp->read_avail);\n\n session->packAdd_channelp = channelp;\n\n /* Adjust the window based on the block we just freed */\n libssh2_packet_add_jump_point1:\n session->packAdd_state = libssh2_NB_state_jump1;\n rc = _libssh2_channel_receive_window_adjust(session->\n packAdd_channelp,\n datalen - 13,\n 1, NULL);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n\n /*\n * REMEMBER! remote means remote as source of data,\n * NOT remote window!\n */\n if(channelp->remote.packet_size < (datalen - data_head)) {\n /*\n * Spec says we MAY ignore bytes sent beyond\n * packet_size\n */\n _libssh2_error(session,\n LIBSSH2_ERROR_CHANNEL_PACKET_EXCEEDED,\n \"Packet contains more data than we offered\"\n \" to receive, truncating\");\n datalen = channelp->remote.packet_size + data_head;\n }\n if(channelp->remote.window_size <= channelp->read_avail) {\n /*\n * Spec says we MAY ignore bytes sent beyond\n * window_size\n */\n _libssh2_error(session,\n LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED,\n \"The current receive window is full,\"\n \" data ignored\");\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n /* Reset EOF status */\n channelp->remote.eof = 0;\n\n if(channelp->read_avail + datalen - data_head >\n channelp->remote.window_size) {\n _libssh2_error(session,\n LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED,\n \"Remote sent more data than current \"\n \"window allows, truncating\");\n datalen = channelp->remote.window_size -\n channelp->read_avail + data_head;\n }\n\n /* Update the read_avail counter. The window size will be\n * updated once the data is actually read from the queue\n * from an upper layer */\n channelp->read_avail += datalen - data_head;\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"increasing read_avail by %lu bytes to %lu/%lu\",\n (long)(datalen - data_head),\n (long)channelp->read_avail,\n (long)channelp->remote.window_size);\n\n break;\n\n /*\n byte SSH_MSG_CHANNEL_EOF\n uint32 recipient channel\n */\n\n case SSH_MSG_CHANNEL_EOF:\n if(datalen >= 5)\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n if(!channelp)\n /* We may have freed already, just quietly ignore this... */\n ;\n else {\n _libssh2_debug(session,\n LIBSSH2_TRACE_CONN,\n \"EOF received for channel %lu/%lu\",\n channelp->local.id,\n channelp->remote.id);\n channelp->remote.eof = 1;\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_CHANNEL_REQUEST\n uint32 recipient channel\n string request type in US-ASCII characters only\n boolean want reply\n .... type-specific data follows\n */\n\n case SSH_MSG_CHANNEL_REQUEST:\n if(datalen >= 9) {\n uint32_t channel = _libssh2_ntohu32(data + 1);\n uint32_t len = _libssh2_ntohu32(data + 5);\n unsigned char want_reply = 1;\n\n if((len + 9) < datalen)\n want_reply = data[len + 9];\n\n _libssh2_debug(session,\n LIBSSH2_TRACE_CONN,\n \"Channel %d received request type %.*s (wr %X)\",\n channel, len, data + 9, want_reply);\n\n if(len == sizeof(\"exit-status\") - 1\n && (sizeof(\"exit-status\") - 1 + 9) <= datalen\n && !memcmp(\"exit-status\", data + 9,\n sizeof(\"exit-status\") - 1)) {\n\n /* we've got \"exit-status\" packet. Set the session value */\n if(datalen >= 20)\n channelp =\n _libssh2_channel_locate(session, channel);\n\n if(channelp && (sizeof(\"exit-status\") + 13) <= datalen) {\n channelp->exit_status =\n _libssh2_ntohu32(data + 9 + sizeof(\"exit-status\"));\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Exit status %lu received for \"\n \"channel %lu/%lu\",\n channelp->exit_status,\n channelp->local.id,\n channelp->remote.id);\n }\n\n }\n else if(len == sizeof(\"exit-signal\") - 1\n && (sizeof(\"exit-signal\") - 1 + 9) <= datalen\n && !memcmp(\"exit-signal\", data + 9,\n sizeof(\"exit-signal\") - 1)) {\n /* command terminated due to signal */\n if(datalen >= 20)\n channelp = _libssh2_channel_locate(session, channel);\n\n if(channelp && (sizeof(\"exit-signal\") + 13) <= datalen) {\n /* set signal name (without SIG prefix) */\n uint32_t namelen =\n _libssh2_ntohu32(data + 9 + sizeof(\"exit-signal\"));\n\n if(namelen <= UINT_MAX - 1) {\n channelp->exit_signal =\n LIBSSH2_ALLOC(session, namelen + 1);\n }\n else {\n channelp->exit_signal = NULL;\n }\n\n if(!channelp->exit_signal)\n rc = _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"memory for signal name\");\n else if((sizeof(\"exit-signal\") + 13 + namelen <=\n datalen)) {\n memcpy(channelp->exit_signal,\n data + 13 + sizeof(\"exit-signal\"), namelen);\n channelp->exit_signal[namelen] = '\\0';\n /* TODO: save error message and language tag */\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Exit signal %s received for \"\n \"channel %lu/%lu\",\n channelp->exit_signal,\n channelp->local.id,\n channelp->remote.id);\n }\n }\n }\n\n\n if(want_reply) {\n unsigned char packet[5];\n libssh2_packet_add_jump_point4:\n session->packAdd_state = libssh2_NB_state_jump4;\n packet[0] = SSH_MSG_CHANNEL_FAILURE;\n memcpy(&packet[1], data + 1, 4);\n rc = _libssh2_transport_send(session, packet, 5, NULL, 0);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return rc;\n\n /*\n byte SSH_MSG_CHANNEL_CLOSE\n uint32 recipient channel\n */\n\n case SSH_MSG_CHANNEL_CLOSE:\n if(datalen >= 5)\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n if(!channelp) {\n /* We may have freed already, just quietly ignore this... */\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n }\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Close received for channel %lu/%lu\",\n channelp->local.id,\n channelp->remote.id);\n\n channelp->remote.close = 1;\n channelp->remote.eof = 1;\n\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n\n /*\n byte SSH_MSG_CHANNEL_OPEN\n string \"session\"\n uint32 sender channel\n uint32 initial window size\n uint32 maximum packet size\n */\n\n case SSH_MSG_CHANNEL_OPEN:\n if(datalen < 17)\n ;\n else if((datalen >= (sizeof(\"forwarded-tcpip\") + 4)) &&\n ((sizeof(\"forwarded-tcpip\") - 1) ==\n _libssh2_ntohu32(data + 1))\n &&\n (memcmp(data + 5, \"forwarded-tcpip\",\n sizeof(\"forwarded-tcpip\") - 1) == 0)) {\n\n /* init the state struct */\n memset(&session->packAdd_Qlstn_state, 0,\n sizeof(session->packAdd_Qlstn_state));\n\n libssh2_packet_add_jump_point2:\n session->packAdd_state = libssh2_NB_state_jump2;\n rc = packet_queue_listener(session, data, datalen,\n &session->packAdd_Qlstn_state);\n }\n else if((datalen >= (sizeof(\"x11\") + 4)) &&\n ((sizeof(\"x11\") - 1) == _libssh2_ntohu32(data + 1)) &&\n (memcmp(data + 5, \"x11\", sizeof(\"x11\") - 1) == 0)) {\n\n /* init the state struct */\n memset(&session->packAdd_x11open_state, 0,\n sizeof(session->packAdd_x11open_state));\n\n libssh2_packet_add_jump_point3:\n session->packAdd_state = libssh2_NB_state_jump3;\n rc = packet_x11_open(session, data, datalen,\n &session->packAdd_x11open_state);\n }\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return rc;\n\n /*\n byte SSH_MSG_CHANNEL_WINDOW_ADJUST\n uint32 recipient channel\n uint32 bytes to add\n */\n case SSH_MSG_CHANNEL_WINDOW_ADJUST:\n if(datalen < 9)\n ;\n else {\n uint32_t bytestoadd = _libssh2_ntohu32(data + 5);\n channelp =\n _libssh2_channel_locate(session,\n _libssh2_ntohu32(data + 1));\n if(channelp) {\n channelp->local.window_size += bytestoadd;\n\n _libssh2_debug(session, LIBSSH2_TRACE_CONN,\n \"Window adjust for channel %lu/%lu, \"\n \"adding %lu bytes, new window_size=%lu\",\n channelp->local.id,\n channelp->remote.id,\n bytestoadd,\n channelp->local.window_size);\n }\n }\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n default:\n break;\n }\n\n session->packAdd_state = libssh2_NB_state_sent;\n }\n\n if(session->packAdd_state == libssh2_NB_state_sent) {\n LIBSSH2_PACKET *packetp =\n LIBSSH2_ALLOC(session, sizeof(LIBSSH2_PACKET));\n if(!packetp) {\n _libssh2_debug(session, LIBSSH2_ERROR_ALLOC,\n \"memory for packet\");\n LIBSSH2_FREE(session, data);\n session->packAdd_state = libssh2_NB_state_idle;\n return LIBSSH2_ERROR_ALLOC;\n }\n packetp->data = data;\n packetp->data_len = datalen;\n packetp->data_head = data_head;\n\n _libssh2_list_add(&session->packets, &packetp->node);\n\n session->packAdd_state = libssh2_NB_state_sent1;\n }\n\n if((msg == SSH_MSG_KEXINIT &&\n !(session->state & LIBSSH2_STATE_EXCHANGING_KEYS)) ||\n (session->packAdd_state == libssh2_NB_state_sent2)) {\n if(session->packAdd_state == libssh2_NB_state_sent1) {\n /*\n * Remote wants new keys\n * Well, it's already in the brigade,\n * let's just call back into ourselves\n */\n _libssh2_debug(session, LIBSSH2_TRACE_TRANS, \"Renegotiating Keys\");\n\n session->packAdd_state = libssh2_NB_state_sent2;\n }\n\n /*\n * The KEXINIT message has been added to the queue. The packAdd and\n * readPack states need to be reset because _libssh2_kex_exchange\n * (eventually) calls upon _libssh2_transport_read to read the rest of\n * the key exchange conversation.\n */\n session->readPack_state = libssh2_NB_state_idle;\n session->packet.total_num = 0;\n session->packAdd_state = libssh2_NB_state_idle;\n session->fullpacket_state = libssh2_NB_state_idle;\n\n memset(&session->startup_key_state, 0, sizeof(key_exchange_state_t));\n\n /*\n * If there was a key reexchange failure, let's just hope we didn't\n * send NEWKEYS yet, otherwise remote will drop us like a rock\n */\n rc = _libssh2_kex_exchange(session, 1, &session->startup_key_state);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n\n session->packAdd_state = libssh2_NB_state_idle;\n return 0;\n}", "project": "libssh2", "hash": 132242532710662252043866474126087535393, "size": 611, "commit_id": "dedcbd106f8e52d5586b0205bc7677e4c9868f9c", "message": "packet.c: improve message parsing (#402)\n\n* packet.c: improve parsing of packets\r\n\r\nfile: packet.c\r\n\r\nnotes:\r\nUse _libssh2_get_string API in SSH_MSG_DEBUG/SSH_MSG_DISCONNECT. Additional uint32 bounds check in SSH_MSG_GLOBAL_REQUEST.", "target": 0, "dataset": "other", "idx": 229853} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& logits_in = context->input(0);\n const Tensor& labels_in = context->input(1);\n\n TensorShape shape_in = logits_in.shape();\n\n BCast bcast(BCast::FromShape(logits_in.shape()),\n BCast::FromShape(labels_in.shape()));\n if (!logits_in.IsSameSize(labels_in)) {\n OP_REQUIRES(context, bcast.IsValid(),\n errors::InvalidArgument(\n \"logits and labels must be broadcastable: logits_size=\",\n logits_in.shape().DebugString(),\n \" labels_size=\", labels_in.shape().DebugString()));\n shape_in = BCast::ToShape(bcast.output_shape());\n }\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(shape_in),\n errors::InvalidArgument(\"logits and labels must be either \"\n \"2-dimensional, or broadcasted to be \"\n \"2-dimensional\"));\n\n if (std::is_same::value) {\n OP_REQUIRES(context, !OpDeterminismRequired(),\n errors::Unimplemented(\n \"The GPU implementation of SoftmaxCrossEntropyWithLogits\"\n \" that would have been executed is not deterministic.\"\n \" Note that the Python API uses an alternative,\"\n \" deterministic, GPU-accelerated path when determinism is\"\n \" enabled.\"));\n }\n\n // loss is 1-D (one per example), and size is batch_size.\n\n Tensor scratch;\n OP_REQUIRES_OK(\n context, context->allocate_temp(DataTypeToEnum::value,\n TensorShape({shape_in.dim_size(0), 1}),\n &scratch));\n\n Tensor* loss_out = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 0, TensorShape({shape_in.dim_size(0)}), &loss_out));\n Tensor* back_out = nullptr;\n // Try to reuse the logits_in buffer for the backprop output.\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {0}, 1, shape_in, &back_out));\n if (shape_in.dim_size(0) > 0) {\n functor::XentFunctor functor;\n if (logits_in.IsSameSize(labels_in)) {\n functor(context->eigen_device(), shape_in.AsEigenDSizes<2>(),\n Eigen::array{1, 1},\n Eigen::array{1, 1}, logits_in.matrix(),\n labels_in.matrix(), scratch.matrix(), loss_out->vec(),\n back_out->matrix());\n } else {\n functor(context->eigen_device(), shape_in.AsEigenDSizes<2>(),\n BCast::ToIndexArray<2>(bcast.x_bcast()),\n BCast::ToIndexArray<2>(bcast.y_bcast()),\n logits_in.template shaped(bcast.x_reshape()),\n labels_in.template shaped(bcast.y_reshape()),\n scratch.matrix(), loss_out->vec(), back_out->matrix());\n }\n }\n }", "project": "tensorflow", "hash": 231911183952942139031599044274210867918, "size": 65, "commit_id": "4d74d8a00b07441cba090a02e0dd9ed385145bf4", "message": "Fix crash in softmax-xent when some input dimensions are 1.\n\nBefore, tf.nn.softmax_cross_entropy_with_logits would fail a CHECK if one input tensor had shape (1, 1) and the other did not.\n\nIn particular, the call to ToIndexArray<2> here https://github.com/tensorflow/tensorflow/blob/1f3da84a89702d3b4f234ee83762d738caffe098/tensorflow/core/kernels/xent_op.cc#L99 would fail, since the call assumed the array had two dimensions. If both dimensions were 1, BCast would merge the two dimensions into a single dimension. Passing fewer_dims_optimization=false stops this optimization\n\nPiperOrigin-RevId: 384844496\nChange-Id: Ifb02dc74964132c3ed3f3bc98b0858dbe4e258b7", "target": 1, "dataset": "other", "idx": 195649} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& logits_in = context->input(0);\n const Tensor& labels_in = context->input(1);\n\n TensorShape shape_in = logits_in.shape();\n\n BCast bcast(BCast::FromShape(logits_in.shape()),\n BCast::FromShape(labels_in.shape()),\n /*fewer_dims_optimization=*/false);\n if (!logits_in.IsSameSize(labels_in)) {\n OP_REQUIRES(context, bcast.IsValid(),\n errors::InvalidArgument(\n \"logits and labels must be broadcastable: logits_size=\",\n logits_in.shape().DebugString(),\n \" labels_size=\", labels_in.shape().DebugString()));\n shape_in = BCast::ToShape(bcast.output_shape());\n }\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(shape_in),\n errors::InvalidArgument(\"logits and labels must be either \"\n \"2-dimensional, or broadcasted to be \"\n \"2-dimensional\"));\n\n if (std::is_same::value) {\n OP_REQUIRES(context, !OpDeterminismRequired(),\n errors::Unimplemented(\n \"The GPU implementation of SoftmaxCrossEntropyWithLogits\"\n \" that would have been executed is not deterministic.\"\n \" Note that the Python API uses an alternative,\"\n \" deterministic, GPU-accelerated path when determinism is\"\n \" enabled.\"));\n }\n\n // loss is 1-D (one per example), and size is batch_size.\n\n Tensor scratch;\n OP_REQUIRES_OK(\n context, context->allocate_temp(DataTypeToEnum::value,\n TensorShape({shape_in.dim_size(0), 1}),\n &scratch));\n\n Tensor* loss_out = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 0, TensorShape({shape_in.dim_size(0)}), &loss_out));\n Tensor* back_out = nullptr;\n // Try to reuse the logits_in buffer for the backprop output.\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {0}, 1, shape_in, &back_out));\n if (shape_in.dim_size(0) > 0) {\n functor::XentFunctor functor;\n functor(context->eigen_device(), shape_in.AsEigenDSizes<2>(),\n BCast::ToIndexArray<2>(bcast.x_bcast()),\n BCast::ToIndexArray<2>(bcast.y_bcast()),\n logits_in.template shaped(bcast.x_reshape()),\n labels_in.template shaped(bcast.y_reshape()),\n scratch.matrix(), loss_out->vec(), back_out->matrix());\n }\n }", "project": "tensorflow", "hash": 24795655124731851084034518111067821112, "size": 58, "commit_id": "4d74d8a00b07441cba090a02e0dd9ed385145bf4", "message": "Fix crash in softmax-xent when some input dimensions are 1.\n\nBefore, tf.nn.softmax_cross_entropy_with_logits would fail a CHECK if one input tensor had shape (1, 1) and the other did not.\n\nIn particular, the call to ToIndexArray<2> here https://github.com/tensorflow/tensorflow/blob/1f3da84a89702d3b4f234ee83762d738caffe098/tensorflow/core/kernels/xent_op.cc#L99 would fail, since the call assumed the array had two dimensions. If both dimensions were 1, BCast would merge the two dimensions into a single dimension. Passing fewer_dims_optimization=false stops this optimization\n\nPiperOrigin-RevId: 384844496\nChange-Id: Ifb02dc74964132c3ed3f3bc98b0858dbe4e258b7", "target": 0, "dataset": "other", "idx": 229858} {"func": " Status BuildFeatureReaders(const OpInputList& ragged_values_list,\n const OpInputList& ragged_splits_list,\n const OpInputList& sparse_indices_list,\n const OpInputList& sparse_values_list,\n const OpInputList& dense_list, int64 batch_size,\n FeatureReaders* features) {\n features->reserve(input_order_.size());\n\n int next_ragged = 0;\n int next_sparse = 0;\n int next_dense = 0;\n for (char c : input_order_) {\n if (c == 'R') {\n TF_RETURN_IF_ERROR(BuildRaggedFeatureReader(\n ragged_values_list[next_ragged], ragged_splits_list[next_ragged],\n features));\n next_ragged++;\n } else if (c == 'S') {\n TF_RETURN_IF_ERROR(BuildSparseFeatureReader(\n sparse_indices_list[next_sparse], sparse_values_list[next_sparse],\n batch_size, features));\n next_sparse++;\n } else if (c == 'D') {\n TF_RETURN_IF_ERROR(\n BuildDenseFeatureReader(dense_list[next_dense++], features));\n } else {\n return errors::InvalidArgument(\"Unexpected input_order value.\");\n }\n }\n\n return Status::OK();\n }", "project": "tensorflow", "hash": 119852077215802301992803812414131651636, "size": 32, "commit_id": "44b7f486c0143f68b56c34e2d01e146ee445134a", "message": "Fix out of bounds read in `ragged_cross_op.cc`.\n\nPiperOrigin-RevId: 369757702\nChange-Id: Ie6e5d2c21513a8d56bf41fcf35960caf76e890f9", "target": 1, "dataset": "other", "idx": 195659} {"func": " Status BuildFeatureReaders(const OpInputList& ragged_values_list,\n const OpInputList& ragged_splits_list,\n const OpInputList& sparse_indices_list,\n const OpInputList& sparse_values_list,\n const OpInputList& dense_list, int64 batch_size,\n FeatureReaders* features) {\n features->reserve(input_order_.size());\n\n int next_ragged = 0;\n int next_sparse = 0;\n int next_dense = 0;\n for (char c : input_order_) {\n if (c == 'R') {\n if (next_ragged >= ragged_values_list.size())\n return errors::InvalidArgument(\n \"input_order \\\"\", input_order_,\n \"\\\" specifies reading a ragged tensor value at index \",\n next_ragged, \" from a list of \", ragged_values_list.size(),\n \" values.\");\n if (next_ragged >= ragged_splits_list.size())\n return errors::InvalidArgument(\n \"input_order \\\"\", input_order_,\n \"\\\" specifies reading a ragged tensor split at index \",\n next_ragged, \" from a list of \", ragged_splits_list.size(),\n \" splits.\");\n TF_RETURN_IF_ERROR(BuildRaggedFeatureReader(\n ragged_values_list[next_ragged], ragged_splits_list[next_ragged],\n features));\n next_ragged++;\n } else if (c == 'S') {\n if (next_sparse >= sparse_values_list.size())\n return errors::InvalidArgument(\n \"input_order \\\"\", input_order_,\n \"\\\" specifies reading a sparse tensor value at index \",\n next_sparse, \" from a list of \", sparse_values_list.size(),\n \" values.\");\n if (next_sparse >= sparse_indices_list.size())\n return errors::InvalidArgument(\n \"input_order \\\"\", input_order_,\n \"\\\" specifies reading a sparse tensor index at index \",\n next_sparse, \" from a list of \", sparse_indices_list.size(),\n \" indices.\");\n TF_RETURN_IF_ERROR(BuildSparseFeatureReader(\n sparse_indices_list[next_sparse], sparse_values_list[next_sparse],\n batch_size, features));\n next_sparse++;\n } else if (c == 'D') {\n if (next_dense >= dense_list.size())\n return errors::InvalidArgument(\n \"input_order \\\"\", input_order_,\n \"\\\" specifies reading a dense tensor at index \", next_dense,\n \" from a list of \", dense_list.size(), \" tensors.\");\n TF_RETURN_IF_ERROR(\n BuildDenseFeatureReader(dense_list[next_dense++], features));\n } else {\n return errors::InvalidArgument(\"Unexpected input_order value.\");\n }\n }\n\n return Status::OK();\n }", "project": "tensorflow", "hash": 17914142839785054126542444128922850158, "size": 61, "commit_id": "44b7f486c0143f68b56c34e2d01e146ee445134a", "message": "Fix out of bounds read in `ragged_cross_op.cc`.\n\nPiperOrigin-RevId: 369757702\nChange-Id: Ie6e5d2c21513a8d56bf41fcf35960caf76e890f9", "target": 0, "dataset": "other", "idx": 230086} {"func": "sc_oberthur_read_file(struct sc_pkcs15_card *p15card, const char *in_path,\n\t\tunsigned char **out, size_t *out_len,\n\t\tint verify_pin)\n{\n\tstruct sc_context *ctx = p15card->card->ctx;\n\tstruct sc_card *card = p15card->card;\n\tstruct sc_file *file = NULL;\n\tstruct sc_path path;\n\tsize_t sz;\n\tint rv;\n\n\tLOG_FUNC_CALLED(ctx);\n\tif (!in_path || !out || !out_len)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Cannot read oberthur file\");\n\n\tsc_log(ctx, \"read file '%s'; verify_pin:%i\", in_path, verify_pin);\n\n\t*out = NULL;\n\t*out_len = 0;\n\n\tsc_format_path(in_path, &path);\n\trv = sc_select_file(card, &path, &file);\n\tif (rv != SC_SUCCESS) {\n\t\tsc_file_free(file);\n\t\tLOG_TEST_RET(ctx, rv, \"Cannot select oberthur file to read\");\n\t}\n\n\tif (file->ef_structure == SC_FILE_EF_TRANSPARENT)\n\t\tsz = file->size;\n\telse\n\t\tsz = (file->record_length + 2) * file->record_count;\n\n\t*out = calloc(sz, 1);\n\tif (*out == NULL) {\n\t\tsc_file_free(file);\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot read oberthur file\");\n\t}\n\n\tif (file->ef_structure == SC_FILE_EF_TRANSPARENT) {\n\t\trv = sc_read_binary(card, 0, *out, sz, 0);\n\t}\n\telse\t{\n\t\tsize_t rec;\n\t\tsize_t offs = 0;\n\t\tsize_t rec_len = file->record_length;\n\n\t\tfor (rec = 1; ; rec++) {\n\t\t\tif (rec > file->record_count) {\n\t\t\t\trv = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\trv = sc_read_record(card, rec, *out + offs + 2, rec_len, SC_RECORD_BY_REC_NR);\n\t\t\tif (rv == SC_ERROR_RECORD_NOT_FOUND) {\n\t\t\t\trv = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (rv < 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\trec_len = rv;\n\n\t\t\t*(*out + offs) = 'R';\n\t\t\t*(*out + offs + 1) = rv;\n\n\t\t\toffs += rv + 2;\n\t\t}\n\n\t\tsz = offs;\n\t}\n\n\tsc_log(ctx, \"read oberthur file result %i\", rv);\n\tif (verify_pin && rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {\n\t\tstruct sc_pkcs15_object *objs[0x10], *pin_obj = NULL;\n\t\tconst struct sc_acl_entry *acl = sc_file_get_acl_entry(file, SC_AC_OP_READ);\n\t\tint ii;\n\n\t\tif (acl == NULL) {\n\t\t\tsc_file_free(file);\n\t\t\tfree(*out);\n\t\t\t*out = NULL;\n\t\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_DATA);\n\t\t}\n\n\t\trv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, objs, 0x10);\n\t\tif (rv != SC_SUCCESS) {\n\t\t\tsc_file_free(file);\n\t\t\tfree(*out);\n\t\t\t*out = NULL;\n\t\t\tLOG_TEST_RET(ctx, rv, \"Cannot read oberthur file: get AUTH objects error\");\n\t\t}\n\n\t\tfor (ii=0; iidata;\n\t\t\tsc_log(ctx, \"compare PIN/ACL refs:%i/%i, method:%i/%i\",\n\t\t\t\t\tauth_info->attrs.pin.reference, acl->key_ref, auth_info->auth_method, acl->method);\n\t\t\tif (auth_info->attrs.pin.reference == (int)acl->key_ref && auth_info->auth_method == (unsigned)acl->method) {\n\t\t\t\tpin_obj = objs[ii];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!pin_obj || !pin_obj->content.value) {\n\t\t\trv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;\n\t\t}\n\t\telse {\n\t\t\trv = sc_pkcs15_verify_pin(p15card, pin_obj, pin_obj->content.value, pin_obj->content.len);\n\t\t\tif (!rv)\n\t\t\t\trv = sc_oberthur_read_file(p15card, in_path, out, out_len, 0);\n\t\t}\n\t}\n\n\tsc_file_free(file);\n\n\tif (rv < 0) {\n\t\tfree(*out);\n\t\t*out = NULL;\n\t\t*out_len = 0;\n\t}\n\n\t*out_len = sz;\n\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "project": "OpenSC", "hash": 327143307223640707157004214003277795771, "size": 124, "commit_id": "1db88374bb7706a115d5c3617c6f16115c33bf27", "message": "oberthur: Correctly check for return values\n\nThanks oss-fuzz\n\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=28843", "target": 1, "dataset": "other", "idx": 195660} {"func": "sc_oberthur_read_file(struct sc_pkcs15_card *p15card, const char *in_path,\n\t\tunsigned char **out, size_t *out_len,\n\t\tint verify_pin)\n{\n\tstruct sc_context *ctx = p15card->card->ctx;\n\tstruct sc_card *card = p15card->card;\n\tstruct sc_file *file = NULL;\n\tstruct sc_path path;\n\tsize_t sz;\n\tint rv;\n\n\tLOG_FUNC_CALLED(ctx);\n\tif (!in_path || !out || !out_len)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Cannot read oberthur file\");\n\n\tsc_log(ctx, \"read file '%s'; verify_pin:%i\", in_path, verify_pin);\n\n\t*out = NULL;\n\t*out_len = 0;\n\n\tsc_format_path(in_path, &path);\n\trv = sc_select_file(card, &path, &file);\n\tif (rv != SC_SUCCESS) {\n\t\tsc_file_free(file);\n\t\tLOG_TEST_RET(ctx, rv, \"Cannot select oberthur file to read\");\n\t}\n\n\tif (file->ef_structure == SC_FILE_EF_TRANSPARENT)\n\t\tsz = file->size;\n\telse\n\t\tsz = (file->record_length + 2) * file->record_count;\n\n\t*out = calloc(sz, 1);\n\tif (*out == NULL) {\n\t\tsc_file_free(file);\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot read oberthur file\");\n\t}\n\n\tif (file->ef_structure == SC_FILE_EF_TRANSPARENT) {\n\t\trv = sc_read_binary(card, 0, *out, sz, 0);\n\t}\n\telse\t{\n\t\tsize_t rec;\n\t\tsize_t offs = 0;\n\t\tsize_t rec_len = file->record_length;\n\n\t\tfor (rec = 1; ; rec++) {\n\t\t\tif (rec > file->record_count) {\n\t\t\t\trv = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\trv = sc_read_record(card, rec, *out + offs + 2, rec_len, SC_RECORD_BY_REC_NR);\n\t\t\tif (rv == SC_ERROR_RECORD_NOT_FOUND) {\n\t\t\t\trv = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (rv < 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\trec_len = rv;\n\n\t\t\t*(*out + offs) = 'R';\n\t\t\t*(*out + offs + 1) = rv;\n\n\t\t\toffs += rv + 2;\n\t\t}\n\n\t\tsz = offs;\n\t}\n\n\tsc_log(ctx, \"read oberthur file result %i\", rv);\n\tif (verify_pin && rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {\n\t\tstruct sc_pkcs15_object *objs[0x10], *pin_obj = NULL;\n\t\tconst struct sc_acl_entry *acl = sc_file_get_acl_entry(file, SC_AC_OP_READ);\n\t\tint ii, nobjs;\n\n\t\tif (acl == NULL) {\n\t\t\tsc_file_free(file);\n\t\t\tfree(*out);\n\t\t\t*out = NULL;\n\t\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_DATA);\n\t\t}\n\n\t\tnobjs = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, objs, 0x10);\n\t\tif (nobjs < 1) {\n\t\t\tsc_file_free(file);\n\t\t\tfree(*out);\n\t\t\t*out = NULL;\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_DATA_OBJECT_NOT_FOUND,\n\t\t\t\t\"Cannot read oberthur file: get AUTH objects error\");\n\t\t}\n\n\t\tfor (ii = 0; ii < nobjs; ii++) {\n\t\t\tstruct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *) objs[ii]->data;\n\t\t\tsc_log(ctx, \"compare PIN/ACL refs:%i/%i, method:%i/%i\",\n\t\t\t\tauth_info->attrs.pin.reference, acl->key_ref, auth_info->auth_method, acl->method);\n\t\t\tif (auth_info->attrs.pin.reference == (int)acl->key_ref && auth_info->auth_method == (unsigned)acl->method) {\n\t\t\t\tpin_obj = objs[ii];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!pin_obj || !pin_obj->content.value) {\n\t\t\trv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;\n\t\t}\n\t\telse {\n\t\t\trv = sc_pkcs15_verify_pin(p15card, pin_obj, pin_obj->content.value, pin_obj->content.len);\n\t\t\tif (!rv)\n\t\t\t\trv = sc_oberthur_read_file(p15card, in_path, out, out_len, 0);\n\t\t}\n\t}\n\n\tsc_file_free(file);\n\n\tif (rv < 0) {\n\t\tfree(*out);\n\t\t*out = NULL;\n\t\t*out_len = 0;\n\t}\n\n\t*out_len = sz;\n\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "project": "OpenSC", "hash": 219491834048613279001620385704271437400, "size": 125, "commit_id": "1db88374bb7706a115d5c3617c6f16115c33bf27", "message": "oberthur: Correctly check for return values\n\nThanks oss-fuzz\n\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=28843", "target": 0, "dataset": "other", "idx": 230105} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n const Tensor& input_min_tensor = ctx->input(1);\n const Tensor& input_max_tensor = ctx->input(2);\n\n int num_slices = 1;\n if (axis_ > -1) {\n num_slices = input.dim_size(axis_);\n }\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n Tensor float_output =\n need_cast_ ? tensorflow::Tensor(DT_FLOAT, input.shape()) : *output;\n if (num_slices == 1) {\n const float min_range = input_min_tensor.flat()(0);\n const float max_range = input_max_tensor.flat()(0);\n DequantizeTensor(ctx, input, min_range, max_range, &float_output);\n } else {\n OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST,\n errors::Unimplemented(\"MIN_FIRST mode is not implemented for \"\n \"Dequantize with axis != -1.\"));\n\n int64 pre_dim = 1, post_dim = 1;\n for (int i = 0; i < axis_; ++i) {\n pre_dim *= float_output.dim_size(i);\n }\n for (int i = axis_ + 1; i < float_output.dims(); ++i) {\n post_dim *= float_output.dim_size(i);\n }\n auto input_tensor = input.template bit_casted_shaped(\n {pre_dim, num_slices, post_dim});\n auto output_tensor =\n float_output.flat_inner_outer_dims(axis_ - 1);\n auto min_ranges = input_min_tensor.vec();\n auto max_ranges = input_max_tensor.vec();\n for (int i = 0; i < num_slices; ++i) {\n DequantizeSlice(ctx->eigen_device(), ctx,\n input_tensor.template chip<1>(i), min_ranges(i),\n max_ranges(i), output_tensor.template chip<1>(i));\n }\n }\n if (need_cast_) {\n S* out_ptr = output->flat().data();\n float* in_ptr = float_output.flat().data();\n for (int64 i = 0; i < float_output.NumElements(); ++i) {\n out_ptr[i] = static_cast(in_ptr[i]);\n }\n }\n }", "project": "tensorflow", "hash": 301693154738415813623979332331002049816, "size": 50, "commit_id": "5899741d0421391ca878da47907b1452f06aaf1b", "message": "Fix heap OOB read in dequantize op.\n\nAlso fixes SEGV in same op\n\nPiperOrigin-RevId: 372437896\nChange-Id: I135e94d360c2a1ce374c10f7e0fed1af603dbc02", "target": 1, "dataset": "other", "idx": 195663} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n const Tensor& input_min_tensor = ctx->input(1);\n const Tensor& input_max_tensor = ctx->input(2);\n\n int num_slices = 1;\n if (axis_ > -1) {\n num_slices = input.dim_size(axis_);\n }\n OP_REQUIRES(ctx, input_min_tensor.NumElements() == num_slices,\n errors::InvalidArgument(\n \"input_min_tensor must have as many elements as input on \"\n \"the dequantization axis (\",\n axis_, \"), got \", input_min_tensor.NumElements(),\n \", expected \", num_slices));\n OP_REQUIRES(ctx, input_max_tensor.NumElements() == num_slices,\n errors::InvalidArgument(\n \"input_max_tensor must have as many elements as input on \"\n \"the dequantization axis (\",\n axis_, \"), got \", input_max_tensor.NumElements(),\n \", expected \", num_slices));\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n Tensor float_output =\n need_cast_ ? tensorflow::Tensor(DT_FLOAT, input.shape()) : *output;\n if (num_slices == 1) {\n const float min_range = input_min_tensor.flat()(0);\n const float max_range = input_max_tensor.flat()(0);\n DequantizeTensor(ctx, input, min_range, max_range, &float_output);\n } else {\n OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST,\n errors::Unimplemented(\"MIN_FIRST mode is not implemented for \"\n \"Dequantize with axis != -1.\"));\n\n int64 pre_dim = 1, post_dim = 1;\n for (int i = 0; i < axis_; ++i) {\n pre_dim *= float_output.dim_size(i);\n }\n for (int i = axis_ + 1; i < float_output.dims(); ++i) {\n post_dim *= float_output.dim_size(i);\n }\n auto input_tensor = input.template bit_casted_shaped(\n {pre_dim, num_slices, post_dim});\n auto output_tensor =\n float_output.flat_inner_outer_dims(axis_ - 1);\n auto min_ranges = input_min_tensor.vec();\n auto max_ranges = input_max_tensor.vec();\n for (int i = 0; i < num_slices; ++i) {\n DequantizeSlice(ctx->eigen_device(), ctx,\n input_tensor.template chip<1>(i), min_ranges(i),\n max_ranges(i), output_tensor.template chip<1>(i));\n }\n }\n if (need_cast_) {\n S* out_ptr = output->flat().data();\n float* in_ptr = float_output.flat().data();\n for (int64 i = 0; i < float_output.NumElements(); ++i) {\n out_ptr[i] = static_cast(in_ptr[i]);\n }\n }\n }", "project": "tensorflow", "hash": 327725359159328114053466591557219239474, "size": 62, "commit_id": "5899741d0421391ca878da47907b1452f06aaf1b", "message": "Fix heap OOB read in dequantize op.\n\nAlso fixes SEGV in same op\n\nPiperOrigin-RevId: 372437896\nChange-Id: I135e94d360c2a1ce374c10f7e0fed1af603dbc02", "target": 0, "dataset": "other", "idx": 230153} {"func": "CallResult> JSObject::getComputedWithReceiver_RJS(\n Handle selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> receiver) {\n // Try the fast-path first: no \"index-like\" properties and the \"name\" already\n // is a valid integer index.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n // Do we have this value present in our array storage? If so, return it.\n PseudoHandle<> ourValue = createPseudoHandle(\n getOwnIndexed(selfHandle.get(), runtime, *arrayIndex));\n if (LLVM_LIKELY(!ourValue->isEmpty()))\n return ourValue;\n }\n }\n\n // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;\n\n ComputedPropertyDescriptor desc;\n\n // Locate the descriptor. propObj contains the object which may be anywhere\n // along the prototype chain.\n MutableHandle propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n\n if (!propObj)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());\n\n if (LLVM_LIKELY(\n !desc.flags.accessor && !desc.flags.hostObject &&\n !desc.flags.proxyObject))\n return createPseudoHandle(\n getComputedSlotValue(propObj.get(), runtime, desc));\n\n if (desc.flags.accessor) {\n auto *accessor = vmcast(\n getComputedSlotValue(propObj.get(), runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());\n\n // Execute the accessor on this object.\n return accessor->getter.get(runtime)->executeCall0(\n runtime->makeHandle(accessor->getter), runtime, receiver);\n } else if (desc.flags.hostObject) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n auto propRes = vmcast(selfHandle.get())->get(id);\n if (propRes == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return createPseudoHandle(*propRes);\n } else {\n assert(desc.flags.proxyObject && \"descriptor flags are impossible\");\n CallResult> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return JSProxy::getComputed(propObj, runtime, *key, receiver);\n }\n}", "project": "hermes", "hash": 177426946888629742787453579694850240993, "size": 71, "commit_id": "fe52854cdf6725c2eaa9e125995da76e6ceb27da", "message": "[CVE-2020-1911] Look up HostObject computed properties on the right object in the prototype chain.\n\nSummary:\nThe change in the hermes repository fixes the security vulnerability\nCVE-2020-1911. This vulnerability only affects applications which\nallow evaluation of uncontrolled, untrusted JavaScript code not\nshipped with the app, so React Native apps will generally not be affected.\n\nThis revision includes a test for the bug. The test is generic JSI\ncode, so it is included in the hermes and react-native repositories.\n\nChangelog: [Internal]\n\nReviewed By: tmikov\n\nDifferential Revision: D23322992\n\nfbshipit-source-id: 4e88c974afe1ad33a263f9cac03e9dc98d33649a", "target": 1, "dataset": "other", "idx": 195664} {"func": "CallResult> JSObject::getComputedWithReceiver_RJS(\n Handle selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> receiver) {\n // Try the fast-path first: no \"index-like\" properties and the \"name\" already\n // is a valid integer index.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n // Do we have this value present in our array storage? If so, return it.\n PseudoHandle<> ourValue = createPseudoHandle(\n getOwnIndexed(selfHandle.get(), runtime, *arrayIndex));\n if (LLVM_LIKELY(!ourValue->isEmpty()))\n return ourValue;\n }\n }\n\n // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;\n\n ComputedPropertyDescriptor desc;\n\n // Locate the descriptor. propObj contains the object which may be anywhere\n // along the prototype chain.\n MutableHandle propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n\n if (!propObj)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());\n\n if (LLVM_LIKELY(\n !desc.flags.accessor && !desc.flags.hostObject &&\n !desc.flags.proxyObject))\n return createPseudoHandle(\n getComputedSlotValue(propObj.get(), runtime, desc));\n\n if (desc.flags.accessor) {\n auto *accessor = vmcast(\n getComputedSlotValue(propObj.get(), runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());\n\n // Execute the accessor on this object.\n return accessor->getter.get(runtime)->executeCall0(\n runtime->makeHandle(accessor->getter), runtime, receiver);\n } else if (desc.flags.hostObject) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n auto propRes = vmcast(propObj.get())->get(id);\n if (propRes == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return createPseudoHandle(*propRes);\n } else {\n assert(desc.flags.proxyObject && \"descriptor flags are impossible\");\n CallResult> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return JSProxy::getComputed(propObj, runtime, *key, receiver);\n }\n}", "project": "hermes", "hash": 144306568268444659213632345202957132495, "size": 71, "commit_id": "fe52854cdf6725c2eaa9e125995da76e6ceb27da", "message": "[CVE-2020-1911] Look up HostObject computed properties on the right object in the prototype chain.\n\nSummary:\nThe change in the hermes repository fixes the security vulnerability\nCVE-2020-1911. This vulnerability only affects applications which\nallow evaluation of uncontrolled, untrusted JavaScript code not\nshipped with the app, so React Native apps will generally not be affected.\n\nThis revision includes a test for the bug. The test is generic JSI\ncode, so it is included in the hermes and react-native repositories.\n\nChangelog: [Internal]\n\nReviewed By: tmikov\n\nDifferential Revision: D23322992\n\nfbshipit-source-id: 4e88c974afe1ad33a263f9cac03e9dc98d33649a", "target": 0, "dataset": "other", "idx": 230182} {"func": "GF_Err abst_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tGF_AdobeBootstrapInfoBox *ptr = (GF_AdobeBootstrapInfoBox *)s;\n\tint i;\n\tu32 tmp_strsize;\n\tchar *tmp_str;\n\tBool zfound=GF_FALSE;\n\tGF_Err e;\n\n\tISOM_DECREASE_SIZE(ptr, 25)\n\tptr->bootstrapinfo_version = gf_bs_read_u32(bs);\n\tptr->profile = gf_bs_read_int(bs, 2);\n\tptr->live = gf_bs_read_int(bs, 1);\n\tptr->update = gf_bs_read_int(bs, 1);\n\tptr->reserved = gf_bs_read_int(bs, 4);\n\tptr->time_scale = gf_bs_read_u32(bs);\n\tptr->current_media_time = gf_bs_read_u64(bs);\n\tptr->smpte_time_code_offset = gf_bs_read_u64(bs);\n\n\ti=0;\n\tif (ptr->size<8) return GF_ISOM_INVALID_FILE;\n\ttmp_strsize =(u32)ptr->size;\n\ttmp_str = gf_malloc(sizeof(char)*tmp_strsize);\n\tif (!tmp_str) return GF_OUT_OF_MEM;\n\tmemset(tmp_str, 0, sizeof(char)*tmp_strsize);\n\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i]) {\n\t\t\tzfound = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\tif (!zfound)\n\t\treturn GF_ISOM_INVALID_FILE;\n\tif (i) {\n\t\tptr->movie_identifier = gf_strdup(tmp_str);\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->server_entry_count = gf_bs_read_u8(bs);\n\tfor (i=0; iserver_entry_count; i++) {\n\t\tint j=0;\n\t\tzfound = GF_FALSE;\n\t\ttmp_strsize=(u32)ptr->size;\n\t\twhile (tmp_strsize) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\t\ttmp_str[j] = gf_bs_read_u8(bs);\n\t\t\ttmp_strsize--;\n\t\t\tif (!tmp_str[j]) {\n\t\t\t\tzfound = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\t\tif (!zfound)\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\tif (j) {\n\t\t\tgf_list_insert(ptr->server_entry_table, gf_strdup(tmp_str), i);\n\t\t}\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->quality_entry_count = gf_bs_read_u8(bs);\n\tfor (i=0; iquality_entry_count; i++) {\n\t\tint j=0;\n\t\tzfound = GF_FALSE;\n\t\ttmp_strsize=(u32)ptr->size;\n\t\twhile (tmp_strsize) {\n\t\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\t\ttmp_str[j] = gf_bs_read_u8(bs);\n\t\t\ttmp_strsize--;\n\t\t\tif (!tmp_str[j]) {\n\t\t\t\tzfound = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\n\t\tif (!zfound)\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\tif (j) {\n\t\t\tgf_list_insert(ptr->quality_entry_table, gf_strdup(tmp_str), i);\n\t\t}\n\t}\n\n\ti=0;\n\ttmp_strsize=(u32)ptr->size;\n\tzfound = GF_FALSE;\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i]) {\n\t\t\tzfound = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\tif (!zfound)\n\t\treturn GF_ISOM_INVALID_FILE;\n\tif (i) {\n\t\tptr->drm_data = gf_strdup(tmp_str);\n\t}\n\n\ti=0;\n\ttmp_strsize=(u32)ptr->size;\n\tzfound = GF_FALSE;\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i]) {\n\t\t\tzfound = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\tif (!zfound)\n\t\treturn GF_ISOM_INVALID_FILE;\n\tif (i) {\n\t\tptr->meta_data = gf_strdup(tmp_str);\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->segment_run_table_count = gf_bs_read_u8(bs);\n\tfor (i=0; isegment_run_table_count; i++) {\n\t\tGF_AdobeSegmentRunTableBox *asrt = NULL;\n\t\te = gf_isom_box_parse((GF_Box **)&asrt, bs);\n\t\tif (e) {\n\t\t\tif (asrt) gf_isom_box_del((GF_Box*)asrt);\n\t\t\tgf_free(tmp_str);\n\t\t\treturn e;\n\t\t}\n\t\tgf_list_add(ptr->segment_run_table_entries, asrt);\n\t}\n\n\tISOM_DECREASE_SIZE(ptr, 1)\n\tptr->fragment_run_table_count = gf_bs_read_u8(bs);\n\tfor (i=0; ifragment_run_table_count; i++) {\n\t\tGF_AdobeFragmentRunTableBox *afrt = NULL;\n\t\te = gf_isom_box_parse((GF_Box **)&afrt, bs);\n\t\tif (e) {\n\t\t\tif (afrt) gf_isom_box_del((GF_Box*)afrt);\n\t\t\tgf_free(tmp_str);\n\t\t\treturn e;\n\t\t}\n\t\tgf_list_add(ptr->fragment_run_table_entries, afrt);\n\t}\n\n\tgf_free(tmp_str);\n\n\treturn GF_OK;\n}", "project": "gpac", "hash": 65800177890771330818160234491326522750, "size": 157, "commit_id": "e74be5976a6fee059c638050a237893f7e9a3b23", "message": "fixed #1753", "target": 1, "dataset": "other", "idx": 195679} {"func": "GF_Err abst_box_read(GF_Box *s, GF_BitStream *bs)\n{\n\tGF_AdobeBootstrapInfoBox *ptr = (GF_AdobeBootstrapInfoBox *)s;\n\tint i;\n\tu32 tmp_strsize;\n\tchar *tmp_str;\n\tBool zfound=GF_FALSE;\n\tGF_Err e = GF_OK;\n\n\tISOM_DECREASE_SIZE(ptr, 25)\n\tptr->bootstrapinfo_version = gf_bs_read_u32(bs);\n\tptr->profile = gf_bs_read_int(bs, 2);\n\tptr->live = gf_bs_read_int(bs, 1);\n\tptr->update = gf_bs_read_int(bs, 1);\n\tptr->reserved = gf_bs_read_int(bs, 4);\n\tptr->time_scale = gf_bs_read_u32(bs);\n\tptr->current_media_time = gf_bs_read_u64(bs);\n\tptr->smpte_time_code_offset = gf_bs_read_u64(bs);\n\n\ti=0;\n\tif (ptr->size<8) return GF_ISOM_INVALID_FILE;\n\ttmp_strsize =(u32)ptr->size;\n\ttmp_str = gf_malloc(sizeof(char)*tmp_strsize);\n\tif (!tmp_str) return GF_OUT_OF_MEM;\n\tmemset(tmp_str, 0, sizeof(char)*tmp_strsize);\n\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i]) {\n\t\t\tzfound = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\tif (!zfound) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\tif (i) {\n\t\tptr->movie_identifier = gf_strdup(tmp_str);\n\t}\n\n\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\tptr->server_entry_count = gf_bs_read_u8(bs);\n\tfor (i=0; iserver_entry_count; i++) {\n\t\tint j=0;\n\t\tzfound = GF_FALSE;\n\t\ttmp_strsize=(u32)ptr->size;\n\t\twhile (tmp_strsize) {\n\t\t\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\t\t\ttmp_str[j] = gf_bs_read_u8(bs);\n\t\t\ttmp_strsize--;\n\t\t\tif (!tmp_str[j]) {\n\t\t\t\tzfound = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\t\tif (!zfound) {\n\t\t\te = GF_ISOM_INVALID_FILE;\n\t\t\tgoto exit;\n\t\t}\n\t\tif (j) {\n\t\t\tgf_list_insert(ptr->server_entry_table, gf_strdup(tmp_str), i);\n\t\t}\n\t}\n\tif (ptr->server_entry_count != gf_list_count(ptr->server_entry_table)) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\n\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\tptr->quality_entry_count = gf_bs_read_u8(bs);\n\tfor (i=0; iquality_entry_count; i++) {\n\t\tint j=0;\n\t\tzfound = GF_FALSE;\n\t\ttmp_strsize=(u32)ptr->size;\n\t\twhile (tmp_strsize) {\n\t\t\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\t\t\ttmp_str[j] = gf_bs_read_u8(bs);\n\t\t\ttmp_strsize--;\n\t\t\tif (!tmp_str[j]) {\n\t\t\t\tzfound = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\n\t\tif (!zfound) {\n\t\t\te = GF_ISOM_INVALID_FILE;\n\t\t\tgoto exit;\n\t\t}\n\t\tif (j) {\n\t\t\tgf_list_insert(ptr->quality_entry_table, gf_strdup(tmp_str), i);\n\t\t}\n\t}\n\tif (ptr->quality_entry_count != gf_list_count(ptr->quality_entry_table)) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\n\ti=0;\n\ttmp_strsize=(u32)ptr->size;\n\tzfound = GF_FALSE;\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i]) {\n\t\t\tzfound = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\tif (!zfound) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\n\tif (i) {\n\t\tptr->drm_data = gf_strdup(tmp_str);\n\t}\n\n\ti=0;\n\ttmp_strsize=(u32)ptr->size;\n\tzfound = GF_FALSE;\n\twhile (tmp_strsize) {\n\t\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\t\ttmp_str[i] = gf_bs_read_u8(bs);\n\t\ttmp_strsize--;\n\t\tif (!tmp_str[i]) {\n\t\t\tzfound = GF_TRUE;\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\tif (!zfound) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\n\tif (i) {\n\t\tptr->meta_data = gf_strdup(tmp_str);\n\t}\n\n\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\tptr->segment_run_table_count = gf_bs_read_u8(bs);\n\tfor (i=0; isegment_run_table_count; i++) {\n\t\tGF_AdobeSegmentRunTableBox *asrt = NULL;\n\t\te = gf_isom_box_parse((GF_Box **)&asrt, bs);\n\t\tif (e) {\n\t\t\tif (asrt) gf_isom_box_del((GF_Box*)asrt);\n\t\t\tgoto exit;\n\t\t}\n\t\tgf_list_add(ptr->segment_run_table_entries, asrt);\n\t}\n\tif (ptr->segment_run_table_count != gf_list_count(ptr->segment_run_table_entries)) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\n\tISOM_DECREASE_SIZE_GOTO_EXIT(ptr, 1)\n\tptr->fragment_run_table_count = gf_bs_read_u8(bs);\n\tfor (i=0; ifragment_run_table_count; i++) {\n\t\tGF_AdobeFragmentRunTableBox *afrt = NULL;\n\t\te = gf_isom_box_parse((GF_Box **)&afrt, bs);\n\t\tif (e) {\n\t\t\tif (afrt) gf_isom_box_del((GF_Box*)afrt);\n\t\t\tgoto exit;\n\t\t}\n\t\tgf_list_add(ptr->fragment_run_table_entries, afrt);\n\t}\n\tif (ptr->fragment_run_table_count != gf_list_count(ptr->fragment_run_table_entries)) {\n\t\te = GF_ISOM_INVALID_FILE;\n\t\tgoto exit;\n\t}\n\nexit:\n\tgf_free(tmp_str);\n\treturn e;\n}", "project": "gpac", "hash": 263041082295436052908187100475540340486, "size": 183, "commit_id": "e74be5976a6fee059c638050a237893f7e9a3b23", "message": "fixed #1753", "target": 0, "dataset": "other", "idx": 230580} {"func": "void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){\n int i = 0;\n int iTbl = 0;\n while( i<128 ){\n int bToken = aArray[ aFts5UnicodeData[iTbl] & 0x1F ];\n int n = (aFts5UnicodeData[iTbl] >> 5) + i;\n for(; i<128 && i> 5) + i;\n for(; i<128 && i(sizeof(int32_t));\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kLocalLifetimeAllocHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_create_wait_queue\",\n 2);\n int32_t *queue = reinterpret_cast(output.next());\n int klinux_errno = output.next();\n if (queue == nullptr) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n }\n enc_untrusted_disable_waiting(queue);\n return queue;\n}", "project": "asylo", "hash": 37573905407616895373101266094510917833, "size": 16, "commit_id": "a37fb6a0e7daf30134dbbf357c9a518a1026aa02", "message": "Check untrusted queue is in outside enclave\n\nPiperOrigin-RevId: 333370935\nChange-Id: Ic3f15d5db1302d95c7cb199b44172474fecb81ca", "target": 1, "dataset": "other", "idx": 195697} {"func": "int32_t *enc_untrusted_create_wait_queue() {\n MessageWriter input;\n MessageReader output;\n input.Push(sizeof(int32_t));\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kLocalLifetimeAllocHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_create_wait_queue\",\n 2);\n int32_t *queue = reinterpret_cast(output.next());\n if (!TrustedPrimitives::IsOutsideEnclave(queue, sizeof(int32_t))) {\n TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_create_wait_queue: queue should be in untrusted memory\");\n }\n int klinux_errno = output.next();\n if (queue == nullptr) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n }\n enc_untrusted_disable_waiting(queue);\n return queue;\n}", "project": "asylo", "hash": 48703534045389445580807437477821613621, "size": 20, "commit_id": "a37fb6a0e7daf30134dbbf357c9a518a1026aa02", "message": "Check untrusted queue is in outside enclave\n\nPiperOrigin-RevId: 333370935\nChange-Id: Ic3f15d5db1302d95c7cb199b44172474fecb81ca", "target": 0, "dataset": "other", "idx": 231074} {"func": "bool CClient::OnTextMessage(CTextMessage& Message) {\n CString sTargets = Message.GetTarget();\n\n VCString vTargets;\n sTargets.Split(\",\", vTargets, false);\n\n for (CString& sTarget : vTargets) {\n Message.SetTarget(sTarget);\n if (m_pNetwork) {\n // May be nullptr.\n Message.SetChan(m_pNetwork->FindChan(sTarget));\n }\n\n if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {\n if (sTarget.Equals(\"status\")) {\n CString sMsg = Message.GetText();\n UserCommand(sMsg);\n } else {\n CALLMOD(sTarget, this, m_pUser, m_pNetwork,\n OnModCommand(Message.GetText()));\n }\n continue;\n }\n\n bool bContinue = false;\n NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this,\n &bContinue);\n if (bContinue) continue;\n\n if (!GetIRCSock()) {\n // Some lagmeters do a PRIVMSG to their own nick, ignore those.\n if (!sTarget.Equals(m_sNick))\n PutStatus(\n t_f(\"Your message to {1} got lost, you are not connected \"\n \"to IRC!\")(Message.GetTarget()));\n continue;\n }\n\n if (m_pNetwork) {\n AddBuffer(Message);\n EchoMessage(Message);\n PutIRC(Message.ToString(CMessage::ExcludePrefix |\n CMessage::ExcludeTags));\n }\n }\n\n return true;\n}", "project": "znc", "hash": 89511507100186789300014022416773480646, "size": 48, "commit_id": "d229761821da38d984a9e4098ad96842490dc001", "message": "Fix echo-message for *status\n\nClose #1705", "target": 1, "dataset": "other", "idx": 195717} {"func": "bool CClient::OnTextMessage(CTextMessage& Message) {\n CString sTargets = Message.GetTarget();\n\n VCString vTargets;\n sTargets.Split(\",\", vTargets, false);\n\n for (CString& sTarget : vTargets) {\n Message.SetTarget(sTarget);\n if (m_pNetwork) {\n // May be nullptr.\n Message.SetChan(m_pNetwork->FindChan(sTarget));\n }\n\n if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) {\n EchoMessage(Message);\n\n if (sTarget.Equals(\"status\")) {\n CString sMsg = Message.GetText();\n UserCommand(sMsg);\n } else {\n CALLMOD(sTarget, this, m_pUser, m_pNetwork,\n OnModCommand(Message.GetText()));\n }\n continue;\n }\n\n bool bContinue = false;\n NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this,\n &bContinue);\n if (bContinue) continue;\n\n if (!GetIRCSock()) {\n // Some lagmeters do a PRIVMSG to their own nick, ignore those.\n if (!sTarget.Equals(m_sNick))\n PutStatus(\n t_f(\"Your message to {1} got lost, you are not connected \"\n \"to IRC!\")(Message.GetTarget()));\n continue;\n }\n\n if (m_pNetwork) {\n AddBuffer(Message);\n EchoMessage(Message);\n PutIRC(Message.ToString(CMessage::ExcludePrefix |\n CMessage::ExcludeTags));\n }\n }\n\n return true;\n}", "project": "znc", "hash": 224787576817106767054259735051627673489, "size": 50, "commit_id": "d229761821da38d984a9e4098ad96842490dc001", "message": "Fix echo-message for *status\n\nClose #1705", "target": 0, "dataset": "other", "idx": 231582} {"func": "GF_Err Media_CheckDataEntry(GF_MediaBox *mdia, u32 dataEntryIndex)\n{\n\n\tGF_DataEntryURLBox *entry;\n\tGF_DataMap *map;\n\tGF_Err e;\n\tif (!mdia || !dataEntryIndex || dataEntryIndex > gf_list_count(mdia->information->dataInformation->dref->child_boxes)) return GF_BAD_PARAM;\n\n\tentry = (GF_DataEntryURLBox*)gf_list_get(mdia->information->dataInformation->dref->child_boxes, dataEntryIndex - 1);\n\tif (!entry) return GF_ISOM_INVALID_FILE;\n\tif (entry->flags == 1) return GF_OK;\n\n\t//ok, not self contained, let's go for it...\n\t//we don't know what's a URN yet\n\tif (entry->type == GF_ISOM_BOX_TYPE_URN) return GF_NOT_SUPPORTED;\n\tif (mdia->mediaTrack->moov->mov->openMode == GF_ISOM_OPEN_WRITE) {\n\t\te = gf_isom_datamap_new(entry->location, NULL, GF_ISOM_DATA_MAP_READ, &map);\n\t} else {\n\t\te = gf_isom_datamap_new(entry->location, mdia->mediaTrack->moov->mov->fileName, GF_ISOM_DATA_MAP_READ, &map);\n\t}\n\tif (e) return e;\n\tgf_isom_datamap_del(map);\n\treturn GF_OK;\n}", "project": "gpac", "hash": 163064601320028078105851138396564236942, "size": 24, "commit_id": "328def7d3b93847d64ecb6e9e0399684e57c3eca", "message": "fixed #1766 (fuzz)", "target": 1, "dataset": "other", "idx": 195719} {"func": "GF_Err Media_CheckDataEntry(GF_MediaBox *mdia, u32 dataEntryIndex)\n{\n\tGF_DataEntryURLBox *entry;\n\tGF_DataMap *map;\n\tGF_Err e;\n\tif (!mdia || !dataEntryIndex || dataEntryIndex > gf_list_count(mdia->information->dataInformation->dref->child_boxes)) return GF_BAD_PARAM;\n\n\tentry = (GF_DataEntryURLBox*)gf_list_get(mdia->information->dataInformation->dref->child_boxes, dataEntryIndex - 1);\n\tif (!entry) return GF_ISOM_INVALID_FILE;\n\tif (entry->flags == 1) return GF_OK;\n\n\t//ok, not self contained, let's go for it...\n\t//we only support alias and URL boxes\n\tif ((entry->type != GF_ISOM_BOX_TYPE_URL) && (entry->type != GF_QT_BOX_TYPE_ALIS) )\n\t\treturn GF_NOT_SUPPORTED;\n\n\tif (mdia->mediaTrack->moov->mov->openMode == GF_ISOM_OPEN_WRITE) {\n\t\te = gf_isom_datamap_new(entry->location, NULL, GF_ISOM_DATA_MAP_READ, &map);\n\t} else {\n\t\te = gf_isom_datamap_new(entry->location, mdia->mediaTrack->moov->mov->fileName, GF_ISOM_DATA_MAP_READ, &map);\n\t}\n\tif (e) return e;\n\tgf_isom_datamap_del(map);\n\treturn GF_OK;\n}", "project": "gpac", "hash": 334934742632849937568706482655465507791, "size": 25, "commit_id": "328def7d3b93847d64ecb6e9e0399684e57c3eca", "message": "fixed #1766 (fuzz)", "target": 0, "dataset": "other", "idx": 231612} {"func": "PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n MessageWriter *input,\n MessageReader *output) {\n int ret;\n\n UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();\n\n SgxParams *const sgx_params =\n reinterpret_cast(untrusted_cache->Malloc(sizeof(SgxParams)));\n if (!TrustedPrimitives::IsOutsideEnclave(sgx_params, sizeof(SgxParams))) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param should be in untrusted memory\");\n }\n Cleanup clean_up(\n [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });\n sgx_params->input_size = 0;\n sgx_params->input = nullptr;\n if (input) {\n sgx_params->input_size = input->MessageSize();\n if (sgx_params->input_size > 0) {\n // Allocate and copy data to |input_buffer|.\n sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);\n const void *input_pointer = sgx_params->input;\n uint64_t input_size = sgx_params->input_size;\n if (!TrustedPrimitives::IsOutsideEnclave(input_pointer, input_size)) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param input should be in untrusted memory\");\n }\n input->Serialize(const_cast(input_pointer));\n }\n }\n sgx_params->output_size = 0;\n sgx_params->output = nullptr;\n CHECK_OCALL(\n ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n if (sgx_params->input) {\n untrusted_cache->Free(const_cast(sgx_params->input));\n }\n if (!TrustedPrimitives::IsOutsideEnclave(sgx_params->output,\n sgx_params->output_size)) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param output should be in untrusted memory\");\n }\n if (sgx_params->output) {\n // For the results obtained in |output_buffer|, copy them to |output|\n // before freeing the buffer.\n output->Deserialize(sgx_params->output, sgx_params->output_size);\n TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n }\n return PrimitiveStatus::OkStatus();\n}", "project": "asylo", "hash": 257682981429665497503990072998187396956, "size": 51, "commit_id": "53ed5d8fd8118ced1466e509606dd2f473707a5c", "message": "Store untrusted output pointer in enclave\n\nValidate the pointer after it's stored in enclave to avoid unexpected\nmodifications after it's validated.\n\nPiperOrigin-RevId: 365648810\nChange-Id: I3079128040c142e86bab8255b07d03562a6fcb61", "target": 1, "dataset": "other", "idx": 195725} {"func": "PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n MessageWriter *input,\n MessageReader *output) {\n int ret;\n\n UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();\n\n SgxParams *const sgx_params =\n reinterpret_cast(untrusted_cache->Malloc(sizeof(SgxParams)));\n if (!TrustedPrimitives::IsOutsideEnclave(sgx_params, sizeof(SgxParams))) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param should be in untrusted memory\");\n }\n Cleanup clean_up(\n [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });\n sgx_params->input_size = 0;\n sgx_params->input = nullptr;\n if (input) {\n sgx_params->input_size = input->MessageSize();\n if (sgx_params->input_size > 0) {\n // Allocate and copy data to |input_buffer|.\n sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);\n const void *input_pointer = sgx_params->input;\n uint64_t input_size = sgx_params->input_size;\n if (!TrustedPrimitives::IsOutsideEnclave(input_pointer, input_size)) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param input should be in untrusted memory\");\n }\n input->Serialize(const_cast(input_pointer));\n }\n }\n sgx_params->output_size = 0;\n sgx_params->output = nullptr;\n CHECK_OCALL(\n ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n if (sgx_params->input) {\n untrusted_cache->Free(const_cast(sgx_params->input));\n }\n const void *output_pointer = sgx_params->output;\n uint64_t output_size = sgx_params->output_size;\n if (!TrustedPrimitives::IsOutsideEnclave(output_pointer, output_size)) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param output should be in untrusted memory\");\n }\n if (sgx_params->output) {\n // For the results obtained in |output_buffer|, copy them to |output|\n // before freeing the buffer.\n output->Deserialize(output_pointer, output_size);\n TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n }\n return PrimitiveStatus::OkStatus();\n}", "project": "asylo", "hash": 20214115828053448204164555554097192268, "size": 52, "commit_id": "53ed5d8fd8118ced1466e509606dd2f473707a5c", "message": "Store untrusted output pointer in enclave\n\nValidate the pointer after it's stored in enclave to avoid unexpected\nmodifications after it's validated.\n\nPiperOrigin-RevId: 365648810\nChange-Id: I3079128040c142e86bab8255b07d03562a6fcb61", "target": 0, "dataset": "other", "idx": 232064} {"func": "R_API void r_core_fini(RCore *c) {\n\tif (!c) {\n\t\treturn;\n\t}\n\tr_core_task_break_all (&c->tasks);\n\tr_core_task_join (&c->tasks, NULL, -1);\n\tr_core_wait (c);\n\t/* TODO: it leaks as shit */\n\t//update_sdb (c);\n\t// avoid double free\n\tr_list_free (c->ropchain);\n\tr_event_free (c->ev);\n\tfree (c->cmdlog);\n\tfree (c->lastsearch);\n\tR_FREE (c->cons->pager);\n\tfree (c->cmdqueue);\n\tfree (c->lastcmd);\n\tfree (c->stkcmd);\n\tr_list_free (c->visual.tabs);\n\tfree (c->block);\n\tr_core_autocomplete_free (c->autocomplete);\n\n\tr_list_free (c->gadgets);\n\tr_list_free (c->undos);\n\tr_num_free (c->num);\n\t// TODO: sync or not? sdb_sync (c->sdb);\n\t// TODO: sync all dbs?\n\t//r_core_file_free (c->file);\n\t//c->file = NULL;\n\tfree (c->table_query);\n\tr_list_free (c->files);\n\tr_list_free (c->watchers);\n\tr_list_free (c->scriptstack);\n\tr_core_task_scheduler_fini (&c->tasks);\n\tc->rcmd = r_cmd_free (c->rcmd);\n\tr_list_free (c->cmd_descriptors);\n\tc->anal = r_anal_free (c->anal);\n\tr_asm_free (c->assembler);\n\tc->assembler = NULL;\n\tc->print = r_print_free (c->print);\n\tc->bin = (r_bin_free (c->bin), NULL);\n\tc->lang = (r_lang_free (c->lang), NULL);\n\tc->dbg = (r_debug_free (c->dbg), NULL);\n\tr_io_free (c->io);\n\tr_config_free (c->config);\n\t/* after r_config_free, the value of I.teefile is trashed */\n\t/* rconfig doesnt knows how to deinitialize vars, so we\n\tshould probably need to add a r_config_free_payload callback */\n\tr_cons_free ();\n\tr_cons_singleton ()->teefile = NULL; // HACK\n\tr_search_free (c->search);\n\tr_flag_free (c->flags);\n\tr_fs_free (c->fs);\n\tr_egg_free (c->egg);\n\tr_lib_free (c->lib);\n\tr_buf_free (c->yank_buf);\n\tr_agraph_free (c->graph);\n\tfree (c->asmqjmps);\n\tsdb_free (c->sdb);\n\tr_core_log_free (c->log);\n\tr_parse_free (c->parser);\n\tfree (c->times);\n}", "project": "radare2", "hash": 307897061826018138760096537879143991047, "size": 63, "commit_id": "cb8b683758edddae2d2f62e8e63a738c39f92683", "message": "Fix #16303 - c->table_query double free (#16318)", "target": 1, "dataset": "other", "idx": 195727} {"func": "R_API void r_core_fini(RCore *c) {\n\tif (!c) {\n\t\treturn;\n\t}\n\tr_core_task_break_all (&c->tasks);\n\tr_core_task_join (&c->tasks, NULL, -1);\n\tr_core_wait (c);\n\t/* TODO: it leaks as shit */\n\t//update_sdb (c);\n\t// avoid double free\n\tr_list_free (c->ropchain);\n\tr_event_free (c->ev);\n\tfree (c->cmdlog);\n\tfree (c->lastsearch);\n\tR_FREE (c->cons->pager);\n\tfree (c->cmdqueue);\n\tfree (c->lastcmd);\n\tfree (c->stkcmd);\n\tr_list_free (c->visual.tabs);\n\tfree (c->block);\n\tr_core_autocomplete_free (c->autocomplete);\n\n\tr_list_free (c->gadgets);\n\tr_list_free (c->undos);\n\tr_num_free (c->num);\n\t// TODO: sync or not? sdb_sync (c->sdb);\n\t// TODO: sync all dbs?\n\t//r_core_file_free (c->file);\n\t//c->file = NULL;\n\tR_FREE (c->table_query);\n\tr_list_free (c->files);\n\tr_list_free (c->watchers);\n\tr_list_free (c->scriptstack);\n\tr_core_task_scheduler_fini (&c->tasks);\n\tc->rcmd = r_cmd_free (c->rcmd);\n\tr_list_free (c->cmd_descriptors);\n\tc->anal = r_anal_free (c->anal);\n\tr_asm_free (c->assembler);\n\tc->assembler = NULL;\n\tc->print = r_print_free (c->print);\n\tc->bin = (r_bin_free (c->bin), NULL);\n\tc->lang = (r_lang_free (c->lang), NULL);\n\tc->dbg = (r_debug_free (c->dbg), NULL);\n\tr_io_free (c->io);\n\tr_config_free (c->config);\n\t/* after r_config_free, the value of I.teefile is trashed */\n\t/* rconfig doesnt knows how to deinitialize vars, so we\n\tshould probably need to add a r_config_free_payload callback */\n\tr_cons_free ();\n\tr_cons_singleton ()->teefile = NULL; // HACK\n\tr_search_free (c->search);\n\tr_flag_free (c->flags);\n\tr_fs_free (c->fs);\n\tr_egg_free (c->egg);\n\tr_lib_free (c->lib);\n\tr_buf_free (c->yank_buf);\n\tr_agraph_free (c->graph);\n\tfree (c->asmqjmps);\n\tsdb_free (c->sdb);\n\tr_core_log_free (c->log);\n\tr_parse_free (c->parser);\n\tfree (c->times);\n}", "project": "radare2", "hash": 120305734667673744603788082192514109384, "size": 63, "commit_id": "cb8b683758edddae2d2f62e8e63a738c39f92683", "message": "Fix #16303 - c->table_query double free (#16318)", "target": 0, "dataset": "other", "idx": 232153} {"func": "inline void ComputeInterpolationWeights(\n const int64 out_size, const int64 in_size, const float scale,\n const int resolution, InterpolationCache* interpolation) {\n const Scaler scaler;\n interpolation->lower.resize(out_size + 1);\n interpolation->upper.resize(out_size + 1);\n interpolation->lerp.resize(out_size + 1);\n interpolation->ilerp.resize(out_size + 1);\n\n interpolation->lower[out_size] = 0;\n interpolation->upper[out_size] = 0;\n for (int64 i = out_size - 1; i >= 0; --i) {\n const float in = scaler(i, scale);\n const float in_f = std::floor(in);\n interpolation->lower[i] =\n std::max(static_cast(in_f), static_cast(0));\n interpolation->upper[i] =\n std::min(static_cast(std::ceil(in)), in_size - 1);\n interpolation->lerp[i] = in - in_f;\n interpolation->ilerp[i] =\n static_cast((in - in_f) * (1 << resolution));\n }\n}", "project": "tensorflow", "hash": 270585959924700897209636611295822247365, "size": 23, "commit_id": "f851613f8f0fb0c838d160ced13c134f778e3ce7", "message": "Fix heap buffer overflow caused by rounding.\n\nThis was hard to fix. Due to the way we compute the pixels that influence an output pixel in resized images, for certain input configuration we might have issued a read to a pixel that is outside of boundary of the original image. This is because of floating errors that affected truncation results.\n\nPiperOrigin-RevId: 369757871\nChange-Id: If89425fff930983829a2168203c11858883eebc9", "target": 1, "dataset": "other", "idx": 195747} {"func": "inline void ComputeInterpolationWeights(\n const int64 out_size, const int64 in_size, const float scale,\n const int resolution, InterpolationCache* interpolation) {\n const Scaler scaler;\n interpolation->lower.resize(out_size + 1);\n interpolation->upper.resize(out_size + 1);\n interpolation->lerp.resize(out_size + 1);\n interpolation->ilerp.resize(out_size + 1);\n\n interpolation->lower[out_size] = 0;\n interpolation->upper[out_size] = 0;\n for (int64 i = out_size - 1; i >= 0; --i) {\n const float in = scaler(i, scale);\n const float in_f = std::floor(in);\n interpolation->lower[i] =\n std::max(static_cast(in_f), static_cast(0));\n interpolation->upper[i] =\n std::min(static_cast(std::ceil(in)), in_size - 1);\n interpolation->lower[i] =\n std::min(interpolation->lower[i], interpolation->upper[i]);\n interpolation->lerp[i] = in - in_f;\n interpolation->ilerp[i] =\n static_cast((in - in_f) * (1 << resolution));\n }\n}", "project": "tensorflow", "hash": 247234673289123575753752195039643028677, "size": 25, "commit_id": "f851613f8f0fb0c838d160ced13c134f778e3ce7", "message": "Fix heap buffer overflow caused by rounding.\n\nThis was hard to fix. Due to the way we compute the pixels that influence an output pixel in resized images, for certain input configuration we might have issued a read to a pixel that is outside of boundary of the original image. This is because of floating errors that affected truncation results.\n\nPiperOrigin-RevId: 369757871\nChange-Id: If89425fff930983829a2168203c11858883eebc9", "target": 0, "dataset": "other", "idx": 232376} {"func": "static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n\t\t\t\t struct bpf_insn *insn,\n\t\t\t\t struct bpf_reg_state *dst_reg,\n\t\t\t\t struct bpf_reg_state src_reg)\n{\n\tstruct bpf_reg_state *regs = cur_regs(env);\n\tu8 opcode = BPF_OP(insn->code);\n\tbool src_known, dst_known;\n\ts64 smin_val, smax_val;\n\tu64 umin_val, umax_val;\n\tu64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;\n\tu32 dst = insn->dst_reg;\n\tint ret;\n\n\tif (insn_bitness == 32) {\n\t\t/* Relevant for 32-bit RSH: Information can propagate towards\n\t\t * LSB, so it isn't sufficient to only truncate the output to\n\t\t * 32 bits.\n\t\t */\n\t\tcoerce_reg_to_size(dst_reg, 4);\n\t\tcoerce_reg_to_size(&src_reg, 4);\n\t}\n\n\tsmin_val = src_reg.smin_value;\n\tsmax_val = src_reg.smax_value;\n\tumin_val = src_reg.umin_value;\n\tumax_val = src_reg.umax_value;\n\tsrc_known = tnum_is_const(src_reg.var_off);\n\tdst_known = tnum_is_const(dst_reg->var_off);\n\n\tif ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||\n\t smin_val > smax_val || umin_val > umax_val) {\n\t\t/* Taint dst register if offset had invalid bounds derived from\n\t\t * e.g. dead branches.\n\t\t */\n\t\t__mark_reg_unknown(env, dst_reg);\n\t\treturn 0;\n\t}\n\n\tif (!src_known &&\n\t opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {\n\t\t__mark_reg_unknown(env, dst_reg);\n\t\treturn 0;\n\t}\n\n\tswitch (opcode) {\n\tcase BPF_ADD:\n\t\tret = sanitize_val_alu(env, insn);\n\t\tif (ret < 0) {\n\t\t\tverbose(env, \"R%d tried to add from different pointers or scalars\\n\", dst);\n\t\t\treturn ret;\n\t\t}\n\t\tscalar_min_max_add(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_SUB:\n\t\tret = sanitize_val_alu(env, insn);\n\t\tif (ret < 0) {\n\t\t\tverbose(env, \"R%d tried to sub from different pointers or scalars\\n\", dst);\n\t\t\treturn ret;\n\t\t}\n\t\tscalar_min_max_sub(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_MUL:\n\t\tscalar_min_max_mul(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_AND:\n\t\tif (src_known && dst_known) {\n\t\t\t__mark_reg_known(dst_reg, dst_reg->var_off.value &\n\t\t\t\t\t\t src_reg.var_off.value);\n\t\t\tbreak;\n\t\t}\n\t\tscalar_min_max_and(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_OR:\n\t\tif (src_known && dst_known) {\n\t\t\t__mark_reg_known(dst_reg, dst_reg->var_off.value |\n\t\t\t\t\t\t src_reg.var_off.value);\n\t\t\tbreak;\n\t\t}\n\t\tscalar_min_max_or(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_LSH:\n\t\tif (umax_val >= insn_bitness) {\n\t\t\t/* Shifts greater than 31 or 63 are undefined.\n\t\t\t * This includes shifts by a negative number.\n\t\t\t */\n\t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n\t\t\tbreak;\n\t\t}\n\t\tscalar_min_max_lsh(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_RSH:\n\t\tif (umax_val >= insn_bitness) {\n\t\t\t/* Shifts greater than 31 or 63 are undefined.\n\t\t\t * This includes shifts by a negative number.\n\t\t\t */\n\t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n\t\t\tbreak;\n\t\t}\n\t\tscalar_min_max_rsh(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_ARSH:\n\t\tif (umax_val >= insn_bitness) {\n\t\t\t/* Shifts greater than 31 or 63 are undefined.\n\t\t\t * This includes shifts by a negative number.\n\t\t\t */\n\t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n\t\t\tbreak;\n\t\t}\n\t\tscalar_min_max_arsh(dst_reg, &src_reg, insn_bitness);\n\t\tbreak;\n\tdefault:\n\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n\t\tbreak;\n\t}\n\n\tif (BPF_CLASS(insn->code) != BPF_ALU64) {\n\t\t/* 32-bit ALU ops are (32,32)->32 */\n\t\tcoerce_reg_to_size(dst_reg, 4);\n\t}\n\n\t__reg_deduce_bounds(dst_reg);\n\t__reg_bound_offset(dst_reg);\n\treturn 0;\n}", "project": "linux", "hash": 256853574586537399963383949255567066385, "size": 125, "commit_id": "294f2fc6da27620a506e6c050241655459ccd6bd", "message": "bpf: Verifer, adjust_scalar_min_max_vals to always call update_reg_bounds()\n\nCurrently, for all op verification we call __red_deduce_bounds() and\n__red_bound_offset() but we only call __update_reg_bounds() in bitwise\nops. However, we could benefit from calling __update_reg_bounds() in\nBPF_ADD, BPF_SUB, and BPF_MUL cases as well.\n\nFor example, a register with state 'R1_w=invP0' when we subtract from\nit,\n\n w1 -= 2\n\nBefore coerce we will now have an smin_value=S64_MIN, smax_value=U64_MAX\nand unsigned bounds umin_value=0, umax_value=U64_MAX. These will then\nbe clamped to S32_MIN, U32_MAX values by coerce in the case of alu32 op\nas done in above example. However tnum will be a constant because the\nALU op is done on a constant.\n\nWithout update_reg_bounds() we have a scenario where tnum is a const\nbut our unsigned bounds do not reflect this. By calling update_reg_bounds\nafter coerce to 32bit we further refine the umin_value to U64_MAX in the\nalu64 case or U32_MAX in the alu32 case above.\n\nSigned-off-by: John Fastabend \nSigned-off-by: Alexei Starovoitov \nLink: https://lore.kernel.org/bpf/158507151689.15666.566796274289413203.stgit@john-Precision-5820-Tower", "target": 1, "dataset": "other", "idx": 195753} {"func": "static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n\t\t\t\t struct bpf_insn *insn,\n\t\t\t\t struct bpf_reg_state *dst_reg,\n\t\t\t\t struct bpf_reg_state src_reg)\n{\n\tstruct bpf_reg_state *regs = cur_regs(env);\n\tu8 opcode = BPF_OP(insn->code);\n\tbool src_known, dst_known;\n\ts64 smin_val, smax_val;\n\tu64 umin_val, umax_val;\n\tu64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;\n\tu32 dst = insn->dst_reg;\n\tint ret;\n\n\tif (insn_bitness == 32) {\n\t\t/* Relevant for 32-bit RSH: Information can propagate towards\n\t\t * LSB, so it isn't sufficient to only truncate the output to\n\t\t * 32 bits.\n\t\t */\n\t\tcoerce_reg_to_size(dst_reg, 4);\n\t\tcoerce_reg_to_size(&src_reg, 4);\n\t}\n\n\tsmin_val = src_reg.smin_value;\n\tsmax_val = src_reg.smax_value;\n\tumin_val = src_reg.umin_value;\n\tumax_val = src_reg.umax_value;\n\tsrc_known = tnum_is_const(src_reg.var_off);\n\tdst_known = tnum_is_const(dst_reg->var_off);\n\n\tif ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||\n\t smin_val > smax_val || umin_val > umax_val) {\n\t\t/* Taint dst register if offset had invalid bounds derived from\n\t\t * e.g. dead branches.\n\t\t */\n\t\t__mark_reg_unknown(env, dst_reg);\n\t\treturn 0;\n\t}\n\n\tif (!src_known &&\n\t opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {\n\t\t__mark_reg_unknown(env, dst_reg);\n\t\treturn 0;\n\t}\n\n\tswitch (opcode) {\n\tcase BPF_ADD:\n\t\tret = sanitize_val_alu(env, insn);\n\t\tif (ret < 0) {\n\t\t\tverbose(env, \"R%d tried to add from different pointers or scalars\\n\", dst);\n\t\t\treturn ret;\n\t\t}\n\t\tscalar_min_max_add(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_SUB:\n\t\tret = sanitize_val_alu(env, insn);\n\t\tif (ret < 0) {\n\t\t\tverbose(env, \"R%d tried to sub from different pointers or scalars\\n\", dst);\n\t\t\treturn ret;\n\t\t}\n\t\tscalar_min_max_sub(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_MUL:\n\t\tscalar_min_max_mul(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_AND:\n\t\tif (src_known && dst_known) {\n\t\t\t__mark_reg_known(dst_reg, dst_reg->var_off.value &\n\t\t\t\t\t\t src_reg.var_off.value);\n\t\t\tbreak;\n\t\t}\n\t\tscalar_min_max_and(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_OR:\n\t\tif (src_known && dst_known) {\n\t\t\t__mark_reg_known(dst_reg, dst_reg->var_off.value |\n\t\t\t\t\t\t src_reg.var_off.value);\n\t\t\tbreak;\n\t\t}\n\t\tscalar_min_max_or(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_LSH:\n\t\tif (umax_val >= insn_bitness) {\n\t\t\t/* Shifts greater than 31 or 63 are undefined.\n\t\t\t * This includes shifts by a negative number.\n\t\t\t */\n\t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n\t\t\tbreak;\n\t\t}\n\t\tscalar_min_max_lsh(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_RSH:\n\t\tif (umax_val >= insn_bitness) {\n\t\t\t/* Shifts greater than 31 or 63 are undefined.\n\t\t\t * This includes shifts by a negative number.\n\t\t\t */\n\t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n\t\t\tbreak;\n\t\t}\n\t\tscalar_min_max_rsh(dst_reg, &src_reg);\n\t\tbreak;\n\tcase BPF_ARSH:\n\t\tif (umax_val >= insn_bitness) {\n\t\t\t/* Shifts greater than 31 or 63 are undefined.\n\t\t\t * This includes shifts by a negative number.\n\t\t\t */\n\t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n\t\t\tbreak;\n\t\t}\n\t\tscalar_min_max_arsh(dst_reg, &src_reg, insn_bitness);\n\t\tbreak;\n\tdefault:\n\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n\t\tbreak;\n\t}\n\n\tif (BPF_CLASS(insn->code) != BPF_ALU64) {\n\t\t/* 32-bit ALU ops are (32,32)->32 */\n\t\tcoerce_reg_to_size(dst_reg, 4);\n\t}\n\n\t__update_reg_bounds(dst_reg);\n\t__reg_deduce_bounds(dst_reg);\n\t__reg_bound_offset(dst_reg);\n\treturn 0;\n}", "project": "linux", "hash": 201029413509759936437749590618667202456, "size": 126, "commit_id": "294f2fc6da27620a506e6c050241655459ccd6bd", "message": "bpf: Verifer, adjust_scalar_min_max_vals to always call update_reg_bounds()\n\nCurrently, for all op verification we call __red_deduce_bounds() and\n__red_bound_offset() but we only call __update_reg_bounds() in bitwise\nops. However, we could benefit from calling __update_reg_bounds() in\nBPF_ADD, BPF_SUB, and BPF_MUL cases as well.\n\nFor example, a register with state 'R1_w=invP0' when we subtract from\nit,\n\n w1 -= 2\n\nBefore coerce we will now have an smin_value=S64_MIN, smax_value=U64_MAX\nand unsigned bounds umin_value=0, umax_value=U64_MAX. These will then\nbe clamped to S32_MIN, U32_MAX values by coerce in the case of alu32 op\nas done in above example. However tnum will be a constant because the\nALU op is done on a constant.\n\nWithout update_reg_bounds() we have a scenario where tnum is a const\nbut our unsigned bounds do not reflect this. By calling update_reg_bounds\nafter coerce to 32bit we further refine the umin_value to U64_MAX in the\nalu64 case or U32_MAX in the alu32 case above.\n\nSigned-off-by: John Fastabend \nSigned-off-by: Alexei Starovoitov \nLink: https://lore.kernel.org/bpf/158507151689.15666.566796274289413203.stgit@john-Precision-5820-Tower", "target": 0, "dataset": "other", "idx": 232639} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& in0 = ctx->input(0);\n const Tensor& in1 = ctx->input(1);\n\n ValidateInputTensors(ctx, in0, in1);\n\n MatMulBCast bcast(in0.shape().dim_sizes(), in1.shape().dim_sizes());\n OP_REQUIRES(\n ctx, bcast.IsValid(),\n errors::InvalidArgument(\n \"In[0] and In[1] must have compatible batch dimensions: \",\n in0.shape().DebugString(), \" vs. \", in1.shape().DebugString()));\n\n TensorShape out_shape = bcast.output_batch_shape();\n auto batch_size = bcast.output_batch_size();\n auto d0 = in0.dim_size(in0.dims() - 2); // Band size.\n auto d1 = in0.dim_size(in0.dims() - 1);\n Tensor in0_reshaped;\n OP_REQUIRES(\n ctx,\n in0_reshaped.CopyFrom(in0, TensorShape({bcast.x_batch_size(), d0, d1})),\n errors::Internal(\"Failed to reshape In[0] from \",\n in0.shape().DebugString()));\n auto d2 = in1.dim_size(in1.dims() - 2);\n auto d3 = in1.dim_size(in1.dims() - 1);\n Tensor in1_reshaped;\n OP_REQUIRES(\n ctx,\n in1_reshaped.CopyFrom(in1, TensorShape({bcast.y_batch_size(), d2, d3})),\n errors::Internal(\"Failed to reshape In[1] from \",\n in1.shape().DebugString()));\n OP_REQUIRES(ctx, d1 == d2,\n errors::InvalidArgument(\n \"In[0] mismatch In[1] shape: \", d1, \" vs. \", d2, \": \",\n in0.shape().DebugString(), \" \", in1.shape().DebugString(),\n \" \", lower_, \" \", adjoint_));\n out_shape.AddDim(d1);\n out_shape.AddDim(d3);\n Tensor* out = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out));\n if (out->NumElements() == 0) {\n return;\n }\n Tensor out_reshaped;\n OP_REQUIRES(ctx,\n out_reshaped.CopyFrom(*out, TensorShape({batch_size, d1, d3})),\n errors::Internal(\"Failed to reshape output from \",\n out->shape().DebugString()));\n LaunchBatchBandedTriangularSolve::Launch(\n ctx, in0_reshaped, in1_reshaped, adjoint_, lower_, bcast,\n &out_reshaped);\n }", "project": "tensorflow", "hash": 129370171757238809505094793708920834743, "size": 52, "commit_id": "0ab290774f91a23bebe30a358fde4e53ab4876a0", "message": "Ensure validation sticks in banded_triangular_solve_op\n\nPiperOrigin-RevId: 373275480\nChange-Id: Id7717cf275b2d6fdb9441fbbe166d555182d2e79", "target": 1, "dataset": "other", "idx": 195754} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& in0 = ctx->input(0);\n const Tensor& in1 = ctx->input(1);\n\n ValidateInputTensors(ctx, in0, in1);\n if (!ctx->status().ok()) return;\n\n MatMulBCast bcast(in0.shape().dim_sizes(), in1.shape().dim_sizes());\n OP_REQUIRES(\n ctx, bcast.IsValid(),\n errors::InvalidArgument(\n \"In[0] and In[1] must have compatible batch dimensions: \",\n in0.shape().DebugString(), \" vs. \", in1.shape().DebugString()));\n\n TensorShape out_shape = bcast.output_batch_shape();\n auto batch_size = bcast.output_batch_size();\n auto d0 = in0.dim_size(in0.dims() - 2); // Band size.\n auto d1 = in0.dim_size(in0.dims() - 1);\n Tensor in0_reshaped;\n OP_REQUIRES(\n ctx,\n in0_reshaped.CopyFrom(in0, TensorShape({bcast.x_batch_size(), d0, d1})),\n errors::Internal(\"Failed to reshape In[0] from \",\n in0.shape().DebugString()));\n auto d2 = in1.dim_size(in1.dims() - 2);\n auto d3 = in1.dim_size(in1.dims() - 1);\n Tensor in1_reshaped;\n OP_REQUIRES(\n ctx,\n in1_reshaped.CopyFrom(in1, TensorShape({bcast.y_batch_size(), d2, d3})),\n errors::Internal(\"Failed to reshape In[1] from \",\n in1.shape().DebugString()));\n OP_REQUIRES(ctx, d1 == d2,\n errors::InvalidArgument(\n \"In[0] mismatch In[1] shape: \", d1, \" vs. \", d2, \": \",\n in0.shape().DebugString(), \" \", in1.shape().DebugString(),\n \" \", lower_, \" \", adjoint_));\n out_shape.AddDim(d1);\n out_shape.AddDim(d3);\n Tensor* out = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out));\n if (out->NumElements() == 0) {\n return;\n }\n Tensor out_reshaped;\n OP_REQUIRES(ctx,\n out_reshaped.CopyFrom(*out, TensorShape({batch_size, d1, d3})),\n errors::Internal(\"Failed to reshape output from \",\n out->shape().DebugString()));\n LaunchBatchBandedTriangularSolve::Launch(\n ctx, in0_reshaped, in1_reshaped, adjoint_, lower_, bcast,\n &out_reshaped);\n }", "project": "tensorflow", "hash": 126900769494079489680653992675879726552, "size": 53, "commit_id": "0ab290774f91a23bebe30a358fde4e53ab4876a0", "message": "Ensure validation sticks in banded_triangular_solve_op\n\nPiperOrigin-RevId: 373275480\nChange-Id: Id7717cf275b2d6fdb9441fbbe166d555182d2e79", "target": 0, "dataset": "other", "idx": 232648} {"func": "Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr,\n TF_DataType* out_tf_datatype) {\n PyObject* key;\n PyObject* value;\n Py_ssize_t pos = 0;\n if (PyDict_Next(descr->fields, &pos, &key, &value)) {\n // In Python 3, the keys of numpy custom struct types are unicode, unlike\n // Python 2, where the keys are bytes.\n const char* key_string =\n PyBytes_Check(key) ? PyBytes_AsString(key)\n : PyBytes_AsString(PyUnicode_AsASCIIString(key));\n if (!key_string) {\n return errors::Internal(\"Corrupt numpy type descriptor\");\n }\n tensorflow::string key = key_string;\n // The typenames here should match the field names in the custom struct\n // types constructed in test_util.py.\n // TODO(mrry,keveman): Investigate Numpy type registration to replace this\n // hard-coding of names.\n if (key == \"quint8\") {\n *out_tf_datatype = TF_QUINT8;\n } else if (key == \"qint8\") {\n *out_tf_datatype = TF_QINT8;\n } else if (key == \"qint16\") {\n *out_tf_datatype = TF_QINT16;\n } else if (key == \"quint16\") {\n *out_tf_datatype = TF_QUINT16;\n } else if (key == \"qint32\") {\n *out_tf_datatype = TF_QINT32;\n } else if (key == \"resource\") {\n *out_tf_datatype = TF_RESOURCE;\n } else {\n return errors::Internal(\"Unsupported numpy data type\");\n }\n return Status::OK();\n }\n return errors::Internal(\"Unsupported numpy data type\");\n}", "project": "tensorflow", "hash": 29762935772843750891990207013052403837, "size": 38, "commit_id": "030af767d357d1b4088c4a25c72cb3906abac489", "message": "Fix `tf.raw_ops.ResourceCountUpTo` null pointer dereference.\n\nPiperOrigin-RevId: 368294347\nChange-Id: I2c16fbfc9b4966c402c3d8e311f0d665a9c852d8", "target": 1, "dataset": "other", "idx": 195755} {"func": "Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr,\n TF_DataType* out_tf_datatype) {\n PyObject* key;\n PyObject* value;\n Py_ssize_t pos = 0;\n\n // Return an error if the fields attribute is null.\n // Occurs with an improper conversion attempt to resource.\n if (descr->fields == nullptr) {\n return errors::Internal(\"Unexpected numpy data type\");\n }\n\n if (PyDict_Next(descr->fields, &pos, &key, &value)) {\n // In Python 3, the keys of numpy custom struct types are unicode, unlike\n // Python 2, where the keys are bytes.\n const char* key_string =\n PyBytes_Check(key) ? PyBytes_AsString(key)\n : PyBytes_AsString(PyUnicode_AsASCIIString(key));\n if (!key_string) {\n return errors::Internal(\"Corrupt numpy type descriptor\");\n }\n tensorflow::string key = key_string;\n // The typenames here should match the field names in the custom struct\n // types constructed in test_util.py.\n // TODO(mrry,keveman): Investigate Numpy type registration to replace this\n // hard-coding of names.\n if (key == \"quint8\") {\n *out_tf_datatype = TF_QUINT8;\n } else if (key == \"qint8\") {\n *out_tf_datatype = TF_QINT8;\n } else if (key == \"qint16\") {\n *out_tf_datatype = TF_QINT16;\n } else if (key == \"quint16\") {\n *out_tf_datatype = TF_QUINT16;\n } else if (key == \"qint32\") {\n *out_tf_datatype = TF_QINT32;\n } else if (key == \"resource\") {\n *out_tf_datatype = TF_RESOURCE;\n } else {\n return errors::Internal(\"Unsupported numpy data type\");\n }\n return Status::OK();\n }\n return errors::Internal(\"Unsupported numpy data type\");\n}", "project": "tensorflow", "hash": 118618212277768394037584817676898970795, "size": 45, "commit_id": "030af767d357d1b4088c4a25c72cb3906abac489", "message": "Fix `tf.raw_ops.ResourceCountUpTo` null pointer dereference.\n\nPiperOrigin-RevId: 368294347\nChange-Id: I2c16fbfc9b4966c402c3d8e311f0d665a9c852d8", "target": 0, "dataset": "other", "idx": 232661} {"func": "vq_endchains(struct virtio_vq_info *vq, int used_all_avail)\n{\n\tstruct virtio_base *base;\n\tuint16_t event_idx, new_idx, old_idx;\n\tint intr;\n\n\t/*\n\t * Interrupt generation: if we're using EVENT_IDX,\n\t * interrupt if we've crossed the event threshold.\n\t * Otherwise interrupt is generated if we added \"used\" entries,\n\t * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.\n\t *\n\t * In any case, though, if NOTIFY_ON_EMPTY is set and the\n\t * entire avail was processed, we need to interrupt always.\n\t */\n\n\tatomic_thread_fence();\n\n\tbase = vq->base;\n\told_idx = vq->save_used;\n\tvq->save_used = new_idx = vq->used->idx;\n\tif (used_all_avail &&\n\t (base->negotiated_caps & (1 << VIRTIO_F_NOTIFY_ON_EMPTY)))\n\t\tintr = 1;\n\telse if (base->negotiated_caps & (1 << VIRTIO_RING_F_EVENT_IDX)) {\n\t\tevent_idx = VQ_USED_EVENT_IDX(vq);\n\t\t/*\n\t\t * This calculation is per docs and the kernel\n\t\t * (see src/sys/dev/virtio/virtio_ring.h).\n\t\t */\n\t\tintr = (uint16_t)(new_idx - event_idx - 1) <\n\t\t\t(uint16_t)(new_idx - old_idx);\n\t} else {\n\t\tintr = new_idx != old_idx &&\n\t\t !(vq->avail->flags & VRING_AVAIL_F_NO_INTERRUPT);\n\t}\n\tif (intr)\n\t\tvq_interrupt(base, vq);\n}", "project": "acrn-hypervisor", "hash": 93450239856945602125965929759509786033, "size": 39, "commit_id": "154fe59531c12b82e26d1b24b5531f5066d224f5", "message": "dm: validate inputs in vq_endchains\n\n inputs shall be validated to avoid NULL pointer access.\n\nTracked-On: #6129\nSigned-off-by: Yonghua Huang ", "target": 1, "dataset": "other", "idx": 195776} {"func": "vq_endchains(struct virtio_vq_info *vq, int used_all_avail)\n{\n\tstruct virtio_base *base;\n\tuint16_t event_idx, new_idx, old_idx;\n\tint intr;\n\n\tif (!vq || !vq->used)\n\t\treturn;\n\n\t/*\n\t * Interrupt generation: if we're using EVENT_IDX,\n\t * interrupt if we've crossed the event threshold.\n\t * Otherwise interrupt is generated if we added \"used\" entries,\n\t * but suppressed by VRING_AVAIL_F_NO_INTERRUPT.\n\t *\n\t * In any case, though, if NOTIFY_ON_EMPTY is set and the\n\t * entire avail was processed, we need to interrupt always.\n\t */\n\n\tatomic_thread_fence();\n\n\tbase = vq->base;\n\told_idx = vq->save_used;\n\tvq->save_used = new_idx = vq->used->idx;\n\tif (used_all_avail &&\n\t (base->negotiated_caps & (1 << VIRTIO_F_NOTIFY_ON_EMPTY)))\n\t\tintr = 1;\n\telse if (base->negotiated_caps & (1 << VIRTIO_RING_F_EVENT_IDX)) {\n\t\tevent_idx = VQ_USED_EVENT_IDX(vq);\n\t\t/*\n\t\t * This calculation is per docs and the kernel\n\t\t * (see src/sys/dev/virtio/virtio_ring.h).\n\t\t */\n\t\tintr = (uint16_t)(new_idx - event_idx - 1) <\n\t\t\t(uint16_t)(new_idx - old_idx);\n\t} else {\n\t\tintr = new_idx != old_idx &&\n\t\t !(vq->avail->flags & VRING_AVAIL_F_NO_INTERRUPT);\n\t}\n\tif (intr)\n\t\tvq_interrupt(base, vq);\n}", "project": "acrn-hypervisor", "hash": 116982534787850067763114019938336435522, "size": 42, "commit_id": "154fe59531c12b82e26d1b24b5531f5066d224f5", "message": "dm: validate inputs in vq_endchains\n\n inputs shall be validated to avoid NULL pointer access.\n\nTracked-On: #6129\nSigned-off-by: Yonghua Huang ", "target": 0, "dataset": "other", "idx": 232979} {"func": " void ComputeEasyCases(OpKernelContext* context, bool* done,\n std::vector* split_sizes_vec) {\n const int32_t num_split = context->num_outputs();\n const Tensor& input = context->input(0);\n const TensorShape& input_shape = input.shape();\n const Tensor& split_tensor = context->input(1);\n const Tensor& split_dim_tensor = context->input(2);\n\n OP_REQUIRES(context, split_dim_tensor.NumElements() == 1,\n errors::InvalidArgument(\"split_dim_tensor must have \"\n \"exactly one element.\"));\n\n const int32_t split_dim_orig = split_dim_tensor.flat()(0);\n const int32_t split_dim =\n split_dim_orig < 0 ? split_dim_orig + input.dims() : split_dim_orig;\n\n OP_REQUIRES(\n context,\n split_tensor.dims() == 1 && split_tensor.NumElements() == num_split,\n errors::InvalidArgument(\"size of the split_tensor must be 1-D and have \"\n \"the same elements as outputs got \",\n split_tensor.dims(), \" -D and \",\n split_tensor.NumElements(), \" elements\"));\n\n auto split_sizes_d = split_tensor.vec();\n\n split_sizes_vec->resize(split_sizes_d.size());\n\n std::copy(split_sizes_d.data(), split_sizes_d.data() + split_sizes_d.size(),\n split_sizes_vec->begin());\n\n OP_REQUIRES(\n context, num_split > 0,\n errors::InvalidArgument(\n \"Number of ways to split should be > 0, but got \", num_split));\n\n OP_REQUIRES(\n context, 0 <= split_dim && split_dim < input.dims(),\n errors::InvalidArgument(\"-input rank(-\", input.dims(),\n \") <= split_dim < input rank (\", input.dims(),\n \"), but got \", split_dim_orig));\n\n Tlen input_size_split_dim = input_shape.dim_size(split_dim);\n\n // Special case 1: num_split == 1. Nothing to do.\n if (num_split == 1) {\n context->set_output(0, context->input(0));\n OP_REQUIRES(\n context, (*split_sizes_vec)[0] == input_size_split_dim,\n errors::InvalidArgument(\"If there is only one output, it must have \"\n \"the same size as the input. Input size: \",\n input_size_split_dim,\n \" output size: \", (*split_sizes_vec)[0]));\n *done = true;\n return;\n }\n\n // Determine sizes of output, in case of a -1 input value\n int neg_one_dim = -1;\n Tlen determined_size = 0;\n for (int d = 0; d < split_sizes_vec->size(); ++d) {\n Tlen size = (*split_sizes_vec)[d];\n\n if (size == -1) {\n OP_REQUIRES(context, neg_one_dim == -1,\n errors::InvalidArgument(\"There can only be one -1 in the \"\n \"input.\"));\n neg_one_dim = d;\n } else {\n determined_size += size;\n }\n }\n\n OP_REQUIRES(\n context,\n (neg_one_dim == -1 && determined_size == input_size_split_dim) ||\n (neg_one_dim >= 0 && determined_size <= input_size_split_dim),\n errors::InvalidArgument(\"Determined shape must either match \"\n \"input shape along split_dim exactly if \"\n \"fully specified, or be less than the size of \"\n \"the input along split_dim if not fully \"\n \"specified. Got: \",\n determined_size));\n\n if (neg_one_dim >= 0) {\n (*split_sizes_vec)[neg_one_dim] = input_size_split_dim - determined_size;\n }\n\n // Special case 2: split along the 1st dimension. The requirements are that\n // either we are splitting the outer dimension of two or more such that\n // every outer subpart is aligned or that the split sizes mean that they are\n // always aligned. In these cases, we can share the underlying buffer.\n //\n // Apply this optimization conservatively: if input is aligned,\n // the resulting tensors must be aligned. It's conservative\n // because if the immediate consumer of the resulting tensors are\n // not using eigen for computation, its perfectly fine to avoid\n // the copying.\n if (SplitHasAlignedOutputsInFirstDimension(\n input_shape, split_dim, absl::MakeConstSpan(*split_sizes_vec))) {\n Tlen start = 0;\n for (int i = 0; i < num_split; ++i) {\n context->set_output(i,\n input.Slice(start, start + (*split_sizes_vec)[i]));\n start += (*split_sizes_vec)[i];\n }\n *done = true;\n return;\n }\n }", "project": "tensorflow", "hash": 126245865552496072215885042297203605082, "size": 110, "commit_id": "25d622ffc432acc736b14ca3904177579e733cc6", "message": "A negative size in one of the split sizes allowed the computed size of another\nto exceed the total dimension, leading to a segfault and security vulnerability.\nAdding a check for negative sizes prevents this.\n\nPiperOrigin-RevId: 401035665\nChange-Id: I79bbe329787dac82aa4bf60397a9129b716aedab", "target": 1, "dataset": "other", "idx": 195778} {"func": " void ComputeEasyCases(OpKernelContext* context, bool* done,\n std::vector* split_sizes_vec) {\n const int32_t num_split = context->num_outputs();\n const Tensor& input = context->input(0);\n const TensorShape& input_shape = input.shape();\n const Tensor& split_tensor = context->input(1);\n const Tensor& split_dim_tensor = context->input(2);\n\n OP_REQUIRES(context, split_dim_tensor.NumElements() == 1,\n errors::InvalidArgument(\"split_dim_tensor must have \"\n \"exactly one element.\"));\n\n const int32_t split_dim_orig = split_dim_tensor.flat()(0);\n const int32_t split_dim =\n split_dim_orig < 0 ? split_dim_orig + input.dims() : split_dim_orig;\n\n OP_REQUIRES(\n context,\n split_tensor.dims() == 1 && split_tensor.NumElements() == num_split,\n errors::InvalidArgument(\"size of the split_tensor must be 1-D and have \"\n \"the same elements as outputs got \",\n split_tensor.dims(), \" -D and \",\n split_tensor.NumElements(), \" elements\"));\n\n auto split_sizes_d = split_tensor.vec();\n\n split_sizes_vec->resize(split_sizes_d.size());\n\n std::copy(split_sizes_d.data(), split_sizes_d.data() + split_sizes_d.size(),\n split_sizes_vec->begin());\n\n OP_REQUIRES(\n context, num_split > 0,\n errors::InvalidArgument(\n \"Number of ways to split should be > 0, but got \", num_split));\n\n OP_REQUIRES(\n context, 0 <= split_dim && split_dim < input.dims(),\n errors::InvalidArgument(\"-input rank(-\", input.dims(),\n \") <= split_dim < input rank (\", input.dims(),\n \"), but got \", split_dim_orig));\n\n Tlen input_size_split_dim = input_shape.dim_size(split_dim);\n\n // Special case 1: num_split == 1. Nothing to do.\n if (num_split == 1) {\n context->set_output(0, context->input(0));\n OP_REQUIRES(\n context, (*split_sizes_vec)[0] == input_size_split_dim,\n errors::InvalidArgument(\"If there is only one output, it must have \"\n \"the same size as the input. Input size: \",\n input_size_split_dim,\n \" output size: \", (*split_sizes_vec)[0]));\n *done = true;\n return;\n }\n\n // Determine sizes of output, in case of a -1 input value\n int neg_one_dim = -1;\n Tlen determined_size = 0;\n for (int d = 0; d < split_sizes_vec->size(); ++d) {\n Tlen size = (*split_sizes_vec)[d];\n\n if (size == -1) {\n OP_REQUIRES(context, neg_one_dim == -1,\n errors::InvalidArgument(\"There can only be one -1 in the \"\n \"input.\"));\n neg_one_dim = d;\n } else {\n determined_size += size;\n }\n }\n\n OP_REQUIRES(\n context,\n (neg_one_dim == -1 && determined_size == input_size_split_dim) ||\n (neg_one_dim >= 0 && determined_size <= input_size_split_dim),\n errors::InvalidArgument(\"Determined shape must either match \"\n \"input shape along split_dim exactly if \"\n \"fully specified, or be less than the size of \"\n \"the input along split_dim if not fully \"\n \"specified. Got: \",\n determined_size));\n\n if (neg_one_dim >= 0) {\n (*split_sizes_vec)[neg_one_dim] = input_size_split_dim - determined_size;\n }\n\n for (int i = 0; i < split_sizes_vec->size(); ++i) {\n const Tlen& split_size = (*split_sizes_vec)[i];\n OP_REQUIRES(context, split_size >= Tlen(0),\n errors::InvalidArgument(\"Split size at index \", i,\n \" must be >= 0. Got: \", split_size));\n }\n\n // Special case 2: split along the 1st dimension. The requirements are that\n // either we are splitting the outer dimension of two or more such that\n // every outer subpart is aligned or that the split sizes mean that they are\n // always aligned. In these cases, we can share the underlying buffer.\n //\n // Apply this optimization conservatively: if input is aligned,\n // the resulting tensors must be aligned. It's conservative\n // because if the immediate consumer of the resulting tensors are\n // not using eigen for computation, its perfectly fine to avoid\n // the copying.\n if (SplitHasAlignedOutputsInFirstDimension(\n input_shape, split_dim, absl::MakeConstSpan(*split_sizes_vec))) {\n Tlen start = 0;\n for (int i = 0; i < num_split; ++i) {\n context->set_output(i,\n input.Slice(start, start + (*split_sizes_vec)[i]));\n start += (*split_sizes_vec)[i];\n }\n *done = true;\n return;\n }\n }", "project": "tensorflow", "hash": 246328078065637501416321248235339183827, "size": 117, "commit_id": "25d622ffc432acc736b14ca3904177579e733cc6", "message": "A negative size in one of the split sizes allowed the computed size of another\nto exceed the total dimension, leading to a segfault and security vulnerability.\nAdding a check for negative sizes prevents this.\n\nPiperOrigin-RevId: 401035665\nChange-Id: I79bbe329787dac82aa4bf60397a9129b716aedab", "target": 0, "dataset": "other", "idx": 233116} {"func": "int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct,\n\t\t\t struct ndpi_flow_struct *flow, uint32_t quic_version) {\n struct ndpi_packet_struct *packet = &flow->packet;\n union ja3_info ja3;\n u_int8_t invalid_ja3 = 0;\n u_int16_t tls_version, ja3_str_len;\n char ja3_str[JA3_STR_LEN];\n ndpi_MD5_CTX ctx;\n u_char md5_hash[16];\n int i;\n u_int16_t total_len;\n u_int8_t handshake_type;\n char buffer[64] = { '\\0' };\n int is_quic = (quic_version != 0);\n int is_dtls = packet->udp && (!is_quic);\n\n#ifdef DEBUG_TLS\n printf(\"TLS %s() called\\n\", __FUNCTION__);\n#endif\n\n memset(&ja3, 0, sizeof(ja3));\n\n handshake_type = packet->payload[0];\n total_len = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3];\n\n if((total_len > packet->payload_packet_len) || (packet->payload[1] != 0x0))\n return(0); /* Not found */\n\n total_len = packet->payload_packet_len;\n\n /* At least \"magic\" 3 bytes, null for string end, otherwise no need to waste cpu cycles */\n if(total_len > 4) {\n u_int16_t base_offset = (!is_dtls) ? 38 : 46;\n u_int16_t version_offset = (!is_dtls) ? 4 : 12;\n u_int16_t offset = (!is_dtls) ? 38 : 46, extension_len, j;\n u_int8_t session_id_len = 0;\n\n if((base_offset >= total_len) ||\n (version_offset + 1) >= total_len)\n return 0; /* Not found */\n\n session_id_len = packet->payload[base_offset];\n\n#ifdef DEBUG_TLS\n printf(\"TLS [len: %u][handshake_type: %02X]\\n\", packet->payload_packet_len, handshake_type);\n#endif\n\n tls_version = ntohs(*((u_int16_t*)&packet->payload[version_offset]));\n\n if(handshake_type == 0x02 /* Server Hello */) {\n int i, rc;\n\n ja3.server.tls_handshake_version = tls_version;\n\n#ifdef DEBUG_TLS\n printf(\"TLS Server Hello [version: 0x%04X]\\n\", tls_version);\n#endif\n\n /*\n\tThe server hello decides about the TLS version of this flow\n\thttps://networkengineering.stackexchange.com/questions/55752/why-does-wireshark-show-version-tls-1-2-here-instead-of-tls-1-3\n */\n if(packet->udp)\n\toffset += session_id_len + 1;\n else {\n\tif(tls_version < 0x7F15 /* TLS 1.3 lacks of session id */)\n\t offset += session_id_len+1;\n }\n\n if((offset+3) > packet->payload_packet_len)\n\treturn(0); /* Not found */\n\n ja3.server.num_cipher = 1, ja3.server.cipher[0] = ntohs(*((u_int16_t*)&packet->payload[offset]));\n if((flow->protos.tls_quic_stun.tls_quic.server_unsafe_cipher = ndpi_is_safe_ssl_cipher(ja3.server.cipher[0])) == 1)\n\tndpi_set_risk(flow, NDPI_TLS_WEAK_CIPHER);\n\n flow->protos.tls_quic_stun.tls_quic.server_cipher = ja3.server.cipher[0];\n\n#ifdef DEBUG_TLS\n printf(\"TLS [server][session_id_len: %u][cipher: %04X]\\n\", session_id_len, ja3.server.cipher[0]);\n#endif\n\n offset += 2 + 1;\n\n if((offset + 1) < packet->payload_packet_len) /* +1 because we are goint to read 2 bytes */\n\textension_len = ntohs(*((u_int16_t*)&packet->payload[offset]));\n else\n\textension_len = 0;\n\n#ifdef DEBUG_TLS\n printf(\"TLS [server][extension_len: %u]\\n\", extension_len);\n#endif\n offset += 2;\n\n for(i=0; i packet->payload_packet_len) break;\n\n\textension_id = ntohs(*((u_int16_t*)&packet->payload[offset]));\n\textension_len = ntohs(*((u_int16_t*)&packet->payload[offset+2]));\n\n\tif(ja3.server.num_tls_extension < MAX_NUM_JA3)\n\t ja3.server.tls_extension[ja3.server.num_tls_extension++] = extension_id;\n\n#ifdef DEBUG_TLS\n\tprintf(\"TLS [server][extension_id: %u/0x%04X][len: %u]\\n\",\n\t extension_id, extension_id, extension_len);\n#endif\n\n\tif(extension_id == 43 /* supported versions */) {\n\t if(extension_len >= 2) {\n\t u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[offset+4]));\n\n#ifdef DEBUG_TLS\n\t printf(\"TLS [server] [TLS version: 0x%04X]\\n\", tls_version);\n#endif\n\n\t flow->protos.tls_quic_stun.tls_quic.ssl_version = ja3.server.tls_supported_version = tls_version;\n\t }\n\t} else if(extension_id == 16 /* application_layer_protocol_negotiation (ALPN) */) {\n\t u_int16_t s_offset = offset+4;\n\t u_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t char alpn_str[256];\n\t u_int8_t alpn_str_len = 0, i;\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: block_len=%u/len=%u]\\n\", extension_len, tot_alpn_len);\n#endif\n\t s_offset += 2;\n\t tot_alpn_len += s_offset;\n\n\t while(s_offset < tot_alpn_len && s_offset < total_len) {\n\t u_int8_t alpn_i, alpn_len = packet->payload[s_offset++];\n\n\t if((s_offset + alpn_len) <= tot_alpn_len) {\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: %u]\\n\", alpn_len);\n#endif\n\n\t if((alpn_str_len+alpn_len+1) < (sizeof(alpn_str)-1)) {\n\t if(alpn_str_len > 0) {\n\t alpn_str[alpn_str_len] = ',';\n\t alpn_str_len++;\n\t }\n\n\t for(alpn_i=0; alpn_ipayload[s_offset+alpn_i];\n\t }\n\n\t s_offset += alpn_len, alpn_str_len += alpn_len;;\n\t } else {\n\t ndpi_set_risk(flow, NDPI_TLS_UNCOMMON_ALPN);\n\t break;\n\t }\n\t } else {\n\t ndpi_set_risk(flow, NDPI_TLS_UNCOMMON_ALPN);\n\t break;\n\t }\n\t } /* while */\n\n\t alpn_str[alpn_str_len] = '\\0';\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: %s][len: %u]\\n\", alpn_str, alpn_str_len);\n#endif\n\t if(flow->protos.tls_quic_stun.tls_quic.alpn == NULL)\n\t flow->protos.tls_quic_stun.tls_quic.alpn = ndpi_strdup(alpn_str);\n\n\t if(flow->protos.tls_quic_stun.tls_quic.alpn != NULL)\n\t tlsCheckUncommonALPN(flow);\n\n\t snprintf(ja3.server.alpn, sizeof(ja3.server.alpn), \"%s\", alpn_str);\n\n\t /* Replace , with - as in JA3 */\n\t for(i=0; ja3.server.alpn[i] != '\\0'; i++)\n\t if(ja3.server.alpn[i] == ',') ja3.server.alpn[i] = '-';\n\t} else if(extension_id == 11 /* ec_point_formats groups */) {\n\t u_int16_t s_offset = offset+4 + 1;\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [EllipticCurveFormat: len=%u]\\n\", extension_len);\n#endif\n\t if((s_offset+extension_len-1) <= total_len) {\n\t for(i=0; ipayload[s_offset+i];\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [EllipticCurveFormat: %u]\\n\", s_group);\n#endif\n\n\t if(ja3.server.num_elliptic_curve_point_format < MAX_NUM_JA3)\n\t\tja3.server.elliptic_curve_point_format[ja3.server.num_elliptic_curve_point_format++] = s_group;\n\t else {\n\t\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\tprintf(\"Server TLS Invalid num elliptic %u\\n\", ja3.server.num_elliptic_curve_point_format);\n#endif\n\t }\n\t }\n\t } else {\n\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS Invalid len %u vs %u\\n\", s_offset+extension_len, total_len);\n#endif\n\t }\n\t}\n\n\ti += 4 + extension_len, offset += 4 + extension_len;\n } /* for */\n\n ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), \"%u,\", ja3.server.tls_handshake_version);\n\n for(i=0; i 0) ? \"-\" : \"\", ja3.server.cipher[i]);\n\n\tif(rc <= 0) break; else ja3_str_len += rc;\n }\n\n rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",\");\n if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc;\n\n /* ********** */\n\n for(i=0; i 0) ? \"-\" : \"\", ja3.server.tls_extension[i]);\n\n\tif(rc <= 0) break; else ja3_str_len += rc;\n }\n\n if(ndpi_struct->enable_ja3_plus) {\n\tfor(i=0; i 0) ? \"-\" : \"\", ja3.server.elliptic_curve_point_format[i]);\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t}\n\n\tif(ja3.server.alpn[0] != '\\0') {\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",%s\", ja3.server.alpn);\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\t}\n\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3+] Server: %s \\n\", ja3_str);\n#endif\n } else {\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Server: %s \\n\", ja3_str);\n#endif\n }\n\n ndpi_MD5Init(&ctx);\n ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str));\n ndpi_MD5Final(md5_hash, &ctx);\n\n for(i=0, j=0; i<16; i++) {\n\tint rc = snprintf(&flow->protos.tls_quic_stun.tls_quic.ja3_server[j],\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.ja3_server)-j, \"%02x\", md5_hash[i]);\n\tif(rc <= 0) break; else j += rc;\n }\n\n#ifdef DEBUG_TLS\n printf(\"[JA3] Server: %s \\n\", flow->protos.tls_quic_stun.tls_quic.ja3_server);\n#endif\n } else if(handshake_type == 0x01 /* Client Hello */) {\n u_int16_t cipher_len, cipher_offset;\n u_int8_t cookie_len = 0;\n\n flow->protos.tls_quic_stun.tls_quic.ssl_version = ja3.client.tls_handshake_version = tls_version;\n if(flow->protos.tls_quic_stun.tls_quic.ssl_version < 0x0302) /* TLSv1.1 */\n\tndpi_set_risk(flow, NDPI_TLS_OBSOLETE_VERSION);\n\n if((session_id_len+base_offset+3) > packet->payload_packet_len)\n\treturn(0); /* Not found */\n\n if(!is_dtls) {\n\tcipher_len = packet->payload[session_id_len+base_offset+2] + (packet->payload[session_id_len+base_offset+1] << 8);\n\tcipher_offset = base_offset + session_id_len + 3;\n } else {\n\tcookie_len = packet->payload[base_offset+session_id_len+1];\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Client: DTLS cookie len %d\\n\", cookie_len);\n#endif\n\tif((session_id_len+base_offset+cookie_len+4) > packet->payload_packet_len)\n\t return(0); /* Not found */\n\tcipher_len = ntohs(*((u_int16_t*)&packet->payload[base_offset+session_id_len+cookie_len+2]));\n\tcipher_offset = base_offset + session_id_len + cookie_len + 4;\n }\n\n#ifdef DEBUG_TLS\n printf(\"Client TLS [client cipher_len: %u][tls_version: 0x%04X]\\n\", cipher_len, tls_version);\n#endif\n\n if((cipher_offset+cipher_len) <= total_len) {\n\tu_int8_t safari_ciphers = 0, chrome_ciphers = 0;\n\n\tfor(i=0; ipayload[cipher_offset+i];\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [cipher suite: %u/0x%04X] [%d/%u]\\n\", ntohs(*id), ntohs(*id), i, cipher_len);\n#endif\n\t if((*id == 0) || (packet->payload[cipher_offset+i] != packet->payload[cipher_offset+i+1])) {\n\t u_int16_t cipher_id = ntohs(*id);\n\t /*\n\t Skip GREASE [https://tools.ietf.org/id/draft-ietf-tls-grease-01.html]\n\t https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967\n\t */\n\n\t if(ja3.client.num_cipher < MAX_NUM_JA3)\n\t ja3.client.cipher[ja3.client.num_cipher++] = cipher_id;\n\t else {\n\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS Invalid cipher %u\\n\", ja3.client.num_cipher);\n#endif\n\t }\n\n\t switch(cipher_id) {\n\t case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:\n\t safari_ciphers++;\n\t break;\n\n\t case TLS_CIPHER_GREASE_RESERVED_0:\n\t case TLS_AES_128_GCM_SHA256:\n\t case TLS_AES_256_GCM_SHA384:\n\t case TLS_CHACHA20_POLY1305_SHA256:\n\t chrome_ciphers++;\n\t break;\n\n\t case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:\n\t case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:\n\t case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:\n\t case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:\n\t case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:\n\t case TLS_RSA_WITH_AES_128_CBC_SHA:\n\t case TLS_RSA_WITH_AES_256_CBC_SHA:\n\t case TLS_RSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_RSA_WITH_AES_256_GCM_SHA384:\n\t safari_ciphers++, chrome_ciphers++;\n\t break;\n\t }\n\t }\n\n\t i += 2;\n\t} /* for */\n\n\tif(chrome_ciphers == 13)\n\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 1;\n\telse if(safari_ciphers == 12)\n\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 1;\n } else {\n\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\tprintf(\"Client TLS Invalid len %u vs %u\\n\", (cipher_offset+cipher_len), total_len);\n#endif\n }\n\n offset = base_offset + session_id_len + cookie_len + cipher_len + 2;\n offset += (!is_dtls) ? 1 : 2;\n\n if(offset < total_len) {\n\tu_int16_t compression_len;\n\tu_int16_t extensions_len;\n\n\tcompression_len = packet->payload[offset];\n\toffset++;\n\n#ifdef DEBUG_TLS\n\tprintf(\"Client TLS [compression_len: %u]\\n\", compression_len);\n#endif\n\n\t// offset += compression_len + 3;\n\toffset += compression_len;\n\n\tif(offset+1 < total_len) {\n\t extensions_len = ntohs(*((u_int16_t*)&packet->payload[offset]));\n\t offset += 2;\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extensions_len: %u]\\n\", extensions_len);\n#endif\n\n\t if((extensions_len+offset) <= total_len) {\n\t /* Move to the first extension\n\t Type is u_int to avoid possible overflow on extension_len addition */\n\t u_int extension_offset = 0;\n\t u_int32_t j;\n\n\t while(extension_offset < extensions_len &&\n\t\t offset+extension_offset+4 <= total_len) {\n\t u_int16_t extension_id, extension_len, extn_off = offset+extension_offset;\n\n\n\t extension_id = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset]));\n\t extension_offset += 2;\n\n\t extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset]));\n\t extension_offset += 2;\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extension_id: %u][extension_len: %u]\\n\", extension_id, extension_len);\n#endif\n\n\t if((extension_id == 0) || (packet->payload[extn_off] != packet->payload[extn_off+1])) {\n\t\t/* Skip GREASE */\n\n\t\tif(ja3.client.num_tls_extension < MAX_NUM_JA3)\n\t\t ja3.client.tls_extension[ja3.client.num_tls_extension++] = extension_id;\n\t\telse {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid extensions %u\\n\", ja3.client.num_tls_extension);\n#endif\n\t\t}\n\t }\n\n\t if(extension_id == 0 /* server name */) {\n\t\tu_int16_t len;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"[TLS] Extensions: found server name\\n\");\n#endif\n\t\tif((offset+extension_offset+4) < packet->payload_packet_len) {\n\n\t\t len = (packet->payload[offset+extension_offset+3] << 8) + packet->payload[offset+extension_offset+4];\n\t\t len = (u_int)ndpi_min(len, sizeof(buffer)-1);\n\n\t\t if((offset+extension_offset+5+len) <= packet->payload_packet_len) {\n\t\t strncpy(buffer, (char*)&packet->payload[offset+extension_offset+5], len);\n\t\t buffer[len] = '\\0';\n\n\t\t cleanupServerName(buffer, sizeof(buffer));\n\n\t\t snprintf(flow->protos.tls_quic_stun.tls_quic.client_requested_server_name,\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.client_requested_server_name),\n\t\t\t \"%s\", buffer);\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: [%s]\\n\", buffer);\n#endif\n\t\t if(!is_quic) {\n\t\t if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, buffer, strlen(buffer)))\n\t\t flow->l4.tcp.tls.subprotocol_detected = 1;\n\t\t } else {\n\t\t if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_QUIC, buffer, strlen(buffer)))\n\t\t flow->l4.tcp.tls.subprotocol_detected = 1;\n\t\t }\n\n\t\t if(ndpi_check_dga_name(ndpi_struct, flow,\n\t\t\t\t\t flow->protos.tls_quic_stun.tls_quic.client_requested_server_name, 1)) {\n\t\t char *sni = flow->protos.tls_quic_stun.tls_quic.client_requested_server_name;\n\t\t int len = strlen(sni);\n\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: (DGA) [%s]\\n\", flow->protos.tls_quic_stun.tls_quic.client_requested_server_name);\n#endif\n\n\t\t if((len >= 4)\n\t\t /* Check if it ends in .com or .net */\n\t\t && ((strcmp(&sni[len-4], \".com\") == 0) || (strcmp(&sni[len-4], \".net\") == 0))\n\t\t && (strncmp(sni, \"www.\", 4) == 0)) /* Not starting with www.... */\n\t\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TOR, NDPI_PROTOCOL_TLS);\n\t\t } else {\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: (NO DGA) [%s]\\n\", flow->protos.tls_quic_stun.tls_quic.client_requested_server_name);\n#endif\n\t\t }\n\t\t } else {\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] Extensions server len too short: %u vs %u\\n\",\n\t\t\t offset+extension_offset+5+len,\n\t\t\t packet->payload_packet_len);\n#endif\n\t\t }\n\t\t}\n\t } else if(extension_id == 10 /* supported groups */) {\n\t\tu_int16_t s_offset = offset+extension_offset + 2;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [EllipticCurveGroups: len=%u]\\n\", extension_len);\n#endif\n\n\t\tif((s_offset+extension_len-2) <= total_len) {\n\t\t for(i=0; ipayload[s_offset+i]));\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [EllipticCurve: %u/0x%04X]\\n\", s_group, s_group);\n#endif\n\t\t if((s_group == 0) || (packet->payload[s_offset+i] != packet->payload[s_offset+i+1])) {\n\t\t /* Skip GREASE */\n\t\t if(ja3.client.num_elliptic_curve < MAX_NUM_JA3)\n\t\t\tja3.client.elliptic_curve[ja3.client.num_elliptic_curve++] = s_group;\n\t\t else {\n\t\t\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t\tprintf(\"Client TLS Invalid num elliptic %u\\n\", ja3.client.num_elliptic_curve);\n#endif\n\t\t }\n\t\t }\n\n\t\t i += 2;\n\t\t }\n\t\t} else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid len %u vs %u\\n\", (s_offset+extension_len-1), total_len);\n#endif\n\t\t}\n\t } else if(extension_id == 11 /* ec_point_formats groups */) {\n\t\tu_int16_t s_offset = offset+extension_offset + 1;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [EllipticCurveFormat: len=%u]\\n\", extension_len);\n#endif\n\t\tif((s_offset+extension_len-1) <= total_len) {\n\t\t for(i=0; ipayload[s_offset+i];\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [EllipticCurveFormat: %u]\\n\", s_group);\n#endif\n\n\t\t if(ja3.client.num_elliptic_curve_point_format < MAX_NUM_JA3)\n\t\t ja3.client.elliptic_curve_point_format[ja3.client.num_elliptic_curve_point_format++] = s_group;\n\t\t else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid num elliptic %u\\n\", ja3.client.num_elliptic_curve_point_format);\n#endif\n\t\t }\n\t\t }\n\t\t} else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid len %u vs %u\\n\", s_offset+extension_len, total_len);\n#endif\n\t\t}\n\t } else if(extension_id == 13 /* signature algorithms */) {\n\t\tu_int16_t s_offset = offset+extension_offset, safari_signature_algorithms = 0, chrome_signature_algorithms = 0;\n\t\tu_int16_t tot_signature_algorithms_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [SIGNATURE_ALGORITHMS: block_len=%u/len=%u]\\n\", extension_len, tot_signature_algorithms_len);\n#endif\n\n\t\ts_offset += 2;\n\t\ttot_signature_algorithms_len = ndpi_min((sizeof(ja3.client.signature_algorithms) / 2) - 1, tot_signature_algorithms_len);\n\n#ifdef TLS_HANDLE_SIGNATURE_ALGORITMS\n\t\tflow->protos.tls_quic_stun.tls_quic.num_tls_signature_algorithms = ndpi_min(tot_signature_algorithms_len / 2, MAX_NUM_TLS_SIGNATURE_ALGORITHMS);\n\n\t\tmemcpy(flow->protos.tls_quic_stun.tls_quic.client_signature_algorithms,\n\t\t &packet->payload[s_offset], 2 /* 16 bit */*flow->protos.tls_quic_stun.tls_quic.num_tls_signature_algorithms);\n#endif\n\n\t\tfor(i=0; ipayload[s_offset+i]);\n\n\t\t if(rc < 0) break;\n\t\t}\n\n\t\tfor(i=0; ipayload[s_offset+i]));\n\n\t\t // printf(\"=>> %04X\\n\", cipher_id);\n\n\t\t switch(cipher_id) {\n\t\t case ECDSA_SECP521R1_SHA512:\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_firefox_tls = 1;\n\t\t break;\n\n\t\t case ECDSA_SECP256R1_SHA256:\n\t\t case ECDSA_SECP384R1_SHA384:\n\t\t case RSA_PKCS1_SHA256:\n\t\t case RSA_PKCS1_SHA384:\n\t\t case RSA_PKCS1_SHA512:\n\t\t case RSA_PSS_RSAE_SHA256:\n\t\t case RSA_PSS_RSAE_SHA384:\n\t\t case RSA_PSS_RSAE_SHA512:\n\t\t chrome_signature_algorithms++, safari_signature_algorithms++;\n\t\t break;\n\t\t }\n\t\t}\n\n\t\tif(flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_firefox_tls)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 0,\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 0;\n\n\t\tif(safari_signature_algorithms != 8)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 0;\n\n\t\tif(chrome_signature_algorithms != 8)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 0;\n\n\t\tja3.client.signature_algorithms[i*2] = '\\0';\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [SIGNATURE_ALGORITHMS: %s]\\n\", ja3.client.signature_algorithms);\n#endif\n\t } else if(extension_id == 16 /* application_layer_protocol_negotiation */) {\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tu_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\tchar alpn_str[256];\n\t\tu_int8_t alpn_str_len = 0, i;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [ALPN: block_len=%u/len=%u]\\n\", extension_len, tot_alpn_len);\n#endif\n\t\ts_offset += 2;\n\t\ttot_alpn_len += s_offset;\n\n\t\twhile(s_offset < tot_alpn_len && s_offset < total_len) {\n\t\t u_int8_t alpn_i, alpn_len = packet->payload[s_offset++];\n\n\t\t if((s_offset + alpn_len) <= tot_alpn_len &&\n\t\t (s_offset + alpn_len) <= total_len) {\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [ALPN: %u]\\n\", alpn_len);\n#endif\n\n\t\t if((alpn_str_len+alpn_len+1) < (sizeof(alpn_str)-1)) {\n\t\t if(alpn_str_len > 0) {\n\t\t\talpn_str[alpn_str_len] = ',';\n\t\t\talpn_str_len++;\n\t\t }\n\n\t\t for(alpn_i=0; alpn_ipayload[s_offset+alpn_i];\n\n\t\t s_offset += alpn_len, alpn_str_len += alpn_len;;\n\t\t } else\n\t\t break;\n\t\t } else\n\t\t break;\n\t\t} /* while */\n\n\t\talpn_str[alpn_str_len] = '\\0';\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [ALPN: %s][len: %u]\\n\", alpn_str, alpn_str_len);\n#endif\n\t\tif(flow->protos.tls_quic_stun.tls_quic.alpn == NULL)\n\t\t flow->protos.tls_quic_stun.tls_quic.alpn = ndpi_strdup(alpn_str);\n\n\t\tsnprintf(ja3.client.alpn, sizeof(ja3.client.alpn), \"%s\", alpn_str);\n\n\t\t/* Replace , with - as in JA3 */\n\t\tfor(i=0; ja3.client.alpn[i] != '\\0'; i++)\n\t\t if(ja3.client.alpn[i] == ',') ja3.client.alpn[i] = '-';\n\n\t } else if(extension_id == 43 /* supported versions */) {\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tu_int8_t version_len = packet->payload[s_offset];\n\t\tchar version_str[256];\n\t\tu_int8_t version_str_len = 0;\n\t\tversion_str[0] = 0;\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [TLS version len: %u]\\n\", version_len);\n#endif\n\n\t\tif(version_len == (extension_len-1)) {\n\t\t u_int8_t j;\n\t\t u_int16_t supported_versions_offset = 0;\n\n\t\t s_offset++;\n\n\t\t // careful not to overflow and loop forever with u_int8_t\n\t\t for(j=0; j+1payload[s_offset+j]));\n\t\t u_int8_t unknown_tls_version;\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [TLS version: %s/0x%04X]\\n\",\n\t\t\t ndpi_ssl_version2str(flow, tls_version, &unknown_tls_version), tls_version);\n#endif\n\n\t\t if((version_str_len+8) < sizeof(version_str)) {\n\t\t int rc = snprintf(&version_str[version_str_len],\n\t\t\t\t\tsizeof(version_str) - version_str_len, \"%s%s\",\n\t\t\t\t\t(version_str_len > 0) ? \",\" : \"\",\n\t\t\t\t\tndpi_ssl_version2str(flow, tls_version, &unknown_tls_version));\n\t\t if(rc <= 0)\n\t\t\tbreak;\n\t\t else\n\t\t\tversion_str_len += rc;\n\n\t\t rc = snprintf(&ja3.client.supported_versions[supported_versions_offset],\n\t\t\t\t sizeof(ja3.client.supported_versions)-supported_versions_offset,\n\t\t\t\t \"%s%04X\", (j > 0) ? \"-\" : \"\", tls_version);\n\n\t\t if(rc > 0)\n\t\t\tsupported_versions_offset += rc;\n\t\t }\n\t\t }\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [SUPPORTED_VERSIONS: %s]\\n\", ja3.client.supported_versions);\n#endif\n\n\t\t if(flow->protos.tls_quic_stun.tls_quic.tls_supported_versions == NULL)\n\t\t flow->protos.tls_quic_stun.tls_quic.tls_supported_versions = ndpi_strdup(version_str);\n\t\t}\n\t } else if(extension_id == 65486 /* encrypted server name */) {\n\t\t/*\n\t\t - https://tools.ietf.org/html/draft-ietf-tls-esni-06\n\t\t - https://blog.cloudflare.com/encrypted-sni/\n\t\t*/\n\t\tu_int16_t e_offset = offset+extension_offset;\n\t\tu_int16_t initial_offset = e_offset;\n\t\tu_int16_t e_sni_len, cipher_suite = ntohs(*((u_int16_t*)&packet->payload[e_offset]));\n\n\t\tflow->protos.tls_quic_stun.tls_quic.encrypted_sni.cipher_suite = cipher_suite;\n\n\t\te_offset += 2; /* Cipher suite len */\n\n\t\t/* Key Share Entry */\n\t\te_offset += 2; /* Group */\n\t\te_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */\n\n\t\tif((e_offset+4) < packet->payload_packet_len) {\n\t\t /* Record Digest */\n\t\t e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */\n\n\t\t if((e_offset+4) < packet->payload_packet_len) {\n\t\t e_sni_len = ntohs(*((u_int16_t*)&packet->payload[e_offset]));\n\t\t e_offset += 2;\n\n\t\t if((e_offset+e_sni_len-extension_len-initial_offset) >= 0 &&\n\t\t e_offset+e_sni_len < packet->payload_packet_len) {\n#ifdef DEBUG_ENCRYPTED_SNI\n\t\t printf(\"Client TLS [Encrypted Server Name len: %u]\\n\", e_sni_len);\n#endif\n\n\t\t if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni == NULL) {\n\t\t\tflow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni = (char*)ndpi_malloc(e_sni_len*2+1);\n\n\t\t\tif(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni) {\n\t\t\t u_int16_t i, off;\n\n\t\t\t for(i=e_offset, off=0; i<(e_offset+e_sni_len); i++) {\n\t\t\t int rc = sprintf(&flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni[off], \"%02X\", packet->payload[i] & 0XFF);\n\n\t\t\t if(rc <= 0) {\n\t\t\t flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni[off] = '\\0';\n\t\t\t break;\n\t\t\t } else\n\t\t\t off += rc;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t }\n\t\t }\n\t\t}\n\t } else if(extension_id == 65445 || /* QUIC transport parameters (drafts version) */\n\t\t extension_id == 57) { /* QUIC transport parameters (final version) */\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tuint16_t final_offset;\n\t\tint using_var_int = is_version_with_var_int_transport_params(quic_version);\n\n\t\tif(!using_var_int) {\n\t\t if(s_offset+1 >= total_len) {\n\t\t final_offset = 0; /* Force skipping extension */\n\t\t } else {\n\t\t u_int16_t seq_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\t s_offset += 2;\n\t final_offset = MIN(total_len, s_offset + seq_len);\n\t\t }\n\t\t} else {\n\t final_offset = MIN(total_len, s_offset + extension_len);\n\t\t}\n\n\t\twhile(s_offset < final_offset) {\n\t\t u_int64_t param_type, param_len;\n\n if(!using_var_int) {\n\t\t if(s_offset+3 >= final_offset)\n\t\t break;\n\t\t param_type = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\t param_len = ntohs(*((u_int16_t*)&packet->payload[s_offset + 2]));\n\t\t s_offset += 4;\n\t\t } else {\n\t\t if(s_offset >= final_offset ||\n\t\t (s_offset + quic_len_buffer_still_required(packet->payload[s_offset])) >= final_offset)\n\t\t break;\n\t\t s_offset += quic_len(&packet->payload[s_offset], ¶m_type);\n\n\t\t if(s_offset >= final_offset ||\n\t\t (s_offset + quic_len_buffer_still_required(packet->payload[s_offset])) >= final_offset)\n\t\t break;\n\t\t s_offset += quic_len(&packet->payload[s_offset], ¶m_len);\n\t\t }\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [QUIC TP: Param 0x%x Len %d]\\n\", (int)param_type, (int)param_len);\n#endif\n\t\t if(s_offset+param_len > final_offset)\n\t\t break;\n\n\t\t if(param_type==0x3129) {\n#ifdef DEBUG_TLS\n\t\t printf(\"UA [%.*s]\\n\", (int)param_len, &packet->payload[s_offset]);\n#endif\n\t\t http_process_user_agent(ndpi_struct, flow,\n\t\t\t\t\t &packet->payload[s_offset], param_len);\n\t\t break;\n\t\t }\n\t\t s_offset += param_len;\n\t\t}\n\t }\n\n\t extension_offset += extension_len; /* Move to the next extension */\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extension_offset/len: %u/%u]\\n\", extension_offset, extension_len);\n#endif\n\t } /* while */\n\n\t if(!invalid_ja3) {\n\t int rc;\n\n\t compute_ja3c:\n\t ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), \"%u,\", ja3.client.tls_handshake_version);\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.cipher[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t /* ********** */\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.tls_extension[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t /* ********** */\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.elliptic_curve[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.elliptic_curve_point_format[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t if(ndpi_struct->enable_ja3_plus) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len,\n\t\t\t \",%s,%s,%s\", ja3.client.signature_algorithms, ja3.client.supported_versions, ja3.client.alpn);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\t }\n\n#ifdef DEBUG_JA3C\n\t printf(\"[JA3+] Client: %s \\n\", ja3_str);\n#endif\n\n\t ndpi_MD5Init(&ctx);\n\t ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str));\n\t ndpi_MD5Final(md5_hash, &ctx);\n\n\t for(i=0, j=0; i<16; i++) {\n\t\trc = snprintf(&flow->protos.tls_quic_stun.tls_quic.ja3_client[j],\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.ja3_client)-j, \"%02x\",\n\t\t\t md5_hash[i]);\n\t\tif(rc > 0) j += rc; else break;\n\t }\n\n#ifdef DEBUG_JA3C\n\t printf(\"[JA3] Client: %s \\n\", flow->protos.tls_quic_stun.tls_quic.ja3_client);\n#endif\n\n\t if(ndpi_struct->malicious_ja3_automa.ac_automa != NULL) {\n\t\tu_int16_t rc1 = ndpi_match_string(ndpi_struct->malicious_ja3_automa.ac_automa,\n\t\t\t\t\t\t flow->protos.tls_quic_stun.tls_quic.ja3_client);\n\n\t\tif(rc1 > 0)\n\t\t ndpi_set_risk(flow, NDPI_MALICIOUS_JA3);\n\t }\n\t }\n\n\t /* Before returning to the caller we need to make a final check */\n\t if((flow->protos.tls_quic_stun.tls_quic.ssl_version >= 0x0303) /* >= TLSv1.2 */\n\t && (flow->protos.tls_quic_stun.tls_quic.alpn == NULL) /* No ALPN */) {\n\t ndpi_set_risk(flow, NDPI_TLS_NOT_CARRYING_HTTPS);\n\t }\n\n\t /* Suspicious Domain Fronting:\n\t https://github.com/SixGenInc/Noctilucent/blob/master/docs/ */\n\t if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni &&\n\t flow->protos.tls_quic_stun.tls_quic.client_requested_server_name[0] != '\\0') {\n\t ndpi_set_risk(flow, NDPI_TLS_SUSPICIOUS_ESNI_USAGE);\n\t }\n\n\t /* Add check for missing SNI */\n\t if((flow->protos.tls_quic_stun.tls_quic.client_requested_server_name[0] == 0)\n\t && (flow->protos.tls_quic_stun.tls_quic.ssl_version >= 0x0302) /* TLSv1.1 */\n\t && (flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni == NULL) /* No ESNI */\n\t ) {\n\t /* This is a bit suspicious */\n\t ndpi_set_risk(flow, NDPI_TLS_MISSING_SNI);\n\t }\n\n\t return(2 /* Client Certificate */);\n\t } else {\n#ifdef DEBUG_TLS\n\t printf(\"[TLS] Client: too short [%u vs %u]\\n\",\n\t\t (extensions_len+offset), total_len);\n#endif\n\t }\n\t} else if(offset == total_len) {\n\t /* TLS does not have extensions etc */\n\t goto compute_ja3c;\n\t}\n } else {\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Client: invalid length detected\\n\");\n#endif\n }\n }\n }\n\n return(0); /* Not found */\n}", "project": "nDPI", "hash": 257200396347775652568989609363155151045, "size": 941, "commit_id": "1ec621c85b9411cc611652fd57a892cfef478af3", "message": "Added further checks", "target": 1, "dataset": "other", "idx": 195820} {"func": "int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct,\n\t\t\t struct ndpi_flow_struct *flow, uint32_t quic_version) {\n struct ndpi_packet_struct *packet = &flow->packet;\n union ja3_info ja3;\n u_int8_t invalid_ja3 = 0;\n u_int16_t tls_version, ja3_str_len;\n char ja3_str[JA3_STR_LEN];\n ndpi_MD5_CTX ctx;\n u_char md5_hash[16];\n int i;\n u_int16_t total_len;\n u_int8_t handshake_type;\n char buffer[64] = { '\\0' };\n int is_quic = (quic_version != 0);\n int is_dtls = packet->udp && (!is_quic);\n\n#ifdef DEBUG_TLS\n printf(\"TLS %s() called\\n\", __FUNCTION__);\n#endif\n\n memset(&ja3, 0, sizeof(ja3));\n\n handshake_type = packet->payload[0];\n total_len = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3];\n\n if((total_len > packet->payload_packet_len) || (packet->payload[1] != 0x0))\n return(0); /* Not found */\n\n total_len = packet->payload_packet_len;\n\n /* At least \"magic\" 3 bytes, null for string end, otherwise no need to waste cpu cycles */\n if(total_len > 4) {\n u_int16_t base_offset = (!is_dtls) ? 38 : 46;\n u_int16_t version_offset = (!is_dtls) ? 4 : 12;\n u_int16_t offset = (!is_dtls) ? 38 : 46, extension_len, j;\n u_int8_t session_id_len = 0;\n\n if((base_offset >= total_len) ||\n (version_offset + 1) >= total_len)\n return 0; /* Not found */\n\n session_id_len = packet->payload[base_offset];\n\n#ifdef DEBUG_TLS\n printf(\"TLS [len: %u][handshake_type: %02X]\\n\", packet->payload_packet_len, handshake_type);\n#endif\n\n tls_version = ntohs(*((u_int16_t*)&packet->payload[version_offset]));\n\n if(handshake_type == 0x02 /* Server Hello */) {\n int i, rc;\n\n ja3.server.tls_handshake_version = tls_version;\n\n#ifdef DEBUG_TLS\n printf(\"TLS Server Hello [version: 0x%04X]\\n\", tls_version);\n#endif\n\n /*\n\tThe server hello decides about the TLS version of this flow\n\thttps://networkengineering.stackexchange.com/questions/55752/why-does-wireshark-show-version-tls-1-2-here-instead-of-tls-1-3\n */\n if(packet->udp)\n\toffset += session_id_len + 1;\n else {\n\tif(tls_version < 0x7F15 /* TLS 1.3 lacks of session id */)\n\t offset += session_id_len+1;\n }\n\n if((offset+3) > packet->payload_packet_len)\n\treturn(0); /* Not found */\n\n ja3.server.num_cipher = 1, ja3.server.cipher[0] = ntohs(*((u_int16_t*)&packet->payload[offset]));\n if((flow->protos.tls_quic_stun.tls_quic.server_unsafe_cipher = ndpi_is_safe_ssl_cipher(ja3.server.cipher[0])) == 1)\n\tndpi_set_risk(flow, NDPI_TLS_WEAK_CIPHER);\n\n flow->protos.tls_quic_stun.tls_quic.server_cipher = ja3.server.cipher[0];\n\n#ifdef DEBUG_TLS\n printf(\"TLS [server][session_id_len: %u][cipher: %04X]\\n\", session_id_len, ja3.server.cipher[0]);\n#endif\n\n offset += 2 + 1;\n\n if((offset + 1) < packet->payload_packet_len) /* +1 because we are goint to read 2 bytes */\n\textension_len = ntohs(*((u_int16_t*)&packet->payload[offset]));\n else\n\textension_len = 0;\n\n#ifdef DEBUG_TLS\n printf(\"TLS [server][extension_len: %u]\\n\", extension_len);\n#endif\n offset += 2;\n\n for(i=0; i packet->payload_packet_len) break;\n\n\textension_id = ntohs(*((u_int16_t*)&packet->payload[offset]));\n\textension_len = ntohs(*((u_int16_t*)&packet->payload[offset+2]));\n\n\tif(ja3.server.num_tls_extension < MAX_NUM_JA3)\n\t ja3.server.tls_extension[ja3.server.num_tls_extension++] = extension_id;\n\n#ifdef DEBUG_TLS\n\tprintf(\"TLS [server][extension_id: %u/0x%04X][len: %u]\\n\",\n\t extension_id, extension_id, extension_len);\n#endif\n\n\tif(extension_id == 43 /* supported versions */) {\n\t if(extension_len >= 2) {\n\t u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[offset+4]));\n\n#ifdef DEBUG_TLS\n\t printf(\"TLS [server] [TLS version: 0x%04X]\\n\", tls_version);\n#endif\n\n\t flow->protos.tls_quic_stun.tls_quic.ssl_version = ja3.server.tls_supported_version = tls_version;\n\t }\n\t} else if(extension_id == 16 /* application_layer_protocol_negotiation (ALPN) */) {\n\t u_int16_t s_offset = offset+4;\n\t u_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t char alpn_str[256];\n\t u_int8_t alpn_str_len = 0, i;\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: block_len=%u/len=%u]\\n\", extension_len, tot_alpn_len);\n#endif\n\t s_offset += 2;\n\t tot_alpn_len += s_offset;\n\n\t while(s_offset < tot_alpn_len && s_offset < total_len) {\n\t u_int8_t alpn_i, alpn_len = packet->payload[s_offset++];\n\n\t if((s_offset + alpn_len) <= tot_alpn_len) {\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: %u]\\n\", alpn_len);\n#endif\n\n\t if((alpn_str_len+alpn_len+1) < (sizeof(alpn_str)-1)) {\n\t if(alpn_str_len > 0) {\n\t alpn_str[alpn_str_len] = ',';\n\t alpn_str_len++;\n\t }\n\n\t for(alpn_i=0; alpn_ipayload[s_offset+alpn_i];\n\t }\n\n\t s_offset += alpn_len, alpn_str_len += alpn_len;;\n\t } else {\n\t ndpi_set_risk(flow, NDPI_TLS_UNCOMMON_ALPN);\n\t break;\n\t }\n\t } else {\n\t ndpi_set_risk(flow, NDPI_TLS_UNCOMMON_ALPN);\n\t break;\n\t }\n\t } /* while */\n\n\t alpn_str[alpn_str_len] = '\\0';\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [ALPN: %s][len: %u]\\n\", alpn_str, alpn_str_len);\n#endif\n\t if(flow->protos.tls_quic_stun.tls_quic.alpn == NULL)\n\t flow->protos.tls_quic_stun.tls_quic.alpn = ndpi_strdup(alpn_str);\n\n\t if(flow->protos.tls_quic_stun.tls_quic.alpn != NULL)\n\t tlsCheckUncommonALPN(flow);\n\n\t snprintf(ja3.server.alpn, sizeof(ja3.server.alpn), \"%s\", alpn_str);\n\n\t /* Replace , with - as in JA3 */\n\t for(i=0; ja3.server.alpn[i] != '\\0'; i++)\n\t if(ja3.server.alpn[i] == ',') ja3.server.alpn[i] = '-';\n\t} else if(extension_id == 11 /* ec_point_formats groups */) {\n\t u_int16_t s_offset = offset+4 + 1;\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [EllipticCurveFormat: len=%u]\\n\", extension_len);\n#endif\n\t if((s_offset+extension_len-1) <= total_len) {\n\t for(i=0; ipayload[s_offset+i];\n\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS [EllipticCurveFormat: %u]\\n\", s_group);\n#endif\n\n\t if(ja3.server.num_elliptic_curve_point_format < MAX_NUM_JA3)\n\t\tja3.server.elliptic_curve_point_format[ja3.server.num_elliptic_curve_point_format++] = s_group;\n\t else {\n\t\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\tprintf(\"Server TLS Invalid num elliptic %u\\n\", ja3.server.num_elliptic_curve_point_format);\n#endif\n\t }\n\t }\n\t } else {\n\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t printf(\"Server TLS Invalid len %u vs %u\\n\", s_offset+extension_len, total_len);\n#endif\n\t }\n\t}\n\n\ti += 4 + extension_len, offset += 4 + extension_len;\n } /* for */\n\n ja3_str_len = snprintf(ja3_str, JA3_STR_LEN, \"%u,\", ja3.server.tls_handshake_version);\n\n for(i=0; (i ja3_str_len); i++) {\n\trc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \"%s%u\", (i > 0) ? \"-\" : \"\", ja3.server.cipher[i]);\n\n\tif(rc <= 0) break; else ja3_str_len += rc;\n }\n\n if(JA3_STR_LEN > ja3_str_len) {\n\trc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \",\");\n\tif(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc;\n }\n \n /* ********** */\n\n for(i=0; (i ja3_str_len); i++) {\n\tint rc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \"%s%u\", (i > 0) ? \"-\" : \"\", ja3.server.tls_extension[i]);\n\n\tif(rc <= 0) break; else ja3_str_len += rc;\n }\n\n if(ndpi_struct->enable_ja3_plus) {\n\tfor(i=0; (i ja3_str_len); i++) {\n\t rc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \"%s%u\",\n\t\t\t(i > 0) ? \"-\" : \"\", ja3.server.elliptic_curve_point_format[i]);\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t}\n\n\tif((ja3.server.alpn[0] != '\\0') && (JA3_STR_LEN > ja3_str_len)) {\n\t rc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \",%s\", ja3.server.alpn);\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\t}\n\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3+] Server: %s \\n\", ja3_str);\n#endif\n } else {\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Server: %s \\n\", ja3_str);\n#endif\n }\n\n ndpi_MD5Init(&ctx);\n ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str));\n ndpi_MD5Final(md5_hash, &ctx);\n\n for(i=0, j=0; i<16; i++) {\n\tint rc = snprintf(&flow->protos.tls_quic_stun.tls_quic.ja3_server[j],\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.ja3_server)-j, \"%02x\", md5_hash[i]);\n\tif(rc <= 0) break; else j += rc;\n }\n\n#ifdef DEBUG_TLS\n printf(\"[JA3] Server: %s \\n\", flow->protos.tls_quic_stun.tls_quic.ja3_server);\n#endif\n } else if(handshake_type == 0x01 /* Client Hello */) {\n u_int16_t cipher_len, cipher_offset;\n u_int8_t cookie_len = 0;\n\n flow->protos.tls_quic_stun.tls_quic.ssl_version = ja3.client.tls_handshake_version = tls_version;\n if(flow->protos.tls_quic_stun.tls_quic.ssl_version < 0x0302) /* TLSv1.1 */\n\tndpi_set_risk(flow, NDPI_TLS_OBSOLETE_VERSION);\n\n if((session_id_len+base_offset+3) > packet->payload_packet_len)\n\treturn(0); /* Not found */\n\n if(!is_dtls) {\n\tcipher_len = packet->payload[session_id_len+base_offset+2] + (packet->payload[session_id_len+base_offset+1] << 8);\n\tcipher_offset = base_offset + session_id_len + 3;\n } else {\n\tcookie_len = packet->payload[base_offset+session_id_len+1];\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Client: DTLS cookie len %d\\n\", cookie_len);\n#endif\n\tif((session_id_len+base_offset+cookie_len+4) > packet->payload_packet_len)\n\t return(0); /* Not found */\n\tcipher_len = ntohs(*((u_int16_t*)&packet->payload[base_offset+session_id_len+cookie_len+2]));\n\tcipher_offset = base_offset + session_id_len + cookie_len + 4;\n }\n\n#ifdef DEBUG_TLS\n printf(\"Client TLS [client cipher_len: %u][tls_version: 0x%04X]\\n\", cipher_len, tls_version);\n#endif\n\n if((cipher_offset+cipher_len) <= total_len) {\n\tu_int8_t safari_ciphers = 0, chrome_ciphers = 0;\n\n\tfor(i=0; ipayload[cipher_offset+i];\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [cipher suite: %u/0x%04X] [%d/%u]\\n\", ntohs(*id), ntohs(*id), i, cipher_len);\n#endif\n\t if((*id == 0) || (packet->payload[cipher_offset+i] != packet->payload[cipher_offset+i+1])) {\n\t u_int16_t cipher_id = ntohs(*id);\n\t /*\n\t Skip GREASE [https://tools.ietf.org/id/draft-ietf-tls-grease-01.html]\n\t https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967\n\t */\n\n\t if(ja3.client.num_cipher < MAX_NUM_JA3)\n\t ja3.client.cipher[ja3.client.num_cipher++] = cipher_id;\n\t else {\n\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS Invalid cipher %u\\n\", ja3.client.num_cipher);\n#endif\n\t }\n\n\t switch(cipher_id) {\n\t case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:\n\t safari_ciphers++;\n\t break;\n\n\t case TLS_CIPHER_GREASE_RESERVED_0:\n\t case TLS_AES_128_GCM_SHA256:\n\t case TLS_AES_256_GCM_SHA384:\n\t case TLS_CHACHA20_POLY1305_SHA256:\n\t chrome_ciphers++;\n\t break;\n\n\t case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:\n\t case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:\n\t case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:\n\t case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:\n\t case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:\n\t case TLS_RSA_WITH_AES_128_CBC_SHA:\n\t case TLS_RSA_WITH_AES_256_CBC_SHA:\n\t case TLS_RSA_WITH_AES_128_GCM_SHA256:\n\t case TLS_RSA_WITH_AES_256_GCM_SHA384:\n\t safari_ciphers++, chrome_ciphers++;\n\t break;\n\t }\n\t }\n\n\t i += 2;\n\t} /* for */\n\n\tif(chrome_ciphers == 13)\n\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 1;\n\telse if(safari_ciphers == 12)\n\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 1;\n } else {\n\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\tprintf(\"Client TLS Invalid len %u vs %u\\n\", (cipher_offset+cipher_len), total_len);\n#endif\n }\n\n offset = base_offset + session_id_len + cookie_len + cipher_len + 2;\n offset += (!is_dtls) ? 1 : 2;\n\n if(offset < total_len) {\n\tu_int16_t compression_len;\n\tu_int16_t extensions_len;\n\n\tcompression_len = packet->payload[offset];\n\toffset++;\n\n#ifdef DEBUG_TLS\n\tprintf(\"Client TLS [compression_len: %u]\\n\", compression_len);\n#endif\n\n\t// offset += compression_len + 3;\n\toffset += compression_len;\n\n\tif(offset+1 < total_len) {\n\t extensions_len = ntohs(*((u_int16_t*)&packet->payload[offset]));\n\t offset += 2;\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extensions_len: %u]\\n\", extensions_len);\n#endif\n\n\t if((extensions_len+offset) <= total_len) {\n\t /* Move to the first extension\n\t Type is u_int to avoid possible overflow on extension_len addition */\n\t u_int extension_offset = 0;\n\t u_int32_t j;\n\n\t while(extension_offset < extensions_len &&\n\t\t offset+extension_offset+4 <= total_len) {\n\t u_int16_t extension_id, extension_len, extn_off = offset+extension_offset;\n\n\n\t extension_id = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset]));\n\t extension_offset += 2;\n\n\t extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset]));\n\t extension_offset += 2;\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extension_id: %u][extension_len: %u]\\n\", extension_id, extension_len);\n#endif\n\n\t if((extension_id == 0) || (packet->payload[extn_off] != packet->payload[extn_off+1])) {\n\t\t/* Skip GREASE */\n\n\t\tif(ja3.client.num_tls_extension < MAX_NUM_JA3)\n\t\t ja3.client.tls_extension[ja3.client.num_tls_extension++] = extension_id;\n\t\telse {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid extensions %u\\n\", ja3.client.num_tls_extension);\n#endif\n\t\t}\n\t }\n\n\t if(extension_id == 0 /* server name */) {\n\t\tu_int16_t len;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"[TLS] Extensions: found server name\\n\");\n#endif\n\t\tif((offset+extension_offset+4) < packet->payload_packet_len) {\n\n\t\t len = (packet->payload[offset+extension_offset+3] << 8) + packet->payload[offset+extension_offset+4];\n\t\t len = (u_int)ndpi_min(len, sizeof(buffer)-1);\n\n\t\t if((offset+extension_offset+5+len) <= packet->payload_packet_len) {\n\t\t strncpy(buffer, (char*)&packet->payload[offset+extension_offset+5], len);\n\t\t buffer[len] = '\\0';\n\n\t\t cleanupServerName(buffer, sizeof(buffer));\n\n\t\t snprintf(flow->protos.tls_quic_stun.tls_quic.client_requested_server_name,\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.client_requested_server_name),\n\t\t\t \"%s\", buffer);\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: [%s]\\n\", buffer);\n#endif\n\t\t if(!is_quic) {\n\t\t if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, buffer, strlen(buffer)))\n\t\t flow->l4.tcp.tls.subprotocol_detected = 1;\n\t\t } else {\n\t\t if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_QUIC, buffer, strlen(buffer)))\n\t\t flow->l4.tcp.tls.subprotocol_detected = 1;\n\t\t }\n\n\t\t if(ndpi_check_dga_name(ndpi_struct, flow,\n\t\t\t\t\t flow->protos.tls_quic_stun.tls_quic.client_requested_server_name, 1)) {\n\t\t char *sni = flow->protos.tls_quic_stun.tls_quic.client_requested_server_name;\n\t\t int len = strlen(sni);\n\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: (DGA) [%s]\\n\", flow->protos.tls_quic_stun.tls_quic.client_requested_server_name);\n#endif\n\n\t\t if((len >= 4)\n\t\t /* Check if it ends in .com or .net */\n\t\t && ((strcmp(&sni[len-4], \".com\") == 0) || (strcmp(&sni[len-4], \".net\") == 0))\n\t\t && (strncmp(sni, \"www.\", 4) == 0)) /* Not starting with www.... */\n\t\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TOR, NDPI_PROTOCOL_TLS);\n\t\t } else {\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] SNI: (NO DGA) [%s]\\n\", flow->protos.tls_quic_stun.tls_quic.client_requested_server_name);\n#endif\n\t\t }\n\t\t } else {\n#ifdef DEBUG_TLS\n\t\t printf(\"[TLS] Extensions server len too short: %u vs %u\\n\",\n\t\t\t offset+extension_offset+5+len,\n\t\t\t packet->payload_packet_len);\n#endif\n\t\t }\n\t\t}\n\t } else if(extension_id == 10 /* supported groups */) {\n\t\tu_int16_t s_offset = offset+extension_offset + 2;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [EllipticCurveGroups: len=%u]\\n\", extension_len);\n#endif\n\n\t\tif((s_offset+extension_len-2) <= total_len) {\n\t\t for(i=0; ipayload[s_offset+i]));\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [EllipticCurve: %u/0x%04X]\\n\", s_group, s_group);\n#endif\n\t\t if((s_group == 0) || (packet->payload[s_offset+i] != packet->payload[s_offset+i+1])) {\n\t\t /* Skip GREASE */\n\t\t if(ja3.client.num_elliptic_curve < MAX_NUM_JA3)\n\t\t\tja3.client.elliptic_curve[ja3.client.num_elliptic_curve++] = s_group;\n\t\t else {\n\t\t\tinvalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t\tprintf(\"Client TLS Invalid num elliptic %u\\n\", ja3.client.num_elliptic_curve);\n#endif\n\t\t }\n\t\t }\n\n\t\t i += 2;\n\t\t }\n\t\t} else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid len %u vs %u\\n\", (s_offset+extension_len-1), total_len);\n#endif\n\t\t}\n\t } else if(extension_id == 11 /* ec_point_formats groups */) {\n\t\tu_int16_t s_offset = offset+extension_offset + 1;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [EllipticCurveFormat: len=%u]\\n\", extension_len);\n#endif\n\t\tif((s_offset+extension_len-1) <= total_len) {\n\t\t for(i=0; ipayload[s_offset+i];\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [EllipticCurveFormat: %u]\\n\", s_group);\n#endif\n\n\t\t if(ja3.client.num_elliptic_curve_point_format < MAX_NUM_JA3)\n\t\t ja3.client.elliptic_curve_point_format[ja3.client.num_elliptic_curve_point_format++] = s_group;\n\t\t else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid num elliptic %u\\n\", ja3.client.num_elliptic_curve_point_format);\n#endif\n\t\t }\n\t\t }\n\t\t} else {\n\t\t invalid_ja3 = 1;\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS Invalid len %u vs %u\\n\", s_offset+extension_len, total_len);\n#endif\n\t\t}\n\t } else if(extension_id == 13 /* signature algorithms */) {\n\t\tu_int16_t s_offset = offset+extension_offset, safari_signature_algorithms = 0, chrome_signature_algorithms = 0;\n\t\tu_int16_t tot_signature_algorithms_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [SIGNATURE_ALGORITHMS: block_len=%u/len=%u]\\n\", extension_len, tot_signature_algorithms_len);\n#endif\n\n\t\ts_offset += 2;\n\t\ttot_signature_algorithms_len = ndpi_min((sizeof(ja3.client.signature_algorithms) / 2) - 1, tot_signature_algorithms_len);\n\n#ifdef TLS_HANDLE_SIGNATURE_ALGORITMS\n\t\tflow->protos.tls_quic_stun.tls_quic.num_tls_signature_algorithms = ndpi_min(tot_signature_algorithms_len / 2, MAX_NUM_TLS_SIGNATURE_ALGORITHMS);\n\n\t\tmemcpy(flow->protos.tls_quic_stun.tls_quic.client_signature_algorithms,\n\t\t &packet->payload[s_offset], 2 /* 16 bit */*flow->protos.tls_quic_stun.tls_quic.num_tls_signature_algorithms);\n#endif\n\n\t\tfor(i=0; ipayload[s_offset+i]);\n\n\t\t if(rc < 0) break;\n\t\t}\n\n\t\tfor(i=0; ipayload[s_offset+i]));\n\n\t\t // printf(\"=>> %04X\\n\", cipher_id);\n\n\t\t switch(cipher_id) {\n\t\t case ECDSA_SECP521R1_SHA512:\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_firefox_tls = 1;\n\t\t break;\n\n\t\t case ECDSA_SECP256R1_SHA256:\n\t\t case ECDSA_SECP384R1_SHA384:\n\t\t case RSA_PKCS1_SHA256:\n\t\t case RSA_PKCS1_SHA384:\n\t\t case RSA_PKCS1_SHA512:\n\t\t case RSA_PSS_RSAE_SHA256:\n\t\t case RSA_PSS_RSAE_SHA384:\n\t\t case RSA_PSS_RSAE_SHA512:\n\t\t chrome_signature_algorithms++, safari_signature_algorithms++;\n\t\t break;\n\t\t }\n\t\t}\n\n\t\tif(flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_firefox_tls)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 0,\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 0;\n\n\t\tif(safari_signature_algorithms != 8)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 0;\n\n\t\tif(chrome_signature_algorithms != 8)\n\t\t flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 0;\n\n\t\tja3.client.signature_algorithms[i*2] = '\\0';\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [SIGNATURE_ALGORITHMS: %s]\\n\", ja3.client.signature_algorithms);\n#endif\n\t } else if(extension_id == 16 /* application_layer_protocol_negotiation */) {\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tu_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\tchar alpn_str[256];\n\t\tu_int8_t alpn_str_len = 0, i;\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [ALPN: block_len=%u/len=%u]\\n\", extension_len, tot_alpn_len);\n#endif\n\t\ts_offset += 2;\n\t\ttot_alpn_len += s_offset;\n\n\t\twhile(s_offset < tot_alpn_len && s_offset < total_len) {\n\t\t u_int8_t alpn_i, alpn_len = packet->payload[s_offset++];\n\n\t\t if((s_offset + alpn_len) <= tot_alpn_len &&\n\t\t (s_offset + alpn_len) <= total_len) {\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [ALPN: %u]\\n\", alpn_len);\n#endif\n\n\t\t if((alpn_str_len+alpn_len+1) < (sizeof(alpn_str)-1)) {\n\t\t if(alpn_str_len > 0) {\n\t\t\talpn_str[alpn_str_len] = ',';\n\t\t\talpn_str_len++;\n\t\t }\n\n\t\t for(alpn_i=0; alpn_ipayload[s_offset+alpn_i];\n\n\t\t s_offset += alpn_len, alpn_str_len += alpn_len;;\n\t\t } else\n\t\t break;\n\t\t } else\n\t\t break;\n\t\t} /* while */\n\n\t\talpn_str[alpn_str_len] = '\\0';\n\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [ALPN: %s][len: %u]\\n\", alpn_str, alpn_str_len);\n#endif\n\t\tif(flow->protos.tls_quic_stun.tls_quic.alpn == NULL)\n\t\t flow->protos.tls_quic_stun.tls_quic.alpn = ndpi_strdup(alpn_str);\n\n\t\tsnprintf(ja3.client.alpn, sizeof(ja3.client.alpn), \"%s\", alpn_str);\n\n\t\t/* Replace , with - as in JA3 */\n\t\tfor(i=0; ja3.client.alpn[i] != '\\0'; i++)\n\t\t if(ja3.client.alpn[i] == ',') ja3.client.alpn[i] = '-';\n\n\t } else if(extension_id == 43 /* supported versions */) {\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tu_int8_t version_len = packet->payload[s_offset];\n\t\tchar version_str[256];\n\t\tu_int8_t version_str_len = 0;\n\t\tversion_str[0] = 0;\n#ifdef DEBUG_TLS\n\t\tprintf(\"Client TLS [TLS version len: %u]\\n\", version_len);\n#endif\n\n\t\tif(version_len == (extension_len-1)) {\n\t\t u_int8_t j;\n\t\t u_int16_t supported_versions_offset = 0;\n\n\t\t s_offset++;\n\n\t\t // careful not to overflow and loop forever with u_int8_t\n\t\t for(j=0; j+1payload[s_offset+j]));\n\t\t u_int8_t unknown_tls_version;\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [TLS version: %s/0x%04X]\\n\",\n\t\t\t ndpi_ssl_version2str(flow, tls_version, &unknown_tls_version), tls_version);\n#endif\n\n\t\t if((version_str_len+8) < sizeof(version_str)) {\n\t\t int rc = snprintf(&version_str[version_str_len],\n\t\t\t\t\tsizeof(version_str) - version_str_len, \"%s%s\",\n\t\t\t\t\t(version_str_len > 0) ? \",\" : \"\",\n\t\t\t\t\tndpi_ssl_version2str(flow, tls_version, &unknown_tls_version));\n\t\t if(rc <= 0)\n\t\t\tbreak;\n\t\t else\n\t\t\tversion_str_len += rc;\n\n\t\t rc = snprintf(&ja3.client.supported_versions[supported_versions_offset],\n\t\t\t\t sizeof(ja3.client.supported_versions)-supported_versions_offset,\n\t\t\t\t \"%s%04X\", (j > 0) ? \"-\" : \"\", tls_version);\n\n\t\t if(rc > 0)\n\t\t\tsupported_versions_offset += rc;\n\t\t }\n\t\t }\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [SUPPORTED_VERSIONS: %s]\\n\", ja3.client.supported_versions);\n#endif\n\n\t\t if(flow->protos.tls_quic_stun.tls_quic.tls_supported_versions == NULL)\n\t\t flow->protos.tls_quic_stun.tls_quic.tls_supported_versions = ndpi_strdup(version_str);\n\t\t}\n\t } else if(extension_id == 65486 /* encrypted server name */) {\n\t\t/*\n\t\t - https://tools.ietf.org/html/draft-ietf-tls-esni-06\n\t\t - https://blog.cloudflare.com/encrypted-sni/\n\t\t*/\n\t\tu_int16_t e_offset = offset+extension_offset;\n\t\tu_int16_t initial_offset = e_offset;\n\t\tu_int16_t e_sni_len, cipher_suite = ntohs(*((u_int16_t*)&packet->payload[e_offset]));\n\n\t\tflow->protos.tls_quic_stun.tls_quic.encrypted_sni.cipher_suite = cipher_suite;\n\n\t\te_offset += 2; /* Cipher suite len */\n\n\t\t/* Key Share Entry */\n\t\te_offset += 2; /* Group */\n\t\te_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */\n\n\t\tif((e_offset+4) < packet->payload_packet_len) {\n\t\t /* Record Digest */\n\t\t e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */\n\n\t\t if((e_offset+4) < packet->payload_packet_len) {\n\t\t e_sni_len = ntohs(*((u_int16_t*)&packet->payload[e_offset]));\n\t\t e_offset += 2;\n\n\t\t if((e_offset+e_sni_len-extension_len-initial_offset) >= 0 &&\n\t\t e_offset+e_sni_len < packet->payload_packet_len) {\n#ifdef DEBUG_ENCRYPTED_SNI\n\t\t printf(\"Client TLS [Encrypted Server Name len: %u]\\n\", e_sni_len);\n#endif\n\n\t\t if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni == NULL) {\n\t\t\tflow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni = (char*)ndpi_malloc(e_sni_len*2+1);\n\n\t\t\tif(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni) {\n\t\t\t u_int16_t i, off;\n\n\t\t\t for(i=e_offset, off=0; i<(e_offset+e_sni_len); i++) {\n\t\t\t int rc = sprintf(&flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni[off], \"%02X\", packet->payload[i] & 0XFF);\n\n\t\t\t if(rc <= 0) {\n\t\t\t flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni[off] = '\\0';\n\t\t\t break;\n\t\t\t } else\n\t\t\t off += rc;\n\t\t\t }\n\t\t\t}\n\t\t }\n\t\t }\n\t\t }\n\t\t}\n\t } else if(extension_id == 65445 || /* QUIC transport parameters (drafts version) */\n\t\t extension_id == 57) { /* QUIC transport parameters (final version) */\n\t\tu_int16_t s_offset = offset+extension_offset;\n\t\tuint16_t final_offset;\n\t\tint using_var_int = is_version_with_var_int_transport_params(quic_version);\n\n\t\tif(!using_var_int) {\n\t\t if(s_offset+1 >= total_len) {\n\t\t final_offset = 0; /* Force skipping extension */\n\t\t } else {\n\t\t u_int16_t seq_len = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\t s_offset += 2;\n\t final_offset = MIN(total_len, s_offset + seq_len);\n\t\t }\n\t\t} else {\n\t final_offset = MIN(total_len, s_offset + extension_len);\n\t\t}\n\n\t\twhile(s_offset < final_offset) {\n\t\t u_int64_t param_type, param_len;\n\n if(!using_var_int) {\n\t\t if(s_offset+3 >= final_offset)\n\t\t break;\n\t\t param_type = ntohs(*((u_int16_t*)&packet->payload[s_offset]));\n\t\t param_len = ntohs(*((u_int16_t*)&packet->payload[s_offset + 2]));\n\t\t s_offset += 4;\n\t\t } else {\n\t\t if(s_offset >= final_offset ||\n\t\t (s_offset + quic_len_buffer_still_required(packet->payload[s_offset])) >= final_offset)\n\t\t break;\n\t\t s_offset += quic_len(&packet->payload[s_offset], ¶m_type);\n\n\t\t if(s_offset >= final_offset ||\n\t\t (s_offset + quic_len_buffer_still_required(packet->payload[s_offset])) >= final_offset)\n\t\t break;\n\t\t s_offset += quic_len(&packet->payload[s_offset], ¶m_len);\n\t\t }\n\n#ifdef DEBUG_TLS\n\t\t printf(\"Client TLS [QUIC TP: Param 0x%x Len %d]\\n\", (int)param_type, (int)param_len);\n#endif\n\t\t if(s_offset+param_len > final_offset)\n\t\t break;\n\n\t\t if(param_type==0x3129) {\n#ifdef DEBUG_TLS\n\t\t printf(\"UA [%.*s]\\n\", (int)param_len, &packet->payload[s_offset]);\n#endif\n\t\t http_process_user_agent(ndpi_struct, flow,\n\t\t\t\t\t &packet->payload[s_offset], param_len);\n\t\t break;\n\t\t }\n\t\t s_offset += param_len;\n\t\t}\n\t }\n\n\t extension_offset += extension_len; /* Move to the next extension */\n\n#ifdef DEBUG_TLS\n\t printf(\"Client TLS [extension_offset/len: %u/%u]\\n\", extension_offset, extension_len);\n#endif\n\t } /* while */\n\n\t if(!invalid_ja3) {\n\t int rc;\n\n\t compute_ja3c:\n\t ja3_str_len = snprintf(ja3_str, JA3_STR_LEN, \"%u,\", ja3.client.tls_handshake_version);\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.cipher[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t /* ********** */\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.tls_extension[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t /* ********** */\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.elliptic_curve[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t rc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len, \",\");\n\t if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\n\t for(i=0; i 0) ? \"-\" : \"\", ja3.client.elliptic_curve_point_format[i]);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break;\n\t }\n\n\t if(ndpi_struct->enable_ja3_plus) {\n\t\trc = snprintf(&ja3_str[ja3_str_len], JA3_STR_LEN-ja3_str_len,\n\t\t\t \",%s,%s,%s\", ja3.client.signature_algorithms, ja3.client.supported_versions, ja3.client.alpn);\n\t\tif((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc;\n\t }\n\n#ifdef DEBUG_JA3C\n\t printf(\"[JA3+] Client: %s \\n\", ja3_str);\n#endif\n\n\t ndpi_MD5Init(&ctx);\n\t ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str));\n\t ndpi_MD5Final(md5_hash, &ctx);\n\n\t for(i=0, j=0; i<16; i++) {\n\t\trc = snprintf(&flow->protos.tls_quic_stun.tls_quic.ja3_client[j],\n\t\t\t sizeof(flow->protos.tls_quic_stun.tls_quic.ja3_client)-j, \"%02x\",\n\t\t\t md5_hash[i]);\n\t\tif(rc > 0) j += rc; else break;\n\t }\n\n#ifdef DEBUG_JA3C\n\t printf(\"[JA3] Client: %s \\n\", flow->protos.tls_quic_stun.tls_quic.ja3_client);\n#endif\n\n\t if(ndpi_struct->malicious_ja3_automa.ac_automa != NULL) {\n\t\tu_int16_t rc1 = ndpi_match_string(ndpi_struct->malicious_ja3_automa.ac_automa,\n\t\t\t\t\t\t flow->protos.tls_quic_stun.tls_quic.ja3_client);\n\n\t\tif(rc1 > 0)\n\t\t ndpi_set_risk(flow, NDPI_MALICIOUS_JA3);\n\t }\n\t }\n\n\t /* Before returning to the caller we need to make a final check */\n\t if((flow->protos.tls_quic_stun.tls_quic.ssl_version >= 0x0303) /* >= TLSv1.2 */\n\t && (flow->protos.tls_quic_stun.tls_quic.alpn == NULL) /* No ALPN */) {\n\t ndpi_set_risk(flow, NDPI_TLS_NOT_CARRYING_HTTPS);\n\t }\n\n\t /* Suspicious Domain Fronting:\n\t https://github.com/SixGenInc/Noctilucent/blob/master/docs/ */\n\t if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni &&\n\t flow->protos.tls_quic_stun.tls_quic.client_requested_server_name[0] != '\\0') {\n\t ndpi_set_risk(flow, NDPI_TLS_SUSPICIOUS_ESNI_USAGE);\n\t }\n\n\t /* Add check for missing SNI */\n\t if((flow->protos.tls_quic_stun.tls_quic.client_requested_server_name[0] == 0)\n\t && (flow->protos.tls_quic_stun.tls_quic.ssl_version >= 0x0302) /* TLSv1.1 */\n\t && (flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni == NULL) /* No ESNI */\n\t ) {\n\t /* This is a bit suspicious */\n\t ndpi_set_risk(flow, NDPI_TLS_MISSING_SNI);\n\t }\n\n\t return(2 /* Client Certificate */);\n\t } else {\n#ifdef DEBUG_TLS\n\t printf(\"[TLS] Client: too short [%u vs %u]\\n\",\n\t\t (extensions_len+offset), total_len);\n#endif\n\t }\n\t} else if(offset == total_len) {\n\t /* TLS does not have extensions etc */\n\t goto compute_ja3c;\n\t}\n } else {\n#ifdef DEBUG_TLS\n\tprintf(\"[JA3] Client: invalid length detected\\n\");\n#endif\n }\n }\n }\n\n return(0); /* Not found */\n}", "project": "nDPI", "hash": 178466311908364350569618120682794749914, "size": 943, "commit_id": "1ec621c85b9411cc611652fd57a892cfef478af3", "message": "Added further checks", "target": 0, "dataset": "other", "idx": 234082} {"func": "static int decode_nfs_fh(struct xdr_stream *xdr, struct nfs_fh *fh)\n{\n\t__be32 *p;\n\n\tp = xdr_inline_decode(xdr, 4);\n\tif (unlikely(!p))\n\t\treturn -ENOBUFS;\n\tfh->size = be32_to_cpup(p++);\n\tif (fh->size > sizeof(struct nfs_fh)) {\n\t\tprintk(KERN_ERR \"NFS flexfiles: Too big fh received %d\\n\",\n\t\t fh->size);\n\t\treturn -EOVERFLOW;\n\t}\n\t/* fh.data */\n\tp = xdr_inline_decode(xdr, fh->size);\n\tif (unlikely(!p))\n\t\treturn -ENOBUFS;\n\tmemcpy(&fh->data, p, fh->size);\n\tdprintk(\"%s: fh len %d\\n\", __func__, fh->size);\n\n\treturn 0;\n}", "project": "linux", "hash": 234844035562921129628265308957208614973, "size": 22, "commit_id": "ed34695e15aba74f45247f1ee2cf7e09d449f925", "message": "pNFS/flexfiles: fix incorrect size check in decode_nfs_fh()\n\nWe (adam zabrocki, alexander matrosov, alexander tereshkin, maksym\nbazalii) observed the check:\n\n\tif (fh->size > sizeof(struct nfs_fh))\n\nshould not use the size of the nfs_fh struct which includes an extra two\nbytes from the size field.\n\nstruct nfs_fh {\n\tunsigned short size;\n\tunsigned char data[NFS_MAXFHSIZE];\n}\n\nbut should determine the size from data[NFS_MAXFHSIZE] so the memcpy\nwill not write 2 bytes beyond destination. The proposed fix is to\ncompare against the NFS_MAXFHSIZE directly, as is done elsewhere in fs\ncode base.\n\nFixes: d67ae825a59d (\"pnfs/flexfiles: Add the FlexFile Layout Driver\")\nSigned-off-by: Nikola Livic \nSigned-off-by: Dan Carpenter \nSigned-off-by: Trond Myklebust ", "target": 1, "dataset": "other", "idx": 195843} {"func": "static int decode_nfs_fh(struct xdr_stream *xdr, struct nfs_fh *fh)\n{\n\t__be32 *p;\n\n\tp = xdr_inline_decode(xdr, 4);\n\tif (unlikely(!p))\n\t\treturn -ENOBUFS;\n\tfh->size = be32_to_cpup(p++);\n\tif (fh->size > NFS_MAXFHSIZE) {\n\t\tprintk(KERN_ERR \"NFS flexfiles: Too big fh received %d\\n\",\n\t\t fh->size);\n\t\treturn -EOVERFLOW;\n\t}\n\t/* fh.data */\n\tp = xdr_inline_decode(xdr, fh->size);\n\tif (unlikely(!p))\n\t\treturn -ENOBUFS;\n\tmemcpy(&fh->data, p, fh->size);\n\tdprintk(\"%s: fh len %d\\n\", __func__, fh->size);\n\n\treturn 0;\n}", "project": "linux", "hash": 53704026130374252810142557328449284293, "size": 22, "commit_id": "ed34695e15aba74f45247f1ee2cf7e09d449f925", "message": "pNFS/flexfiles: fix incorrect size check in decode_nfs_fh()\n\nWe (adam zabrocki, alexander matrosov, alexander tereshkin, maksym\nbazalii) observed the check:\n\n\tif (fh->size > sizeof(struct nfs_fh))\n\nshould not use the size of the nfs_fh struct which includes an extra two\nbytes from the size field.\n\nstruct nfs_fh {\n\tunsigned short size;\n\tunsigned char data[NFS_MAXFHSIZE];\n}\n\nbut should determine the size from data[NFS_MAXFHSIZE] so the memcpy\nwill not write 2 bytes beyond destination. The proposed fix is to\ncompare against the NFS_MAXFHSIZE directly, as is done elsewhere in fs\ncode base.\n\nFixes: d67ae825a59d (\"pnfs/flexfiles: Add the FlexFile Layout Driver\")\nSigned-off-by: Nikola Livic \nSigned-off-by: Dan Carpenter \nSigned-off-by: Trond Myklebust ", "target": 0, "dataset": "other", "idx": 234482} {"func": " void DoRealForwardFFT(OpKernelContext* ctx, uint64* fft_shape,\n const Tensor& in, Tensor* out) {\n // Create the axes (which are always trailing).\n const auto axes = Eigen::ArrayXi::LinSpaced(FFTRank, 1, FFTRank);\n auto device = ctx->eigen_device();\n auto input = Tensor(in).flat_inner_dims();\n const auto input_dims = input.dimensions();\n\n // Slice input to fft_shape on its inner-most dimensions.\n Eigen::DSizes input_slice_sizes;\n input_slice_sizes[0] = input_dims[0];\n TensorShape temp_shape{input_dims[0]};\n for (int i = 1; i <= FFTRank; ++i) {\n input_slice_sizes[i] = fft_shape[i - 1];\n temp_shape.AddDim(fft_shape[i - 1]);\n }\n\n auto output = out->flat_inner_dims();\n const Eigen::DSizes zero_start_indices;\n\n // Compute the full FFT using a temporary tensor.\n Tensor temp;\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::v(),\n temp_shape, &temp));\n auto full_fft = temp.flat_inner_dims();\n full_fft.device(device) =\n input.slice(zero_start_indices, input_slice_sizes)\n .template fft(axes);\n\n // Slice away the negative frequency components.\n output.device(device) =\n full_fft.slice(zero_start_indices, output.dimensions());\n }", "project": "tensorflow", "hash": 280992516761239439019736638647860473416, "size": 33, "commit_id": "31bd5026304677faa8a0b77602c6154171b9aec1", "message": "Prevent check fail in FFT\n\nPiperOrigin-RevId: 372031044\nChange-Id: I50994e3e8a5d1342d01bde80256f6bf2730ca299", "target": 1, "dataset": "other", "idx": 195958} {"func": " void DoRealForwardFFT(OpKernelContext* ctx, uint64* fft_shape,\n const Tensor& in, Tensor* out) {\n // Create the axes (which are always trailing).\n const auto axes = Eigen::ArrayXi::LinSpaced(FFTRank, 1, FFTRank);\n auto device = ctx->eigen_device();\n auto input = Tensor(in).flat_inner_dims();\n const auto input_dims = input.dimensions();\n\n // Slice input to fft_shape on its inner-most dimensions.\n Eigen::DSizes input_slice_sizes;\n input_slice_sizes[0] = input_dims[0];\n TensorShape temp_shape{input_dims[0]};\n for (int i = 1; i <= FFTRank; ++i) {\n input_slice_sizes[i] = fft_shape[i - 1];\n temp_shape.AddDim(fft_shape[i - 1]);\n }\n OP_REQUIRES(ctx, temp_shape.num_elements() > 0,\n errors::InvalidArgument(\"Obtained a FFT shape of 0 elements: \",\n temp_shape.DebugString()));\n\n auto output = out->flat_inner_dims();\n const Eigen::DSizes zero_start_indices;\n\n // Compute the full FFT using a temporary tensor.\n Tensor temp;\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::v(),\n temp_shape, &temp));\n auto full_fft = temp.flat_inner_dims();\n full_fft.device(device) =\n input.slice(zero_start_indices, input_slice_sizes)\n .template fft(axes);\n\n // Slice away the negative frequency components.\n output.device(device) =\n full_fft.slice(zero_start_indices, output.dimensions());\n }", "project": "tensorflow", "hash": 309164948673975832942418971794723232104, "size": 36, "commit_id": "31bd5026304677faa8a0b77602c6154171b9aec1", "message": "Prevent check fail in FFT\n\nPiperOrigin-RevId: 372031044\nChange-Id: I50994e3e8a5d1342d01bde80256f6bf2730ca299", "target": 0, "dataset": "other", "idx": 235720} {"func": "bool initiate_stratum(struct pool *pool)\n{\n\tchar s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;\n\tjson_t *val = NULL, *res_val, *err_val;\n\tbool ret = false, recvd = false;\n\tjson_error_t err;\n\tint n2size;\n\n\tif (!setup_stratum_curl(pool))\n\t\tgoto out;\n\nresend:\n\tif (pool->sessionid)\n\t\tsprintf(s, \"{\\\"id\\\": %d, \\\"method\\\": \\\"mining.subscribe\\\", \\\"params\\\": [\\\"%s\\\"]}\", swork_id++, pool->sessionid);\n\telse\n\t\tsprintf(s, \"{\\\"id\\\": %d, \\\"method\\\": \\\"mining.subscribe\\\", \\\"params\\\": []}\", swork_id++);\n\n\tif (!__stratum_send(pool, s, strlen(s))) {\n\t\tapplog(LOG_DEBUG, \"Failed to send s in initiate_stratum\");\n\t\tgoto out;\n\t}\n\n\tif (!socket_full(pool, true)) {\n\t\tapplog(LOG_DEBUG, \"Timed out waiting for response in initiate_stratum\");\n\t\tgoto out;\n\t}\n\n\tsret = recv_line(pool);\n\tif (!sret)\n\t\tgoto out;\n\n\trecvd = true;\n\n\tval = JSON_LOADS(sret, &err);\n\tfree(sret);\n\tif (!val) {\n\t\tapplog(LOG_INFO, \"JSON decode failed(%d): %s\", err.line, err.text);\n\t\tgoto out;\n\t}\n\n\tres_val = json_object_get(val, \"result\");\n\terr_val = json_object_get(val, \"error\");\n\n\tif (!res_val || json_is_null(res_val) ||\n\t (err_val && !json_is_null(err_val))) {\n\t\tchar *ss;\n\n\t\tif (err_val)\n\t\t\tss = json_dumps(err_val, JSON_INDENT(3));\n\t\telse\n\t\t\tss = strdup(\"(unknown reason)\");\n\n\t\tapplog(LOG_INFO, \"JSON-RPC decode failed: %s\", ss);\n\n\t\tfree(ss);\n\n\t\tgoto out;\n\t}\n\n\tsessionid = json_array_string(json_array_get(res_val, 0), 1);\n\tif (!sessionid) {\n\t\tapplog(LOG_INFO, \"Failed to get sessionid in initiate_stratum\");\n\t\tgoto out;\n\t}\n\tnonce1 = json_array_string(res_val, 1);\n\tif (!nonce1) {\n\t\tapplog(LOG_INFO, \"Failed to get nonce1 in initiate_stratum\");\n\t\tfree(sessionid);\n\t\tgoto out;\n\t}\n\tn2size = json_integer_value(json_array_get(res_val, 2));\n\tif (!n2size) {\n\t\tapplog(LOG_INFO, \"Failed to get n2size in initiate_stratum\");\n\t\tfree(sessionid);\n\t\tfree(nonce1);\n\t\tgoto out;\n\t}\n\n\tmutex_lock(&pool->pool_lock);\n\tpool->sessionid = sessionid;\n\tfree(pool->nonce1);\n\tpool->nonce1 = nonce1;\n\tpool->n1_len = strlen(nonce1) / 2;\n\tpool->n2size = n2size;\n\tmutex_unlock(&pool->pool_lock);\n\n\tapplog(LOG_DEBUG, \"Pool %d stratum session id: %s\", pool->pool_no, pool->sessionid);\n\n\tret = true;\nout:\n\tif (val)\n\t\tjson_decref(val);\n\n\tif (ret) {\n\t\tif (!pool->stratum_url)\n\t\t\tpool->stratum_url = pool->sockaddr_url;\n\t\tpool->stratum_active = true;\n\t\tpool->swork.diff = 1;\n\t\tif (opt_protocol) {\n\t\t\tapplog(LOG_DEBUG, \"Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d\",\n\t\t\t pool->pool_no, pool->nonce1, pool->n2size);\n\t\t}\n\t} else {\n\t\tif (recvd && pool->sessionid) {\n\t\t\t/* Reset the sessionid used for stratum resuming in case the pool\n\t\t\t* does not support it, or does not know how to respond to the\n\t\t\t* presence of the sessionid parameter. */\n\t\t\tmutex_lock(&pool->pool_lock);\n\t\t\tfree(pool->sessionid);\n\t\t\tfree(pool->nonce1);\n\t\t\tpool->sessionid = pool->nonce1 = NULL;\n\t\t\tmutex_unlock(&pool->pool_lock);\n\t\t\tapplog(LOG_DEBUG, \"Failed to resume stratum, trying afresh\");\n\t\t\tgoto resend;\n\t\t}\n\t\tapplog(LOG_DEBUG, \"Initiate stratum failed\");\n\t\tif (pool->sock != INVSOCK) {\n\t\t\tshutdown(pool->sock, SHUT_RDWR);\n\t\t\tpool->sock = INVSOCK;\n\t\t}\n\t}\n\n\treturn ret;\n}", "project": "bfgminer", "hash": 53047281314977669876157597332818027856, "size": 124, "commit_id": "ff7f30129f15f7a2213f8ced0cd65c9a331493d9", "message": "Bugfix: initiate_stratum: Ensure extranonce2 size is not negative (which could lead to exploits later as too little memory gets allocated)\n\nThanks to Mick Ayzenberg for finding this!", "target": 1, "dataset": "other", "idx": 195966} {"func": "bool initiate_stratum(struct pool *pool)\n{\n\tchar s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;\n\tjson_t *val = NULL, *res_val, *err_val;\n\tbool ret = false, recvd = false;\n\tjson_error_t err;\n\tint n2size;\n\n\tif (!setup_stratum_curl(pool))\n\t\tgoto out;\n\nresend:\n\tif (pool->sessionid)\n\t\tsprintf(s, \"{\\\"id\\\": %d, \\\"method\\\": \\\"mining.subscribe\\\", \\\"params\\\": [\\\"%s\\\"]}\", swork_id++, pool->sessionid);\n\telse\n\t\tsprintf(s, \"{\\\"id\\\": %d, \\\"method\\\": \\\"mining.subscribe\\\", \\\"params\\\": []}\", swork_id++);\n\n\tif (!__stratum_send(pool, s, strlen(s))) {\n\t\tapplog(LOG_DEBUG, \"Failed to send s in initiate_stratum\");\n\t\tgoto out;\n\t}\n\n\tif (!socket_full(pool, true)) {\n\t\tapplog(LOG_DEBUG, \"Timed out waiting for response in initiate_stratum\");\n\t\tgoto out;\n\t}\n\n\tsret = recv_line(pool);\n\tif (!sret)\n\t\tgoto out;\n\n\trecvd = true;\n\n\tval = JSON_LOADS(sret, &err);\n\tfree(sret);\n\tif (!val) {\n\t\tapplog(LOG_INFO, \"JSON decode failed(%d): %s\", err.line, err.text);\n\t\tgoto out;\n\t}\n\n\tres_val = json_object_get(val, \"result\");\n\terr_val = json_object_get(val, \"error\");\n\n\tif (!res_val || json_is_null(res_val) ||\n\t (err_val && !json_is_null(err_val))) {\n\t\tchar *ss;\n\n\t\tif (err_val)\n\t\t\tss = json_dumps(err_val, JSON_INDENT(3));\n\t\telse\n\t\t\tss = strdup(\"(unknown reason)\");\n\n\t\tapplog(LOG_INFO, \"JSON-RPC decode failed: %s\", ss);\n\n\t\tfree(ss);\n\n\t\tgoto out;\n\t}\n\n\tsessionid = json_array_string(json_array_get(res_val, 0), 1);\n\tif (!sessionid) {\n\t\tapplog(LOG_INFO, \"Failed to get sessionid in initiate_stratum\");\n\t\tgoto out;\n\t}\n\tnonce1 = json_array_string(res_val, 1);\n\tif (!nonce1) {\n\t\tapplog(LOG_INFO, \"Failed to get nonce1 in initiate_stratum\");\n\t\tfree(sessionid);\n\t\tgoto out;\n\t}\n\tn2size = json_integer_value(json_array_get(res_val, 2));\n\tif (n2size < 1)\n\t{\n\t\tapplog(LOG_INFO, \"Failed to get n2size in initiate_stratum\");\n\t\tfree(sessionid);\n\t\tfree(nonce1);\n\t\tgoto out;\n\t}\n\n\tmutex_lock(&pool->pool_lock);\n\tpool->sessionid = sessionid;\n\tfree(pool->nonce1);\n\tpool->nonce1 = nonce1;\n\tpool->n1_len = strlen(nonce1) / 2;\n\tpool->n2size = n2size;\n\tmutex_unlock(&pool->pool_lock);\n\n\tapplog(LOG_DEBUG, \"Pool %d stratum session id: %s\", pool->pool_no, pool->sessionid);\n\n\tret = true;\nout:\n\tif (val)\n\t\tjson_decref(val);\n\n\tif (ret) {\n\t\tif (!pool->stratum_url)\n\t\t\tpool->stratum_url = pool->sockaddr_url;\n\t\tpool->stratum_active = true;\n\t\tpool->swork.diff = 1;\n\t\tif (opt_protocol) {\n\t\t\tapplog(LOG_DEBUG, \"Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d\",\n\t\t\t pool->pool_no, pool->nonce1, pool->n2size);\n\t\t}\n\t} else {\n\t\tif (recvd && pool->sessionid) {\n\t\t\t/* Reset the sessionid used for stratum resuming in case the pool\n\t\t\t* does not support it, or does not know how to respond to the\n\t\t\t* presence of the sessionid parameter. */\n\t\t\tmutex_lock(&pool->pool_lock);\n\t\t\tfree(pool->sessionid);\n\t\t\tfree(pool->nonce1);\n\t\t\tpool->sessionid = pool->nonce1 = NULL;\n\t\t\tmutex_unlock(&pool->pool_lock);\n\t\t\tapplog(LOG_DEBUG, \"Failed to resume stratum, trying afresh\");\n\t\t\tgoto resend;\n\t\t}\n\t\tapplog(LOG_DEBUG, \"Initiate stratum failed\");\n\t\tif (pool->sock != INVSOCK) {\n\t\t\tshutdown(pool->sock, SHUT_RDWR);\n\t\t\tpool->sock = INVSOCK;\n\t\t}\n\t}\n\n\treturn ret;\n}", "project": "bfgminer", "hash": 38082979272544137077318747389004597030, "size": 125, "commit_id": "ff7f30129f15f7a2213f8ced0cd65c9a331493d9", "message": "Bugfix: initiate_stratum: Ensure extranonce2 size is not negative (which could lead to exploits later as too little memory gets allocated)\n\nThanks to Mick Ayzenberg for finding this!", "target": 0, "dataset": "other", "idx": 235766} {"func": " void Compute(OpKernelContext *ctx) override {\n const Tensor *indices_t, *values_t, *shape_t, *dense_t;\n OP_REQUIRES_OK(ctx, ctx->input(\"sp_indices\", &indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"sp_values\", &values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"sp_shape\", &shape_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"dense\", &dense_t));\n\n // Validations.\n OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()),\n errors::InvalidArgument(\n \"Input sp_indices should be a matrix but received shape: \",\n indices_t->shape().DebugString()));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(values_t->shape()) &&\n TensorShapeUtils::IsVector(shape_t->shape()),\n errors::InvalidArgument(\n \"Inputs sp_values and sp_shape should be vectors \"\n \"but received shapes: \",\n values_t->shape().DebugString(), \" and \",\n shape_t->shape().DebugString()));\n OP_REQUIRES(\n ctx, values_t->dim_size(0) == indices_t->dim_size(0),\n errors::InvalidArgument(\n \"The first dimension of values and indices should match. (\",\n values_t->dim_size(0), \" vs. \", indices_t->dim_size(0), \")\"));\n\n const auto indices_mat = indices_t->matrix();\n const auto shape_vec = shape_t->vec();\n const auto lhs_dims = BCast::FromShape(TensorShape(shape_vec));\n const auto rhs_dims = BCast::FromShape(dense_t->shape());\n BCast b(lhs_dims, rhs_dims, false); // false for keeping the same num dims.\n\n // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal\n // to dims in rhs (from right to left).\n auto VecGreaterEq = [](ArraySlice lhs, ArraySlice rhs) {\n if (lhs.size() < rhs.size()) return false;\n for (size_t i = 0; i < rhs.size(); ++i) {\n if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false;\n }\n return true;\n };\n OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(),\n errors::InvalidArgument(\n \"SparseDenseBinaryOpShared broadcasts dense to sparse \"\n \"only; got incompatible shapes: [\",\n absl::StrJoin(lhs_dims, \",\"), \"] vs. [\",\n absl::StrJoin(rhs_dims, \",\"), \"]\"));\n\n Tensor *output_values = nullptr;\n Tensor dense_gathered;\n const int64 nnz = indices_t->dim_size(0);\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({nnz}), &output_values));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_temp(DataTypeToEnum::value, TensorShape({nnz}),\n &dense_gathered));\n\n // Pulls relevant entries from the dense side, with reshape and broadcasting\n // *of the dense side* taken into account. Use a TensorRef to avoid blowing\n // up memory.\n //\n // We can directly use the sparse indices to look up dense side, because\n // \"b.y_reshape()\" and \"b.y_bcast()\" are guaranteed to have rank \"ndims\".\n auto dense_gathered_flat = dense_gathered.flat();\n const int ndims = lhs_dims.size();\n switch (ndims) {\n#define CASE(NDIM) \\\n case NDIM: { \\\n TensorRef> rhs_ref = \\\n dense_t->shaped(b.y_reshape()) \\\n .broadcast(BCast::ToIndexArray(b.y_bcast())); \\\n Eigen::array idx; \\\n bool indices_valid = true; \\\n for (int i = 0; i < nnz; ++i) { \\\n for (int d = 0; d < NDIM; ++d) { \\\n idx[d] = internal::SubtleMustCopy(indices_mat(i, d)); \\\n if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) { \\\n indices_valid = false; \\\n } \\\n } \\\n OP_REQUIRES( \\\n ctx, indices_valid, \\\n errors::InvalidArgument(\"Provided indices are out-of-bounds w.r.t. \" \\\n \"dense side with broadcasted shape\")); \\\n dense_gathered_flat(i) = rhs_ref.coeff(idx); \\\n } \\\n break; \\\n }\n\n CASE(1);\n CASE(2);\n CASE(3);\n CASE(4);\n CASE(5);\n default:\n OP_REQUIRES(\n ctx, false,\n errors::InvalidArgument(\"Only tensors with ranks between 1 and 5 \"\n \"are currently supported. Tensor rank: \",\n ndims));\n#undef CASE\n }\n\n output_values->flat().device(ctx->eigen_device()) =\n values_t->flat().binaryExpr(dense_gathered_flat,\n typename Functor::func());\n }", "project": "tensorflow", "hash": 157920771574414128903170642379842966624, "size": 107, "commit_id": "d9204be9f49520cdaaeb2541d1dc5187b23f31d9", "message": "Disallow division by zero FPE in tf.raw_ops.SparseDenseCwiseDiv\n\nPiperOrigin-RevId: 383959809\nChange-Id: Ibe88458bdf66a686c93e354b8255dec94285c560", "target": 1, "dataset": "other", "idx": 195972} {"func": " void Compute(OpKernelContext *ctx) override {\n const Tensor *indices_t, *values_t, *shape_t, *dense_t;\n OP_REQUIRES_OK(ctx, ctx->input(\"sp_indices\", &indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"sp_values\", &values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"sp_shape\", &shape_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"dense\", &dense_t));\n\n // Validations.\n OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()),\n errors::InvalidArgument(\n \"Input sp_indices should be a matrix but received shape: \",\n indices_t->shape().DebugString()));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(values_t->shape()) &&\n TensorShapeUtils::IsVector(shape_t->shape()),\n errors::InvalidArgument(\n \"Inputs sp_values and sp_shape should be vectors \"\n \"but received shapes: \",\n values_t->shape().DebugString(), \" and \",\n shape_t->shape().DebugString()));\n OP_REQUIRES(\n ctx, values_t->dim_size(0) == indices_t->dim_size(0),\n errors::InvalidArgument(\n \"The first dimension of values and indices should match. (\",\n values_t->dim_size(0), \" vs. \", indices_t->dim_size(0), \")\"));\n\n const auto indices_mat = indices_t->matrix();\n const auto shape_vec = shape_t->vec();\n const auto lhs_dims = BCast::FromShape(TensorShape(shape_vec));\n const auto rhs_dims = BCast::FromShape(dense_t->shape());\n BCast b(lhs_dims, rhs_dims, false); // false for keeping the same num dims.\n\n // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal\n // to dims in rhs (from right to left).\n auto VecGreaterEq = [](ArraySlice lhs, ArraySlice rhs) {\n if (lhs.size() < rhs.size()) return false;\n for (size_t i = 0; i < rhs.size(); ++i) {\n if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false;\n }\n return true;\n };\n OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(),\n errors::InvalidArgument(\n \"SparseDenseBinaryOpShared broadcasts dense to sparse \"\n \"only; got incompatible shapes: [\",\n absl::StrJoin(lhs_dims, \",\"), \"] vs. [\",\n absl::StrJoin(rhs_dims, \",\"), \"]\"));\n\n Tensor *output_values = nullptr;\n Tensor dense_gathered;\n const int64 nnz = indices_t->dim_size(0);\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({nnz}), &output_values));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_temp(DataTypeToEnum::value, TensorShape({nnz}),\n &dense_gathered));\n bool op_is_div = false;\n if (absl::StrContains(ctx->op_kernel().type_string_view(), \"Div\")) {\n op_is_div = true;\n }\n // Pulls relevant entries from the dense side, with reshape and broadcasting\n // *of the dense side* taken into account. Use a TensorRef to avoid blowing\n // up memory.\n //\n // We can directly use the sparse indices to look up dense side, because\n // \"b.y_reshape()\" and \"b.y_bcast()\" are guaranteed to have rank \"ndims\".\n auto dense_gathered_flat = dense_gathered.flat();\n const int ndims = lhs_dims.size();\n switch (ndims) {\n#define CASE(NDIM) \\\n case NDIM: { \\\n TensorRef> rhs_ref = \\\n dense_t->shaped(b.y_reshape()) \\\n .broadcast(BCast::ToIndexArray(b.y_bcast())); \\\n Eigen::array idx; \\\n bool indices_valid = true; \\\n for (int i = 0; i < nnz; ++i) { \\\n for (int d = 0; d < NDIM; ++d) { \\\n idx[d] = internal::SubtleMustCopy(indices_mat(i, d)); \\\n if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) { \\\n indices_valid = false; \\\n } \\\n } \\\n OP_REQUIRES( \\\n ctx, indices_valid, \\\n errors::InvalidArgument(\"Provided indices are out-of-bounds w.r.t. \" \\\n \"dense side with broadcasted shape\")); \\\n dense_gathered_flat(i) = rhs_ref.coeff(idx); \\\n if (op_is_div) { \\\n OP_REQUIRES(ctx, dense_gathered_flat(i) != 0, \\\n errors::InvalidArgument( \\\n \"SparseDenseCwiseDiv cannot divide by zero,\" \\\n \"but input dense tensor contains zero \")); \\\n } \\\n } \\\n break; \\\n }\n\n CASE(1);\n CASE(2);\n CASE(3);\n CASE(4);\n CASE(5);\n default:\n OP_REQUIRES(\n ctx, false,\n errors::InvalidArgument(\"Only tensors with ranks between 1 and 5 \"\n \"are currently supported. Tensor rank: \",\n ndims));\n#undef CASE\n }\n\n output_values->flat().device(ctx->eigen_device()) =\n values_t->flat().binaryExpr(dense_gathered_flat,\n typename Functor::func());\n }", "project": "tensorflow", "hash": 76360371434450887584761667916814072129, "size": 116, "commit_id": "d9204be9f49520cdaaeb2541d1dc5187b23f31d9", "message": "Disallow division by zero FPE in tf.raw_ops.SparseDenseCwiseDiv\n\nPiperOrigin-RevId: 383959809\nChange-Id: Ibe88458bdf66a686c93e354b8255dec94285c560", "target": 0, "dataset": "other", "idx": 235840} {"func": "static GF_Err av1dmx_parse_flush_sample(GF_Filter *filter, GF_AV1DmxCtx *ctx)\n{\n\tu32 pck_size;\n\tGF_FilterPacket *pck;\n\tu8 *output;\n\n\tgf_bs_get_content_no_truncate(ctx->state.bs, &ctx->state.frame_obus, &pck_size, &ctx->state.frame_obus_alloc);\n\n\tif (!pck_size) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1Dmx] no frame OBU, skipping OBU\\n\"));\n\t\treturn GF_OK;\n\t}\n\n\tpck = gf_filter_pck_new_alloc(ctx->opid, pck_size, &output);\n\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, pck);\n\n\tgf_filter_pck_set_cts(pck, ctx->cts);\n\tgf_filter_pck_set_sap(pck, ctx->state.frame_state.key_frame ? GF_FILTER_SAP_1 : 0);\n\n\tmemcpy(output, ctx->state.frame_obus, pck_size);\n\n\tif (ctx->deps) {\n\t\tu8 flags = 0;\n\t\t//dependsOn\n\t\tflags = ( ctx->state.frame_state.key_frame) ? 2 : 1;\n\t\tflags <<= 2;\n\t\t//dependedOn\n\t \tflags |= ctx->state.frame_state.refresh_frame_flags ? 1 : 2;\n\t\tflags <<= 2;\n\t\t//hasRedundant\n\t \t//flags |= ctx->has_redundant ? 1 : 2;\n\t \tgf_filter_pck_set_dependency_flags(pck, flags);\n\t}\n\n\tgf_filter_pck_send(pck);\n\n\tav1dmx_update_cts(ctx);\n\tgf_av1_reset_state(&ctx->state, GF_FALSE);\n\n\treturn GF_OK;\n\n}", "project": "gpac", "hash": 124123704759614734447704073729222685997, "size": 42, "commit_id": "13dad7d5ef74ca2e6fe4010f5b03eb12e9bbe0ec", "message": "fixed #1719", "target": 1, "dataset": "other", "idx": 195985} {"func": "static GF_Err av1dmx_parse_flush_sample(GF_Filter *filter, GF_AV1DmxCtx *ctx)\n{\n\tu32 pck_size;\n\tGF_FilterPacket *pck;\n\tu8 *output;\n\n\tif (!ctx->opid)\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\n\tgf_bs_get_content_no_truncate(ctx->state.bs, &ctx->state.frame_obus, &pck_size, &ctx->state.frame_obus_alloc);\n\n\tif (!pck_size) {\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[AV1Dmx] no frame OBU, skipping OBU\\n\"));\n\t\treturn GF_OK;\n\t}\n\n\tpck = gf_filter_pck_new_alloc(ctx->opid, pck_size, &output);\n\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, pck);\n\n\tgf_filter_pck_set_cts(pck, ctx->cts);\n\tgf_filter_pck_set_sap(pck, ctx->state.frame_state.key_frame ? GF_FILTER_SAP_1 : 0);\n\n\tmemcpy(output, ctx->state.frame_obus, pck_size);\n\n\tif (ctx->deps) {\n\t\tu8 flags = 0;\n\t\t//dependsOn\n\t\tflags = ( ctx->state.frame_state.key_frame) ? 2 : 1;\n\t\tflags <<= 2;\n\t\t//dependedOn\n\t \tflags |= ctx->state.frame_state.refresh_frame_flags ? 1 : 2;\n\t\tflags <<= 2;\n\t\t//hasRedundant\n\t \t//flags |= ctx->has_redundant ? 1 : 2;\n\t \tgf_filter_pck_set_dependency_flags(pck, flags);\n\t}\n\n\tgf_filter_pck_send(pck);\n\n\tav1dmx_update_cts(ctx);\n\tgf_av1_reset_state(&ctx->state, GF_FALSE);\n\n\treturn GF_OK;\n\n}", "project": "gpac", "hash": 155851759706352627613263901786806712657, "size": 45, "commit_id": "13dad7d5ef74ca2e6fe4010f5b03eb12e9bbe0ec", "message": "fixed #1719", "target": 0, "dataset": "other", "idx": 236225} {"func": "NativeModule::NativeModule(const std::string& filename) : init(nullptr) {\n\tif (uv_dlopen(filename.c_str(), &lib) != 0) {\n\t\tthrow RuntimeGenericError(\"Failed to load module\");\n\t}\n\tif (uv_dlsym(&lib, \"InitForContext\", reinterpret_cast(&init)) != 0 || init == nullptr) {\n\t\tuv_dlclose(&lib);\n\t\tthrow RuntimeGenericError(\"Module is not isolated-vm compatible\");\n\t}\n}", "project": "isolated-vm", "hash": 137961370509523293475357475023661605207, "size": 9, "commit_id": "27151bfecc260e96714443613880e3b2e6596704", "message": "Disallow NativeModule creation unless main isolate", "target": 1, "dataset": "other", "idx": 195986} {"func": "NativeModule::NativeModule(const std::string& filename) : init(nullptr) {\n\tif (!IsolateEnvironment::GetCurrent()->IsDefault()) {\n\t\tthrow RuntimeGenericError(\"NativeModule may only be instantiated from default nodejs isolate\");\n\t}\n\tif (uv_dlopen(filename.c_str(), &lib) != 0) {\n\t\tthrow RuntimeGenericError(\"Failed to load module\");\n\t}\n\tif (uv_dlsym(&lib, \"InitForContext\", reinterpret_cast(&init)) != 0 || init == nullptr) {\n\t\tuv_dlclose(&lib);\n\t\tthrow RuntimeGenericError(\"Module is not isolated-vm compatible\");\n\t}\n}", "project": "isolated-vm", "hash": 331411135769016276128654023219291021075, "size": 12, "commit_id": "27151bfecc260e96714443613880e3b2e6596704", "message": "Disallow NativeModule creation unless main isolate", "target": 0, "dataset": "other", "idx": 236238} {"func": "codegen(codegen_scope *s, node *tree, int val)\n{\n int nt;\n int rlev = s->rlev;\n\n if (!tree) {\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n return;\n }\n\n s->rlev++;\n if (s->rlev > MRB_CODEGEN_LEVEL_MAX) {\n codegen_error(s, \"too complex expression\");\n }\n if (s->irep && s->filename_index != tree->filename_index) {\n mrb_sym fname = mrb_parser_get_filename(s->parser, s->filename_index);\n const char *filename = mrb_sym_name_len(s->mrb, fname, NULL);\n\n mrb_debug_info_append_file(s->mrb, s->irep->debug_info,\n filename, s->lines, s->debug_start_pos, s->pc);\n s->debug_start_pos = s->pc;\n s->filename_index = tree->filename_index;\n s->filename_sym = mrb_parser_get_filename(s->parser, tree->filename_index);\n }\n\n nt = nint(tree->car);\n s->lineno = tree->lineno;\n tree = tree->cdr;\n switch (nt) {\n case NODE_BEGIN:\n if (val && !tree) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n while (tree) {\n codegen(s, tree->car, tree->cdr ? NOVAL : val);\n tree = tree->cdr;\n }\n break;\n\n case NODE_RESCUE:\n {\n int noexc;\n uint32_t exend, pos1, pos2, tmp;\n struct loopinfo *lp;\n int catch_entry, begin, end;\n\n if (tree->car == NULL) goto exit;\n lp = loop_push(s, LOOP_BEGIN);\n lp->pc0 = new_label(s);\n catch_entry = catch_handler_new(s);\n begin = s->pc;\n codegen(s, tree->car, VAL);\n pop();\n lp->type = LOOP_RESCUE;\n end = s->pc;\n noexc = genjmp_0(s, OP_JMP);\n catch_handler_set(s, catch_entry, MRB_CATCH_RESCUE, begin, end, s->pc);\n tree = tree->cdr;\n exend = JMPLINK_START;\n pos1 = JMPLINK_START;\n if (tree->car) {\n node *n2 = tree->car;\n int exc = cursp();\n\n genop_1(s, OP_EXCEPT, exc);\n push();\n while (n2) {\n node *n3 = n2->car;\n node *n4 = n3->car;\n\n dispatch(s, pos1);\n pos2 = JMPLINK_START;\n do {\n if (n4 && n4->car && nint(n4->car->car) == NODE_SPLAT) {\n codegen(s, n4->car, VAL);\n gen_move(s, cursp(), exc, 0);\n push_n(2); pop_n(2); /* space for one arg and a block */\n pop();\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, __case_eqq)), 1);\n }\n else {\n if (n4) {\n codegen(s, n4->car, VAL);\n }\n else {\n genop_2(s, OP_GETCONST, cursp(), new_sym(s, MRB_SYM_2(s->mrb, StandardError)));\n push();\n }\n pop();\n genop_2(s, OP_RESCUE, exc, cursp());\n }\n tmp = genjmp2(s, OP_JMPIF, cursp(), pos2, val);\n pos2 = tmp;\n if (n4) {\n n4 = n4->cdr;\n }\n } while (n4);\n pos1 = genjmp_0(s, OP_JMP);\n dispatch_linked(s, pos2);\n\n pop();\n if (n3->cdr->car) {\n gen_assignment(s, n3->cdr->car, NULL, exc, NOVAL);\n }\n if (n3->cdr->cdr->car) {\n codegen(s, n3->cdr->cdr->car, val);\n if (val) pop();\n }\n tmp = genjmp(s, OP_JMP, exend);\n exend = tmp;\n n2 = n2->cdr;\n push();\n }\n if (pos1 != JMPLINK_START) {\n dispatch(s, pos1);\n genop_1(s, OP_RAISEIF, exc);\n }\n }\n pop();\n tree = tree->cdr;\n dispatch(s, noexc);\n if (tree->car) {\n codegen(s, tree->car, val);\n }\n else if (val) {\n push();\n }\n dispatch_linked(s, exend);\n loop_pop(s, NOVAL);\n }\n break;\n\n case NODE_ENSURE:\n if (!tree->cdr || !tree->cdr->cdr ||\n (nint(tree->cdr->cdr->car) == NODE_BEGIN &&\n tree->cdr->cdr->cdr)) {\n int catch_entry, begin, end, target;\n int idx;\n\n catch_entry = catch_handler_new(s);\n begin = s->pc;\n codegen(s, tree->car, val);\n end = target = s->pc;\n push();\n idx = cursp();\n genop_1(s, OP_EXCEPT, idx);\n push();\n codegen(s, tree->cdr->cdr, NOVAL);\n pop();\n genop_1(s, OP_RAISEIF, idx);\n pop();\n catch_handler_set(s, catch_entry, MRB_CATCH_ENSURE, begin, end, target);\n }\n else { /* empty ensure ignored */\n codegen(s, tree->car, val);\n }\n break;\n\n case NODE_LAMBDA:\n if (val) {\n int idx = lambda_body(s, tree, 1);\n\n genop_2(s, OP_LAMBDA, cursp(), idx);\n push();\n }\n break;\n\n case NODE_BLOCK:\n if (val) {\n int idx = lambda_body(s, tree, 1);\n\n genop_2(s, OP_BLOCK, cursp(), idx);\n push();\n }\n break;\n\n case NODE_IF:\n {\n uint32_t pos1, pos2;\n mrb_bool nil_p = FALSE;\n node *elsepart = tree->cdr->cdr->car;\n\n if (!tree->car) {\n codegen(s, elsepart, val);\n goto exit;\n }\n if (true_always(tree->car)) {\n codegen(s, tree->cdr->car, val);\n goto exit;\n }\n if (false_always(tree->car)) {\n codegen(s, elsepart, val);\n goto exit;\n }\n if (nint(tree->car->car) == NODE_CALL) {\n node *n = tree->car->cdr;\n mrb_sym mid = nsym(n->cdr->car);\n mrb_sym sym_nil_p = MRB_SYM_Q_2(s->mrb, nil);\n if (mid == sym_nil_p && n->cdr->cdr->car == NULL) {\n nil_p = TRUE;\n codegen(s, n->car, VAL);\n }\n }\n if (!nil_p) {\n codegen(s, tree->car, VAL);\n }\n pop();\n if (val || tree->cdr->car) {\n if (nil_p) {\n pos2 = genjmp2_0(s, OP_JMPNIL, cursp(), val);\n pos1 = genjmp_0(s, OP_JMP);\n dispatch(s, pos2);\n }\n else {\n pos1 = genjmp2_0(s, OP_JMPNOT, cursp(), val);\n }\n codegen(s, tree->cdr->car, val);\n if (val) pop();\n if (elsepart || val) {\n pos2 = genjmp_0(s, OP_JMP);\n dispatch(s, pos1);\n codegen(s, elsepart, val);\n dispatch(s, pos2);\n }\n else {\n dispatch(s, pos1);\n }\n }\n else { /* empty then-part */\n if (elsepart) {\n if (nil_p) {\n pos1 = genjmp2_0(s, OP_JMPNIL, cursp(), val);\n }\n else {\n pos1 = genjmp2_0(s, OP_JMPIF, cursp(), val);\n }\n codegen(s, elsepart, val);\n dispatch(s, pos1);\n }\n else if (val && !nil_p) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n }\n break;\n\n case NODE_AND:\n {\n uint32_t pos;\n\n if (true_always(tree->car)) {\n codegen(s, tree->cdr, val);\n goto exit;\n }\n if (false_always(tree->car)) {\n codegen(s, tree->car, val);\n goto exit;\n }\n codegen(s, tree->car, VAL);\n pop();\n pos = genjmp2_0(s, OP_JMPNOT, cursp(), val);\n codegen(s, tree->cdr, val);\n dispatch(s, pos);\n }\n break;\n\n case NODE_OR:\n {\n uint32_t pos;\n\n if (true_always(tree->car)) {\n codegen(s, tree->car, val);\n goto exit;\n }\n if (false_always(tree->car)) {\n codegen(s, tree->cdr, val);\n goto exit;\n }\n codegen(s, tree->car, VAL);\n pop();\n pos = genjmp2_0(s, OP_JMPIF, cursp(), val);\n codegen(s, tree->cdr, val);\n dispatch(s, pos);\n }\n break;\n\n case NODE_WHILE:\n case NODE_UNTIL:\n {\n if (true_always(tree->car)) {\n if (nt == NODE_UNTIL) {\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n goto exit;\n }\n }\n else if (false_always(tree->car)) {\n if (nt == NODE_WHILE) {\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n goto exit;\n }\n }\n\n uint32_t pos = JMPLINK_START;\n struct loopinfo *lp = loop_push(s, LOOP_NORMAL);\n\n if (!val) lp->reg = -1;\n lp->pc0 = new_label(s);\n codegen(s, tree->car, VAL);\n pop();\n if (nt == NODE_WHILE) {\n pos = genjmp2_0(s, OP_JMPNOT, cursp(), NOVAL);\n }\n else {\n pos = genjmp2_0(s, OP_JMPIF, cursp(), NOVAL);\n }\n lp->pc1 = new_label(s);\n codegen(s, tree->cdr, NOVAL);\n genjmp(s, OP_JMP, lp->pc0);\n dispatch(s, pos);\n loop_pop(s, val);\n }\n break;\n\n case NODE_FOR:\n for_body(s, tree);\n if (val) push();\n break;\n\n case NODE_CASE:\n {\n int head = 0;\n uint32_t pos1, pos2, pos3, tmp;\n node *n;\n\n pos3 = JMPLINK_START;\n if (tree->car) {\n head = cursp();\n codegen(s, tree->car, VAL);\n }\n tree = tree->cdr;\n while (tree) {\n n = tree->car->car;\n pos1 = pos2 = JMPLINK_START;\n while (n) {\n codegen(s, n->car, VAL);\n if (head) {\n gen_move(s, cursp(), head, 0);\n push(); push(); pop(); pop(); pop();\n if (nint(n->car->car) == NODE_SPLAT) {\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, __case_eqq)), 1);\n }\n else {\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_OPSYM_2(s->mrb, eqq)), 1);\n }\n }\n else {\n pop();\n }\n tmp = genjmp2(s, OP_JMPIF, cursp(), pos2, NOVAL);\n pos2 = tmp;\n n = n->cdr;\n }\n if (tree->car->car) {\n pos1 = genjmp_0(s, OP_JMP);\n dispatch_linked(s, pos2);\n }\n codegen(s, tree->car->cdr, val);\n if (val) pop();\n tmp = genjmp(s, OP_JMP, pos3);\n pos3 = tmp;\n dispatch(s, pos1);\n tree = tree->cdr;\n }\n if (val) {\n uint32_t pos = cursp();\n genop_1(s, OP_LOADNIL, cursp());\n if (pos3 != JMPLINK_START) dispatch_linked(s, pos3);\n if (head) pop();\n if (cursp() != pos) {\n gen_move(s, cursp(), pos, 0);\n }\n push();\n }\n else {\n if (pos3 != JMPLINK_START) {\n dispatch_linked(s, pos3);\n }\n if (head) {\n pop();\n }\n }\n }\n break;\n\n case NODE_SCOPE:\n scope_body(s, tree, NOVAL);\n break;\n\n case NODE_FCALL:\n case NODE_CALL:\n gen_call(s, tree, val, 0);\n break;\n case NODE_SCALL:\n gen_call(s, tree, val, 1);\n break;\n\n case NODE_DOT2:\n codegen(s, tree->car, val);\n codegen(s, tree->cdr, val);\n if (val) {\n pop(); pop();\n genop_1(s, OP_RANGE_INC, cursp());\n push();\n }\n break;\n\n case NODE_DOT3:\n codegen(s, tree->car, val);\n codegen(s, tree->cdr, val);\n if (val) {\n pop(); pop();\n genop_1(s, OP_RANGE_EXC, cursp());\n push();\n }\n break;\n\n case NODE_COLON2:\n {\n int sym = new_sym(s, nsym(tree->cdr));\n\n codegen(s, tree->car, VAL);\n pop();\n genop_2(s, OP_GETMCNST, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_COLON3:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_1(s, OP_OCLASS, cursp());\n genop_2(s, OP_GETMCNST, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_ARRAY:\n {\n int n;\n\n n = gen_values(s, tree, val, 0);\n if (val) {\n if (n >= 0) {\n pop_n(n);\n genop_2(s, OP_ARRAY, cursp(), n);\n }\n push();\n }\n }\n break;\n\n case NODE_HASH:\n case NODE_KW_HASH:\n {\n int nk = gen_hash(s, tree, val, GEN_LIT_ARY_MAX);\n if (val && nk >= 0) {\n pop_n(nk*2);\n genop_2(s, OP_HASH, cursp(), nk);\n push();\n }\n }\n break;\n\n case NODE_SPLAT:\n codegen(s, tree, val);\n break;\n\n case NODE_ASGN:\n gen_assignment(s, tree->car, tree->cdr, 0, val);\n break;\n\n case NODE_MASGN:\n {\n int len = 0, n = 0, post = 0;\n node *t = tree->cdr, *p;\n int rhs = cursp();\n\n if (nint(t->car) == NODE_ARRAY && t->cdr && nosplat(t->cdr)) {\n /* fixed rhs */\n t = t->cdr;\n while (t) {\n codegen(s, t->car, VAL);\n len++;\n t = t->cdr;\n }\n tree = tree->car;\n if (tree->car) { /* pre */\n t = tree->car;\n n = 0;\n while (t) {\n if (n < len) {\n gen_assignment(s, t->car, NULL, rhs+n, NOVAL);\n n++;\n }\n else {\n genop_1(s, OP_LOADNIL, rhs+n);\n gen_assignment(s, t->car, NULL, rhs+n, NOVAL);\n }\n t = t->cdr;\n }\n }\n t = tree->cdr;\n if (t) {\n if (t->cdr) { /* post count */\n p = t->cdr->car;\n while (p) {\n post++;\n p = p->cdr;\n }\n }\n if (t->car) { /* rest (len - pre - post) */\n int rn;\n\n if (len < post + n) {\n rn = 0;\n }\n else {\n rn = len - post - n;\n }\n genop_3(s, OP_ARRAY2, cursp(), rhs+n, rn);\n gen_assignment(s, t->car, NULL, cursp(), NOVAL);\n n += rn;\n }\n if (t->cdr && t->cdr->car) {\n t = t->cdr->car;\n while (ncar, NULL, rhs+n, NOVAL);\n t = t->cdr;\n n++;\n }\n }\n }\n pop_n(len);\n if (val) {\n genop_2(s, OP_ARRAY, rhs, len);\n push();\n }\n }\n else {\n /* variable rhs */\n codegen(s, t, VAL);\n gen_vmassignment(s, tree->car, rhs, val);\n if (!val) {\n pop();\n }\n }\n }\n break;\n\n case NODE_OP_ASGN:\n {\n mrb_sym sym = nsym(tree->cdr->car);\n mrb_int len;\n const char *name = mrb_sym_name_len(s->mrb, sym, &len);\n int idx, callargs = -1, vsp = -1;\n\n if ((len == 2 && name[0] == '|' && name[1] == '|') &&\n (nint(tree->car->car) == NODE_CONST ||\n nint(tree->car->car) == NODE_CVAR)) {\n int catch_entry, begin, end;\n int noexc, exc;\n struct loopinfo *lp;\n\n lp = loop_push(s, LOOP_BEGIN);\n lp->pc0 = new_label(s);\n catch_entry = catch_handler_new(s);\n begin = s->pc;\n exc = cursp();\n codegen(s, tree->car, VAL);\n end = s->pc;\n noexc = genjmp_0(s, OP_JMP);\n lp->type = LOOP_RESCUE;\n catch_handler_set(s, catch_entry, MRB_CATCH_RESCUE, begin, end, s->pc);\n genop_1(s, OP_EXCEPT, exc);\n genop_1(s, OP_LOADF, exc);\n dispatch(s, noexc);\n loop_pop(s, NOVAL);\n }\n else if (nint(tree->car->car) == NODE_CALL) {\n node *n = tree->car->cdr;\n int base, i, nargs = 0;\n callargs = 0;\n\n if (val) {\n vsp = cursp();\n push();\n }\n codegen(s, n->car, VAL); /* receiver */\n idx = new_sym(s, nsym(n->cdr->car));\n base = cursp()-1;\n if (n->cdr->cdr->car) {\n nargs = gen_values(s, n->cdr->cdr->car->car, VAL, 13);\n if (nargs >= 0) {\n callargs = nargs;\n }\n else { /* varargs */\n push();\n nargs = 1;\n callargs = CALL_MAXARGS;\n }\n }\n /* copy receiver and arguments */\n gen_move(s, cursp(), base, 1);\n for (i=0; icar, VAL);\n }\n if (len == 2 &&\n ((name[0] == '|' && name[1] == '|') ||\n (name[0] == '&' && name[1] == '&'))) {\n uint32_t pos;\n\n pop();\n if (val) {\n if (vsp >= 0) {\n gen_move(s, vsp, cursp(), 1);\n }\n pos = genjmp2_0(s, name[0]=='|'?OP_JMPIF:OP_JMPNOT, cursp(), val);\n }\n else {\n pos = genjmp2_0(s, name[0]=='|'?OP_JMPIF:OP_JMPNOT, cursp(), val);\n }\n codegen(s, tree->cdr->cdr->car, VAL);\n pop();\n if (val && vsp >= 0) {\n gen_move(s, vsp, cursp(), 1);\n }\n if (nint(tree->car->car) == NODE_CALL) {\n if (callargs == CALL_MAXARGS) {\n pop();\n genop_2(s, OP_ARYPUSH, cursp(), 1);\n }\n else {\n pop_n(callargs);\n callargs++;\n }\n pop();\n idx = new_sym(s, attrsym(s, nsym(tree->car->cdr->cdr->car)));\n genop_3(s, OP_SEND, cursp(), idx, callargs);\n }\n else {\n gen_assignment(s, tree->car, NULL, cursp(), val);\n }\n dispatch(s, pos);\n goto exit;\n }\n codegen(s, tree->cdr->cdr->car, VAL);\n push(); pop();\n pop(); pop();\n\n if (len == 1 && name[0] == '+') {\n gen_addsub(s, OP_ADD, cursp());\n }\n else if (len == 1 && name[0] == '-') {\n gen_addsub(s, OP_SUB, cursp());\n }\n else if (len == 1 && name[0] == '*') {\n genop_1(s, OP_MUL, cursp());\n }\n else if (len == 1 && name[0] == '/') {\n genop_1(s, OP_DIV, cursp());\n }\n else if (len == 1 && name[0] == '<') {\n genop_1(s, OP_LT, cursp());\n }\n else if (len == 2 && name[0] == '<' && name[1] == '=') {\n genop_1(s, OP_LE, cursp());\n }\n else if (len == 1 && name[0] == '>') {\n genop_1(s, OP_GT, cursp());\n }\n else if (len == 2 && name[0] == '>' && name[1] == '=') {\n genop_1(s, OP_GE, cursp());\n }\n else {\n idx = new_sym(s, sym);\n genop_3(s, OP_SEND, cursp(), idx, 1);\n }\n if (callargs < 0) {\n gen_assignment(s, tree->car, NULL, cursp(), val);\n }\n else {\n if (val && vsp >= 0) {\n gen_move(s, vsp, cursp(), 0);\n }\n if (callargs == CALL_MAXARGS) {\n pop();\n genop_2(s, OP_ARYPUSH, cursp(), 1);\n }\n else {\n pop_n(callargs);\n callargs++;\n }\n pop();\n idx = new_sym(s, attrsym(s,nsym(tree->car->cdr->cdr->car)));\n genop_3(s, OP_SEND, cursp(), idx, callargs);\n }\n }\n break;\n\n case NODE_SUPER:\n {\n codegen_scope *s2 = s;\n int lv = 0;\n int n = 0, nk = 0, st = 0;\n\n push();\n while (!s2->mscope) {\n lv++;\n s2 = s2->prev;\n if (!s2) break;\n }\n if (tree) {\n node *args = tree->car;\n if (args) {\n st = n = gen_values(s, args, VAL, 14);\n if (n < 0) {\n st = 1; n = 15;\n push();\n }\n }\n /* keyword arguments */\n if (s2 && (s2->ainfo & 0x1) && tree->cdr->car) {\n nk = gen_hash(s, tree->cdr->car->cdr, VAL, 14);\n if (nk < 0) {st++; nk = 15;}\n else st += nk*2;\n n |= nk<<4;\n }\n /* block arguments */\n if (tree->cdr->cdr) {\n codegen(s, tree->cdr->cdr, VAL);\n }\n else if (!s2) {/* super at top-level */\n push(); /* no need to push block */\n }\n else {\n gen_blkmove(s, s2->ainfo, lv);\n }\n st++;\n }\n else {\n if (!s2) push();\n else gen_blkmove(s, s2->ainfo, lv);\n st++;\n }\n pop_n(st+1);\n genop_2(s, OP_SUPER, cursp(), n);\n if (val) push();\n }\n break;\n\n case NODE_ZSUPER:\n {\n codegen_scope *s2 = s;\n int lv = 0;\n uint16_t ainfo = 0;\n int n = CALL_MAXARGS;\n int sp = cursp();\n\n push(); /* room for receiver */\n while (!s2->mscope) {\n lv++;\n s2 = s2->prev;\n if (!s2) break;\n }\n if (s2 && s2->ainfo > 0) {\n ainfo = s2->ainfo;\n }\n if (ainfo > 0) {\n genop_2S(s, OP_ARGARY, cursp(), (ainfo<<4)|(lv & 0xf));\n push(); push(); push(); /* ARGARY pushes 3 values at most */\n pop(); pop(); pop();\n /* keyword arguments */\n if (ainfo & 0x1) {\n n |= CALL_MAXARGS<<4;\n push();\n }\n /* block argument */\n if (tree && tree->cdr && tree->cdr->cdr) {\n push();\n codegen(s, tree->cdr->cdr, VAL);\n }\n }\n else {\n /* block argument */\n if (tree && tree->cdr && tree->cdr->cdr) {\n codegen(s, tree->cdr->cdr, VAL);\n }\n else {\n gen_blkmove(s, 0, lv);\n }\n n = 0;\n }\n s->sp = sp;\n genop_2(s, OP_SUPER, cursp(), n);\n if (val) push();\n }\n break;\n\n case NODE_RETURN:\n if (tree) {\n gen_retval(s, tree);\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n }\n if (s->loop) {\n gen_return(s, OP_RETURN_BLK, cursp());\n }\n else {\n gen_return(s, OP_RETURN, cursp());\n }\n if (val) push();\n break;\n\n case NODE_YIELD:\n {\n codegen_scope *s2 = s;\n int lv = 0, ainfo = -1;\n int n = 0, sendv = 0;\n\n while (!s2->mscope) {\n lv++;\n s2 = s2->prev;\n if (!s2) break;\n }\n if (s2) {\n ainfo = (int)s2->ainfo;\n }\n if (ainfo < 0) codegen_error(s, \"invalid yield (SyntaxError)\");\n push();\n if (tree) {\n n = gen_values(s, tree, VAL, 14);\n if (n < 0) {\n n = sendv = 1;\n push();\n }\n }\n push();pop(); /* space for a block */\n pop_n(n+1);\n genop_2S(s, OP_BLKPUSH, cursp(), (ainfo<<4)|(lv & 0xf));\n if (sendv) n = CALL_MAXARGS;\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, call)), n);\n if (val) push();\n }\n break;\n\n case NODE_BREAK:\n loop_break(s, tree);\n if (val) push();\n break;\n\n case NODE_NEXT:\n if (!s->loop) {\n raise_error(s, \"unexpected next\");\n }\n else if (s->loop->type == LOOP_NORMAL) {\n codegen(s, tree, NOVAL);\n genjmp(s, OP_JMPUW, s->loop->pc0);\n }\n else {\n if (tree) {\n codegen(s, tree, VAL);\n pop();\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n }\n gen_return(s, OP_RETURN, cursp());\n }\n if (val) push();\n break;\n\n case NODE_REDO:\n if (!s->loop || s->loop->type == LOOP_BEGIN || s->loop->type == LOOP_RESCUE) {\n raise_error(s, \"unexpected redo\");\n }\n else {\n genjmp(s, OP_JMPUW, s->loop->pc1);\n }\n if (val) push();\n break;\n\n case NODE_RETRY:\n {\n const char *msg = \"unexpected retry\";\n const struct loopinfo *lp = s->loop;\n\n while (lp && lp->type != LOOP_RESCUE) {\n lp = lp->prev;\n }\n if (!lp) {\n raise_error(s, msg);\n }\n else {\n genjmp(s, OP_JMPUW, lp->pc0);\n }\n if (val) push();\n }\n break;\n\n case NODE_LVAR:\n if (val) {\n int idx = lv_idx(s, nsym(tree));\n\n if (idx > 0) {\n gen_move(s, cursp(), idx, val);\n }\n else {\n gen_getupvar(s, cursp(), nsym(tree));\n }\n push();\n }\n break;\n\n case NODE_NVAR:\n if (val) {\n int idx = nint(tree);\n\n gen_move(s, cursp(), idx, val);\n\n push();\n }\n break;\n\n case NODE_GVAR:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETGV, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_IVAR:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETIV, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_CVAR:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETCV, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_CONST:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETCONST, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_BACK_REF:\n if (val) {\n char buf[] = {'$', nchar(tree)};\n int sym = new_sym(s, mrb_intern(s->mrb, buf, sizeof(buf)));\n\n genop_2(s, OP_GETGV, cursp(), sym);\n push();\n }\n break;\n\n case NODE_NTH_REF:\n if (val) {\n mrb_state *mrb = s->mrb;\n mrb_value str;\n int sym;\n\n str = mrb_format(mrb, \"$%d\", nint(tree));\n sym = new_sym(s, mrb_intern_str(mrb, str));\n genop_2(s, OP_GETGV, cursp(), sym);\n push();\n }\n break;\n\n case NODE_ARG:\n /* should not happen */\n break;\n\n case NODE_BLOCK_ARG:\n if (!tree) {\n int idx = lv_idx(s, MRB_OPSYM_2(s->mrb, and));\n\n if (idx == 0) {\n codegen_error(s, \"no anonymous block argument\");\n }\n gen_move(s, cursp(), idx, val);\n }\n else {\n codegen(s, tree, val);\n }\n break;\n\n case NODE_INT:\n if (val) {\n char *p = (char*)tree->car;\n int base = nint(tree->cdr->car);\n mrb_int i;\n mrb_bool overflow;\n\n i = readint(s, p, base, FALSE, &overflow);\n if (overflow) {\n int off = new_litbn(s, p, base, FALSE);\n genop_2(s, OP_LOADL, cursp(), off);\n }\n else {\n gen_int(s, cursp(), i);\n }\n push();\n }\n break;\n\n#ifndef MRB_NO_FLOAT\n case NODE_FLOAT:\n if (val) {\n char *p = (char*)tree;\n mrb_float f = mrb_float_read(p, NULL);\n int off = new_lit(s, mrb_float_value(s->mrb, f));\n\n genop_2(s, OP_LOADL, cursp(), off);\n push();\n }\n break;\n#endif\n\n case NODE_NEGATE:\n {\n nt = nint(tree->car);\n switch (nt) {\n#ifndef MRB_NO_FLOAT\n case NODE_FLOAT:\n if (val) {\n char *p = (char*)tree->cdr;\n mrb_float f = mrb_float_read(p, NULL);\n int off = new_lit(s, mrb_float_value(s->mrb, -f));\n\n genop_2(s, OP_LOADL, cursp(), off);\n push();\n }\n break;\n#endif\n\n case NODE_INT:\n if (val) {\n char *p = (char*)tree->cdr->car;\n int base = nint(tree->cdr->cdr->car);\n mrb_int i;\n mrb_bool overflow;\n\n i = readint(s, p, base, TRUE, &overflow);\n if (overflow) {\n int off = new_litbn(s, p, base, TRUE);\n genop_2(s, OP_LOADL, cursp(), off);\n }\n else {\n gen_int(s, cursp(), i);\n }\n push();\n }\n break;\n\n default:\n if (val) {\n codegen(s, tree, VAL);\n pop();\n push_n(2);pop_n(2); /* space for receiver&block */\n mrb_sym minus = MRB_OPSYM_2(s->mrb, minus);\n if (!gen_uniop(s, minus, cursp())) {\n genop_3(s, OP_SEND, cursp(), new_sym(s, minus), 0);\n }\n push();\n }\n else {\n codegen(s, tree, NOVAL);\n }\n break;\n }\n }\n break;\n\n case NODE_STR:\n if (val) {\n char *p = (char*)tree->car;\n size_t len = (intptr_t)tree->cdr;\n int ai = mrb_gc_arena_save(s->mrb);\n int off = new_lit(s, mrb_str_new(s->mrb, p, len));\n\n mrb_gc_arena_restore(s->mrb, ai);\n genop_2(s, OP_STRING, cursp(), off);\n push();\n }\n break;\n\n case NODE_HEREDOC:\n tree = ((struct mrb_parser_heredoc_info *)tree)->doc;\n /* fall through */\n case NODE_DSTR:\n if (val) {\n node *n = tree;\n\n if (!n) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n break;\n }\n codegen(s, n->car, VAL);\n n = n->cdr;\n while (n) {\n codegen(s, n->car, VAL);\n pop(); pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n n = n->cdr;\n }\n }\n else {\n node *n = tree;\n\n while (n) {\n if (nint(n->car->car) != NODE_STR) {\n codegen(s, n->car, NOVAL);\n }\n n = n->cdr;\n }\n }\n break;\n\n case NODE_WORDS:\n gen_literal_array(s, tree, FALSE, val);\n break;\n\n case NODE_SYMBOLS:\n gen_literal_array(s, tree, TRUE, val);\n break;\n\n case NODE_DXSTR:\n {\n node *n;\n int ai = mrb_gc_arena_save(s->mrb);\n int sym = new_sym(s, MRB_SYM_2(s->mrb, Kernel));\n\n genop_1(s, OP_LOADSELF, cursp());\n push();\n codegen(s, tree->car, VAL);\n n = tree->cdr;\n while (n) {\n if (nint(n->car->car) == NODE_XSTR) {\n n->car->car = (struct mrb_ast_node*)(intptr_t)NODE_STR;\n mrb_assert(!n->cdr); /* must be the end */\n }\n codegen(s, n->car, VAL);\n pop(); pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n n = n->cdr;\n }\n push(); /* for block */\n pop_n(3);\n sym = new_sym(s, MRB_OPSYM_2(s->mrb, tick)); /* ` */\n genop_3(s, OP_SEND, cursp(), sym, 1);\n if (val) push();\n mrb_gc_arena_restore(s->mrb, ai);\n }\n break;\n\n case NODE_XSTR:\n {\n char *p = (char*)tree->car;\n size_t len = (intptr_t)tree->cdr;\n int ai = mrb_gc_arena_save(s->mrb);\n int off = new_lit(s, mrb_str_new(s->mrb, p, len));\n int sym;\n\n genop_1(s, OP_LOADSELF, cursp());\n push();\n genop_2(s, OP_STRING, cursp(), off);\n push(); push();\n pop_n(3);\n sym = new_sym(s, MRB_OPSYM_2(s->mrb, tick)); /* ` */\n genop_3(s, OP_SEND, cursp(), sym, 1);\n if (val) push();\n mrb_gc_arena_restore(s->mrb, ai);\n }\n break;\n\n case NODE_REGX:\n if (val) {\n char *p1 = (char*)tree->car;\n char *p2 = (char*)tree->cdr->car;\n char *p3 = (char*)tree->cdr->cdr;\n int ai = mrb_gc_arena_save(s->mrb);\n int sym = new_sym(s, mrb_intern_lit(s->mrb, REGEXP_CLASS));\n int off = new_lit(s, mrb_str_new_cstr(s->mrb, p1));\n int argc = 1;\n\n genop_1(s, OP_OCLASS, cursp());\n genop_2(s, OP_GETMCNST, cursp(), sym);\n push();\n genop_2(s, OP_STRING, cursp(), off);\n push();\n if (p2 || p3) {\n if (p2) { /* opt */\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));\n genop_2(s, OP_STRING, cursp(), off);\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n }\n push();\n argc++;\n if (p3) { /* enc */\n off = new_lit(s, mrb_str_new(s->mrb, p3, 1));\n genop_2(s, OP_STRING, cursp(), off);\n push();\n argc++;\n }\n }\n push(); /* space for a block */\n pop_n(argc+2);\n sym = new_sym(s, MRB_SYM_2(s->mrb, compile));\n genop_3(s, OP_SEND, cursp(), sym, argc);\n mrb_gc_arena_restore(s->mrb, ai);\n push();\n }\n break;\n\n case NODE_DREGX:\n if (val) {\n node *n = tree->car;\n int ai = mrb_gc_arena_save(s->mrb);\n int sym = new_sym(s, mrb_intern_lit(s->mrb, REGEXP_CLASS));\n int argc = 1;\n int off;\n char *p;\n\n genop_1(s, OP_OCLASS, cursp());\n genop_2(s, OP_GETMCNST, cursp(), sym);\n push();\n codegen(s, n->car, VAL);\n n = n->cdr;\n while (n) {\n codegen(s, n->car, VAL);\n pop(); pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n n = n->cdr;\n }\n n = tree->cdr->cdr;\n if (n->car) { /* tail */\n p = (char*)n->car;\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p));\n codegen(s, tree->car, VAL);\n genop_2(s, OP_STRING, cursp(), off);\n pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n }\n if (n->cdr->car) { /* opt */\n char *p2 = (char*)n->cdr->car;\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));\n genop_2(s, OP_STRING, cursp(), off);\n push();\n argc++;\n }\n if (n->cdr->cdr) { /* enc */\n char *p2 = (char*)n->cdr->cdr;\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));\n genop_2(s, OP_STRING, cursp(), off);\n push();\n argc++;\n }\n push(); /* space for a block */\n pop_n(argc+2);\n sym = new_sym(s, MRB_SYM_2(s->mrb, compile));\n genop_3(s, OP_SEND, cursp(), sym, argc);\n mrb_gc_arena_restore(s->mrb, ai);\n push();\n }\n else {\n node *n = tree->car;\n\n while (n) {\n if (nint(n->car->car) != NODE_STR) {\n codegen(s, n->car, NOVAL);\n }\n n = n->cdr;\n }\n }\n break;\n\n case NODE_SYM:\n if (val) {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_LOADSYM, cursp(), sym);\n push();\n }\n break;\n\n case NODE_DSYM:\n codegen(s, tree, val);\n if (val) {\n gen_intern(s);\n }\n break;\n\n case NODE_SELF:\n if (val) {\n genop_1(s, OP_LOADSELF, cursp());\n push();\n }\n break;\n\n case NODE_NIL:\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n break;\n\n case NODE_TRUE:\n if (val) {\n genop_1(s, OP_LOADT, cursp());\n push();\n }\n break;\n\n case NODE_FALSE:\n if (val) {\n genop_1(s, OP_LOADF, cursp());\n push();\n }\n break;\n\n case NODE_ALIAS:\n {\n int a = new_sym(s, nsym(tree->car));\n int b = new_sym(s, nsym(tree->cdr));\n\n genop_2(s, OP_ALIAS, a, b);\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n break;\n\n case NODE_UNDEF:\n {\n node *t = tree;\n\n while (t) {\n int symbol = new_sym(s, nsym(t->car));\n genop_1(s, OP_UNDEF, symbol);\n t = t->cdr;\n }\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n break;\n\n case NODE_CLASS:\n {\n int idx;\n node *body;\n\n if (tree->car->car == (node*)0) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n else if (tree->car->car == (node*)1) {\n genop_1(s, OP_OCLASS, cursp());\n push();\n }\n else {\n codegen(s, tree->car->car, VAL);\n }\n if (tree->cdr->car) {\n codegen(s, tree->cdr->car, VAL);\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n pop(); pop();\n idx = new_sym(s, nsym(tree->car->cdr));\n genop_2(s, OP_CLASS, cursp(), idx);\n body = tree->cdr->cdr->car;\n if (nint(body->cdr->car) == NODE_BEGIN && body->cdr->cdr == NULL) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n else {\n idx = scope_body(s, body, val);\n genop_2(s, OP_EXEC, cursp(), idx);\n }\n if (val) {\n push();\n }\n }\n break;\n\n case NODE_MODULE:\n {\n int idx;\n\n if (tree->car->car == (node*)0) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n else if (tree->car->car == (node*)1) {\n genop_1(s, OP_OCLASS, cursp());\n push();\n }\n else {\n codegen(s, tree->car->car, VAL);\n }\n pop();\n idx = new_sym(s, nsym(tree->car->cdr));\n genop_2(s, OP_MODULE, cursp(), idx);\n if (nint(tree->cdr->car->cdr->car) == NODE_BEGIN &&\n tree->cdr->car->cdr->cdr == NULL) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n else {\n idx = scope_body(s, tree->cdr->car, val);\n genop_2(s, OP_EXEC, cursp(), idx);\n }\n if (val) {\n push();\n }\n }\n break;\n\n case NODE_SCLASS:\n {\n int idx;\n\n codegen(s, tree->car, VAL);\n pop();\n genop_1(s, OP_SCLASS, cursp());\n if (nint(tree->cdr->car->cdr->car) == NODE_BEGIN &&\n tree->cdr->car->cdr->cdr == NULL) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n else {\n idx = scope_body(s, tree->cdr->car, val);\n genop_2(s, OP_EXEC, cursp(), idx);\n }\n if (val) {\n push();\n }\n }\n break;\n\n case NODE_DEF:\n {\n int sym = new_sym(s, nsym(tree->car));\n int idx = lambda_body(s, tree->cdr, 0);\n\n genop_1(s, OP_TCLASS, cursp());\n push();\n genop_2(s, OP_METHOD, cursp(), idx);\n push(); pop();\n pop();\n genop_2(s, OP_DEF, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_SDEF:\n {\n node *recv = tree->car;\n int sym = new_sym(s, nsym(tree->cdr->car));\n int idx = lambda_body(s, tree->cdr->cdr, 0);\n\n codegen(s, recv, VAL);\n pop();\n genop_1(s, OP_SCLASS, cursp());\n push();\n genop_2(s, OP_METHOD, cursp(), idx);\n pop();\n genop_2(s, OP_DEF, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_POSTEXE:\n codegen(s, tree, NOVAL);\n break;\n\n default:\n break;\n }\n exit:\n s->rlev = rlev;\n}", "project": "mruby", "hash": 230573661446267941821122200387226170788, "size": 1535, "commit_id": "44f591aa8f7091e6ca6cb418e428ae6d4ceaf77d", "message": "codegen.c: adjust stack position for `OP_SUPER` instruction.", "target": 1, "dataset": "other", "idx": 196318} {"func": "codegen(codegen_scope *s, node *tree, int val)\n{\n int nt;\n int rlev = s->rlev;\n\n if (!tree) {\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n return;\n }\n\n s->rlev++;\n if (s->rlev > MRB_CODEGEN_LEVEL_MAX) {\n codegen_error(s, \"too complex expression\");\n }\n if (s->irep && s->filename_index != tree->filename_index) {\n mrb_sym fname = mrb_parser_get_filename(s->parser, s->filename_index);\n const char *filename = mrb_sym_name_len(s->mrb, fname, NULL);\n\n mrb_debug_info_append_file(s->mrb, s->irep->debug_info,\n filename, s->lines, s->debug_start_pos, s->pc);\n s->debug_start_pos = s->pc;\n s->filename_index = tree->filename_index;\n s->filename_sym = mrb_parser_get_filename(s->parser, tree->filename_index);\n }\n\n nt = nint(tree->car);\n s->lineno = tree->lineno;\n tree = tree->cdr;\n switch (nt) {\n case NODE_BEGIN:\n if (val && !tree) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n while (tree) {\n codegen(s, tree->car, tree->cdr ? NOVAL : val);\n tree = tree->cdr;\n }\n break;\n\n case NODE_RESCUE:\n {\n int noexc;\n uint32_t exend, pos1, pos2, tmp;\n struct loopinfo *lp;\n int catch_entry, begin, end;\n\n if (tree->car == NULL) goto exit;\n lp = loop_push(s, LOOP_BEGIN);\n lp->pc0 = new_label(s);\n catch_entry = catch_handler_new(s);\n begin = s->pc;\n codegen(s, tree->car, VAL);\n pop();\n lp->type = LOOP_RESCUE;\n end = s->pc;\n noexc = genjmp_0(s, OP_JMP);\n catch_handler_set(s, catch_entry, MRB_CATCH_RESCUE, begin, end, s->pc);\n tree = tree->cdr;\n exend = JMPLINK_START;\n pos1 = JMPLINK_START;\n if (tree->car) {\n node *n2 = tree->car;\n int exc = cursp();\n\n genop_1(s, OP_EXCEPT, exc);\n push();\n while (n2) {\n node *n3 = n2->car;\n node *n4 = n3->car;\n\n dispatch(s, pos1);\n pos2 = JMPLINK_START;\n do {\n if (n4 && n4->car && nint(n4->car->car) == NODE_SPLAT) {\n codegen(s, n4->car, VAL);\n gen_move(s, cursp(), exc, 0);\n push_n(2); pop_n(2); /* space for one arg and a block */\n pop();\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, __case_eqq)), 1);\n }\n else {\n if (n4) {\n codegen(s, n4->car, VAL);\n }\n else {\n genop_2(s, OP_GETCONST, cursp(), new_sym(s, MRB_SYM_2(s->mrb, StandardError)));\n push();\n }\n pop();\n genop_2(s, OP_RESCUE, exc, cursp());\n }\n tmp = genjmp2(s, OP_JMPIF, cursp(), pos2, val);\n pos2 = tmp;\n if (n4) {\n n4 = n4->cdr;\n }\n } while (n4);\n pos1 = genjmp_0(s, OP_JMP);\n dispatch_linked(s, pos2);\n\n pop();\n if (n3->cdr->car) {\n gen_assignment(s, n3->cdr->car, NULL, exc, NOVAL);\n }\n if (n3->cdr->cdr->car) {\n codegen(s, n3->cdr->cdr->car, val);\n if (val) pop();\n }\n tmp = genjmp(s, OP_JMP, exend);\n exend = tmp;\n n2 = n2->cdr;\n push();\n }\n if (pos1 != JMPLINK_START) {\n dispatch(s, pos1);\n genop_1(s, OP_RAISEIF, exc);\n }\n }\n pop();\n tree = tree->cdr;\n dispatch(s, noexc);\n if (tree->car) {\n codegen(s, tree->car, val);\n }\n else if (val) {\n push();\n }\n dispatch_linked(s, exend);\n loop_pop(s, NOVAL);\n }\n break;\n\n case NODE_ENSURE:\n if (!tree->cdr || !tree->cdr->cdr ||\n (nint(tree->cdr->cdr->car) == NODE_BEGIN &&\n tree->cdr->cdr->cdr)) {\n int catch_entry, begin, end, target;\n int idx;\n\n catch_entry = catch_handler_new(s);\n begin = s->pc;\n codegen(s, tree->car, val);\n end = target = s->pc;\n push();\n idx = cursp();\n genop_1(s, OP_EXCEPT, idx);\n push();\n codegen(s, tree->cdr->cdr, NOVAL);\n pop();\n genop_1(s, OP_RAISEIF, idx);\n pop();\n catch_handler_set(s, catch_entry, MRB_CATCH_ENSURE, begin, end, target);\n }\n else { /* empty ensure ignored */\n codegen(s, tree->car, val);\n }\n break;\n\n case NODE_LAMBDA:\n if (val) {\n int idx = lambda_body(s, tree, 1);\n\n genop_2(s, OP_LAMBDA, cursp(), idx);\n push();\n }\n break;\n\n case NODE_BLOCK:\n if (val) {\n int idx = lambda_body(s, tree, 1);\n\n genop_2(s, OP_BLOCK, cursp(), idx);\n push();\n }\n break;\n\n case NODE_IF:\n {\n uint32_t pos1, pos2;\n mrb_bool nil_p = FALSE;\n node *elsepart = tree->cdr->cdr->car;\n\n if (!tree->car) {\n codegen(s, elsepart, val);\n goto exit;\n }\n if (true_always(tree->car)) {\n codegen(s, tree->cdr->car, val);\n goto exit;\n }\n if (false_always(tree->car)) {\n codegen(s, elsepart, val);\n goto exit;\n }\n if (nint(tree->car->car) == NODE_CALL) {\n node *n = tree->car->cdr;\n mrb_sym mid = nsym(n->cdr->car);\n mrb_sym sym_nil_p = MRB_SYM_Q_2(s->mrb, nil);\n if (mid == sym_nil_p && n->cdr->cdr->car == NULL) {\n nil_p = TRUE;\n codegen(s, n->car, VAL);\n }\n }\n if (!nil_p) {\n codegen(s, tree->car, VAL);\n }\n pop();\n if (val || tree->cdr->car) {\n if (nil_p) {\n pos2 = genjmp2_0(s, OP_JMPNIL, cursp(), val);\n pos1 = genjmp_0(s, OP_JMP);\n dispatch(s, pos2);\n }\n else {\n pos1 = genjmp2_0(s, OP_JMPNOT, cursp(), val);\n }\n codegen(s, tree->cdr->car, val);\n if (val) pop();\n if (elsepart || val) {\n pos2 = genjmp_0(s, OP_JMP);\n dispatch(s, pos1);\n codegen(s, elsepart, val);\n dispatch(s, pos2);\n }\n else {\n dispatch(s, pos1);\n }\n }\n else { /* empty then-part */\n if (elsepart) {\n if (nil_p) {\n pos1 = genjmp2_0(s, OP_JMPNIL, cursp(), val);\n }\n else {\n pos1 = genjmp2_0(s, OP_JMPIF, cursp(), val);\n }\n codegen(s, elsepart, val);\n dispatch(s, pos1);\n }\n else if (val && !nil_p) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n }\n break;\n\n case NODE_AND:\n {\n uint32_t pos;\n\n if (true_always(tree->car)) {\n codegen(s, tree->cdr, val);\n goto exit;\n }\n if (false_always(tree->car)) {\n codegen(s, tree->car, val);\n goto exit;\n }\n codegen(s, tree->car, VAL);\n pop();\n pos = genjmp2_0(s, OP_JMPNOT, cursp(), val);\n codegen(s, tree->cdr, val);\n dispatch(s, pos);\n }\n break;\n\n case NODE_OR:\n {\n uint32_t pos;\n\n if (true_always(tree->car)) {\n codegen(s, tree->car, val);\n goto exit;\n }\n if (false_always(tree->car)) {\n codegen(s, tree->cdr, val);\n goto exit;\n }\n codegen(s, tree->car, VAL);\n pop();\n pos = genjmp2_0(s, OP_JMPIF, cursp(), val);\n codegen(s, tree->cdr, val);\n dispatch(s, pos);\n }\n break;\n\n case NODE_WHILE:\n case NODE_UNTIL:\n {\n if (true_always(tree->car)) {\n if (nt == NODE_UNTIL) {\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n goto exit;\n }\n }\n else if (false_always(tree->car)) {\n if (nt == NODE_WHILE) {\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n goto exit;\n }\n }\n\n uint32_t pos = JMPLINK_START;\n struct loopinfo *lp = loop_push(s, LOOP_NORMAL);\n\n if (!val) lp->reg = -1;\n lp->pc0 = new_label(s);\n codegen(s, tree->car, VAL);\n pop();\n if (nt == NODE_WHILE) {\n pos = genjmp2_0(s, OP_JMPNOT, cursp(), NOVAL);\n }\n else {\n pos = genjmp2_0(s, OP_JMPIF, cursp(), NOVAL);\n }\n lp->pc1 = new_label(s);\n codegen(s, tree->cdr, NOVAL);\n genjmp(s, OP_JMP, lp->pc0);\n dispatch(s, pos);\n loop_pop(s, val);\n }\n break;\n\n case NODE_FOR:\n for_body(s, tree);\n if (val) push();\n break;\n\n case NODE_CASE:\n {\n int head = 0;\n uint32_t pos1, pos2, pos3, tmp;\n node *n;\n\n pos3 = JMPLINK_START;\n if (tree->car) {\n head = cursp();\n codegen(s, tree->car, VAL);\n }\n tree = tree->cdr;\n while (tree) {\n n = tree->car->car;\n pos1 = pos2 = JMPLINK_START;\n while (n) {\n codegen(s, n->car, VAL);\n if (head) {\n gen_move(s, cursp(), head, 0);\n push(); push(); pop(); pop(); pop();\n if (nint(n->car->car) == NODE_SPLAT) {\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, __case_eqq)), 1);\n }\n else {\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_OPSYM_2(s->mrb, eqq)), 1);\n }\n }\n else {\n pop();\n }\n tmp = genjmp2(s, OP_JMPIF, cursp(), pos2, NOVAL);\n pos2 = tmp;\n n = n->cdr;\n }\n if (tree->car->car) {\n pos1 = genjmp_0(s, OP_JMP);\n dispatch_linked(s, pos2);\n }\n codegen(s, tree->car->cdr, val);\n if (val) pop();\n tmp = genjmp(s, OP_JMP, pos3);\n pos3 = tmp;\n dispatch(s, pos1);\n tree = tree->cdr;\n }\n if (val) {\n uint32_t pos = cursp();\n genop_1(s, OP_LOADNIL, cursp());\n if (pos3 != JMPLINK_START) dispatch_linked(s, pos3);\n if (head) pop();\n if (cursp() != pos) {\n gen_move(s, cursp(), pos, 0);\n }\n push();\n }\n else {\n if (pos3 != JMPLINK_START) {\n dispatch_linked(s, pos3);\n }\n if (head) {\n pop();\n }\n }\n }\n break;\n\n case NODE_SCOPE:\n scope_body(s, tree, NOVAL);\n break;\n\n case NODE_FCALL:\n case NODE_CALL:\n gen_call(s, tree, val, 0);\n break;\n case NODE_SCALL:\n gen_call(s, tree, val, 1);\n break;\n\n case NODE_DOT2:\n codegen(s, tree->car, val);\n codegen(s, tree->cdr, val);\n if (val) {\n pop(); pop();\n genop_1(s, OP_RANGE_INC, cursp());\n push();\n }\n break;\n\n case NODE_DOT3:\n codegen(s, tree->car, val);\n codegen(s, tree->cdr, val);\n if (val) {\n pop(); pop();\n genop_1(s, OP_RANGE_EXC, cursp());\n push();\n }\n break;\n\n case NODE_COLON2:\n {\n int sym = new_sym(s, nsym(tree->cdr));\n\n codegen(s, tree->car, VAL);\n pop();\n genop_2(s, OP_GETMCNST, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_COLON3:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_1(s, OP_OCLASS, cursp());\n genop_2(s, OP_GETMCNST, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_ARRAY:\n {\n int n;\n\n n = gen_values(s, tree, val, 0);\n if (val) {\n if (n >= 0) {\n pop_n(n);\n genop_2(s, OP_ARRAY, cursp(), n);\n }\n push();\n }\n }\n break;\n\n case NODE_HASH:\n case NODE_KW_HASH:\n {\n int nk = gen_hash(s, tree, val, GEN_LIT_ARY_MAX);\n if (val && nk >= 0) {\n pop_n(nk*2);\n genop_2(s, OP_HASH, cursp(), nk);\n push();\n }\n }\n break;\n\n case NODE_SPLAT:\n codegen(s, tree, val);\n break;\n\n case NODE_ASGN:\n gen_assignment(s, tree->car, tree->cdr, 0, val);\n break;\n\n case NODE_MASGN:\n {\n int len = 0, n = 0, post = 0;\n node *t = tree->cdr, *p;\n int rhs = cursp();\n\n if (nint(t->car) == NODE_ARRAY && t->cdr && nosplat(t->cdr)) {\n /* fixed rhs */\n t = t->cdr;\n while (t) {\n codegen(s, t->car, VAL);\n len++;\n t = t->cdr;\n }\n tree = tree->car;\n if (tree->car) { /* pre */\n t = tree->car;\n n = 0;\n while (t) {\n if (n < len) {\n gen_assignment(s, t->car, NULL, rhs+n, NOVAL);\n n++;\n }\n else {\n genop_1(s, OP_LOADNIL, rhs+n);\n gen_assignment(s, t->car, NULL, rhs+n, NOVAL);\n }\n t = t->cdr;\n }\n }\n t = tree->cdr;\n if (t) {\n if (t->cdr) { /* post count */\n p = t->cdr->car;\n while (p) {\n post++;\n p = p->cdr;\n }\n }\n if (t->car) { /* rest (len - pre - post) */\n int rn;\n\n if (len < post + n) {\n rn = 0;\n }\n else {\n rn = len - post - n;\n }\n genop_3(s, OP_ARRAY2, cursp(), rhs+n, rn);\n gen_assignment(s, t->car, NULL, cursp(), NOVAL);\n n += rn;\n }\n if (t->cdr && t->cdr->car) {\n t = t->cdr->car;\n while (ncar, NULL, rhs+n, NOVAL);\n t = t->cdr;\n n++;\n }\n }\n }\n pop_n(len);\n if (val) {\n genop_2(s, OP_ARRAY, rhs, len);\n push();\n }\n }\n else {\n /* variable rhs */\n codegen(s, t, VAL);\n gen_vmassignment(s, tree->car, rhs, val);\n if (!val) {\n pop();\n }\n }\n }\n break;\n\n case NODE_OP_ASGN:\n {\n mrb_sym sym = nsym(tree->cdr->car);\n mrb_int len;\n const char *name = mrb_sym_name_len(s->mrb, sym, &len);\n int idx, callargs = -1, vsp = -1;\n\n if ((len == 2 && name[0] == '|' && name[1] == '|') &&\n (nint(tree->car->car) == NODE_CONST ||\n nint(tree->car->car) == NODE_CVAR)) {\n int catch_entry, begin, end;\n int noexc, exc;\n struct loopinfo *lp;\n\n lp = loop_push(s, LOOP_BEGIN);\n lp->pc0 = new_label(s);\n catch_entry = catch_handler_new(s);\n begin = s->pc;\n exc = cursp();\n codegen(s, tree->car, VAL);\n end = s->pc;\n noexc = genjmp_0(s, OP_JMP);\n lp->type = LOOP_RESCUE;\n catch_handler_set(s, catch_entry, MRB_CATCH_RESCUE, begin, end, s->pc);\n genop_1(s, OP_EXCEPT, exc);\n genop_1(s, OP_LOADF, exc);\n dispatch(s, noexc);\n loop_pop(s, NOVAL);\n }\n else if (nint(tree->car->car) == NODE_CALL) {\n node *n = tree->car->cdr;\n int base, i, nargs = 0;\n callargs = 0;\n\n if (val) {\n vsp = cursp();\n push();\n }\n codegen(s, n->car, VAL); /* receiver */\n idx = new_sym(s, nsym(n->cdr->car));\n base = cursp()-1;\n if (n->cdr->cdr->car) {\n nargs = gen_values(s, n->cdr->cdr->car->car, VAL, 13);\n if (nargs >= 0) {\n callargs = nargs;\n }\n else { /* varargs */\n push();\n nargs = 1;\n callargs = CALL_MAXARGS;\n }\n }\n /* copy receiver and arguments */\n gen_move(s, cursp(), base, 1);\n for (i=0; icar, VAL);\n }\n if (len == 2 &&\n ((name[0] == '|' && name[1] == '|') ||\n (name[0] == '&' && name[1] == '&'))) {\n uint32_t pos;\n\n pop();\n if (val) {\n if (vsp >= 0) {\n gen_move(s, vsp, cursp(), 1);\n }\n pos = genjmp2_0(s, name[0]=='|'?OP_JMPIF:OP_JMPNOT, cursp(), val);\n }\n else {\n pos = genjmp2_0(s, name[0]=='|'?OP_JMPIF:OP_JMPNOT, cursp(), val);\n }\n codegen(s, tree->cdr->cdr->car, VAL);\n pop();\n if (val && vsp >= 0) {\n gen_move(s, vsp, cursp(), 1);\n }\n if (nint(tree->car->car) == NODE_CALL) {\n if (callargs == CALL_MAXARGS) {\n pop();\n genop_2(s, OP_ARYPUSH, cursp(), 1);\n }\n else {\n pop_n(callargs);\n callargs++;\n }\n pop();\n idx = new_sym(s, attrsym(s, nsym(tree->car->cdr->cdr->car)));\n genop_3(s, OP_SEND, cursp(), idx, callargs);\n }\n else {\n gen_assignment(s, tree->car, NULL, cursp(), val);\n }\n dispatch(s, pos);\n goto exit;\n }\n codegen(s, tree->cdr->cdr->car, VAL);\n push(); pop();\n pop(); pop();\n\n if (len == 1 && name[0] == '+') {\n gen_addsub(s, OP_ADD, cursp());\n }\n else if (len == 1 && name[0] == '-') {\n gen_addsub(s, OP_SUB, cursp());\n }\n else if (len == 1 && name[0] == '*') {\n genop_1(s, OP_MUL, cursp());\n }\n else if (len == 1 && name[0] == '/') {\n genop_1(s, OP_DIV, cursp());\n }\n else if (len == 1 && name[0] == '<') {\n genop_1(s, OP_LT, cursp());\n }\n else if (len == 2 && name[0] == '<' && name[1] == '=') {\n genop_1(s, OP_LE, cursp());\n }\n else if (len == 1 && name[0] == '>') {\n genop_1(s, OP_GT, cursp());\n }\n else if (len == 2 && name[0] == '>' && name[1] == '=') {\n genop_1(s, OP_GE, cursp());\n }\n else {\n idx = new_sym(s, sym);\n genop_3(s, OP_SEND, cursp(), idx, 1);\n }\n if (callargs < 0) {\n gen_assignment(s, tree->car, NULL, cursp(), val);\n }\n else {\n if (val && vsp >= 0) {\n gen_move(s, vsp, cursp(), 0);\n }\n if (callargs == CALL_MAXARGS) {\n pop();\n genop_2(s, OP_ARYPUSH, cursp(), 1);\n }\n else {\n pop_n(callargs);\n callargs++;\n }\n pop();\n idx = new_sym(s, attrsym(s,nsym(tree->car->cdr->cdr->car)));\n genop_3(s, OP_SEND, cursp(), idx, callargs);\n }\n }\n break;\n\n case NODE_SUPER:\n {\n codegen_scope *s2 = s;\n int lv = 0;\n int n = 0, nk = 0, st = 0;\n\n push();\n while (!s2->mscope) {\n lv++;\n s2 = s2->prev;\n if (!s2) break;\n }\n if (tree) {\n node *args = tree->car;\n if (args) {\n st = n = gen_values(s, args, VAL, 14);\n if (n < 0) {\n st = 1; n = 15;\n push();\n }\n }\n /* keyword arguments */\n if (s2 && (s2->ainfo & 0x1) && tree->cdr->car) {\n nk = gen_hash(s, tree->cdr->car->cdr, VAL, 14);\n if (nk < 0) {st++; nk = 15;}\n else st += nk*2;\n n |= nk<<4;\n }\n /* block arguments */\n if (tree->cdr->cdr) {\n codegen(s, tree->cdr->cdr, VAL);\n }\n else if (s2) gen_blkmove(s, s2->ainfo, lv);\n else {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n else {\n if (s2) gen_blkmove(s, s2->ainfo, lv);\n else {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n st++;\n pop_n(st+1);\n genop_2(s, OP_SUPER, cursp(), n);\n if (val) push();\n }\n break;\n\n case NODE_ZSUPER:\n {\n codegen_scope *s2 = s;\n int lv = 0;\n uint16_t ainfo = 0;\n int n = CALL_MAXARGS;\n int sp = cursp();\n\n push(); /* room for receiver */\n while (!s2->mscope) {\n lv++;\n s2 = s2->prev;\n if (!s2) break;\n }\n if (s2 && s2->ainfo > 0) {\n ainfo = s2->ainfo;\n }\n if (ainfo > 0) {\n genop_2S(s, OP_ARGARY, cursp(), (ainfo<<4)|(lv & 0xf));\n push(); push(); push(); /* ARGARY pushes 3 values at most */\n pop(); pop(); pop();\n /* keyword arguments */\n if (ainfo & 0x1) {\n n |= CALL_MAXARGS<<4;\n push();\n }\n /* block argument */\n if (tree && tree->cdr && tree->cdr->cdr) {\n push();\n codegen(s, tree->cdr->cdr, VAL);\n }\n }\n else {\n /* block argument */\n if (tree && tree->cdr && tree->cdr->cdr) {\n codegen(s, tree->cdr->cdr, VAL);\n }\n else {\n gen_blkmove(s, 0, lv);\n }\n n = 0;\n }\n s->sp = sp;\n genop_2(s, OP_SUPER, cursp(), n);\n if (val) push();\n }\n break;\n\n case NODE_RETURN:\n if (tree) {\n gen_retval(s, tree);\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n }\n if (s->loop) {\n gen_return(s, OP_RETURN_BLK, cursp());\n }\n else {\n gen_return(s, OP_RETURN, cursp());\n }\n if (val) push();\n break;\n\n case NODE_YIELD:\n {\n codegen_scope *s2 = s;\n int lv = 0, ainfo = -1;\n int n = 0, sendv = 0;\n\n while (!s2->mscope) {\n lv++;\n s2 = s2->prev;\n if (!s2) break;\n }\n if (s2) {\n ainfo = (int)s2->ainfo;\n }\n if (ainfo < 0) codegen_error(s, \"invalid yield (SyntaxError)\");\n push();\n if (tree) {\n n = gen_values(s, tree, VAL, 14);\n if (n < 0) {\n n = sendv = 1;\n push();\n }\n }\n push();pop(); /* space for a block */\n pop_n(n+1);\n genop_2S(s, OP_BLKPUSH, cursp(), (ainfo<<4)|(lv & 0xf));\n if (sendv) n = CALL_MAXARGS;\n genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, call)), n);\n if (val) push();\n }\n break;\n\n case NODE_BREAK:\n loop_break(s, tree);\n if (val) push();\n break;\n\n case NODE_NEXT:\n if (!s->loop) {\n raise_error(s, \"unexpected next\");\n }\n else if (s->loop->type == LOOP_NORMAL) {\n codegen(s, tree, NOVAL);\n genjmp(s, OP_JMPUW, s->loop->pc0);\n }\n else {\n if (tree) {\n codegen(s, tree, VAL);\n pop();\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n }\n gen_return(s, OP_RETURN, cursp());\n }\n if (val) push();\n break;\n\n case NODE_REDO:\n if (!s->loop || s->loop->type == LOOP_BEGIN || s->loop->type == LOOP_RESCUE) {\n raise_error(s, \"unexpected redo\");\n }\n else {\n genjmp(s, OP_JMPUW, s->loop->pc1);\n }\n if (val) push();\n break;\n\n case NODE_RETRY:\n {\n const char *msg = \"unexpected retry\";\n const struct loopinfo *lp = s->loop;\n\n while (lp && lp->type != LOOP_RESCUE) {\n lp = lp->prev;\n }\n if (!lp) {\n raise_error(s, msg);\n }\n else {\n genjmp(s, OP_JMPUW, lp->pc0);\n }\n if (val) push();\n }\n break;\n\n case NODE_LVAR:\n if (val) {\n int idx = lv_idx(s, nsym(tree));\n\n if (idx > 0) {\n gen_move(s, cursp(), idx, val);\n }\n else {\n gen_getupvar(s, cursp(), nsym(tree));\n }\n push();\n }\n break;\n\n case NODE_NVAR:\n if (val) {\n int idx = nint(tree);\n\n gen_move(s, cursp(), idx, val);\n\n push();\n }\n break;\n\n case NODE_GVAR:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETGV, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_IVAR:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETIV, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_CVAR:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETCV, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_CONST:\n {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_GETCONST, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_BACK_REF:\n if (val) {\n char buf[] = {'$', nchar(tree)};\n int sym = new_sym(s, mrb_intern(s->mrb, buf, sizeof(buf)));\n\n genop_2(s, OP_GETGV, cursp(), sym);\n push();\n }\n break;\n\n case NODE_NTH_REF:\n if (val) {\n mrb_state *mrb = s->mrb;\n mrb_value str;\n int sym;\n\n str = mrb_format(mrb, \"$%d\", nint(tree));\n sym = new_sym(s, mrb_intern_str(mrb, str));\n genop_2(s, OP_GETGV, cursp(), sym);\n push();\n }\n break;\n\n case NODE_ARG:\n /* should not happen */\n break;\n\n case NODE_BLOCK_ARG:\n if (!tree) {\n int idx = lv_idx(s, MRB_OPSYM_2(s->mrb, and));\n\n if (idx == 0) {\n codegen_error(s, \"no anonymous block argument\");\n }\n gen_move(s, cursp(), idx, val);\n if (val) push();\n }\n else {\n codegen(s, tree, val);\n }\n break;\n\n case NODE_INT:\n if (val) {\n char *p = (char*)tree->car;\n int base = nint(tree->cdr->car);\n mrb_int i;\n mrb_bool overflow;\n\n i = readint(s, p, base, FALSE, &overflow);\n if (overflow) {\n int off = new_litbn(s, p, base, FALSE);\n genop_2(s, OP_LOADL, cursp(), off);\n }\n else {\n gen_int(s, cursp(), i);\n }\n push();\n }\n break;\n\n#ifndef MRB_NO_FLOAT\n case NODE_FLOAT:\n if (val) {\n char *p = (char*)tree;\n mrb_float f = mrb_float_read(p, NULL);\n int off = new_lit(s, mrb_float_value(s->mrb, f));\n\n genop_2(s, OP_LOADL, cursp(), off);\n push();\n }\n break;\n#endif\n\n case NODE_NEGATE:\n {\n nt = nint(tree->car);\n switch (nt) {\n#ifndef MRB_NO_FLOAT\n case NODE_FLOAT:\n if (val) {\n char *p = (char*)tree->cdr;\n mrb_float f = mrb_float_read(p, NULL);\n int off = new_lit(s, mrb_float_value(s->mrb, -f));\n\n genop_2(s, OP_LOADL, cursp(), off);\n push();\n }\n break;\n#endif\n\n case NODE_INT:\n if (val) {\n char *p = (char*)tree->cdr->car;\n int base = nint(tree->cdr->cdr->car);\n mrb_int i;\n mrb_bool overflow;\n\n i = readint(s, p, base, TRUE, &overflow);\n if (overflow) {\n int off = new_litbn(s, p, base, TRUE);\n genop_2(s, OP_LOADL, cursp(), off);\n }\n else {\n gen_int(s, cursp(), i);\n }\n push();\n }\n break;\n\n default:\n if (val) {\n codegen(s, tree, VAL);\n pop();\n push_n(2);pop_n(2); /* space for receiver&block */\n mrb_sym minus = MRB_OPSYM_2(s->mrb, minus);\n if (!gen_uniop(s, minus, cursp())) {\n genop_3(s, OP_SEND, cursp(), new_sym(s, minus), 0);\n }\n push();\n }\n else {\n codegen(s, tree, NOVAL);\n }\n break;\n }\n }\n break;\n\n case NODE_STR:\n if (val) {\n char *p = (char*)tree->car;\n size_t len = (intptr_t)tree->cdr;\n int ai = mrb_gc_arena_save(s->mrb);\n int off = new_lit(s, mrb_str_new(s->mrb, p, len));\n\n mrb_gc_arena_restore(s->mrb, ai);\n genop_2(s, OP_STRING, cursp(), off);\n push();\n }\n break;\n\n case NODE_HEREDOC:\n tree = ((struct mrb_parser_heredoc_info *)tree)->doc;\n /* fall through */\n case NODE_DSTR:\n if (val) {\n node *n = tree;\n\n if (!n) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n break;\n }\n codegen(s, n->car, VAL);\n n = n->cdr;\n while (n) {\n codegen(s, n->car, VAL);\n pop(); pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n n = n->cdr;\n }\n }\n else {\n node *n = tree;\n\n while (n) {\n if (nint(n->car->car) != NODE_STR) {\n codegen(s, n->car, NOVAL);\n }\n n = n->cdr;\n }\n }\n break;\n\n case NODE_WORDS:\n gen_literal_array(s, tree, FALSE, val);\n break;\n\n case NODE_SYMBOLS:\n gen_literal_array(s, tree, TRUE, val);\n break;\n\n case NODE_DXSTR:\n {\n node *n;\n int ai = mrb_gc_arena_save(s->mrb);\n int sym = new_sym(s, MRB_SYM_2(s->mrb, Kernel));\n\n genop_1(s, OP_LOADSELF, cursp());\n push();\n codegen(s, tree->car, VAL);\n n = tree->cdr;\n while (n) {\n if (nint(n->car->car) == NODE_XSTR) {\n n->car->car = (struct mrb_ast_node*)(intptr_t)NODE_STR;\n mrb_assert(!n->cdr); /* must be the end */\n }\n codegen(s, n->car, VAL);\n pop(); pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n n = n->cdr;\n }\n push(); /* for block */\n pop_n(3);\n sym = new_sym(s, MRB_OPSYM_2(s->mrb, tick)); /* ` */\n genop_3(s, OP_SEND, cursp(), sym, 1);\n if (val) push();\n mrb_gc_arena_restore(s->mrb, ai);\n }\n break;\n\n case NODE_XSTR:\n {\n char *p = (char*)tree->car;\n size_t len = (intptr_t)tree->cdr;\n int ai = mrb_gc_arena_save(s->mrb);\n int off = new_lit(s, mrb_str_new(s->mrb, p, len));\n int sym;\n\n genop_1(s, OP_LOADSELF, cursp());\n push();\n genop_2(s, OP_STRING, cursp(), off);\n push(); push();\n pop_n(3);\n sym = new_sym(s, MRB_OPSYM_2(s->mrb, tick)); /* ` */\n genop_3(s, OP_SEND, cursp(), sym, 1);\n if (val) push();\n mrb_gc_arena_restore(s->mrb, ai);\n }\n break;\n\n case NODE_REGX:\n if (val) {\n char *p1 = (char*)tree->car;\n char *p2 = (char*)tree->cdr->car;\n char *p3 = (char*)tree->cdr->cdr;\n int ai = mrb_gc_arena_save(s->mrb);\n int sym = new_sym(s, mrb_intern_lit(s->mrb, REGEXP_CLASS));\n int off = new_lit(s, mrb_str_new_cstr(s->mrb, p1));\n int argc = 1;\n\n genop_1(s, OP_OCLASS, cursp());\n genop_2(s, OP_GETMCNST, cursp(), sym);\n push();\n genop_2(s, OP_STRING, cursp(), off);\n push();\n if (p2 || p3) {\n if (p2) { /* opt */\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));\n genop_2(s, OP_STRING, cursp(), off);\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n }\n push();\n argc++;\n if (p3) { /* enc */\n off = new_lit(s, mrb_str_new(s->mrb, p3, 1));\n genop_2(s, OP_STRING, cursp(), off);\n push();\n argc++;\n }\n }\n push(); /* space for a block */\n pop_n(argc+2);\n sym = new_sym(s, MRB_SYM_2(s->mrb, compile));\n genop_3(s, OP_SEND, cursp(), sym, argc);\n mrb_gc_arena_restore(s->mrb, ai);\n push();\n }\n break;\n\n case NODE_DREGX:\n if (val) {\n node *n = tree->car;\n int ai = mrb_gc_arena_save(s->mrb);\n int sym = new_sym(s, mrb_intern_lit(s->mrb, REGEXP_CLASS));\n int argc = 1;\n int off;\n char *p;\n\n genop_1(s, OP_OCLASS, cursp());\n genop_2(s, OP_GETMCNST, cursp(), sym);\n push();\n codegen(s, n->car, VAL);\n n = n->cdr;\n while (n) {\n codegen(s, n->car, VAL);\n pop(); pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n n = n->cdr;\n }\n n = tree->cdr->cdr;\n if (n->car) { /* tail */\n p = (char*)n->car;\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p));\n codegen(s, tree->car, VAL);\n genop_2(s, OP_STRING, cursp(), off);\n pop();\n genop_1(s, OP_STRCAT, cursp());\n push();\n }\n if (n->cdr->car) { /* opt */\n char *p2 = (char*)n->cdr->car;\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));\n genop_2(s, OP_STRING, cursp(), off);\n push();\n argc++;\n }\n if (n->cdr->cdr) { /* enc */\n char *p2 = (char*)n->cdr->cdr;\n off = new_lit(s, mrb_str_new_cstr(s->mrb, p2));\n genop_2(s, OP_STRING, cursp(), off);\n push();\n argc++;\n }\n push(); /* space for a block */\n pop_n(argc+2);\n sym = new_sym(s, MRB_SYM_2(s->mrb, compile));\n genop_3(s, OP_SEND, cursp(), sym, argc);\n mrb_gc_arena_restore(s->mrb, ai);\n push();\n }\n else {\n node *n = tree->car;\n\n while (n) {\n if (nint(n->car->car) != NODE_STR) {\n codegen(s, n->car, NOVAL);\n }\n n = n->cdr;\n }\n }\n break;\n\n case NODE_SYM:\n if (val) {\n int sym = new_sym(s, nsym(tree));\n\n genop_2(s, OP_LOADSYM, cursp(), sym);\n push();\n }\n break;\n\n case NODE_DSYM:\n codegen(s, tree, val);\n if (val) {\n gen_intern(s);\n }\n break;\n\n case NODE_SELF:\n if (val) {\n genop_1(s, OP_LOADSELF, cursp());\n push();\n }\n break;\n\n case NODE_NIL:\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n break;\n\n case NODE_TRUE:\n if (val) {\n genop_1(s, OP_LOADT, cursp());\n push();\n }\n break;\n\n case NODE_FALSE:\n if (val) {\n genop_1(s, OP_LOADF, cursp());\n push();\n }\n break;\n\n case NODE_ALIAS:\n {\n int a = new_sym(s, nsym(tree->car));\n int b = new_sym(s, nsym(tree->cdr));\n\n genop_2(s, OP_ALIAS, a, b);\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n break;\n\n case NODE_UNDEF:\n {\n node *t = tree;\n\n while (t) {\n int symbol = new_sym(s, nsym(t->car));\n genop_1(s, OP_UNDEF, symbol);\n t = t->cdr;\n }\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n }\n break;\n\n case NODE_CLASS:\n {\n int idx;\n node *body;\n\n if (tree->car->car == (node*)0) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n else if (tree->car->car == (node*)1) {\n genop_1(s, OP_OCLASS, cursp());\n push();\n }\n else {\n codegen(s, tree->car->car, VAL);\n }\n if (tree->cdr->car) {\n codegen(s, tree->cdr->car, VAL);\n }\n else {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n pop(); pop();\n idx = new_sym(s, nsym(tree->car->cdr));\n genop_2(s, OP_CLASS, cursp(), idx);\n body = tree->cdr->cdr->car;\n if (nint(body->cdr->car) == NODE_BEGIN && body->cdr->cdr == NULL) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n else {\n idx = scope_body(s, body, val);\n genop_2(s, OP_EXEC, cursp(), idx);\n }\n if (val) {\n push();\n }\n }\n break;\n\n case NODE_MODULE:\n {\n int idx;\n\n if (tree->car->car == (node*)0) {\n genop_1(s, OP_LOADNIL, cursp());\n push();\n }\n else if (tree->car->car == (node*)1) {\n genop_1(s, OP_OCLASS, cursp());\n push();\n }\n else {\n codegen(s, tree->car->car, VAL);\n }\n pop();\n idx = new_sym(s, nsym(tree->car->cdr));\n genop_2(s, OP_MODULE, cursp(), idx);\n if (nint(tree->cdr->car->cdr->car) == NODE_BEGIN &&\n tree->cdr->car->cdr->cdr == NULL) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n else {\n idx = scope_body(s, tree->cdr->car, val);\n genop_2(s, OP_EXEC, cursp(), idx);\n }\n if (val) {\n push();\n }\n }\n break;\n\n case NODE_SCLASS:\n {\n int idx;\n\n codegen(s, tree->car, VAL);\n pop();\n genop_1(s, OP_SCLASS, cursp());\n if (nint(tree->cdr->car->cdr->car) == NODE_BEGIN &&\n tree->cdr->car->cdr->cdr == NULL) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n else {\n idx = scope_body(s, tree->cdr->car, val);\n genop_2(s, OP_EXEC, cursp(), idx);\n }\n if (val) {\n push();\n }\n }\n break;\n\n case NODE_DEF:\n {\n int sym = new_sym(s, nsym(tree->car));\n int idx = lambda_body(s, tree->cdr, 0);\n\n genop_1(s, OP_TCLASS, cursp());\n push();\n genop_2(s, OP_METHOD, cursp(), idx);\n push(); pop();\n pop();\n genop_2(s, OP_DEF, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_SDEF:\n {\n node *recv = tree->car;\n int sym = new_sym(s, nsym(tree->cdr->car));\n int idx = lambda_body(s, tree->cdr->cdr, 0);\n\n codegen(s, recv, VAL);\n pop();\n genop_1(s, OP_SCLASS, cursp());\n push();\n genop_2(s, OP_METHOD, cursp(), idx);\n pop();\n genop_2(s, OP_DEF, cursp(), sym);\n if (val) push();\n }\n break;\n\n case NODE_POSTEXE:\n codegen(s, tree, NOVAL);\n break;\n\n default:\n break;\n }\n exit:\n s->rlev = rlev;\n}", "project": "mruby", "hash": 331098739854123957172781686688963498599, "size": 1537, "commit_id": "44f591aa8f7091e6ca6cb418e428ae6d4ceaf77d", "message": "codegen.c: adjust stack position for `OP_SUPER` instruction.", "target": 0, "dataset": "other", "idx": 238366} {"func": "ecma_op_internal_buffer_append (ecma_collection_t *container_p, /**< internal container pointer */\n ecma_value_t key_arg, /**< key argument */\n ecma_value_t value_arg, /**< value argument */\n lit_magic_string_id_t lit_id) /**< class id */\n{\n JERRY_ASSERT (container_p != NULL);\n\n ecma_collection_push_back (container_p, ecma_copy_value_if_not_object (key_arg));\n\n if (lit_id == LIT_MAGIC_STRING_WEAKMAP_UL || lit_id == LIT_MAGIC_STRING_MAP_UL)\n {\n ecma_collection_push_back (container_p, ecma_copy_value_if_not_object (value_arg));\n }\n\n ECMA_CONTAINER_SET_SIZE (container_p, ECMA_CONTAINER_GET_SIZE (container_p) + 1);\n} /* ecma_op_internal_buffer_append */", "project": "jerryscript", "hash": 289394230641505307974784830249750953781, "size": 16, "commit_id": "c2b662170245a16f46ce02eae68815c325d99821", "message": "Fix adding entries to the internal buffer of a Map object (#3805)\n\nWhen appending the key/value pair separately, garbage collection could be\r\ntriggered before the value is added, which could cause problems during\r\nmarking. This patch changes insertion to add both values at the same\r\ntime, which prevents partial entries from being present in the internal\r\nbuffer.\r\n\r\nFixes #3804.\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: D\u00e1niel B\u00e1tyai dbatyai@inf.u-szeged.hu", "target": 1, "dataset": "other", "idx": 196327} {"func": "ecma_op_internal_buffer_append (ecma_collection_t *container_p, /**< internal container pointer */\n ecma_value_t key_arg, /**< key argument */\n ecma_value_t value_arg, /**< value argument */\n lit_magic_string_id_t lit_id) /**< class id */\n{\n JERRY_ASSERT (container_p != NULL);\n\n if (lit_id == LIT_MAGIC_STRING_WEAKMAP_UL || lit_id == LIT_MAGIC_STRING_MAP_UL)\n {\n ecma_value_t values[] = { ecma_copy_value_if_not_object (key_arg), ecma_copy_value_if_not_object (value_arg) };\n ecma_collection_append (container_p, values, 2);\n }\n else\n {\n ecma_collection_push_back (container_p, ecma_copy_value_if_not_object (key_arg));\n }\n\n ECMA_CONTAINER_SET_SIZE (container_p, ECMA_CONTAINER_GET_SIZE (container_p) + 1);\n} /* ecma_op_internal_buffer_append */", "project": "jerryscript", "hash": 269950026591073206896646719908346441717, "size": 19, "commit_id": "c2b662170245a16f46ce02eae68815c325d99821", "message": "Fix adding entries to the internal buffer of a Map object (#3805)\n\nWhen appending the key/value pair separately, garbage collection could be\r\ntriggered before the value is added, which could cause problems during\r\nmarking. This patch changes insertion to add both values at the same\r\ntime, which prevents partial entries from being present in the internal\r\nbuffer.\r\n\r\nFixes #3804.\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: D\u00e1niel B\u00e1tyai dbatyai@inf.u-szeged.hu", "target": 0, "dataset": "other", "idx": 238757} {"func": " void Compute(OpKernelContext* context) override {\n // Get inputs\n const Tensor& input_tensor = context->input(0);\n const auto input_tensor_flat = input_tensor.flat();\n const Tensor& input_splits = context->input(1);\n const auto input_splits_flat = input_splits.flat();\n\n // Operation will treat first argument in input_splits as if it were zero\n // regardless of its actual value since splits should begin with zero and\n // end with the length of the input values vector.\n OP_REQUIRES(\n context, input_splits_flat(0) == 0,\n errors::InvalidArgument(\"First value in input_splits must be zero.\"));\n OP_REQUIRES(context,\n input_splits_flat(input_splits_flat.size() - 1) ==\n input_tensor_flat.size(),\n errors::InvalidArgument(\"Last value in input_splits must be \"\n \"equal to length of input_tensor.\"));\n // Since we limit to a 2-D input (flat_values of rank 1 and a single splits\n // tensor), our output dimension will be 1 with it's size equal to the\n // number of splits (outer dimension or ragged tensor).\n TensorShape output_shape({input_splits.dim_size(0) - 1});\n Tensor* output_tensor;\n OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n &output_tensor));\n auto output_tensor_flat = output_tensor->flat();\n\n // Use a single index over the flattened input values tensor.\n int idx = 0;\n // Loop through our split dimension to create a new string at each split.\n for (int i = 1; i < input_splits_flat.size(); ++i) {\n icu::UnicodeString unicode_string;\n icu::UnicodeStringAppendable appendable_unicode_string(unicode_string);\n OP_REQUIRES(\n context, input_splits_flat(i - 1) <= input_splits_flat(i),\n errors::InvalidArgument(\n \"Values in input_splits must be equal or in ascending order.\"));\n OP_REQUIRES(\n context, input_splits_flat(i) <= input_tensor_flat.size(),\n errors::InvalidArgument(\"Values in input_splits must be less than or \"\n \"equal to input_tensor length.\"));\n for (; idx < input_splits_flat(i); ++idx) {\n int32_t code_point = input_tensor_flat(idx);\n // Check for invalid code point\n if (!U_IS_UNICODE_CHAR(code_point)) {\n if (error_options_.error_on_malformatting) {\n context->CtxFailure(errors::InvalidArgument(\n \"Code point is out of range for Unicode, or a noncharacter.\"));\n return;\n } else if (!error_options_.elide_replacement) {\n code_point = error_options_.subst;\n }\n }\n appendable_unicode_string.appendCodePoint(code_point);\n }\n // Encode our string and save in the output.\n tstring result;\n Encode(encoding_, unicode_string, &result);\n output_tensor_flat(i - 1) = std::move(result);\n }\n }", "project": "tensorflow", "hash": 95725917459110570359817499250275418833, "size": 61, "commit_id": "2e0ee46f1a47675152d3d865797a18358881d7a6", "message": "Ensure non-empty input_splits in tf.raw_ops.UnicodeEncode\n\nPiperOrigin-RevId: 387170080\nChange-Id: I3b489acc51c5cb4124c535b9df7cc6e62ef21766", "target": 1, "dataset": "other", "idx": 196329} {"func": " void Compute(OpKernelContext* context) override {\n // Get inputs\n const Tensor& input_tensor = context->input(0);\n const auto input_tensor_flat = input_tensor.flat();\n const Tensor& input_splits = context->input(1);\n const auto input_splits_flat = input_splits.flat();\n\n OP_REQUIRES(\n context, input_splits.NumElements() > 0,\n errors::InvalidArgument(\"Input_splits should contain elements, but \"\n \"given input_values has 0 elements\"));\n // Operation will treat first argument in input_splits as if it were zero\n // regardless of its actual value since splits should begin with zero and\n // end with the length of the input values vector.\n OP_REQUIRES(\n context, input_splits_flat(0) == 0,\n errors::InvalidArgument(\"First value in input_splits must be zero.\"));\n OP_REQUIRES(context,\n input_splits_flat(input_splits_flat.size() - 1) ==\n input_tensor_flat.size(),\n errors::InvalidArgument(\"Last value in input_splits must be \"\n \"equal to length of input_tensor.\"));\n // Since we limit to a 2-D input (flat_values of rank 1 and a single splits\n // tensor), our output dimension will be 1 with it's size equal to the\n // number of splits (outer dimension or ragged tensor).\n TensorShape output_shape({input_splits.dim_size(0) - 1});\n Tensor* output_tensor;\n OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n &output_tensor));\n auto output_tensor_flat = output_tensor->flat();\n\n // Use a single index over the flattened input values tensor.\n int idx = 0;\n // Loop through our split dimension to create a new string at each split.\n for (int i = 1; i < input_splits_flat.size(); ++i) {\n icu::UnicodeString unicode_string;\n icu::UnicodeStringAppendable appendable_unicode_string(unicode_string);\n OP_REQUIRES(\n context, input_splits_flat(i - 1) <= input_splits_flat(i),\n errors::InvalidArgument(\n \"Values in input_splits must be equal or in ascending order.\"));\n OP_REQUIRES(\n context, input_splits_flat(i) <= input_tensor_flat.size(),\n errors::InvalidArgument(\"Values in input_splits must be less than or \"\n \"equal to input_tensor length.\"));\n for (; idx < input_splits_flat(i); ++idx) {\n int32_t code_point = input_tensor_flat(idx);\n // Check for invalid code point\n if (!U_IS_UNICODE_CHAR(code_point)) {\n if (error_options_.error_on_malformatting) {\n context->CtxFailure(errors::InvalidArgument(\n \"Code point is out of range for Unicode, or a noncharacter.\"));\n return;\n } else if (!error_options_.elide_replacement) {\n code_point = error_options_.subst;\n }\n }\n appendable_unicode_string.appendCodePoint(code_point);\n }\n // Encode our string and save in the output.\n tstring result;\n Encode(encoding_, unicode_string, &result);\n output_tensor_flat(i - 1) = std::move(result);\n }\n }", "project": "tensorflow", "hash": 191582078444848979487063653458796885790, "size": 65, "commit_id": "2e0ee46f1a47675152d3d865797a18358881d7a6", "message": "Ensure non-empty input_splits in tf.raw_ops.UnicodeEncode\n\nPiperOrigin-RevId: 387170080\nChange-Id: I3b489acc51c5cb4124c535b9df7cc6e62ef21766", "target": 0, "dataset": "other", "idx": 238838} {"func": "static inline Status ParseAndCheckBoxSizes(const Tensor& boxes,\n const Tensor& box_index,\n int* num_boxes) {\n if (boxes.NumElements() == 0 && box_index.NumElements() == 0) {\n *num_boxes = 0;\n return Status::OK();\n }\n // The shape of 'boxes' is [num_boxes, 4].\n if (boxes.dims() != 2) {\n return errors::InvalidArgument(\"boxes must be 2-D\",\n boxes.shape().DebugString());\n }\n *num_boxes = boxes.dim_size(0);\n if (boxes.dim_size(1) != 4) {\n return errors::InvalidArgument(\"boxes must have 4 columns\");\n }\n // The shape of 'box_index' is [num_boxes].\n if (box_index.dims() != 1) {\n return errors::InvalidArgument(\"box_index must be 1-D\",\n box_index.shape().DebugString());\n }\n if (box_index.dim_size(0) != *num_boxes) {\n return errors::InvalidArgument(\"box_index has incompatible shape\");\n }\n return Status::OK();\n}", "project": "tensorflow", "hash": 327348859222179558551343679127178889587, "size": 26, "commit_id": "3ade2efec2e90c6237de32a19680caaa3ebc2845", "message": "Fix segmentation fault in tf.image.crop_and_resize when boxes is inf or nan\n\nThis fix tries to address the issue raised in 42129 where segmentation fault\nhappened in tf.image.crop_and_resize when boxes is inf or nan.\n\nThis fix adds the check to make sure boxes is not inf or nan (isfinite)\n\nThis fix fixes 42129.\n\nSigned-off-by: Yong Tang ", "target": 1, "dataset": "other", "idx": 196330} {"func": "static inline Status ParseAndCheckBoxSizes(const Tensor& boxes,\n const Tensor& box_index,\n int* num_boxes) {\n if (boxes.NumElements() == 0 && box_index.NumElements() == 0) {\n *num_boxes = 0;\n return Status::OK();\n }\n // The shape of 'boxes' is [num_boxes, 4].\n if (boxes.dims() != 2) {\n return errors::InvalidArgument(\"boxes must be 2-D\",\n boxes.shape().DebugString());\n }\n *num_boxes = boxes.dim_size(0);\n if (boxes.dim_size(1) != 4) {\n return errors::InvalidArgument(\"boxes must have 4 columns\");\n }\n for (int64 i = 0; i < *num_boxes; i++) {\n for (int64 j = 0; j < 4; j++) {\n if (!isfinite(boxes.tensor()(i, j))) {\n return errors::InvalidArgument(\n \"boxes values must be finite, received boxes[\", i, \"]: \",\n boxes.tensor()(i, 0), \", \",\n boxes.tensor()(i, 1), \", \",\n boxes.tensor()(i, 2), \", \",\n boxes.tensor()(i, 3));\n }\n }\n }\n // The shape of 'box_index' is [num_boxes].\n if (box_index.dims() != 1) {\n return errors::InvalidArgument(\"box_index must be 1-D\",\n box_index.shape().DebugString());\n }\n if (box_index.dim_size(0) != *num_boxes) {\n return errors::InvalidArgument(\"box_index has incompatible shape\");\n }\n return Status::OK();\n}", "project": "tensorflow", "hash": 162824839659560449491498365320039591607, "size": 38, "commit_id": "3ade2efec2e90c6237de32a19680caaa3ebc2845", "message": "Fix segmentation fault in tf.image.crop_and_resize when boxes is inf or nan\n\nThis fix tries to address the issue raised in 42129 where segmentation fault\nhappened in tf.image.crop_and_resize when boxes is inf or nan.\n\nThis fix adds the check to make sure boxes is not inf or nan (isfinite)\n\nThis fix fixes 42129.\n\nSigned-off-by: Yong Tang ", "target": 0, "dataset": "other", "idx": 238855} {"func": "int flb_parser_json_do(struct flb_parser *parser,\n const char *in_buf, size_t in_size,\n void **out_buf, size_t *out_size,\n struct flb_time *out_time)\n{\n int i;\n int skip;\n int ret;\n int slen;\n int root_type;\n int records;\n double tmfrac = 0;\n char *mp_buf = NULL;\n char *time_key;\n char *tmp_out_buf = NULL;\n char tmp[255];\n size_t tmp_out_size = 0;\n size_t off = 0;\n size_t map_size;\n size_t mp_size;\n size_t len;\n msgpack_sbuffer mp_sbuf;\n msgpack_packer mp_pck;\n msgpack_unpacked result;\n msgpack_object map;\n msgpack_object *k = NULL;\n msgpack_object *v = NULL;\n time_t time_lookup;\n struct tm tm = {0};\n struct flb_time *t;\n\n /* Convert incoming in_buf JSON message to message pack format */\n ret = flb_pack_json_recs(in_buf, in_size, &mp_buf, &mp_size, &root_type,\n &records);\n if (ret != 0) {\n return -1;\n }\n\n if (records != 1) {\n flb_free(mp_buf);\n return -1;\n }\n\n /* Make sure object is a map */\n msgpack_unpacked_init(&result);\n if (msgpack_unpack_next(&result, mp_buf, mp_size, &off) == MSGPACK_UNPACK_SUCCESS) {\n map = result.data;\n if (map.type != MSGPACK_OBJECT_MAP) {\n flb_free(mp_buf);\n msgpack_unpacked_destroy(&result);\n return -1;\n }\n }\n else {\n if (mp_size > 0) {\n flb_free(mp_buf);\n }\n msgpack_unpacked_destroy(&result);\n return -1;\n }\n\n /* Export results (might change later) */\n tmp_out_buf = mp_buf;\n tmp_out_size = mp_size;\n\n /* Do we have some decoders set ? */\n if (parser->decoders) {\n ret = flb_parser_decoder_do(parser->decoders,\n mp_buf, mp_size,\n &tmp_out_buf, &tmp_out_size);\n if (ret == 0) {\n /* re-process the unpack context */\n off = 0;\n msgpack_unpacked_destroy(&result);\n msgpack_unpacked_init(&result);\n msgpack_unpack_next(&result, tmp_out_buf, tmp_out_size, &off);\n map = result.data;\n }\n }\n\n /* Set the possible outgoing buffer */\n *out_buf = tmp_out_buf;\n *out_size = tmp_out_size;\n if (mp_buf != tmp_out_buf) {\n flb_free(mp_buf);\n }\n\n /* Do time resolution ? */\n if (!parser->time_fmt) {\n msgpack_unpacked_destroy(&result);\n return *out_size;\n }\n\n if (parser->time_key) {\n time_key = parser->time_key;\n }\n else {\n time_key = \"time\";\n }\n slen = strlen(time_key);\n\n /* Lookup time field */\n map_size = map.via.map.size;\n skip = map_size;\n for (i = 0; i < map_size; i++) {\n k = &map.via.map.ptr[i].key;\n v = &map.via.map.ptr[i].val;\n\n if (k->via.str.size != slen) {\n continue;\n }\n\n /* Ensure the pointer we are about to read is not NULL */\n if (k->via.str.ptr == NULL) {\n flb_free(mp_buf);\n *out_buf = NULL;\n msgpack_unpacked_destroy(&result);\n return -1;\n }\n\n if (strncmp(k->via.str.ptr, time_key, k->via.str.size) == 0) {\n /* We found the key, break the loop and keep the index */\n if (parser->time_keep == FLB_FALSE) {\n skip = i;\n break;\n }\n else {\n skip = -1;\n }\n break;\n }\n\n k = NULL;\n v = NULL;\n }\n\n /* No time_key field found */\n if (i >= map_size || !k || !v) {\n msgpack_unpacked_destroy(&result);\n return *out_size;\n }\n\n /* Ensure we have an accurate type */\n if (v->type != MSGPACK_OBJECT_STR) {\n msgpack_unpacked_destroy(&result);\n return *out_size;\n }\n\n /* Lookup time */\n ret = flb_parser_time_lookup(v->via.str.ptr, v->via.str.size,\n 0, parser, &tm, &tmfrac);\n if (ret == -1) {\n len = v->via.str.size;\n if (len > sizeof(tmp) - 1) {\n len = sizeof(tmp) - 1;\n }\n memcpy(tmp, v->via.str.ptr, len);\n tmp[len] = '\\0';\n flb_warn(\"[parser:%s] invalid time format %s for '%s'\",\n parser->name, parser->time_fmt_full, tmp);\n time_lookup = 0;\n }\n else {\n time_lookup = flb_parser_tm2time(&tm);\n }\n\n /* Compose a new map without the time_key field */\n msgpack_sbuffer_init(&mp_sbuf);\n msgpack_packer_init(&mp_pck, &mp_sbuf, msgpack_sbuffer_write);\n\n if (parser->time_keep == FLB_FALSE) {\n msgpack_pack_map(&mp_pck, map_size - 1);\n }\n else {\n msgpack_pack_map(&mp_pck, map_size);\n }\n\n for (i = 0; i < map_size; i++) {\n if (i == skip) {\n continue;\n }\n msgpack_pack_object(&mp_pck, map.via.map.ptr[i].key);\n msgpack_pack_object(&mp_pck, map.via.map.ptr[i].val);\n }\n\n /* Export the proper buffer */\n flb_free(tmp_out_buf);\n *out_buf = mp_sbuf.data;\n *out_size = mp_sbuf.size;\n\n t = out_time;\n t->tm.tv_sec = time_lookup;\n t->tm.tv_nsec = (tmfrac * 1000000000);\n\n msgpack_unpacked_destroy(&result);\n return *out_size;\n}", "project": "fluent-bit", "hash": 88227932456379194164638143524160893177, "size": 197, "commit_id": "22346a74c07ceb90296be872be2d53eb92252a54", "message": "parser: json: fix double-free (#3453)\n\nSigned-off-by: davkor ", "target": 1, "dataset": "other", "idx": 196589} {"func": "int flb_parser_json_do(struct flb_parser *parser,\n const char *in_buf, size_t in_size,\n void **out_buf, size_t *out_size,\n struct flb_time *out_time)\n{\n int i;\n int skip;\n int ret;\n int slen;\n int root_type;\n int records;\n double tmfrac = 0;\n char *mp_buf = NULL;\n char *time_key;\n char *tmp_out_buf = NULL;\n char tmp[255];\n size_t tmp_out_size = 0;\n size_t off = 0;\n size_t map_size;\n size_t mp_size;\n size_t len;\n msgpack_sbuffer mp_sbuf;\n msgpack_packer mp_pck;\n msgpack_unpacked result;\n msgpack_object map;\n msgpack_object *k = NULL;\n msgpack_object *v = NULL;\n time_t time_lookup;\n struct tm tm = {0};\n struct flb_time *t;\n\n /* Convert incoming in_buf JSON message to message pack format */\n ret = flb_pack_json_recs(in_buf, in_size, &mp_buf, &mp_size, &root_type,\n &records);\n if (ret != 0) {\n return -1;\n }\n\n if (records != 1) {\n flb_free(mp_buf);\n return -1;\n }\n\n /* Make sure object is a map */\n msgpack_unpacked_init(&result);\n if (msgpack_unpack_next(&result, mp_buf, mp_size, &off) == MSGPACK_UNPACK_SUCCESS) {\n map = result.data;\n if (map.type != MSGPACK_OBJECT_MAP) {\n flb_free(mp_buf);\n msgpack_unpacked_destroy(&result);\n return -1;\n }\n }\n else {\n if (mp_size > 0) {\n flb_free(mp_buf);\n }\n msgpack_unpacked_destroy(&result);\n return -1;\n }\n\n /* Export results (might change later) */\n tmp_out_buf = mp_buf;\n tmp_out_size = mp_size;\n\n /* Do we have some decoders set ? */\n if (parser->decoders) {\n ret = flb_parser_decoder_do(parser->decoders,\n mp_buf, mp_size,\n &tmp_out_buf, &tmp_out_size);\n if (ret == 0) {\n /* re-process the unpack context */\n off = 0;\n msgpack_unpacked_destroy(&result);\n msgpack_unpacked_init(&result);\n msgpack_unpack_next(&result, tmp_out_buf, tmp_out_size, &off);\n map = result.data;\n }\n }\n\n /* Set the possible outgoing buffer */\n *out_buf = tmp_out_buf;\n *out_size = tmp_out_size;\n if (mp_buf != tmp_out_buf) {\n flb_free(mp_buf);\n mp_buf = NULL;\n }\n\n /* Do time resolution ? */\n if (!parser->time_fmt) {\n msgpack_unpacked_destroy(&result);\n return *out_size;\n }\n\n if (parser->time_key) {\n time_key = parser->time_key;\n }\n else {\n time_key = \"time\";\n }\n slen = strlen(time_key);\n\n /* Lookup time field */\n map_size = map.via.map.size;\n skip = map_size;\n for (i = 0; i < map_size; i++) {\n k = &map.via.map.ptr[i].key;\n v = &map.via.map.ptr[i].val;\n\n if (k->via.str.size != slen) {\n continue;\n }\n\n /* Ensure the pointer we are about to read is not NULL */\n if (k->via.str.ptr == NULL) {\n flb_free(mp_buf);\n flb_free(tmp_out_buf);\n *out_buf = NULL;\n msgpack_unpacked_destroy(&result);\n return -1;\n }\n\n if (strncmp(k->via.str.ptr, time_key, k->via.str.size) == 0) {\n /* We found the key, break the loop and keep the index */\n if (parser->time_keep == FLB_FALSE) {\n skip = i;\n break;\n }\n else {\n skip = -1;\n }\n break;\n }\n\n k = NULL;\n v = NULL;\n }\n\n /* No time_key field found */\n if (i >= map_size || !k || !v) {\n msgpack_unpacked_destroy(&result);\n return *out_size;\n }\n\n /* Ensure we have an accurate type */\n if (v->type != MSGPACK_OBJECT_STR) {\n msgpack_unpacked_destroy(&result);\n return *out_size;\n }\n\n /* Lookup time */\n ret = flb_parser_time_lookup(v->via.str.ptr, v->via.str.size,\n 0, parser, &tm, &tmfrac);\n if (ret == -1) {\n len = v->via.str.size;\n if (len > sizeof(tmp) - 1) {\n len = sizeof(tmp) - 1;\n }\n memcpy(tmp, v->via.str.ptr, len);\n tmp[len] = '\\0';\n flb_warn(\"[parser:%s] invalid time format %s for '%s'\",\n parser->name, parser->time_fmt_full, tmp);\n time_lookup = 0;\n }\n else {\n time_lookup = flb_parser_tm2time(&tm);\n }\n\n /* Compose a new map without the time_key field */\n msgpack_sbuffer_init(&mp_sbuf);\n msgpack_packer_init(&mp_pck, &mp_sbuf, msgpack_sbuffer_write);\n\n if (parser->time_keep == FLB_FALSE) {\n msgpack_pack_map(&mp_pck, map_size - 1);\n }\n else {\n msgpack_pack_map(&mp_pck, map_size);\n }\n\n for (i = 0; i < map_size; i++) {\n if (i == skip) {\n continue;\n }\n msgpack_pack_object(&mp_pck, map.via.map.ptr[i].key);\n msgpack_pack_object(&mp_pck, map.via.map.ptr[i].val);\n }\n\n /* Export the proper buffer */\n flb_free(tmp_out_buf);\n *out_buf = mp_sbuf.data;\n *out_size = mp_sbuf.size;\n\n t = out_time;\n t->tm.tv_sec = time_lookup;\n t->tm.tv_nsec = (tmfrac * 1000000000);\n\n msgpack_unpacked_destroy(&result);\n return *out_size;\n}", "project": "fluent-bit", "hash": 271145738730261777712614129952005894298, "size": 199, "commit_id": "22346a74c07ceb90296be872be2d53eb92252a54", "message": "parser: json: fix double-free (#3453)\n\nSigned-off-by: davkor ", "target": 0, "dataset": "other", "idx": 240791} {"func": "main(int argc, char **argv)\n{\n\tconst char *safepath = \"/bin:/sbin:/usr/bin:/usr/sbin:\"\n\t \"/usr/local/bin:/usr/local/sbin\";\n\tconst char *confpath = NULL;\n\tchar *shargv[] = { NULL, NULL };\n\tchar *sh;\n\tconst char *p;\n\tconst char *cmd;\n\tchar cmdline[LINE_MAX];\n\tstruct passwd mypwstore, targpwstore;\n\tstruct passwd *mypw, *targpw;\n\tconst struct rule *rule;\n\tuid_t uid;\n\tuid_t target = 0;\n\tgid_t groups[NGROUPS_MAX + 1];\n\tint ngroups;\n\tint i, ch, rv;\n\tint sflag = 0;\n\tint nflag = 0;\n\tchar cwdpath[PATH_MAX];\n\tconst char *cwd;\n\tchar **envp;\n\n\tsetprogname(\"doas\");\n\n\tclosefrom(STDERR_FILENO + 1);\n\n\tuid = getuid();\n\n\twhile ((ch = getopt(argc, argv, \"+C:Lnsu:\")) != -1) {\n\t\tswitch (ch) {\n\t\tcase 'C':\n\t\t\tconfpath = optarg;\n\t\t\tbreak;\n\t\tcase 'L':\n#if defined(USE_TIMESTAMP)\n\t\t\texit(timestamp_clear() == -1);\n#else\n\t\t\texit(0);\n#endif\n\t\tcase 'u':\n\t\t\tif (parseuid(optarg, &target) != 0)\n\t\t\t\terrx(1, \"unknown user\");\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\tnflag = 1;\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tsflag = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage();\n\t\t\tbreak;\n\t\t}\n\t}\n\targv += optind;\n\targc -= optind;\n\n\tif (confpath) {\n\t\tif (sflag)\n\t\t\tusage();\n\t} else if ((!sflag && !argc) || (sflag && argc))\n\t\tusage();\n\n\trv = mygetpwuid_r(uid, &mypwstore, &mypw);\n\tif (rv != 0)\n\t\terr(1, \"getpwuid_r failed\");\n\tif (mypw == NULL)\n\t\terrx(1, \"no passwd entry for self\");\n\tngroups = getgroups(NGROUPS_MAX, groups);\n\tif (ngroups == -1)\n\t\terr(1, \"can't get groups\");\n\tgroups[ngroups++] = getgid();\n\n\tif (sflag) {\n\t\tsh = getenv(\"SHELL\");\n\t\tif (sh == NULL || *sh == '\\0') {\n\t\t\tshargv[0] = mypw->pw_shell;\n\t\t} else\n\t\t\tshargv[0] = sh;\n\t\targv = shargv;\n\t\targc = 1;\n\t}\n\n\tif (confpath) {\n\t\tcheckconfig(confpath, argc, argv, uid, groups, ngroups,\n\t\t target);\n\t\texit(1);\t/* fail safe */\n\t}\n\n\tif (geteuid())\n\t\terrx(1, \"not installed setuid\");\n\n\tparseconfig(DOAS_CONF, 1);\n\n\t/* cmdline is used only for logging, no need to abort on truncate */\n\t(void)strlcpy(cmdline, argv[0], sizeof(cmdline));\n\tfor (i = 1; i < argc; i++) {\n\t\tif (strlcat(cmdline, \" \", sizeof(cmdline)) >= sizeof(cmdline))\n\t\t\tbreak;\n\t\tif (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))\n\t\t\tbreak;\n\t}\n\n\tcmd = argv[0];\n\tif (!permit(uid, groups, ngroups, &rule, target, cmd,\n\t (const char **)argv + 1)) {\n\t\tsyslog(LOG_AUTHPRIV | LOG_NOTICE,\n\t\t \"command not permitted for %s: %s\", mypw->pw_name, cmdline);\n\t\terrc(1, EPERM, NULL);\n\t}\n\n#if defined(USE_SHADOW)\n\tif (!(rule->options & NOPASS)) {\n\t\tif (nflag)\n\t\t\terrx(1, \"Authorization required\");\n\n\t\tshadowauth(mypw->pw_name, rule->options & PERSIST);\n\t}\n#elif !defined(USE_PAM)\n\t/* no authentication provider, only allow NOPASS rules */\n\t(void) nflag;\n\tif (!(rule->options & NOPASS))\n\t\terrx(1, \"Authorization required\");\n#endif\n\n\tif ((p = getenv(\"PATH\")) != NULL)\n\t\tformerpath = strdup(p);\n\tif (formerpath == NULL)\n\t\tformerpath = \"\";\n\n\tif (rule->cmd) {\n\t\tif (setenv(\"PATH\", safepath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", safepath);\n\t}\n\n\trv = mygetpwuid_r(target, &targpwstore, &targpw);\n\tif (rv != 0)\n\t\terr(1, \"getpwuid_r failed\");\n\tif (targpw == NULL)\n\t\terrx(1, \"no passwd entry for target\");\n\n#if defined(USE_PAM)\n\tpamauth(targpw->pw_name, mypw->pw_name, !nflag, rule->options & NOPASS,\n\t rule->options & PERSIST);\n#endif\n\n#ifdef HAVE_LOGIN_CAP_H\n\tif (setusercontext(NULL, targpw, target, LOGIN_SETGROUP |\n\t LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |\n\t LOGIN_SETUSER) != 0)\n\t\terrx(1, \"failed to set user context for target\");\n#else\n\tif (setresgid(targpw->pw_gid, targpw->pw_gid, targpw->pw_gid) != 0)\n\t\terr(1, \"setresgid\");\n\tif (initgroups(targpw->pw_name, targpw->pw_gid) != 0)\n\t\terr(1, \"initgroups\");\n\tif (setresuid(target, target, target) != 0)\n\t\terr(1, \"setresuid\");\n#endif\n\n\tif (getcwd(cwdpath, sizeof(cwdpath)) == NULL)\n\t\tcwd = \"(failed)\";\n\telse\n\t\tcwd = cwdpath;\n\n\tif (!(rule->options & NOLOG)) {\n\t\tsyslog(LOG_AUTHPRIV | LOG_INFO,\n\t\t \"%s ran command %s as %s from %s\",\n\t\t mypw->pw_name, cmdline, targpw->pw_name, cwd);\n\t}\n\n\tenvp = prepenv(rule, mypw, targpw);\n\n\t/* setusercontext set path for the next process, so reset it for us */\n\tif (rule->cmd) {\n\t\tif (setenv(\"PATH\", safepath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", safepath);\n\t} else {\n\t\tif (setenv(\"PATH\", formerpath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", formerpath);\n\t}\n\texecvpe(cmd, argv, envp);\n\tif (errno == ENOENT)\n\t\terrx(1, \"%s: command not found\", cmd);\n\terr(1, \"%s\", cmd);\n}", "project": "OpenDoas", "hash": 321353994930714283258779977752854978365, "size": 188, "commit_id": "d5acd52e2a15c36a8e06f9103d35622933aa422d", "message": "correctly reset path for rules without specific command\n\nThis is a fixup for commit 01c658f8c45cb92a343be5f32aa6da70b2032168\nwhere the behaviour was changed to not inherit the PATH variable\nby default.", "target": 1, "dataset": "other", "idx": 196601} {"func": "main(int argc, char **argv)\n{\n\tconst char *safepath = \"/bin:/sbin:/usr/bin:/usr/sbin:\"\n\t \"/usr/local/bin:/usr/local/sbin\";\n\tconst char *confpath = NULL;\n\tchar *shargv[] = { NULL, NULL };\n\tchar *sh;\n\tconst char *p;\n\tconst char *cmd;\n\tchar cmdline[LINE_MAX];\n\tstruct passwd mypwstore, targpwstore;\n\tstruct passwd *mypw, *targpw;\n\tconst struct rule *rule;\n\tuid_t uid;\n\tuid_t target = 0;\n\tgid_t groups[NGROUPS_MAX + 1];\n\tint ngroups;\n\tint i, ch, rv;\n\tint sflag = 0;\n\tint nflag = 0;\n\tchar cwdpath[PATH_MAX];\n\tconst char *cwd;\n\tchar **envp;\n\n\tsetprogname(\"doas\");\n\n\tclosefrom(STDERR_FILENO + 1);\n\n\tuid = getuid();\n\n\twhile ((ch = getopt(argc, argv, \"+C:Lnsu:\")) != -1) {\n\t\tswitch (ch) {\n\t\tcase 'C':\n\t\t\tconfpath = optarg;\n\t\t\tbreak;\n\t\tcase 'L':\n#if defined(USE_TIMESTAMP)\n\t\t\texit(timestamp_clear() == -1);\n#else\n\t\t\texit(0);\n#endif\n\t\tcase 'u':\n\t\t\tif (parseuid(optarg, &target) != 0)\n\t\t\t\terrx(1, \"unknown user\");\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\tnflag = 1;\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tsflag = 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage();\n\t\t\tbreak;\n\t\t}\n\t}\n\targv += optind;\n\targc -= optind;\n\n\tif (confpath) {\n\t\tif (sflag)\n\t\t\tusage();\n\t} else if ((!sflag && !argc) || (sflag && argc))\n\t\tusage();\n\n\trv = mygetpwuid_r(uid, &mypwstore, &mypw);\n\tif (rv != 0)\n\t\terr(1, \"getpwuid_r failed\");\n\tif (mypw == NULL)\n\t\terrx(1, \"no passwd entry for self\");\n\tngroups = getgroups(NGROUPS_MAX, groups);\n\tif (ngroups == -1)\n\t\terr(1, \"can't get groups\");\n\tgroups[ngroups++] = getgid();\n\n\tif (sflag) {\n\t\tsh = getenv(\"SHELL\");\n\t\tif (sh == NULL || *sh == '\\0') {\n\t\t\tshargv[0] = mypw->pw_shell;\n\t\t} else\n\t\t\tshargv[0] = sh;\n\t\targv = shargv;\n\t\targc = 1;\n\t}\n\n\tif (confpath) {\n\t\tcheckconfig(confpath, argc, argv, uid, groups, ngroups,\n\t\t target);\n\t\texit(1);\t/* fail safe */\n\t}\n\n\tif (geteuid())\n\t\terrx(1, \"not installed setuid\");\n\n\tparseconfig(DOAS_CONF, 1);\n\n\t/* cmdline is used only for logging, no need to abort on truncate */\n\t(void)strlcpy(cmdline, argv[0], sizeof(cmdline));\n\tfor (i = 1; i < argc; i++) {\n\t\tif (strlcat(cmdline, \" \", sizeof(cmdline)) >= sizeof(cmdline))\n\t\t\tbreak;\n\t\tif (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))\n\t\t\tbreak;\n\t}\n\n\tcmd = argv[0];\n\tif (!permit(uid, groups, ngroups, &rule, target, cmd,\n\t (const char **)argv + 1)) {\n\t\tsyslog(LOG_AUTHPRIV | LOG_NOTICE,\n\t\t \"command not permitted for %s: %s\", mypw->pw_name, cmdline);\n\t\terrc(1, EPERM, NULL);\n\t}\n\n#if defined(USE_SHADOW)\n\tif (!(rule->options & NOPASS)) {\n\t\tif (nflag)\n\t\t\terrx(1, \"Authorization required\");\n\n\t\tshadowauth(mypw->pw_name, rule->options & PERSIST);\n\t}\n#elif !defined(USE_PAM)\n\t/* no authentication provider, only allow NOPASS rules */\n\t(void) nflag;\n\tif (!(rule->options & NOPASS))\n\t\terrx(1, \"Authorization required\");\n#endif\n\n\tif ((p = getenv(\"PATH\")) != NULL)\n\t\tformerpath = strdup(p);\n\tif (formerpath == NULL)\n\t\tformerpath = \"\";\n\n\tif (rule->cmd) {\n\t\tif (setenv(\"PATH\", safepath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", safepath);\n\t}\n\n\trv = mygetpwuid_r(target, &targpwstore, &targpw);\n\tif (rv != 0)\n\t\terr(1, \"getpwuid_r failed\");\n\tif (targpw == NULL)\n\t\terrx(1, \"no passwd entry for target\");\n\n#if defined(USE_PAM)\n\tpamauth(targpw->pw_name, mypw->pw_name, !nflag, rule->options & NOPASS,\n\t rule->options & PERSIST);\n#endif\n\n#ifdef HAVE_LOGIN_CAP_H\n\tif (setusercontext(NULL, targpw, target, LOGIN_SETGROUP |\n\t LOGIN_SETPATH |\n\t LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |\n\t LOGIN_SETUSER) != 0)\n\t\terrx(1, \"failed to set user context for target\");\n#else\n\tif (setresgid(targpw->pw_gid, targpw->pw_gid, targpw->pw_gid) != 0)\n\t\terr(1, \"setresgid\");\n\tif (initgroups(targpw->pw_name, targpw->pw_gid) != 0)\n\t\terr(1, \"initgroups\");\n\tif (setresuid(target, target, target) != 0)\n\t\terr(1, \"setresuid\");\n\tif (setenv(\"PATH\", safepath, 1) == -1)\n\t\terr(1, \"failed to set PATH '%s'\", safepath);\n#endif\n\n\tif (getcwd(cwdpath, sizeof(cwdpath)) == NULL)\n\t\tcwd = \"(failed)\";\n\telse\n\t\tcwd = cwdpath;\n\n\tif (!(rule->options & NOLOG)) {\n\t\tsyslog(LOG_AUTHPRIV | LOG_INFO,\n\t\t \"%s ran command %s as %s from %s\",\n\t\t mypw->pw_name, cmdline, targpw->pw_name, cwd);\n\t}\n\n\tenvp = prepenv(rule, mypw, targpw);\n\n\t/* setusercontext set path for the next process, so reset it for us */\n\tif (rule->cmd) {\n\t\tif (setenv(\"PATH\", safepath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", safepath);\n\t} else {\n\t\tif (setenv(\"PATH\", formerpath, 1) == -1)\n\t\t\terr(1, \"failed to set PATH '%s'\", formerpath);\n\t}\n\texecvpe(cmd, argv, envp);\n\tif (errno == ENOENT)\n\t\terrx(1, \"%s: command not found\", cmd);\n\terr(1, \"%s\", cmd);\n}", "project": "OpenDoas", "hash": 292077285564712260600228001977188221108, "size": 191, "commit_id": "d5acd52e2a15c36a8e06f9103d35622933aa422d", "message": "correctly reset path for rules without specific command\n\nThis is a fixup for commit 01c658f8c45cb92a343be5f32aa6da70b2032168\nwhere the behaviour was changed to not inherit the PATH variable\nby default.", "target": 0, "dataset": "other", "idx": 240829} {"func": "bool WindowsServiceControl::install( const QString& filePath, const QString& displayName )\n{\n\tm_serviceHandle = CreateService(\n\t\t\t\tm_serviceManager,\t\t// SCManager database\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( m_name ),\t// name of service\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( displayName ),// name to display\n\t\t\t\tSERVICE_ALL_ACCESS,\t// desired access\n\t\t\t\tSERVICE_WIN32_OWN_PROCESS,\n\t\t\t\t// service type\n\t\t\t\tSERVICE_AUTO_START,\t// start type\n\t\t\t\tSERVICE_ERROR_NORMAL,\t// error control type\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( filePath ),\t\t// service's binary\n\t\t\t\tnullptr,\t\t\t// no load ordering group\n\t\t\t\tnullptr,\t\t\t// no tag identifier\n\t\t\t\tL\"Tcpip\\0RpcSs\\0\\0\",\t\t// dependencies\n\t\t\t\tnullptr,\t\t\t// LocalSystem account\n\t\t\t\tnullptr );\t\t\t// no password\n\n\tif( m_serviceHandle == nullptr )\n\t{\n\t\tconst auto error = GetLastError();\n\t\tif( error == ERROR_SERVICE_EXISTS )\n\t\t{\n\t\t\tvCritical() << qUtf8Printable( tr( \"The service \\\"%1\\\" is already installed.\" ).arg( m_name ) );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvCritical() << qUtf8Printable( tr( \"The service \\\"%1\\\" could not be installed.\" ).arg( m_name ) );\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tSC_ACTION serviceActions;\n\tserviceActions.Delay = 10000;\n\tserviceActions.Type = SC_ACTION_RESTART;\n\n\tSERVICE_FAILURE_ACTIONS serviceFailureActions;\n\tserviceFailureActions.dwResetPeriod = 0;\n\tserviceFailureActions.lpRebootMsg = nullptr;\n\tserviceFailureActions.lpCommand = nullptr;\n\tserviceFailureActions.lpsaActions = &serviceActions;\n\tserviceFailureActions.cActions = 1;\n\tChangeServiceConfig2( m_serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS, &serviceFailureActions );\n\n\t// Everything went fine\n\tvInfo() << qUtf8Printable( tr( \"The service \\\"%1\\\" has been installed successfully.\" ).arg( m_name ) );\n\n\treturn true;\n}", "project": "veyon", "hash": 215268809291038026293397703676241296444, "size": 50, "commit_id": "f231ec511b9a09f43f49b2c7bb7c60b8046276b1", "message": "WindowsServiceControl: quote service binary path\n\nFix unquoted service path vulnerability.\n\nCloses #657.", "target": 1, "dataset": "other", "idx": 196610} {"func": "bool WindowsServiceControl::install( const QString& filePath, const QString& displayName )\n{\n\tconst auto binaryPath = QStringLiteral(\"\\\"%1\\\"\").arg( QString( filePath ).replace( QLatin1Char('\"'), QString() ) );\n\n\tm_serviceHandle = CreateService(\n\t\t\t\tm_serviceManager,\t\t// SCManager database\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( m_name ),\t// name of service\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( displayName ),// name to display\n\t\t\t\tSERVICE_ALL_ACCESS,\t// desired access\n\t\t\t\tSERVICE_WIN32_OWN_PROCESS,\n\t\t\t\t// service type\n\t\t\t\tSERVICE_AUTO_START,\t// start type\n\t\t\t\tSERVICE_ERROR_NORMAL,\t// error control type\n\t\t\t\tWindowsCoreFunctions::toConstWCharArray( binaryPath ),\t\t// service's binary\n\t\t\t\tnullptr,\t\t\t// no load ordering group\n\t\t\t\tnullptr,\t\t\t// no tag identifier\n\t\t\t\tL\"Tcpip\\0RpcSs\\0\\0\",\t\t// dependencies\n\t\t\t\tnullptr,\t\t\t// LocalSystem account\n\t\t\t\tnullptr );\t\t\t// no password\n\n\tif( m_serviceHandle == nullptr )\n\t{\n\t\tconst auto error = GetLastError();\n\t\tif( error == ERROR_SERVICE_EXISTS )\n\t\t{\n\t\t\tvCritical() << qUtf8Printable( tr( \"The service \\\"%1\\\" is already installed.\" ).arg( m_name ) );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvCritical() << qUtf8Printable( tr( \"The service \\\"%1\\\" could not be installed.\" ).arg( m_name ) );\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tSC_ACTION serviceActions;\n\tserviceActions.Delay = 10000;\n\tserviceActions.Type = SC_ACTION_RESTART;\n\n\tSERVICE_FAILURE_ACTIONS serviceFailureActions;\n\tserviceFailureActions.dwResetPeriod = 0;\n\tserviceFailureActions.lpRebootMsg = nullptr;\n\tserviceFailureActions.lpCommand = nullptr;\n\tserviceFailureActions.lpsaActions = &serviceActions;\n\tserviceFailureActions.cActions = 1;\n\tChangeServiceConfig2( m_serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS, &serviceFailureActions );\n\n\t// Everything went fine\n\tvInfo() << qUtf8Printable( tr( \"The service \\\"%1\\\" has been installed successfully.\" ).arg( m_name ) );\n\n\treturn true;\n}", "project": "veyon", "hash": 54175189195648828986613730583176708145, "size": 52, "commit_id": "f231ec511b9a09f43f49b2c7bb7c60b8046276b1", "message": "WindowsServiceControl: quote service binary path\n\nFix unquoted service path vulnerability.\n\nCloses #657.", "target": 0, "dataset": "other", "idx": 241036} {"func": "void ndpi_search_openvpn(struct ndpi_detection_module_struct* ndpi_struct,\n struct ndpi_flow_struct* flow) {\n struct ndpi_packet_struct* packet = &flow->packet;\n const u_int8_t * ovpn_payload = packet->payload;\n const u_int8_t * session_remote;\n u_int8_t opcode;\n u_int8_t alen;\n int8_t hmac_size;\n int8_t failed = 0;\n\n if(packet->payload_packet_len >= 40) {\n // skip openvpn TCP transport packet size\n if(packet->tcp != NULL)\n ovpn_payload += 2;\n\n opcode = ovpn_payload[0] & P_OPCODE_MASK;\n\n if(packet->udp) {\n#ifdef DEBUG\n printf(\"[packet_id: %u][opcode: %u][Packet ID: %d][%u <-> %u][len: %u]\\n\",\n\t flow->num_processed_pkts,\n\t opcode, check_pkid_and_detect_hmac_size(ovpn_payload),\n\t htons(packet->udp->source), htons(packet->udp->dest), packet->payload_packet_len);\t \n#endif\n \n if(\n\t (flow->num_processed_pkts == 1)\n\t && (\n\t ((packet->payload_packet_len == 112)\n\t && ((opcode == 168) || (opcode == 192))\n\t )\n\t || ((packet->payload_packet_len == 80)\n\t\t && ((opcode == 184) || (opcode == 88) || (opcode == 160) || (opcode == 168) || (opcode == 200)))\n\t )) {\n\tNDPI_LOG_INFO(ndpi_struct,\"found openvpn\\n\");\n\tndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_OPENVPN, NDPI_PROTOCOL_UNKNOWN);\n\treturn;\n }\n }\n \n if(flow->ovpn_counter < P_HARD_RESET_CLIENT_MAX_COUNT && (opcode == P_CONTROL_HARD_RESET_CLIENT_V1 ||\n\t\t\t\t opcode == P_CONTROL_HARD_RESET_CLIENT_V2)) {\n if(check_pkid_and_detect_hmac_size(ovpn_payload) > 0) {\n memcpy(flow->ovpn_session_id, ovpn_payload+1, 8);\n\n NDPI_LOG_DBG2(ndpi_struct,\n\t\t \"session key: %02x%02x%02x%02x%02x%02x%02x%02x\\n\",\n\t\t flow->ovpn_session_id[0], flow->ovpn_session_id[1], flow->ovpn_session_id[2], flow->ovpn_session_id[3],\n\t\t flow->ovpn_session_id[4], flow->ovpn_session_id[5], flow->ovpn_session_id[6], flow->ovpn_session_id[7]);\n }\n } else if(flow->ovpn_counter >= 1 && flow->ovpn_counter <= P_HARD_RESET_CLIENT_MAX_COUNT &&\n (opcode == P_CONTROL_HARD_RESET_SERVER_V1 || opcode == P_CONTROL_HARD_RESET_SERVER_V2)) {\n\n hmac_size = check_pkid_and_detect_hmac_size(ovpn_payload);\n\n if(hmac_size > 0) {\n alen = ovpn_payload[P_PACKET_ID_ARRAY_LEN_OFFSET(hmac_size)];\n if (alen > 0) {\n\t session_remote = ovpn_payload + P_PACKET_ID_ARRAY_LEN_OFFSET(hmac_size) + 1 + alen * 4;\n\n if(memcmp(flow->ovpn_session_id, session_remote, 8) == 0) {\n\t NDPI_LOG_INFO(ndpi_struct,\"found openvpn\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_OPENVPN, NDPI_PROTOCOL_UNKNOWN);\n\t return;\n\t } else {\n NDPI_LOG_DBG2(ndpi_struct,\n\t\t \"key mismatch: %02x%02x%02x%02x%02x%02x%02x%02x\\n\",\n\t\t session_remote[0], session_remote[1], session_remote[2], session_remote[3],\n\t\t session_remote[4], session_remote[5], session_remote[6], session_remote[7]);\n failed = 1;\n }\n } else\n failed = 1;\n } else\n failed = 1;\n } else\n failed = 1;\n\n flow->ovpn_counter++;\n \n if(failed) {\n NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n }\n }\n}", "project": "nDPI", "hash": 263464745339090965084831362920390201622, "size": 85, "commit_id": "8e7b1ea7a136cc4e4aa9880072ec2d69900a825e", "message": "Fix for potential heap-buffer-overflow in ndpi_search_openvpn", "target": 1, "dataset": "other", "idx": 196624} {"func": "void ndpi_search_openvpn(struct ndpi_detection_module_struct* ndpi_struct,\n struct ndpi_flow_struct* flow) {\n struct ndpi_packet_struct* packet = &flow->packet;\n const u_int8_t * ovpn_payload = packet->payload;\n const u_int8_t * session_remote;\n u_int8_t opcode;\n u_int8_t alen;\n int8_t hmac_size;\n int8_t failed = 0;\n /* No u_ */int16_t ovpn_payload_len = packet->payload_packet_len;\n \n if(ovpn_payload_len >= 40) {\n // skip openvpn TCP transport packet size\n if(packet->tcp != NULL)\n ovpn_payload += 2, ovpn_payload_len -= 2;;\n\n opcode = ovpn_payload[0] & P_OPCODE_MASK;\n\n if(packet->udp) {\n#ifdef DEBUG\n printf(\"[packet_id: %u][opcode: %u][Packet ID: %d][%u <-> %u][len: %u]\\n\",\n\t flow->num_processed_pkts,\n\t opcode, check_pkid_and_detect_hmac_size(ovpn_payload),\n\t htons(packet->udp->source), htons(packet->udp->dest), ovpn_payload_len);\t \n#endif\n \n if(\n\t (flow->num_processed_pkts == 1)\n\t && (\n\t ((ovpn_payload_len == 112)\n\t && ((opcode == 168) || (opcode == 192))\n\t )\n\t || ((ovpn_payload_len == 80)\n\t\t && ((opcode == 184) || (opcode == 88) || (opcode == 160) || (opcode == 168) || (opcode == 200)))\n\t )) {\n\tNDPI_LOG_INFO(ndpi_struct,\"found openvpn\\n\");\n\tndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_OPENVPN, NDPI_PROTOCOL_UNKNOWN);\n\treturn;\n }\n }\n \n if(flow->ovpn_counter < P_HARD_RESET_CLIENT_MAX_COUNT && (opcode == P_CONTROL_HARD_RESET_CLIENT_V1 ||\n\t\t\t\t opcode == P_CONTROL_HARD_RESET_CLIENT_V2)) {\n if(check_pkid_and_detect_hmac_size(ovpn_payload) > 0) {\n memcpy(flow->ovpn_session_id, ovpn_payload+1, 8);\n\n NDPI_LOG_DBG2(ndpi_struct,\n\t\t \"session key: %02x%02x%02x%02x%02x%02x%02x%02x\\n\",\n\t\t flow->ovpn_session_id[0], flow->ovpn_session_id[1], flow->ovpn_session_id[2], flow->ovpn_session_id[3],\n\t\t flow->ovpn_session_id[4], flow->ovpn_session_id[5], flow->ovpn_session_id[6], flow->ovpn_session_id[7]);\n }\n } else if(flow->ovpn_counter >= 1 && flow->ovpn_counter <= P_HARD_RESET_CLIENT_MAX_COUNT &&\n (opcode == P_CONTROL_HARD_RESET_SERVER_V1 || opcode == P_CONTROL_HARD_RESET_SERVER_V2)) {\n\n hmac_size = check_pkid_and_detect_hmac_size(ovpn_payload);\n\n if(hmac_size > 0) {\n\tu_int16_t offset = P_PACKET_ID_ARRAY_LEN_OFFSET(hmac_size);\n\t \n alen = ovpn_payload[offset];\n\t\n if (alen > 0) {\n\t offset += 1 + alen * 4;\n\n\t if((offset+8) <= ovpn_payload_len) {\n\t session_remote = &ovpn_payload[offset];\n\t \n\t if(memcmp(flow->ovpn_session_id, session_remote, 8) == 0) {\n\t NDPI_LOG_INFO(ndpi_struct,\"found openvpn\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_OPENVPN, NDPI_PROTOCOL_UNKNOWN);\n\t return;\n\t } else {\n\t NDPI_LOG_DBG2(ndpi_struct,\n\t\t\t \"key mismatch: %02x%02x%02x%02x%02x%02x%02x%02x\\n\",\n\t\t\t session_remote[0], session_remote[1], session_remote[2], session_remote[3],\n\t\t\t session_remote[4], session_remote[5], session_remote[6], session_remote[7]);\n\t failed = 1;\n\t }\n\t } else\n\t failed = 1;\n\t} else\n failed = 1;\n } else\n failed = 1;\n } else\n failed = 1;\n\n flow->ovpn_counter++;\n \n if(failed) {\n NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n }\n }\n}", "project": "nDPI", "hash": 292660118622334727722308632088083734812, "size": 94, "commit_id": "8e7b1ea7a136cc4e4aa9880072ec2d69900a825e", "message": "Fix for potential heap-buffer-overflow in ndpi_search_openvpn", "target": 0, "dataset": "other", "idx": 241321} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& input_sizes = context->input(0);\n const Tensor& filter = context->input(1);\n const Tensor& out_backprop = context->input(2);\n\n TensorShape input_shape;\n OP_REQUIRES_OK(context,\n Conv2DBackpropComputeInputShape(input_sizes, filter.shape(),\n out_backprop.shape(),\n data_format_, &input_shape));\n\n ConvBackpropDimensions dims;\n OP_REQUIRES_OK(context,\n ConvBackpropComputeDimensionsV2(\n \"Conv2DCustomBackpropInput\", /*num_spatial_dims=*/2,\n input_shape, filter.shape(), out_backprop.shape(),\n /*dilations=*/{1, 1, 1, 1}, strides_, padding_,\n explicit_paddings_, data_format_, &dims));\n\n OP_REQUIRES(context, dims.in_depth == filter.shape().dim_size(2),\n errors::InvalidArgument(\"Computed input depth \", dims.in_depth,\n \" doesn't match filter input depth \",\n filter.shape().dim_size(2)));\n OP_REQUIRES(\n context, dims.out_depth == filter.shape().dim_size(3),\n errors::InvalidArgument(\"Computed output depth \", dims.out_depth,\n \" doesn't match filter output depth \",\n filter.shape().dim_size(3)));\n\n Tensor* in_backprop = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, input_shape, &in_backprop));\n\n // If there is nothing to compute, return.\n if (input_shape.num_elements() == 0) {\n return;\n }\n\n// TODO(ezhulenev): Remove custom kernel and move XSMM support to\n// LaunchConv2DBackpropInputOp functor.\n#if defined TENSORFLOW_USE_LIBXSMM_CONVOLUTIONS && \\\n defined TENSORFLOW_USE_LIBXSMM_BACKWARD_CONVOLUTIONS\n int64 pad_top, pad_bottom;\n int64 pad_left, pad_right;\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[0].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[0].stride, padding_,\n &dims.spatial_dims[0].output_size, &pad_top, &pad_bottom));\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[1].input_size, dims.spatial_dims[1].filter_size,\n dims.spatial_dims[1].stride, padding_,\n &dims.spatial_dims[1].output_size, &pad_left, &pad_right));\n\n if (pad_left == pad_right && pad_top == pad_bottom) {\n if (LaunchXsmmBackwardInputConvolution()(\n context, context->eigen_device(),\n in_backprop->tensor(), filter.tensor(),\n out_backprop.tensor(), dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size,\n static_cast(dims.spatial_dims[0].stride),\n static_cast(dims.spatial_dims[1].stride),\n static_cast(pad_top), static_cast(pad_left),\n data_format_)) {\n return;\n }\n }\n#else\n int64 pad_top, pad_bottom;\n int64 pad_left, pad_right;\n#endif\n if (padding_ == Padding::EXPLICIT) {\n pad_top = explicit_paddings_[2];\n pad_bottom = explicit_paddings_[3];\n pad_left = explicit_paddings_[4];\n pad_right = explicit_paddings_[5];\n }\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[0].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[0].stride, padding_,\n &dims.spatial_dims[0].output_size, &pad_top, &pad_bottom));\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[1].input_size, dims.spatial_dims[1].filter_size,\n dims.spatial_dims[1].stride, padding_,\n &dims.spatial_dims[1].output_size, &pad_left, &pad_right));\n\n // The total dimension size of each kernel.\n const int filter_total_size = dims.spatial_dims[0].filter_size *\n dims.spatial_dims[1].filter_size *\n dims.in_depth;\n // The output image size is the spatial size of the output.\n const int output_image_size =\n dims.spatial_dims[0].output_size * dims.spatial_dims[1].output_size;\n\n // TODO(andydavis) Get L2/L3 cache sizes from device.\n const size_t l2_cache_size = 256LL << 10;\n const size_t l3_cache_size = 30LL << 20;\n\n // Use L3 cache size as target working set size.\n const size_t target_working_set_size = l3_cache_size / sizeof(T);\n\n // Calculate size of matrices involved in MatMul: C = A x B.\n const size_t size_A = output_image_size * dims.out_depth;\n\n const size_t size_B = filter_total_size * dims.out_depth;\n\n const size_t size_C = output_image_size * filter_total_size;\n\n const size_t work_unit_size = size_A + size_B + size_C;\n\n auto worker_threads = *(context->device()->tensorflow_cpu_worker_threads());\n\n // Calculate per-thread work unit size.\n const size_t thread_work_unit_size =\n work_unit_size / worker_threads.num_threads;\n\n // Set minimum per-thread work unit size to size of L2 cache.\n const size_t min_thread_work_unit_size = l2_cache_size / sizeof(T);\n\n // Use parallel tensor contractions if there is no batching, or if the\n // minimum per-thread work unit size threshold has been exceeded.\n // Otherwise, revert to multiple single-threaded matmul ops running in\n // parallel to keep all threads busy.\n // TODO(andydavis) Explore alternatives to branching the code in this way\n // (i.e. run multiple, parallel tensor contractions in another thread pool).\n const bool use_parallel_contraction =\n dims.batch_size == 1 ||\n thread_work_unit_size >= min_thread_work_unit_size;\n\n const size_t shard_size =\n use_parallel_contraction\n ? 1\n : (target_working_set_size + work_unit_size - 1) / work_unit_size;\n\n Tensor col_buffer;\n OP_REQUIRES_OK(context,\n context->allocate_temp(\n DataTypeToEnum::value,\n TensorShape({static_cast(shard_size),\n static_cast(output_image_size),\n static_cast(filter_total_size)}),\n &col_buffer));\n\n // The input offset corresponding to a single input image.\n const int input_offset = dims.spatial_dims[0].input_size *\n dims.spatial_dims[1].input_size * dims.in_depth;\n // The output offset corresponding to a single output image.\n const int output_offset = dims.spatial_dims[0].output_size *\n dims.spatial_dims[1].output_size * dims.out_depth;\n\n const T* filter_data = filter.template flat().data();\n T* col_buffer_data = col_buffer.template flat().data();\n const T* out_backprop_data = out_backprop.template flat().data();\n\n auto in_backprop_flat = in_backprop->template flat();\n T* input_backprop_data = in_backprop_flat.data();\n in_backprop_flat.device(context->eigen_device()) =\n in_backprop_flat.constant(T(0));\n\n if (use_parallel_contraction) {\n typedef Eigen::TensorMap,\n Eigen::Unaligned>\n TensorMap;\n typedef Eigen::TensorMap,\n Eigen::Unaligned>\n ConstTensorMap;\n\n // Initialize contraction dims (we need to transpose 'B' below).\n Eigen::array, 1> contract_dims;\n contract_dims[0].first = 1;\n contract_dims[0].second = 1;\n\n for (int image_id = 0; image_id < dims.batch_size; ++image_id) {\n // Compute gradient into col_buffer.\n TensorMap C(col_buffer_data, output_image_size, filter_total_size);\n\n ConstTensorMap A(out_backprop_data + output_offset * image_id,\n output_image_size, dims.out_depth);\n ConstTensorMap B(filter_data, filter_total_size, dims.out_depth);\n\n C.device(context->eigen_cpu_device()) = A.contract(B, contract_dims);\n\n Col2im(\n col_buffer_data, dims.in_depth, dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[1].filter_size, pad_top, pad_left, pad_bottom,\n pad_right, dims.spatial_dims[0].stride, dims.spatial_dims[1].stride,\n input_backprop_data);\n\n input_backprop_data += input_offset;\n }\n } else {\n for (int image_id = 0; image_id < dims.batch_size;\n image_id += shard_size) {\n const int shard_limit =\n std::min(static_cast(shard_size),\n static_cast(dims.batch_size) - image_id);\n\n auto shard = [&context, &dims, &pad_top, &pad_left, &pad_bottom,\n &pad_right, &output_image_size, &filter_total_size,\n &input_backprop_data, &col_buffer_data,\n &out_backprop_data, &filter_data, &input_offset,\n &output_offset, &size_C](int64 start, int64 limit) {\n for (int shard_id = start; shard_id < limit; ++shard_id) {\n T* im2col_buf = col_buffer_data + shard_id * size_C;\n T* input_data = input_backprop_data + shard_id * input_offset;\n const T* out_data = out_backprop_data + shard_id * output_offset;\n\n Conv2DCustomBackpropInputMatMulFunctor()(\n context, out_data, filter_data, filter_total_size,\n output_image_size, dims.out_depth, im2col_buf);\n\n Col2im(im2col_buf, dims.in_depth,\n dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size,\n dims.spatial_dims[0].filter_size,\n dims.spatial_dims[1].filter_size, pad_top, pad_left,\n pad_bottom, pad_right, dims.spatial_dims[0].stride,\n dims.spatial_dims[1].stride, input_data);\n }\n };\n Shard(worker_threads.num_threads, worker_threads.workers, shard_limit,\n work_unit_size, shard);\n\n input_backprop_data += input_offset * shard_limit;\n out_backprop_data += output_offset * shard_limit;\n }\n }\n }", "project": "tensorflow", "hash": 221795662216558573434423513228112279102, "size": 236, "commit_id": "2be2cdf3a123e231b16f766aa0e27d56b4606535", "message": "Prevent yet another division by zero\n\nPiperOrigin-RevId: 369343977\nChange-Id: I1a60da4cf512e60fd91e069c16e026544632fe7f", "target": 1, "dataset": "other", "idx": 196632} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& input_sizes = context->input(0);\n const Tensor& filter = context->input(1);\n const Tensor& out_backprop = context->input(2);\n\n TensorShape input_shape;\n OP_REQUIRES_OK(context,\n Conv2DBackpropComputeInputShape(input_sizes, filter.shape(),\n out_backprop.shape(),\n data_format_, &input_shape));\n\n ConvBackpropDimensions dims;\n OP_REQUIRES_OK(context,\n ConvBackpropComputeDimensionsV2(\n \"Conv2DCustomBackpropInput\", /*num_spatial_dims=*/2,\n input_shape, filter.shape(), out_backprop.shape(),\n /*dilations=*/{1, 1, 1, 1}, strides_, padding_,\n explicit_paddings_, data_format_, &dims));\n\n OP_REQUIRES(context, dims.in_depth == filter.shape().dim_size(2),\n errors::InvalidArgument(\"Computed input depth \", dims.in_depth,\n \" doesn't match filter input depth \",\n filter.shape().dim_size(2)));\n OP_REQUIRES(\n context, dims.out_depth == filter.shape().dim_size(3),\n errors::InvalidArgument(\"Computed output depth \", dims.out_depth,\n \" doesn't match filter output depth \",\n filter.shape().dim_size(3)));\n\n Tensor* in_backprop = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, input_shape, &in_backprop));\n\n // If there is nothing to compute, return.\n if (input_shape.num_elements() == 0) {\n return;\n }\n\n// TODO(ezhulenev): Remove custom kernel and move XSMM support to\n// LaunchConv2DBackpropInputOp functor.\n#if defined TENSORFLOW_USE_LIBXSMM_CONVOLUTIONS && \\\n defined TENSORFLOW_USE_LIBXSMM_BACKWARD_CONVOLUTIONS\n int64 pad_top, pad_bottom;\n int64 pad_left, pad_right;\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[0].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[0].stride, padding_,\n &dims.spatial_dims[0].output_size, &pad_top, &pad_bottom));\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[1].input_size, dims.spatial_dims[1].filter_size,\n dims.spatial_dims[1].stride, padding_,\n &dims.spatial_dims[1].output_size, &pad_left, &pad_right));\n\n if (pad_left == pad_right && pad_top == pad_bottom) {\n if (LaunchXsmmBackwardInputConvolution()(\n context, context->eigen_device(),\n in_backprop->tensor(), filter.tensor(),\n out_backprop.tensor(), dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size,\n static_cast(dims.spatial_dims[0].stride),\n static_cast(dims.spatial_dims[1].stride),\n static_cast(pad_top), static_cast(pad_left),\n data_format_)) {\n return;\n }\n }\n#else\n int64 pad_top, pad_bottom;\n int64 pad_left, pad_right;\n#endif\n if (padding_ == Padding::EXPLICIT) {\n pad_top = explicit_paddings_[2];\n pad_bottom = explicit_paddings_[3];\n pad_left = explicit_paddings_[4];\n pad_right = explicit_paddings_[5];\n }\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[0].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[0].stride, padding_,\n &dims.spatial_dims[0].output_size, &pad_top, &pad_bottom));\n OP_REQUIRES_OK(\n context,\n GetWindowedOutputSizeVerbose(\n dims.spatial_dims[1].input_size, dims.spatial_dims[1].filter_size,\n dims.spatial_dims[1].stride, padding_,\n &dims.spatial_dims[1].output_size, &pad_left, &pad_right));\n\n // The total dimension size of each kernel.\n const int filter_total_size = dims.spatial_dims[0].filter_size *\n dims.spatial_dims[1].filter_size *\n dims.in_depth;\n // The output image size is the spatial size of the output.\n const int output_image_size =\n dims.spatial_dims[0].output_size * dims.spatial_dims[1].output_size;\n\n // TODO(andydavis) Get L2/L3 cache sizes from device.\n const size_t l2_cache_size = 256LL << 10;\n const size_t l3_cache_size = 30LL << 20;\n\n // Use L3 cache size as target working set size.\n const size_t target_working_set_size = l3_cache_size / sizeof(T);\n\n // Calculate size of matrices involved in MatMul: C = A x B.\n const size_t size_A = output_image_size * dims.out_depth;\n\n const size_t size_B = filter_total_size * dims.out_depth;\n\n const size_t size_C = output_image_size * filter_total_size;\n\n const size_t work_unit_size = size_A + size_B + size_C;\n\n auto worker_threads = *(context->device()->tensorflow_cpu_worker_threads());\n\n // Calculate per-thread work unit size.\n const size_t thread_work_unit_size =\n work_unit_size / worker_threads.num_threads;\n\n // Set minimum per-thread work unit size to size of L2 cache.\n const size_t min_thread_work_unit_size = l2_cache_size / sizeof(T);\n\n // Use parallel tensor contractions if there is no batching, or if the\n // minimum per-thread work unit size threshold has been exceeded.\n // Otherwise, revert to multiple single-threaded matmul ops running in\n // parallel to keep all threads busy.\n // TODO(andydavis) Explore alternatives to branching the code in this way\n // (i.e. run multiple, parallel tensor contractions in another thread pool).\n const bool use_parallel_contraction =\n dims.batch_size == 1 ||\n thread_work_unit_size >= min_thread_work_unit_size;\n\n OP_REQUIRES(\n context, work_unit_size > 0,\n errors::InvalidArgument(\"input, filter_sizes and out_backprop tensors \"\n \"must all have at least 1 element\"));\n\n const size_t shard_size =\n use_parallel_contraction\n ? 1\n : (target_working_set_size + work_unit_size - 1) / work_unit_size;\n\n Tensor col_buffer;\n OP_REQUIRES_OK(context,\n context->allocate_temp(\n DataTypeToEnum::value,\n TensorShape({static_cast(shard_size),\n static_cast(output_image_size),\n static_cast(filter_total_size)}),\n &col_buffer));\n\n // The input offset corresponding to a single input image.\n const int input_offset = dims.spatial_dims[0].input_size *\n dims.spatial_dims[1].input_size * dims.in_depth;\n // The output offset corresponding to a single output image.\n const int output_offset = dims.spatial_dims[0].output_size *\n dims.spatial_dims[1].output_size * dims.out_depth;\n\n const T* filter_data = filter.template flat().data();\n T* col_buffer_data = col_buffer.template flat().data();\n const T* out_backprop_data = out_backprop.template flat().data();\n\n auto in_backprop_flat = in_backprop->template flat();\n T* input_backprop_data = in_backprop_flat.data();\n in_backprop_flat.device(context->eigen_device()) =\n in_backprop_flat.constant(T(0));\n\n if (use_parallel_contraction) {\n typedef Eigen::TensorMap,\n Eigen::Unaligned>\n TensorMap;\n typedef Eigen::TensorMap,\n Eigen::Unaligned>\n ConstTensorMap;\n\n // Initialize contraction dims (we need to transpose 'B' below).\n Eigen::array, 1> contract_dims;\n contract_dims[0].first = 1;\n contract_dims[0].second = 1;\n\n for (int image_id = 0; image_id < dims.batch_size; ++image_id) {\n // Compute gradient into col_buffer.\n TensorMap C(col_buffer_data, output_image_size, filter_total_size);\n\n ConstTensorMap A(out_backprop_data + output_offset * image_id,\n output_image_size, dims.out_depth);\n ConstTensorMap B(filter_data, filter_total_size, dims.out_depth);\n\n C.device(context->eigen_cpu_device()) = A.contract(B, contract_dims);\n\n Col2im(\n col_buffer_data, dims.in_depth, dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size, dims.spatial_dims[0].filter_size,\n dims.spatial_dims[1].filter_size, pad_top, pad_left, pad_bottom,\n pad_right, dims.spatial_dims[0].stride, dims.spatial_dims[1].stride,\n input_backprop_data);\n\n input_backprop_data += input_offset;\n }\n } else {\n for (int image_id = 0; image_id < dims.batch_size;\n image_id += shard_size) {\n const int shard_limit =\n std::min(static_cast(shard_size),\n static_cast(dims.batch_size) - image_id);\n\n auto shard = [&context, &dims, &pad_top, &pad_left, &pad_bottom,\n &pad_right, &output_image_size, &filter_total_size,\n &input_backprop_data, &col_buffer_data,\n &out_backprop_data, &filter_data, &input_offset,\n &output_offset, &size_C](int64 start, int64 limit) {\n for (int shard_id = start; shard_id < limit; ++shard_id) {\n T* im2col_buf = col_buffer_data + shard_id * size_C;\n T* input_data = input_backprop_data + shard_id * input_offset;\n const T* out_data = out_backprop_data + shard_id * output_offset;\n\n Conv2DCustomBackpropInputMatMulFunctor()(\n context, out_data, filter_data, filter_total_size,\n output_image_size, dims.out_depth, im2col_buf);\n\n Col2im(im2col_buf, dims.in_depth,\n dims.spatial_dims[0].input_size,\n dims.spatial_dims[1].input_size,\n dims.spatial_dims[0].filter_size,\n dims.spatial_dims[1].filter_size, pad_top, pad_left,\n pad_bottom, pad_right, dims.spatial_dims[0].stride,\n dims.spatial_dims[1].stride, input_data);\n }\n };\n Shard(worker_threads.num_threads, worker_threads.workers, shard_limit,\n work_unit_size, shard);\n\n input_backprop_data += input_offset * shard_limit;\n out_backprop_data += output_offset * shard_limit;\n }\n }\n }", "project": "tensorflow", "hash": 165188925159723349541537214047020092751, "size": 241, "commit_id": "2be2cdf3a123e231b16f766aa0e27d56b4606535", "message": "Prevent yet another division by zero\n\nPiperOrigin-RevId: 369343977\nChange-Id: I1a60da4cf512e60fd91e069c16e026544632fe7f", "target": 0, "dataset": "other", "idx": 241532} {"func": "escape_xml(const char *text)\n{\n\tstatic char *escaped;\n\tstatic size_t escaped_size;\n\tchar *out;\n\tsize_t len;\n\n\tif (!strlen(text)) return \"empty string\";\n\n\tfor (out=escaped, len=0; *text; ++len, ++out, ++text) {\n\t\t/* Make sure there's plenty of room for a quoted character */\n\t\tif ((len + 8) > escaped_size) {\n\t\t\tchar *bigger_escaped;\n\t\t\tescaped_size += 128;\n\t\t\tbigger_escaped = realloc(escaped, escaped_size);\n\t\t\tif (!bigger_escaped) {\n\t\t\t\tfree(escaped);\t/* avoid leaking memory */\n\t\t\t\tescaped = NULL;\n\t\t\t\tescaped_size = 0;\n\t\t\t\t/* Error string is cleverly chosen to fail XML validation */\n\t\t\t\treturn \">>> out of memory <<<\";\n\t\t\t}\n\t\t\tout = bigger_escaped + len;\n\t\t\tescaped = bigger_escaped;\n\t\t}\n\t\tswitch (*text) {\n\t\t\tcase '&':\n\t\t\t\tstrcpy(out, \"&\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tcase '<':\n\t\t\t\tstrcpy(out, \"<\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tcase '>':\n\t\t\t\tstrcpy(out, \">\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t*out = *text;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t*out = '\\x0'; /* NUL terminate the string */\n\treturn escaped;\n}", "project": "exif", "hash": 130225628845924531529156533690677997225, "size": 49, "commit_id": "eb84b0e3c5f2a86013b6fcfb800d187896a648fa", "message": "actually return empty stringand not 'em,pty string' as expected", "target": 1, "dataset": "other", "idx": 196672} {"func": "escape_xml(const char *text)\n{\n\tstatic char *escaped;\n\tstatic size_t escaped_size;\n\tchar *out;\n\tsize_t len;\n\n\tif (!strlen(text)) return \"\";\n\n\tfor (out=escaped, len=0; *text; ++len, ++out, ++text) {\n\t\t/* Make sure there's plenty of room for a quoted character */\n\t\tif ((len + 8) > escaped_size) {\n\t\t\tchar *bigger_escaped;\n\t\t\tescaped_size += 128;\n\t\t\tbigger_escaped = realloc(escaped, escaped_size);\n\t\t\tif (!bigger_escaped) {\n\t\t\t\tfree(escaped);\t/* avoid leaking memory */\n\t\t\t\tescaped = NULL;\n\t\t\t\tescaped_size = 0;\n\t\t\t\t/* Error string is cleverly chosen to fail XML validation */\n\t\t\t\treturn \">>> out of memory <<<\";\n\t\t\t}\n\t\t\tout = bigger_escaped + len;\n\t\t\tescaped = bigger_escaped;\n\t\t}\n\t\tswitch (*text) {\n\t\t\tcase '&':\n\t\t\t\tstrcpy(out, \"&\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tcase '<':\n\t\t\t\tstrcpy(out, \"<\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tcase '>':\n\t\t\t\tstrcpy(out, \">\");\n\t\t\t\tlen += strlen(out) - 1;\n\t\t\t\tout = escaped + len;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t*out = *text;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t*out = '\\x0'; /* NUL terminate the string */\n\treturn escaped;\n}", "project": "exif", "hash": 264716872538103587635258225337770794121, "size": 49, "commit_id": "eb84b0e3c5f2a86013b6fcfb800d187896a648fa", "message": "actually return empty stringand not 'em,pty string' as expected", "target": 0, "dataset": "other", "idx": 242168} {"func": " void Compute(OpKernelContext* context) override {\n const float in_min = context->input(2).flat()(0);\n const float in_max = context->input(3).flat()(0);\n\n ImageResizerState st(align_corners_, false);\n st.ValidateAndCreateOutput(context);\n\n if (!context->status().ok()) return;\n\n // Return if the output is empty.\n if (st.output->NumElements() == 0) return;\n\n typename TTypes::ConstTensor image_data(\n context->input(0).tensor());\n typename TTypes::Tensor output_data(st.output->tensor());\n\n ResizeBilinear(image_data, st.height_scale, st.width_scale, in_min,\n in_max, half_pixel_centers_, &output_data);\n Tensor* out_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &out_min));\n out_min->flat()(0) = in_min;\n\n Tensor* out_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &out_max));\n out_max->flat()(0) = in_max;\n }", "project": "tensorflow", "hash": 327227610424235160739799447249420118357, "size": 26, "commit_id": "f6c40f0c6cbf00d46c7717a26419f2062f2f8694", "message": "Validate min and max arguments to `QuantizedResizeBilinear`.\n\nPiperOrigin-RevId: 369765091\nChange-Id: I33be8b78273ab7d08b97541692fe05cb7f94963a", "target": 1, "dataset": "other", "idx": 196673} {"func": " void Compute(OpKernelContext* context) override {\n const auto& in_min_tensor = context->input(2);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(in_min_tensor.shape()),\n errors::InvalidArgument(\"min must be a scalar\"));\n const float in_min = in_min_tensor.flat()(0);\n const auto& in_max_tensor = context->input(3);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(in_max_tensor.shape()),\n errors::InvalidArgument(\"max must be a scalar\"));\n const float in_max = in_max_tensor.flat()(0);\n\n ImageResizerState st(align_corners_, false);\n st.ValidateAndCreateOutput(context);\n\n if (!context->status().ok()) return;\n\n // Return if the output is empty.\n if (st.output->NumElements() == 0) return;\n\n typename TTypes::ConstTensor image_data(\n context->input(0).tensor());\n typename TTypes::Tensor output_data(st.output->tensor());\n\n ResizeBilinear(image_data, st.height_scale, st.width_scale, in_min,\n in_max, half_pixel_centers_, &output_data);\n Tensor* out_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &out_min));\n out_min->flat()(0) = in_min;\n\n Tensor* out_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &out_max));\n out_max->flat()(0) = in_max;\n }", "project": "tensorflow", "hash": 230635596964007868338231930811957784418, "size": 32, "commit_id": "f6c40f0c6cbf00d46c7717a26419f2062f2f8694", "message": "Validate min and max arguments to `QuantizedResizeBilinear`.\n\nPiperOrigin-RevId: 369765091\nChange-Id: I33be8b78273ab7d08b97541692fe05cb7f94963a", "target": 0, "dataset": "other", "idx": 242186} {"func": "void gf_inspect_format_timecode(const u8 *data, u32 size, u32 tmcd_flags, u32 tc_num, u32 tc_den, u32 tmcd_fpt, char szFmt[100]);\n\nvoid DumpTrackInfo(GF_ISOFile *file, GF_ISOTrackID trackID, Bool full_dump, Bool is_track_num, Bool dump_m4sys)\n{\n\tchar szCodec[RFC6381_CODEC_NAME_SIZE_MAX];\n\tDouble scale, max_rate, rate;\n\tBool is_od_track = 0;\n\tu32 trackNum, i, j, ts, mtype, msub_type, timescale, sr, nb_ch, count, alt_group, nb_groups, nb_edits, cdur, csize, bps, pfmt, codecid;\n\tu64 time_slice, dur, size;\n\ts32 cts_shift;\n\tGF_ESD *esd;\n\tchar szDur[50];\n\tchar *lang;\n\n\tif (!is_track_num) {\n\t\ttrackNum = gf_isom_get_track_by_id(file, trackID);\n\t} else {\n\t\ttrackNum = trackID;\n\t\ttrackID = gf_isom_get_track_id(file, trackNum);\n\t}\n\tif (!trackNum) {\n\t\tM4_LOG(GF_LOG_ERROR, (\"No track with ID %d found\\n\", trackID));\n\t\treturn;\n\t}\n\n\ttimescale = gf_isom_get_media_timescale(file, trackNum);\n\tfprintf(stderr, \"# Track %d Info - ID %d - TimeScale %d\\n\", trackNum, trackID, timescale);\n\n\tdur = gf_isom_get_media_original_duration(file, trackNum);\n\tsize = gf_isom_get_media_duration(file, trackNum);\n\tfprintf(stderr, \"Media Duration %s \", format_duration(dur, timescale, szDur));\n\tif (dur != size)\n\t\tfprintf(stderr, \" (recomputed %s)\", format_duration(size, timescale, szDur));\n\tfprintf(stderr, \"\\n\");\n\n\tif (gf_isom_check_data_reference(file, trackNum, 1) != GF_OK) {\n\t\tM4_LOG(GF_LOG_WARNING, (\"Track uses external data reference not supported by GPAC!\\n\"));\n\t}\n\n\tnb_edits = gf_isom_get_edits_count(file, trackNum);\n\tif (nb_edits)\n\t\tfprintf(stderr, \"Track has %d edits: track duration is %s\\n\", nb_edits, format_duration(gf_isom_get_track_duration(file, trackNum), gf_isom_get_timescale(file), szDur));\n\n\tcts_shift = gf_isom_get_composition_offset_shift(file, trackNum);\n\tif (cts_shift)\n\t\tfprintf(stderr, \"Track composition offset shift (negative CTS offset): %d\\n\", cts_shift);\n\n\tif (gf_isom_is_track_in_root_od(file, trackNum) ) fprintf(stderr, \"Track is present in Root OD\\n\");\n\tif (!gf_isom_is_track_enabled(file, trackNum)) fprintf(stderr, \"Track is disabled\\n\");\n\tgf_isom_get_media_language(file, trackNum, &lang);\n\tfprintf(stderr, \"Media Info: Language \\\"%s (%s)\\\" - \", GetLanguage(lang), lang );\n\tgf_free(lang);\n\tmtype = gf_isom_get_media_type(file, trackNum);\n\tfprintf(stderr, \"Type \\\"%s:\", gf_4cc_to_str(mtype));\n\tmsub_type = gf_isom_get_mpeg4_subtype(file, trackNum, 1);\n\tif (!msub_type) msub_type = gf_isom_get_media_subtype(file, trackNum, 1);\n\tfprintf(stderr, \"%s\\\" - %d samples\\n\", gf_4cc_to_str(msub_type), gf_isom_get_sample_count(file, trackNum));\n\n\tpfmt = gf_pixel_fmt_from_qt_type(msub_type);\n\tcodecid = gf_codec_id_from_isobmf(msub_type);\n\n\tcount = gf_isom_get_track_kind_count(file, trackNum);\n\tfor (i = 0; i < count; i++) {\n\t\tchar *kind_scheme, *kind_value;\n\t\tgf_isom_get_track_kind(file, trackNum, i, &kind_scheme, &kind_value);\n\t\tfprintf(stderr, \"Kind: %s - %s\\n\", kind_scheme ? kind_scheme : \"null\", kind_value ? kind_value : \"null\");\n\t\tif (kind_scheme) gf_free(kind_scheme);\n\t\tif (kind_value) gf_free(kind_value);\n\t}\n\n\tif (gf_isom_is_track_fragmented(file, trackID) ) {\n\t\tu32 defaultDuration, defaultSize, defaultDescriptionIndex, defaultRandomAccess;\n\t\tu8 defaultPadding;\n\t\tu16 defaultDegradationPriority;\n\t\tu32 frag_samples;\n\t\tu64 frag_duration;\n\t\tgf_isom_get_fragmented_samples_info(file, trackID, &frag_samples, &frag_duration);\n\t\tfprintf(stderr, \"Fragmented track: %d samples - Media Duration %s\\n\", frag_samples, format_duration(frag_duration, timescale, szDur));\n\n\t\tgf_isom_get_fragment_defaults(file, trackNum, &defaultDuration, &defaultSize, &defaultDescriptionIndex, &defaultRandomAccess, &defaultPadding, &defaultDegradationPriority);\n\n\t\tfprintf(stderr, \"Fragment sample defaults: duration %d size %d stsd %d sync %d padding %d degradation_priority %d\\n\",\n\t\t\t\tdefaultDuration, defaultSize, defaultDescriptionIndex, defaultRandomAccess,\n\t\t\t\t(u32) defaultPadding, (u32) defaultDegradationPriority\n\t\t);\n\t}\n\n\tif (!gf_isom_is_self_contained(file, trackNum, 1)) {\n\t\tconst char *url, *urn;\n\t\tgf_isom_get_data_reference(file, trackNum, 1, &url, &urn);\n\t\tfprintf(stderr, \"Media Data Location: %s\\n\", url ? url : urn);\n\t}\n\n\tif (full_dump) {\n\t\tconst char *handler_name;\n\t\tgf_isom_get_handler_name(file, trackNum, &handler_name);\n\t\tfprintf(stderr, \"Handler name: %s\\n\", handler_name);\n\t}\n\n\tprint_udta(file, trackNum, GF_FALSE);\n\n\tif (gf_isom_is_video_handler_type(mtype) ) {\n\t\ts32 tx, ty;\n\t\tu32 w, h;\n\t\tu16 bit_depth;\n\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tgf_isom_get_visual_bit_depth(file, trackNum, 1, &bit_depth);\n\t\tfprintf(stderr, \"Visual Sample Entry Info: width=%d height=%d (depth=%d bits)\\n\", w, h, (int)bit_depth);\n\n\t\tgf_isom_get_track_layout_info(file, trackNum, &w, &h, &tx, &ty, NULL);\n\t\tfprintf(stderr, \"Visual Track layout: x=%d y=%d width=%d height=%d\\n\", tx, ty, w, h);\n\t}\n\n\tgf_isom_get_audio_info(file, trackNum, 1, &sr, &nb_ch, &bps);\n\tgf_isom_set_nalu_extract_mode(file, trackNum, GF_ISOM_NALU_EXTRACT_INSPECT);\n\n\tmsub_type = gf_isom_get_media_subtype(file, trackNum, 1);\n\tif (msub_type==GF_ISOM_SUBTYPE_MPEG4_CRYP)\n\t\tgf_isom_get_original_format_type(file, trackNum, 1, &msub_type);\n\n\tif ((msub_type==GF_ISOM_SUBTYPE_MPEG4)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC2_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC3_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_AVC4_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_SVC_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_MVC_H264)\n\t || (msub_type==GF_ISOM_SUBTYPE_LSR1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HVC1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HEV1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HVC2)\n\t || (msub_type==GF_ISOM_SUBTYPE_HEV2)\n\t || (msub_type==GF_ISOM_SUBTYPE_LHV1)\n\t || (msub_type==GF_ISOM_SUBTYPE_LHE1)\n\t || (msub_type==GF_ISOM_SUBTYPE_HVT1)\n\t ) {\n\t\tesd = gf_isom_get_esd(file, trackNum, 1);\n\t\tif (!esd || !esd->decoderConfig) {\n\t\t\tM4_LOG(GF_LOG_WARNING, (\"WARNING: Broken MPEG-4 Track\\n\"));\n\t\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);\n\t\t} else {\n\t\t\tconst char *st = gf_stream_type_name(esd->decoderConfig->streamType);\n\t\t\tif (dump_m4sys) {\n\t\t\t\tif (st) {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Config%s%s Stream - ObjectTypeIndication 0x%02x\\n\",\n\t\t\t\t\t\t\tfull_dump ? \"\\n\\t\" : \": \", st, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Config%sStream Type 0x%02x - ObjectTypeIndication 0x%02x\\n\",\n\t\t\t\t\t\t\tfull_dump ? \"\\n\\t\" : \": \", esd->decoderConfig->streamType, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_OD)\n\t\t\t\tis_od_track=1;\n\n\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\tu32 w, h;\n\t\t\t\tu16 rvc_predef;\n\t\t\t\tw = h = 0;\n\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\tif (!esd->decoderConfig->decoderSpecificInfo) {\n#else\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Visual Size %d x %d\\n\", w, h);\n#endif\n\t\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Non-compliant MPEG-4 Visual track: video_object_layer infos not found in sample description\\n\"));\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGF_M4VDecSpecInfo dsi;\n\t\t\t\t\t\tgf_m4v_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &dsi);\n\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\tw = dsi.width;\n\t\t\t\t\t\th = dsi.height;\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-4 Visual Size %d x %d - %s\\n\", w, h, gf_m4v_get_profile_name(dsi.VideoPL));\n\t\t\t\t\t\tif (dsi.par_den && dsi.par_num) {\n\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\tfprintf(stderr, \"Pixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", dsi.par_num, dsi.par_den, tw, th);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#endif\n\t\t\t\t} else if (gf_isom_get_avc_svc_type(file, trackNum, 1) != GF_ISOM_AVCTYPE_NONE) {\n\t\t\t\t\tGF_AVCConfig *avccfg, *svccfg, *mvccfg;\n\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"AVC/H264 Video - Visual Size %d x %d\\n\", w, h);\n\n\t\t\t\t\tavccfg = gf_isom_avc_config_get(file, trackNum, 1);\n\t\t\t\t\tsvccfg = gf_isom_svc_config_get(file, trackNum, 1);\n\t\t\t\t\tmvccfg = gf_isom_mvc_config_get(file, trackNum, 1);\n\t\t\t\t\tif (!avccfg && !svccfg && !mvccfg) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\tNon-compliant AVC track: SPS/PPS not found in sample description\\n\"));\n\t\t\t\t\t} else if (avccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tAVC Info: %d SPS - %d PPS\", gf_list_count(avccfg->sequenceParameterSets) , gf_list_count(avccfg->pictureParameterSets) );\n\t\t\t\t\t\tfprintf(stderr, \" - Profile %s @ Level %g\\n\", gf_avc_get_profile_name(avccfg->AVCProfileIndication), ((Double)avccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tNAL Unit length bits: %d\\n\", 8*avccfg->nal_unit_size);\n\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; isequenceParameterSets); i++) {\n\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(avccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, NULL, NULL, NULL, &par_n, &par_d);\n\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!full_dump) break;\n\t\t\t\t\t\t}\n#endif\n\n\t\t\t\t\t\tif (avccfg->chroma_bit_depth) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tChroma format %s - Luma bit depth %d - chroma bit depth %d\\n\", gf_avc_hevc_get_chroma_format_name(avccfg->chroma_format), avccfg->luma_bit_depth, avccfg->chroma_bit_depth);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprint_config_hash(avccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(avccfg->pictureParameterSets, \"PPS\");\n\n\t\t\t\t\t\tgf_odf_avc_cfg_del(avccfg);\n\t\t\t\t\t}\n\t\t\t\t\tif (svccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tSVC Info: %d SPS - %d PPS - Profile %s @ Level %g\\n\", gf_list_count(svccfg->sequenceParameterSets) , gf_list_count(svccfg->pictureParameterSets), gf_avc_get_profile_name(svccfg->AVCProfileIndication), ((Double)svccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tSVC NAL Unit length bits: %d\\n\", 8*svccfg->nal_unit_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; isequenceParameterSets); i++) {\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(svccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tif (slc) {\n\t\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\t\tu32 s_w, s_h, sps_id;\n\t\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, &sps_id, &s_w, &s_h, &par_n, &par_d);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\t\\tSPS ID %d - Visual Size %d x %d\\n\", sps_id, s_w, s_h);\n\t\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\tprint_config_hash(svccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(svccfg->pictureParameterSets, \"PPS\");\n\t\t\t\t\t\tprint_config_hash(svccfg->sequenceParameterSetExtensions, \"SPSEx\");\n\n\t\t\t\t\t\tgf_odf_avc_cfg_del(svccfg);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (mvccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tMVC Info: %d SPS - %d PPS - Profile %s @ Level %g\\n\", gf_list_count(mvccfg->sequenceParameterSets) , gf_list_count(mvccfg->pictureParameterSets), gf_avc_get_profile_name(mvccfg->AVCProfileIndication), ((Double)mvccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tMVC NAL Unit length bits: %d\\n\", 8*mvccfg->nal_unit_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; isequenceParameterSets); i++) {\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(mvccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tif (slc) {\n\t\t\t\t\t\t\t\tu32 s_w, s_h, sps_id;\n\t\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, &sps_id, &s_w, &s_h, &par_n, &par_d);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\t\\tSPS ID %d - Visual Size %d x %d\\n\", sps_id, s_w, s_h);\n\t\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\tprint_config_hash(mvccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(mvccfg->pictureParameterSets, \"PPS\");\n\t\t\t\t\t\tgf_odf_avc_cfg_del(mvccfg);\n\t\t\t\t\t}\n\n\t\t\t\t} else if ((esd->decoderConfig->objectTypeIndication==GF_CODECID_HEVC)\n\t\t\t\t || (esd->decoderConfig->objectTypeIndication==GF_CODECID_LHVC)\n\t\t\t\t ) {\n\t\t\t\t\tGF_HEVCConfig *hevccfg, *lhvccfg;\n\t\t\t\t\tGF_OperatingPointsInformation *oinf;\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\tHEVCState hevc_state;\n\t\t\t\t\tmemset(&hevc_state, 0, sizeof(HEVCState));\n\t\t\t\t\thevc_state.sps_active_idx = -1;\n#endif\n\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"HEVC Video - Visual Size %d x %d\\n\", w, h);\n\t\t\t\t\thevccfg = gf_isom_hevc_config_get(file, trackNum, 1);\n\t\t\t\t\tlhvccfg = gf_isom_lhvc_config_get(file, trackNum, 1);\n\n\t\t\t\t\tif (msub_type==GF_ISOM_SUBTYPE_HVT1) {\n\t\t\t\t\t\tconst u8 *data;\n\t\t\t\t\t\tu32 tsize;\n\t\t\t\t\t\tu32 is_default, tx,ty,tw,th, id, independent;\n\t\t\t\t\t\tBool full_frame;\n\t\t\t\t\t\tif (gf_isom_get_tile_info(file, trackNum, 1, &is_default, &id, &independent, &full_frame, &tx, &ty, &tw, &th)) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile - ID %d independent %d (x,y,w,h)=%d,%d,%d,%d \\n\", id, independent, tx, ty, tw, th);\n\t\t\t\t\t\t} else if (gf_isom_get_sample_group_info(file, trackNum, 1, GF_ISOM_SAMPLE_GROUP_TRIF, &is_default, &data, &tsize)) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile track containing a tile set\\n\");\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile track without tiling info\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (!hevccfg && !lhvccfg) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\tNon-compliant HEVC track: No hvcC or shcC found in sample description\\n\"));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (gf_isom_get_reference_count(file, trackNum, GF_ISOM_REF_SABT)) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile base track\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (hevccfg) {\n\t\t\t\t\t\tdump_hevc_track_info(file, trackNum, hevccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\t\t\t, &hevc_state\n#endif\n\t\t\t\t\t\t);\n\t\t\t\t\t\tgf_odf_hevc_cfg_del(hevccfg);\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (lhvccfg) {\n\t\t\t\t\t\tdump_hevc_track_info(file, trackNum, lhvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\t\t\t, &hevc_state\n#endif\n\t\t\t\t\t\t);\n\t\t\t\t\t\tgf_odf_hevc_cfg_del(lhvccfg);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (gf_isom_get_oinf_info(file, trackNum, &oinf)) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tOperating Points Information -\");\n\t\t\t\t\t\tfprintf(stderr, \" scalability_mask %d (\", oinf->scalability_mask);\n\t\t\t\t\t\tswitch (oinf->scalability_mask) {\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tfprintf(stderr, \"Multiview\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\tfprintf(stderr, \"Spatial scalability\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 8:\n\t\t\t\t\t\t\tfprintf(stderr, \"Auxilary\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfprintf(stderr, \"unknown\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//TODO: need to dump more info ?\n\t\t\t\t\t\tfprintf(stderr, \") num_profile_tier_level %d \", gf_list_count(oinf->profile_tier_levels) );\n\t\t\t\t\t\tfprintf(stderr, \" num_operating_points %d dependency layers %d \\n\", gf_list_count(oinf->operating_points), gf_list_count(oinf->dependency_layers) );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*OGG media*/\n\t\t\t\telse if (esd->decoderConfig->objectTypeIndication==GF_CODECID_THEORA) {\n\t\t\t\t\tchar *szName;\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tif (!strnicmp((char *) &esd->decoderConfig->decoderSpecificInfo->data[3], \"theora\", 6)) szName = \"Theora\";\n\t\t\t\t\telse szName = \"Unknown\";\n\t\t\t\t\tfprintf(stderr, \"Ogg/%s video / GPAC Mux - Visual Size %d x %d\\n\", szName, w, h);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t//check if we know this codec from its OTI\n\t\t\t\t\tu32 codec_id = gf_codecid_from_oti(GF_STREAM_VISUAL, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (codec_id) {\n\t\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\t\tfprintf(stderr, \"%s - Visual Size %d x %d\\n\", gf_codecid_name(codec_id), w, h);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!w || !h) {\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"Visual Size %d x %d\\n\", w, h);\n\t\t\t\t}\n\t\t\t\tif (gf_isom_get_rvc_config(file, trackNum, 1, &rvc_predef, NULL, NULL, NULL)==GF_OK) {\n\t\t\t\t\tfprintf(stderr, \"Has RVC signaled - Predefined configuration %d\\n\", rvc_predef);\n\t\t\t\t}\n\n\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\tGF_M4ADecSpecInfo a_cfg;\n\t\t\t\tGF_Err e;\n\t\t\t\tu32 oti;\n#endif\n\t\t\t\tu32 codec_id;\n\t\t\t\tBool is_mp2 = GF_FALSE;\n\t\t\t\tswitch (esd->decoderConfig->objectTypeIndication) {\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_MP:\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_LCP:\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_SSRP:\n\t\t\t\t\tis_mp2 = GF_TRUE;\n\t\t\t\tcase GF_CODECID_AAC_MPEG4:\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\tif (!esd->decoderConfig->decoderSpecificInfo)\n\t\t\t\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t\t\telse\n\t\t\t\t\t\te = gf_m4a_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &a_cfg);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Corrupted AAC Config\\n\"));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchar *signaling = \"implicit\";\n\t\t\t\t\t\tchar *heaac = \"\";\n\t\t\t\t\t\tif (!is_mp2 && a_cfg.has_sbr) {\n\t\t\t\t\t\t\tif (a_cfg.has_ps) heaac = \"(HE-AAC v2) \";\n\t\t\t\t\t\t\telse heaac = \"(HE-AAC v1) \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (a_cfg.base_object_type==2) {\n\t\t\t\t\t\t\tif (a_cfg.has_ps || a_cfg.has_sbr)\n\t\t\t\t\t\t\t\tsignaling = \"backward compatible\";\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsignaling = \"hierarchical\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfprintf(stderr, \"%s (AOT=%d %s) %s- %d Channel(s) - SampleRate %d\", gf_m4a_object_type_name(a_cfg.base_object_type), a_cfg.base_object_type, signaling, heaac, a_cfg.nb_chan, a_cfg.base_sr);\n\t\t\t\t\t\tif (is_mp2) fprintf(stderr, \" (MPEG-2 Signaling)\");\n\t\t\t\t\t\tif (a_cfg.has_sbr) fprintf(stderr, \" - SBR: SampleRate %d Type %s\", a_cfg.sbr_sr, gf_m4a_object_type_name(a_cfg.sbr_object_type));\n\t\t\t\t\t\tif (a_cfg.has_ps) fprintf(stderr, \" - PS\");\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n#else\n\t\t\t\t\tfprintf(stderr, \"MPEG-2/4 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n#endif\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_MPEG2_PART3:\n\t\t\t\tcase GF_CODECID_MPEG_AUDIO:\n\t\t\t\t\tif (msub_type == GF_ISOM_SUBTYPE_MPEG4_CRYP) {\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-1/2 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n\t\t\t\t\t} else {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, trackNum, 1, &oti);\n\t\t\t\t\t\tif (samp) {\n\t\t\t\t\t\t\tu32 mhdr = GF_4CC((u8)samp->data[0], (u8)samp->data[1], (u8)samp->data[2], (u8)samp->data[3]);\n\t\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\t\tfprintf(stderr, \"%s Audio - %d Channel(s) - SampleRate %d - Layer %d\\n\",\n\t\t\t\t\t\t\t gf_mp3_version_name(mhdr),\n\t\t\t\t\t\t\t gf_mp3_num_channels(mhdr),\n\t\t\t\t\t\t\t gf_mp3_sampling_rate(mhdr),\n\t\t\t\t\t\t\t gf_mp3_layer(mhdr)\n\t\t\t\t\t\t\t );\n\t\t\t\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Error fetching sample: %s\\n\", gf_error_to_string(gf_isom_last_error(file)) ));\n\t\t\t\t\t\t}\n#else\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-1/2 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n#endif\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_EVRC:\n\t\t\t\t\tfprintf(stderr, \"EVRC Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_SMV:\n\t\t\t\t\tfprintf(stderr, \"SMV Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_QCELP:\n\t\t\t\t\tfprintf(stderr, \"QCELP Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t/*packetVideo hack for EVRC...*/\n\t\t\t\tcase GF_CODECID_EVRC_PV:\n\t\t\t\t\tif (esd->decoderConfig->decoderSpecificInfo && (esd->decoderConfig->decoderSpecificInfo->dataLength==8)\n\t\t\t\t\t && !strnicmp((char *)esd->decoderConfig->decoderSpecificInfo->data, \"pvmm\", 4)) {\n\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\tfprintf(stderr, \"EVRC Audio (PacketVideo Mux) - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tcodec_id = gf_codecid_from_oti(GF_STREAM_AUDIO, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (codec_id) {\n\t\t\t\t\t\tfprintf(stderr, \"%s - Sample Rate %d - %d channel(s)\\n\", gf_codecid_name(codec_id), sr, nb_ch);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (esd->decoderConfig->streamType==GF_STREAM_SCENE) {\n\t\t\t\tif (esd->decoderConfig->objectTypeIndication<=4) {\n\t\t\t\t\tGF_BIFSConfig *b_cfg = gf_odf_get_bifs_config(esd->decoderConfig->decoderSpecificInfo, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tfprintf(stderr, \"BIFS Scene description - %s stream\\n\", b_cfg->elementaryMasks ? \"Animation\" : \"Command\");\n\t\t\t\t\tif (full_dump && !b_cfg->elementaryMasks) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tWidth %d Height %d Pixel Metrics %s\\n\", b_cfg->pixelWidth, b_cfg->pixelHeight, b_cfg->pixelMetrics ? \"yes\" : \"no\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)b_cfg);\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_AFX) {\n\t\t\t\t\tu8 tag = esd->decoderConfig->decoderSpecificInfo ? esd->decoderConfig->decoderSpecificInfo->data[0] : 0xFF;\n\t\t\t\t\tconst char *afxtype = gf_stream_type_afx_name(tag);\n\t\t\t\t\tfprintf(stderr, \"AFX Stream - type %s (%d)\\n\", afxtype, tag);\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_FONT) {\n\t\t\t\t\tfprintf(stderr, \"Font Data stream\\n\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_LASER) {\n\t\t\t\t\tGF_LASERConfig l_cfg;\n\t\t\t\t\tgf_odf_get_laser_config(esd->decoderConfig->decoderSpecificInfo, &l_cfg);\n\t\t\t\t\tfprintf(stderr, \"LASER Stream - %s\\n\", l_cfg.newSceneIndicator ? \"Full Scene\" : \"Scene Segment\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_TEXT_MPEG4) {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Streaming Text stream\\n\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_SYNTHESIZED_TEXTURE) {\n\t\t\t\t\tfprintf(stderr, \"Synthetized Texture stream stream\\n\");\n\t\t\t\t} else {\n\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Unknown Systems stream OTI %d\\n\", esd->decoderConfig->objectTypeIndication));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*sync is only valid if we open all tracks to take care of default MP4 sync..*/\n\t\t\tif (!full_dump) {\n\t\t\t\tif (dump_m4sys) {\n\t\t\t\t\tif (!esd->OCRESID || (esd->OCRESID == esd->ESID))\n\t\t\t\t\t\tfprintf(stderr, \"Self-synchronized\\n\");\n\t\t\t\t\telse\n\t\t\t\t\t\tfprintf(stderr, \"Synchronized on stream %d\\n\", esd->OCRESID);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"\\tDecoding Buffer size %d - Bitrate: avg %d - max %d kbps\\n\", esd->decoderConfig->bufferSizeDB, esd->decoderConfig->avgBitrate/1000, esd->decoderConfig->maxBitrate/1000);\n\t\t\t\tif (esd->dependsOnESID)\n\t\t\t\t\tfprintf(stderr, \"\\tDepends on stream %d for decoding\\n\", esd->dependsOnESID);\n\t\t\t\telse\n\t\t\t\t\tfprintf(stderr, \"\\tNo stream dependencies for decoding\\n\");\n\n\t\t\t\tfprintf(stderr, \"\\tStreamPriority %d\\n\", esd->streamPriority);\n\t\t\t\tif (esd->URLString) fprintf(stderr, \"\\tRemote Data Source %s\\n\", esd->URLString);\n\t\t\t}\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t}\n\t} else if (msub_type == GF_ISOM_SUBTYPE_AV01) {\n\t\tGF_AV1Config *av1c;\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\tAOM AV1 stream - Resolution %d x %d\\n\", w, h);\n\n\t\tav1c = gf_isom_av1_config_get(file, trackNum, 1);\n\t\tfprintf(stderr, \"\\tversion=%u, profile=%u, level_idx0=%u, tier=%u\\n\", (u32)av1c->version, (u32)av1c->seq_profile, (u32)av1c->seq_level_idx_0, (u32)av1c->seq_tier_0);\n\t\tfprintf(stderr, \"\\thigh_bitdepth=%u, twelve_bit=%u, monochrome=%u\\n\", (u32)av1c->high_bitdepth, (u32)av1c->twelve_bit, (u32)av1c->monochrome);\n\t\tfprintf(stderr, \"\\tchroma: subsampling_x=%u, subsampling_y=%u, sample_position=%u\\n\", (u32)av1c->chroma_subsampling_x, (u32)av1c->chroma_subsampling_y, (u32)av1c->chroma_sample_position);\n\n\t\tif (av1c->initial_presentation_delay_present)\n\t\t\tfprintf(stderr, \"\\tInitial presentation delay %u\\n\", (u32) av1c->initial_presentation_delay_minus_one+1);\n\n\t\tcount = gf_list_count(av1c->obu_array);\n\t\tfor (i=0; iobu_array, i);\n\t\t\tgf_sha1_csum((u8*)obu->obu, (u32)obu->obu_length, hash);\n\t\t\tfprintf(stderr, \"\\tOBU#%d %s hash: \", i+1, gf_av1_get_obu_name(obu->obu_type) );\n\t\t\tfor (j=0; j<20; j++) fprintf(stderr, \"%02X\", hash[j]);\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t}\n\t\tgf_odf_av1_cfg_del(av1c);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_H263) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\t3GPP H263 stream - Resolution %d x %d\\n\", w, h);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_MJP2) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\tMotionJPEG2000 stream - Resolution %d x %d\\n\", w, h);\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_3GP_AMR) || (msub_type == GF_ISOM_SUBTYPE_3GP_AMR_WB)) {\n\t\tfprintf(stderr, \"\\t3GPP AMR%s stream - Sample Rate %d - %d channel(s) %d bps\\n\", (msub_type == GF_ISOM_SUBTYPE_3GP_AMR_WB) ? \" Wide Band\" : \"\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_EVRC) {\n\t\tfprintf(stderr, \"\\t3GPP EVRC stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_QCELP) {\n\t\tfprintf(stderr, \"\\t3GPP QCELP stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_MP3) {\n\t\tfprintf(stderr, \"\\tMPEG 1/2 Audio stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_AC3) || (msub_type == GF_ISOM_SUBTYPE_EC3)) {\n\t\tu32 br = 0;\n\t\tconst char *lfe = \"\";\n\t\tBool is_ec3 = (msub_type == GF_ISOM_SUBTYPE_EC3) ? GF_TRUE : GF_FALSE;\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\tGF_AC3Config *ac3 = gf_isom_ac3_config_get(file, trackNum, 1);\n\t\tif (ac3) {\n\t\t\tnb_ch = gf_ac3_get_channels(ac3->streams[0].acmod);\n\t\t\tfor (i=0; istreams[0].nb_dep_sub; ++i) {\n\t\t\t\tassert(ac3->streams[0].nb_dep_sub == 1);\n\t\t\t\tnb_ch += gf_ac3_get_channels(ac3->streams[0].chan_loc);\n\t\t\t}\n\t\t\tif (ac3->streams[0].lfon) lfe = \".1\";\n\t\t\tbr = ac3->is_ec3 ? ac3->brcode : gf_ac3_get_bitrate(ac3->brcode);\n\t\t\tis_ec3 = ac3->is_ec3;\n\t\t\tgf_free(ac3);\n\t\t}\n#endif\n\t\tfprintf(stderr, \"\\t%s stream - Sample Rate %d - %d%s channel(s) - bitrate %d\\n\", is_ec3 ? \"EC-3\" : \"AC-3\", sr, nb_ch, lfe, br);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_SMV) {\n\t\tfprintf(stderr, \"\\t3GPP SMV stream - Sample Rate %d - %d channel(s) %d bits per samples\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_DIMS) {\n\t\tu32 w, h;\n\t\tGF_DIMSDescription dims;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\n\t\tgf_isom_get_dims_description(file, trackNum, 1, &dims);\n\t\tfprintf(stderr, \"\\t3GPP DIMS stream - size %d x %d - Profile %d - Level %d\\n\", w, h, dims.profile, dims.level);\n\t\tfprintf(stderr, \"\\tpathComponents: %d - useFullRequestHost: %s\\n\", dims.pathComponents, dims.fullRequestHost ? \"yes\" : \"no\");\n\t\tfprintf(stderr, \"\\tstream type: %s - redundant: %s\\n\", dims.streamType ? \"primary\" : \"secondary\", (dims.containsRedundant==1) ? \"main\" : ((dims.containsRedundant==2) ? \"redundant\" : \"main+redundant\") );\n\t\tif (dims.textEncoding[0]) fprintf(stderr, \"\\ttext encoding %s\\n\", dims.textEncoding);\n\t\tif (dims.contentEncoding[0]) fprintf(stderr, \"\\tcontent encoding %s\\n\", dims.contentEncoding);\n\t\tif (dims.content_script_types) fprintf(stderr, \"\\tscript languages %s\\n\", dims.content_script_types);\n\t} else if (mtype==GF_ISOM_MEDIA_HINT) {\n\t\tu32 refTrack;\n\t\ts32 refCount = gf_isom_get_reference_count(file, trackNum, GF_ISOM_REF_HINT);\n\t\tif (refCount>0) {\n\t\t\tfprintf(stderr, \"Streaming Hint Track for track%s \", (refCount>1) ? \"s\" :\"\");\n\t\t\tfor (i=0; i<(u32) refCount; i++) {\n\t\t\t\tgf_isom_get_reference(file, trackNum, GF_ISOM_REF_HINT, i+1, &refTrack);\n\t\t\t\tif (i) fprintf(stderr, \" - \");\n\t\t\t\tfprintf(stderr, \"ID %d\", gf_isom_get_track_id(file, refTrack));\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Streaming Hint Track (no refs)\\n\");\n\t\t}\n#ifndef GPAC_DISABLE_ISOM_HINTING\n\t\trefCount = gf_isom_get_payt_count(file, trackNum);\n\t\tif (refCount>0) {\n\t\t\tfor (i=0; i<(u32) refCount; i++) {\n\t\t\t\tconst char *name = gf_isom_get_payt_info(file, trackNum, i+1, &refTrack);\n\t\t\t\tfprintf(stderr, \"\\tPayload ID %d: type %s\\n\", refTrack, name);\n\t\t\t}\n\t\t}\n#endif\n\t} else if (mtype==GF_ISOM_MEDIA_FLASH) {\n\t\tfprintf(stderr, \"Macromedia Flash Movie\\n\");\n\t} else if ((mtype==GF_ISOM_MEDIA_TEXT) || (mtype==GF_ISOM_MEDIA_SUBT) || (mtype==GF_ISOM_MEDIA_MPEG_SUBT)) {\n\t\tu32 w, h;\n\t\ts16 l;\n\t\ts32 tx, ty;\n\t\tconst char *content_encoding = NULL;\n\t\tconst char *mime = NULL;\n\t\tconst char *config = NULL;\n\t\tconst char *_namespace = NULL;\n\t\tconst char *schema_loc = NULL;\n\t\tconst char *auxiliary_mimes = NULL;\n\t\tgf_isom_get_track_layout_info(file, trackNum, &w, &h, &tx, &ty, &l);\n\t\tif (msub_type == GF_ISOM_SUBTYPE_SBTT) {\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Textual Subtitle Stream \");\n\t\t\tfprintf(stderr, \"- mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_STXT) {\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Simple Timed Text Stream \");\n\t\t\tfprintf(stderr, \"- mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_STPP) {\n\t\t\tgf_isom_xml_subtitle_get_description(file, trackNum, 1, &_namespace, &schema_loc, &auxiliary_mimes);\n\t\t\tfprintf(stderr, \"XML Subtitle Stream \");\n\t\t\tfprintf(stderr, \"- namespace %s\", _namespace);\n\t\t\tif (schema_loc != NULL) {\n\t\t\t\tfprintf(stderr, \" - schema-location %s\", schema_loc);\n\t\t\t}\n\t\t\tif (auxiliary_mimes != NULL) {\n\t\t\t\tfprintf(stderr, \" - auxiliary-mime-types %s\", auxiliary_mimes);\n\t\t\t}\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown Text Stream\");\n\t\t}\n\t\tfprintf(stderr, \"\\n Size %d x %d - Translation X=%d Y=%d - Layer %d\\n\", w, h, tx, ty, l);\n\t} else if (mtype == GF_ISOM_MEDIA_META) {\n\t\tconst char *content_encoding = NULL;\n\t\tif (msub_type == GF_ISOM_SUBTYPE_METT) {\n\t\t\tconst char *mime = NULL;\n\t\t\tconst char *config = NULL;\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Textual Metadata Stream - mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_METX) {\n\t\t\tconst char *_namespace = NULL;\n\t\t\tconst char *schema_loc = NULL;\n\t\t\tgf_isom_get_xml_metadata_description(file, trackNum, 1, &_namespace, &schema_loc, &content_encoding);\n\t\t\tfprintf(stderr, \"XML Metadata Stream - namespace %s\", _namespace);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (schema_loc != NULL) {\n\t\t\t\tfprintf(stderr, \" - schema-location %s\", schema_loc);\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown Metadata Stream\\n\");\n\t\t}\n\t} else if ((msub_type==GF_ISOM_SUBTYPE_VVC1) || (msub_type==GF_ISOM_SUBTYPE_VVI1)) {\n\t\tGF_VVCConfig *vvccfg;\n\t\tu32 w, h;\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\tVVCState *vvc_state;\n\t\tGF_SAFEALLOC(vvc_state, VVCState);\n\t\tif (vvc_state) vvc_state->sps_active_idx = -1;\n#endif\n\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\tfprintf(stderr, \"VVC Video - Visual Size %d x %d\\n\", w, h);\n\t\tvvccfg = gf_isom_vvc_config_get(file, trackNum, 1);\n\n\t\tif (!vvccfg) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Non-compliant VVC track: No vvcC found in sample description\\n\"));\n\t\t} else {\n\t\t\tdump_vvc_track_info(file, trackNum, vvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\t\t\t, vvc_state\n#endif\n\t\t\t);\n\t\t\tgf_odf_vvc_cfg_del(vvccfg);\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t}\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\tif (vvc_state) gf_free(vvc_state);\n#endif\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_MH3D_MHA1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHA2)\n\t\t\t|| (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM2)\n\t) {\n\t\tconst u8 *compat_profiles;\n\t\tu32 nb_compat_profiles;\n\t\tBool valid = GF_FALSE;\n\t\tBool allow_inband = GF_FALSE;\n\t\tif ( (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM2))\n\t\t\tallow_inband = GF_TRUE;\n\n\t\tfprintf(stderr, \"\\tMPEG-H Audio stream - Sample Rate %d\\n\", sr);\n\n\t\tesd = gf_media_map_esd(file, trackNum, 1);\n\t\tif (!esd || !esd->decoderConfig || !esd->decoderConfig->decoderSpecificInfo\n\t\t\t|| !esd->decoderConfig->decoderSpecificInfo->data\n\t\t) {\n\t\t\tif (allow_inband) {\n\t\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, trackNum, 1, NULL);\n\t\t\t\tif (samp) {\n\t\t\t\t\tu64 ch_layout=0;\n\t\t\t\t\ts32 PL = gf_mpegh_get_mhas_pl(samp->data, samp->dataLength, &ch_layout);\n\t\t\t\t\tif (PL>=0) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tProfileLevelIndication: 0x%02X\", PL);\n\t\t\t\t\t\tif (ch_layout)\n\t\t\t\t\t\t\tfprintf(stderr, \" - Reference Channel Layout %s\", gf_audio_fmt_get_layout_name(ch_layout) );\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t\t}\n\t\t\t\tvalid = GF_TRUE;\n\t\t\t}\n\t\t} else if (esd->decoderConfig->decoderSpecificInfo->dataLength>=5) {\n\t\t\tfprintf(stderr, \"\\tProfileLevelIndication: 0x%02X - Reference Channel Layout %s\\n\", esd->decoderConfig->decoderSpecificInfo->data[1]\n\t\t\t\t, gf_audio_fmt_get_layout_name_from_cicp(esd->decoderConfig->decoderSpecificInfo->data[2])\n\t\t\t);\n\t\t\tvalid = GF_TRUE;\n\t\t}\n\t\tif (!valid) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Invalid MPEG-H audio config\\n\"));\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);\n\t\tcompat_profiles = gf_isom_get_mpegh_compatible_profiles(file, trackNum, 1, &nb_compat_profiles);\n\t\tfor (i=0; idata, sample->dataLength, tmcd_flags, tmcd_num, tmcd_den, tmcd_fpt, szTimecode);\n\n\t\t\tgf_isom_sample_del(&sample);\n\t\t\tfprintf(stderr, \"\\tFirst timecode: %s\\n\", szTimecode);\n\t\t}\n\t} else {\n\t\tGF_GenericSampleDescription *udesc;\n\n\t\tudesc = gf_isom_get_generic_sample_description(file, trackNum, 1);\n\t\tif (udesc) {\n\t\t\tif (gf_isom_is_video_handler_type(mtype) ) {\n fprintf(stderr, \"%s - Compressor \\\"%s\\\" - Resolution %d x %d\\n\",\n\t\t\t\t\t\t( (mtype == GF_ISOM_MEDIA_VISUAL ? \"Visual\" : \"Auxiliary Video\") ),\n udesc->compressor_name, udesc->width, udesc->height);\n\t\t\t} else if (mtype==GF_ISOM_MEDIA_AUDIO) {\n\t\t\t\tfprintf(stderr, \"Audio - Sample Rate %d - %d channel(s)\\n\", udesc->samplerate, udesc->nb_channels);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Unknown media type\\n\");\n\t\t\t}\n\t\t\tif (udesc->vendor_code)\n\t\t\t\tfprintf(stderr, \"\\tVendor code \\\"%s\\\" - Version %d - revision %d\\n\", gf_4cc_to_str(udesc->vendor_code), udesc->version, udesc->revision);\n\n\t\t\tif (udesc->extension_buf) {\n\t\t\t\tfprintf(stderr, \"\\tCodec configuration data size: %d bytes\\n\", udesc->extension_buf_size);\n\t\t\t\tgf_free(udesc->extension_buf);\n\t\t\t}\n\t\t\tgf_free(udesc);\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown track type\\n\");\n\t\t}\n\t}\n\n\n\t/*Crypto info*/\n\tif (gf_isom_is_track_encrypted(file, trackNum)) {\n\t\tconst char *scheme_URI, *KMS_URI;\n\t\tu32 scheme_type, version;\n\t\tu32 IV_size;\n\t\tBool use_sel_enc;\n\n\t\tif (gf_isom_is_ismacryp_media(file, trackNum, 1)) {\n\t\t\tgf_isom_get_ismacryp_info(file, trackNum, 1, NULL, &scheme_type, &version, &scheme_URI, &KMS_URI, &use_sel_enc, &IV_size, NULL);\n\t\t\tfprintf(stderr, \"\\n\\tProtected by ISMA E&A scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t\tif (scheme_URI) fprintf(stderr, \"scheme location: %s\\n\", scheme_URI);\n\t\t\tif (KMS_URI) {\n\t\t\t\tif (!strnicmp(KMS_URI, \"(key)\", 5)) fprintf(stderr, \"\\tKMS location: key in file\\n\");\n\t\t\t\telse fprintf(stderr, \"\\tKMS location: %s\\n\", KMS_URI);\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\tSelective Encryption: %s\\n\", use_sel_enc ? \"Yes\" : \"No\");\n\t\t\tif (IV_size) fprintf(stderr, \"\\tInitialization Vector size: %d bits\\n\", IV_size*8);\n\t\t} else if (gf_isom_is_omadrm_media(file, trackNum, 1)) {\n\t\t\tconst char *textHdrs;\n\t\t\tu32 enc_type, hdr_len;\n\t\t\tu64 orig_len;\n\t\t\tgf_isom_get_omadrm_info(file, trackNum, 1, NULL, &scheme_type, &version, &scheme_URI, &KMS_URI, &textHdrs, &hdr_len, &orig_len, &enc_type, &use_sel_enc, &IV_size, NULL);\n\t\t\tfprintf(stderr, \"\\n\\tProtected by OMA DRM scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t\tfprintf(stderr, \"\\tRights Issuer: %s\\n\", KMS_URI);\n\t\t\tfprintf(stderr, \"\\tContent ID: %s\\n\", scheme_URI);\n\t\t\tif (textHdrs) {\n\t\t\t\tu32 offset;\n\t\t\t\tconst char *start = textHdrs;\n\t\t\t\tfprintf(stderr, \"\\tOMA Textual Headers:\\n\");\n\t\t\t\ti=0;\n\t\t\t\toffset=0;\n\t\t\t\twhile (iDTS+samp->CTS_Offset;\n\t\t\tsize += samp->dataLength;\n\t\t\trate += samp->dataLength;\n\t\t\tif (samp->DTS - time_slice > ts) {\n\t\t\t\tDouble max_tmp = rate * ts / (samp->DTS - time_slice);\n\t\t\t\tif (max_rate < max_tmp )\n\t\t\t\t\tmax_rate = max_tmp;\n\n\t\t\t\trate = 0;\n\t\t\t\ttime_slice = samp->DTS;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t}\n\tfprintf(stderr, \"\\nComputed info from media:\\n\");\n\tif (csize && cdur) {\n\t\tfprintf(stderr, \"\\tConstant sample size %d bytes and dur %d / %d\\n\", csize, cdur, ts);\n\t}\n\tscale = 1000.0 / ts;\n\tdur = (u64) (scale * dur);\n\tfprintf(stderr, \"\\tTotal size \"LLU\" bytes - Total samples duration \"LLU\" ms\\n\", size, dur);\n\tif (!dur) {\n\t\tfprintf(stderr, \"\\n\");\n\t\treturn;\n\t}\n\t/*rate in byte, dur is in ms*/\n\trate = 8000.0 * size / dur;\n\n\tif (!max_rate)\n\t\tmax_rate = rate;\n\telse\n\t\tmax_rate *= 8.0;\n\n\tif (rate >= 1500) {\n\t\tfprintf(stderr, \"\\tAverage rate %.2f kbps - Max Rate %.2f kbps\\n\", rate/1000, max_rate/1000);\n\t} else {\n\t\tfprintf(stderr, \"\\tAverage rate %.2f bps - Max Rate %.2f bps\\n\", rate, max_rate);\n\t}\n\n\t{\n\t\tu32 dmin, dmax, davg, smin, smax, savg;\n\t\tgf_isom_get_chunks_infos(file, trackNum, &dmin, &davg, &dmax, &smin, &savg, &smax);\n\t\tfprintf(stderr, \"\\tChunk durations: min %d ms - max %d ms - average %d ms\\n\", (1000*dmin)/ts, (1000*dmax)/ts, (1000*davg)/ts);\n\t\tfprintf(stderr, \"\\tChunk sizes (bytes): min %d - max %d - average %d\\n\", smin, smax, savg);\n\t}\n\tfprintf(stderr, \"\\n\");\n\n\tcount = gf_isom_get_chapter_count(file, trackNum);\n\tif (count) {\n\t\tconst char *name;\n\t\tu64 time;\n\t\tfprintf(stderr, \"\\nChapters:\\n\");\n\t\tfor (j=0; jdecoderConfig) {\n\t\t\tM4_LOG(GF_LOG_WARNING, (\"WARNING: Broken MPEG-4 Track\\n\"));\n\t\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);\n\t\t} else {\n\t\t\tconst char *st = gf_stream_type_name(esd->decoderConfig->streamType);\n\t\t\tif (dump_m4sys) {\n\t\t\t\tif (st) {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Config%s%s Stream - ObjectTypeIndication 0x%02x\\n\",\n\t\t\t\t\t\t\tfull_dump ? \"\\n\\t\" : \": \", st, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Config%sStream Type 0x%02x - ObjectTypeIndication 0x%02x\\n\",\n\t\t\t\t\t\t\tfull_dump ? \"\\n\\t\" : \": \", esd->decoderConfig->streamType, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_OD)\n\t\t\t\tis_od_track=1;\n\n\t\t\tif (esd->decoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\tu32 w, h;\n\t\t\t\tu16 rvc_predef;\n\t\t\t\tw = h = 0;\n\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\tif (!esd->decoderConfig->decoderSpecificInfo) {\n#else\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Visual Size %d x %d\\n\", w, h);\n#endif\n\t\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Non-compliant MPEG-4 Visual track: video_object_layer infos not found in sample description\\n\"));\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t} else {\n\t\t\t\t\t\tGF_M4VDecSpecInfo dsi;\n\t\t\t\t\t\tgf_m4v_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &dsi);\n\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\tw = dsi.width;\n\t\t\t\t\t\th = dsi.height;\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-4 Visual Size %d x %d - %s\\n\", w, h, gf_m4v_get_profile_name(dsi.VideoPL));\n\t\t\t\t\t\tif (dsi.par_den && dsi.par_num) {\n\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\tfprintf(stderr, \"Pixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", dsi.par_num, dsi.par_den, tw, th);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#endif\n\t\t\t\t} else if (gf_isom_get_avc_svc_type(file, trackNum, 1) != GF_ISOM_AVCTYPE_NONE) {\n\t\t\t\t\tGF_AVCConfig *avccfg, *svccfg, *mvccfg;\n\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"AVC/H264 Video - Visual Size %d x %d\\n\", w, h);\n\n\t\t\t\t\tavccfg = gf_isom_avc_config_get(file, trackNum, 1);\n\t\t\t\t\tsvccfg = gf_isom_svc_config_get(file, trackNum, 1);\n\t\t\t\t\tmvccfg = gf_isom_mvc_config_get(file, trackNum, 1);\n\t\t\t\t\tif (!avccfg && !svccfg && !mvccfg) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\tNon-compliant AVC track: SPS/PPS not found in sample description\\n\"));\n\t\t\t\t\t} else if (avccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tAVC Info: %d SPS - %d PPS\", gf_list_count(avccfg->sequenceParameterSets) , gf_list_count(avccfg->pictureParameterSets) );\n\t\t\t\t\t\tfprintf(stderr, \" - Profile %s @ Level %g\\n\", gf_avc_get_profile_name(avccfg->AVCProfileIndication), ((Double)avccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tNAL Unit length bits: %d\\n\", 8*avccfg->nal_unit_size);\n\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; isequenceParameterSets); i++) {\n\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(avccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, NULL, NULL, NULL, &par_n, &par_d);\n\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!full_dump) break;\n\t\t\t\t\t\t}\n#endif\n\n\t\t\t\t\t\tif (avccfg->chroma_bit_depth) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tChroma format %s - Luma bit depth %d - chroma bit depth %d\\n\", gf_avc_hevc_get_chroma_format_name(avccfg->chroma_format), avccfg->luma_bit_depth, avccfg->chroma_bit_depth);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprint_config_hash(avccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(avccfg->pictureParameterSets, \"PPS\");\n\n\t\t\t\t\t\tgf_odf_avc_cfg_del(avccfg);\n\t\t\t\t\t}\n\t\t\t\t\tif (svccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tSVC Info: %d SPS - %d PPS - Profile %s @ Level %g\\n\", gf_list_count(svccfg->sequenceParameterSets) , gf_list_count(svccfg->pictureParameterSets), gf_avc_get_profile_name(svccfg->AVCProfileIndication), ((Double)svccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tSVC NAL Unit length bits: %d\\n\", 8*svccfg->nal_unit_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; isequenceParameterSets); i++) {\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(svccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tif (slc) {\n\t\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\t\tu32 s_w, s_h, sps_id;\n\t\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, &sps_id, &s_w, &s_h, &par_n, &par_d);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\t\\tSPS ID %d - Visual Size %d x %d\\n\", sps_id, s_w, s_h);\n\t\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\tprint_config_hash(svccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(svccfg->pictureParameterSets, \"PPS\");\n\t\t\t\t\t\tprint_config_hash(svccfg->sequenceParameterSetExtensions, \"SPSEx\");\n\n\t\t\t\t\t\tgf_odf_avc_cfg_del(svccfg);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (mvccfg) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tMVC Info: %d SPS - %d PPS - Profile %s @ Level %g\\n\", gf_list_count(mvccfg->sequenceParameterSets) , gf_list_count(mvccfg->pictureParameterSets), gf_avc_get_profile_name(mvccfg->AVCProfileIndication), ((Double)mvccfg->AVCLevelIndication)/10.0 );\n\t\t\t\t\t\tfprintf(stderr, \"\\tMVC NAL Unit length bits: %d\\n\", 8*mvccfg->nal_unit_size);\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tfor (i=0; isequenceParameterSets); i++) {\n\t\t\t\t\t\t\tGF_NALUFFParam *slc = gf_list_get(mvccfg->sequenceParameterSets, i);\n\t\t\t\t\t\t\tif (slc) {\n\t\t\t\t\t\t\t\tu32 s_w, s_h, sps_id;\n\t\t\t\t\t\t\t\ts32 par_n, par_d;\n\t\t\t\t\t\t\t\tgf_avc_get_sps_info(slc->data, slc->size, &sps_id, &s_w, &s_h, &par_n, &par_d);\n\t\t\t\t\t\t\t\tfprintf(stderr, \"\\t\\tSPS ID %d - Visual Size %d x %d\\n\", sps_id, s_w, s_h);\n\t\t\t\t\t\t\t\tif ((par_n>0) && (par_d>0)) {\n\t\t\t\t\t\t\t\t\tu32 tw, th;\n\t\t\t\t\t\t\t\t\tgf_isom_get_track_layout_info(file, trackNum, &tw, &th, NULL, NULL, NULL);\n\t\t\t\t\t\t\t\t\tfprintf(stderr, \"\\tPixel Aspect Ratio %d:%d - Indicated track size %d x %d\\n\", par_n, par_d, tw, th);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\tprint_config_hash(mvccfg->sequenceParameterSets, \"SPS\");\n\t\t\t\t\t\tprint_config_hash(mvccfg->pictureParameterSets, \"PPS\");\n\t\t\t\t\t\tgf_odf_avc_cfg_del(mvccfg);\n\t\t\t\t\t}\n\n\t\t\t\t} else if ((esd->decoderConfig->objectTypeIndication==GF_CODECID_HEVC)\n\t\t\t\t || (esd->decoderConfig->objectTypeIndication==GF_CODECID_LHVC)\n\t\t\t\t ) {\n\t\t\t\t\tGF_HEVCConfig *hevccfg, *lhvccfg;\n\t\t\t\t\tGF_OperatingPointsInformation *oinf;\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\tHEVCState hevc_state;\n\t\t\t\t\tmemset(&hevc_state, 0, sizeof(HEVCState));\n\t\t\t\t\thevc_state.sps_active_idx = -1;\n#endif\n\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"HEVC Video - Visual Size %d x %d\\n\", w, h);\n\t\t\t\t\thevccfg = gf_isom_hevc_config_get(file, trackNum, 1);\n\t\t\t\t\tlhvccfg = gf_isom_lhvc_config_get(file, trackNum, 1);\n\n\t\t\t\t\tif (msub_type==GF_ISOM_SUBTYPE_HVT1) {\n\t\t\t\t\t\tconst u8 *data;\n\t\t\t\t\t\tu32 tsize;\n\t\t\t\t\t\tu32 is_default, tx,ty,tw,th, id, independent;\n\t\t\t\t\t\tBool full_frame;\n\t\t\t\t\t\tif (gf_isom_get_tile_info(file, trackNum, 1, &is_default, &id, &independent, &full_frame, &tx, &ty, &tw, &th)) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile - ID %d independent %d (x,y,w,h)=%d,%d,%d,%d \\n\", id, independent, tx, ty, tw, th);\n\t\t\t\t\t\t} else if (gf_isom_get_sample_group_info(file, trackNum, 1, GF_ISOM_SAMPLE_GROUP_TRIF, &is_default, &data, &tsize)) {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile track containing a tile set\\n\");\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile track without tiling info\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (!hevccfg && !lhvccfg) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"\\tNon-compliant HEVC track: No hvcC or shcC found in sample description\\n\"));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (gf_isom_get_reference_count(file, trackNum, GF_ISOM_REF_SABT)) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tHEVC Tile base track\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (hevccfg) {\n\t\t\t\t\t\tdump_hevc_track_info(file, trackNum, hevccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\t\t\t, &hevc_state\n#endif\n\t\t\t\t\t\t);\n\t\t\t\t\t\tgf_odf_hevc_cfg_del(hevccfg);\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (lhvccfg) {\n\t\t\t\t\t\tdump_hevc_track_info(file, trackNum, lhvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined(GPAC_DISABLE_HEVC)\n\t\t\t\t\t\t\t, &hevc_state\n#endif\n\t\t\t\t\t\t);\n\t\t\t\t\t\tgf_odf_hevc_cfg_del(lhvccfg);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (gf_isom_get_oinf_info(file, trackNum, &oinf)) {\n\t\t\t\t\t\tfprintf(stderr, \"\\n\\tOperating Points Information -\");\n\t\t\t\t\t\tfprintf(stderr, \" scalability_mask %d (\", oinf->scalability_mask);\n\t\t\t\t\t\tswitch (oinf->scalability_mask) {\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tfprintf(stderr, \"Multiview\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\tfprintf(stderr, \"Spatial scalability\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 8:\n\t\t\t\t\t\t\tfprintf(stderr, \"Auxilary\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfprintf(stderr, \"unknown\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//TODO: need to dump more info ?\n\t\t\t\t\t\tfprintf(stderr, \") num_profile_tier_level %d \", gf_list_count(oinf->profile_tier_levels) );\n\t\t\t\t\t\tfprintf(stderr, \" num_operating_points %d dependency layers %d \\n\", gf_list_count(oinf->operating_points), gf_list_count(oinf->dependency_layers) );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*OGG media*/\n\t\t\t\telse if (esd->decoderConfig->objectTypeIndication==GF_CODECID_THEORA) {\n\t\t\t\t\tchar *szName;\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tif (!strnicmp((char *) &esd->decoderConfig->decoderSpecificInfo->data[3], \"theora\", 6)) szName = \"Theora\";\n\t\t\t\t\telse szName = \"Unknown\";\n\t\t\t\t\tfprintf(stderr, \"Ogg/%s video / GPAC Mux - Visual Size %d x %d\\n\", szName, w, h);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t//check if we know this codec from its OTI\n\t\t\t\t\tu32 codec_id = gf_codecid_from_oti(GF_STREAM_VISUAL, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (codec_id) {\n\t\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\t\tfprintf(stderr, \"%s - Visual Size %d x %d\\n\", gf_codecid_name(codec_id), w, h);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!w || !h) {\n\t\t\t\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tfprintf(stderr, \"Visual Size %d x %d\\n\", w, h);\n\t\t\t\t}\n\t\t\t\tif (gf_isom_get_rvc_config(file, trackNum, 1, &rvc_predef, NULL, NULL, NULL)==GF_OK) {\n\t\t\t\t\tfprintf(stderr, \"Has RVC signaled - Predefined configuration %d\\n\", rvc_predef);\n\t\t\t\t}\n\n\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\tGF_M4ADecSpecInfo a_cfg;\n\t\t\t\tGF_Err e;\n\t\t\t\tu32 oti;\n#endif\n\t\t\t\tu32 codec_id;\n\t\t\t\tBool is_mp2 = GF_FALSE;\n\t\t\t\tswitch (esd->decoderConfig->objectTypeIndication) {\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_MP:\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_LCP:\n\t\t\t\tcase GF_CODECID_AAC_MPEG2_SSRP:\n\t\t\t\t\tis_mp2 = GF_TRUE;\n\t\t\t\tcase GF_CODECID_AAC_MPEG4:\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\tif (!esd->decoderConfig->decoderSpecificInfo)\n\t\t\t\t\t\te = GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t\t\telse\n\t\t\t\t\t\te = gf_m4a_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &a_cfg);\n\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Corrupted AAC Config\\n\"));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchar *signaling = \"implicit\";\n\t\t\t\t\t\tchar *heaac = \"\";\n\t\t\t\t\t\tif (!is_mp2 && a_cfg.has_sbr) {\n\t\t\t\t\t\t\tif (a_cfg.has_ps) heaac = \"(HE-AAC v2) \";\n\t\t\t\t\t\t\telse heaac = \"(HE-AAC v1) \";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (a_cfg.base_object_type==2) {\n\t\t\t\t\t\t\tif (a_cfg.has_ps || a_cfg.has_sbr)\n\t\t\t\t\t\t\t\tsignaling = \"backward compatible\";\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsignaling = \"hierarchical\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfprintf(stderr, \"%s (AOT=%d %s) %s- %d Channel(s) - SampleRate %d\", gf_m4a_object_type_name(a_cfg.base_object_type), a_cfg.base_object_type, signaling, heaac, a_cfg.nb_chan, a_cfg.base_sr);\n\t\t\t\t\t\tif (is_mp2) fprintf(stderr, \" (MPEG-2 Signaling)\");\n\t\t\t\t\t\tif (a_cfg.has_sbr) fprintf(stderr, \" - SBR: SampleRate %d Type %s\", a_cfg.sbr_sr, gf_m4a_object_type_name(a_cfg.sbr_object_type));\n\t\t\t\t\t\tif (a_cfg.has_ps) fprintf(stderr, \" - PS\");\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n#else\n\t\t\t\t\tfprintf(stderr, \"MPEG-2/4 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n#endif\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_MPEG2_PART3:\n\t\t\t\tcase GF_CODECID_MPEG_AUDIO:\n\t\t\t\t\tif (msub_type == GF_ISOM_SUBTYPE_MPEG4_CRYP) {\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-1/2 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n\t\t\t\t\t} else {\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\t\t\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, trackNum, 1, &oti);\n\t\t\t\t\t\tif (samp) {\n\t\t\t\t\t\t\tu32 mhdr = GF_4CC((u8)samp->data[0], (u8)samp->data[1], (u8)samp->data[2], (u8)samp->data[3]);\n\t\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\t\tfprintf(stderr, \"%s Audio - %d Channel(s) - SampleRate %d - Layer %d\\n\",\n\t\t\t\t\t\t\t gf_mp3_version_name(mhdr),\n\t\t\t\t\t\t\t gf_mp3_num_channels(mhdr),\n\t\t\t\t\t\t\t gf_mp3_sampling_rate(mhdr),\n\t\t\t\t\t\t\t gf_mp3_layer(mhdr)\n\t\t\t\t\t\t\t );\n\t\t\t\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tM4_LOG(GF_LOG_ERROR, (\"Error fetching sample: %s\\n\", gf_error_to_string(gf_isom_last_error(file)) ));\n\t\t\t\t\t\t}\n#else\n\t\t\t\t\t\tfprintf(stderr, \"MPEG-1/2 Audio - %d Channels - SampleRate %d\\n\", nb_ch, sr);\n#endif\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_EVRC:\n\t\t\t\t\tfprintf(stderr, \"EVRC Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_SMV:\n\t\t\t\t\tfprintf(stderr, \"SMV Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase GF_CODECID_QCELP:\n\t\t\t\t\tfprintf(stderr, \"QCELP Audio - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t/*packetVideo hack for EVRC...*/\n\t\t\t\tcase GF_CODECID_EVRC_PV:\n\t\t\t\t\tif (esd->decoderConfig->decoderSpecificInfo && (esd->decoderConfig->decoderSpecificInfo->dataLength==8)\n\t\t\t\t\t && !strnicmp((char *)esd->decoderConfig->decoderSpecificInfo->data, \"pvmm\", 4)) {\n\t\t\t\t\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\t\t\t\t\tfprintf(stderr, \"EVRC Audio (PacketVideo Mux) - Sample Rate 8000 - 1 channel\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tcodec_id = gf_codecid_from_oti(GF_STREAM_AUDIO, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tif (codec_id) {\n\t\t\t\t\t\tfprintf(stderr, \"%s - Sample Rate %d - %d channel(s)\\n\", gf_codecid_name(codec_id), sr, nb_ch);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (esd->decoderConfig->streamType==GF_STREAM_SCENE) {\n\t\t\t\tif (esd->decoderConfig->objectTypeIndication<=4) {\n\t\t\t\t\tGF_BIFSConfig *b_cfg = gf_odf_get_bifs_config(esd->decoderConfig->decoderSpecificInfo, esd->decoderConfig->objectTypeIndication);\n\t\t\t\t\tfprintf(stderr, \"BIFS Scene description - %s stream\\n\", b_cfg->elementaryMasks ? \"Animation\" : \"Command\");\n\t\t\t\t\tif (full_dump && !b_cfg->elementaryMasks) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tWidth %d Height %d Pixel Metrics %s\\n\", b_cfg->pixelWidth, b_cfg->pixelHeight, b_cfg->pixelMetrics ? \"yes\" : \"no\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)b_cfg);\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_AFX) {\n\t\t\t\t\tu8 tag = esd->decoderConfig->decoderSpecificInfo ? esd->decoderConfig->decoderSpecificInfo->data[0] : 0xFF;\n\t\t\t\t\tconst char *afxtype = gf_stream_type_afx_name(tag);\n\t\t\t\t\tfprintf(stderr, \"AFX Stream - type %s (%d)\\n\", afxtype, tag);\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_FONT) {\n\t\t\t\t\tfprintf(stderr, \"Font Data stream\\n\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_LASER) {\n\t\t\t\t\tGF_LASERConfig l_cfg;\n\t\t\t\t\tgf_odf_get_laser_config(esd->decoderConfig->decoderSpecificInfo, &l_cfg);\n\t\t\t\t\tfprintf(stderr, \"LASER Stream - %s\\n\", l_cfg.newSceneIndicator ? \"Full Scene\" : \"Scene Segment\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_TEXT_MPEG4) {\n\t\t\t\t\tfprintf(stderr, \"MPEG-4 Streaming Text stream\\n\");\n\t\t\t\t} else if (esd->decoderConfig->objectTypeIndication==GF_CODECID_SYNTHESIZED_TEXTURE) {\n\t\t\t\t\tfprintf(stderr, \"Synthetized Texture stream stream\\n\");\n\t\t\t\t} else {\n\t\t\t\t\tM4_LOG(GF_LOG_WARNING, (\"Unknown Systems stream OTI %d\\n\", esd->decoderConfig->objectTypeIndication));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*sync is only valid if we open all tracks to take care of default MP4 sync..*/\n\t\t\tif (!full_dump) {\n\t\t\t\tif (dump_m4sys) {\n\t\t\t\t\tif (!esd->OCRESID || (esd->OCRESID == esd->ESID))\n\t\t\t\t\t\tfprintf(stderr, \"Self-synchronized\\n\");\n\t\t\t\t\telse\n\t\t\t\t\t\tfprintf(stderr, \"Synchronized on stream %d\\n\", esd->OCRESID);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"\\tDecoding Buffer size %d - Bitrate: avg %d - max %d kbps\\n\", esd->decoderConfig->bufferSizeDB, esd->decoderConfig->avgBitrate/1000, esd->decoderConfig->maxBitrate/1000);\n\t\t\t\tif (esd->dependsOnESID)\n\t\t\t\t\tfprintf(stderr, \"\\tDepends on stream %d for decoding\\n\", esd->dependsOnESID);\n\t\t\t\telse\n\t\t\t\t\tfprintf(stderr, \"\\tNo stream dependencies for decoding\\n\");\n\n\t\t\t\tfprintf(stderr, \"\\tStreamPriority %d\\n\", esd->streamPriority);\n\t\t\t\tif (esd->URLString) fprintf(stderr, \"\\tRemote Data Source %s\\n\", esd->URLString);\n\t\t\t}\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t}\n\t} else if (msub_type == GF_ISOM_SUBTYPE_AV01) {\n\t\tGF_AV1Config *av1c;\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\tAOM AV1 stream - Resolution %d x %d\\n\", w, h);\n\n\t\tav1c = gf_isom_av1_config_get(file, trackNum, 1);\n\t\tif (!av1c) {\n\t\t\tfprintf(stderr, \"\\tCorrupted av1 config\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"\\tversion=%u, profile=%u, level_idx0=%u, tier=%u\\n\", (u32)av1c->version, (u32)av1c->seq_profile, (u32)av1c->seq_level_idx_0, (u32)av1c->seq_tier_0);\n\t\t\tfprintf(stderr, \"\\thigh_bitdepth=%u, twelve_bit=%u, monochrome=%u\\n\", (u32)av1c->high_bitdepth, (u32)av1c->twelve_bit, (u32)av1c->monochrome);\n\t\t\tfprintf(stderr, \"\\tchroma: subsampling_x=%u, subsampling_y=%u, sample_position=%u\\n\", (u32)av1c->chroma_subsampling_x, (u32)av1c->chroma_subsampling_y, (u32)av1c->chroma_sample_position);\n\n\t\t\tif (av1c->initial_presentation_delay_present)\n\t\t\t\tfprintf(stderr, \"\\tInitial presentation delay %u\\n\", (u32) av1c->initial_presentation_delay_minus_one+1);\n\n\t\t\tcount = gf_list_count(av1c->obu_array);\n\t\t\tfor (i=0; iobu_array, i);\n\t\t\t\tgf_sha1_csum((u8*)obu->obu, (u32)obu->obu_length, hash);\n\t\t\t\tfprintf(stderr, \"\\tOBU#%d %s hash: \", i+1, gf_av1_get_obu_name(obu->obu_type) );\n\t\t\t\tfor (j=0; j<20; j++) fprintf(stderr, \"%02X\", hash[j]);\n\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t}\n\t\t\tgf_odf_av1_cfg_del(av1c);\n\t\t}\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_H263) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\t3GPP H263 stream - Resolution %d x %d\\n\", w, h);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_MJP2) {\n\t\tu32 w, h;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tfprintf(stderr, \"\\tMotionJPEG2000 stream - Resolution %d x %d\\n\", w, h);\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_3GP_AMR) || (msub_type == GF_ISOM_SUBTYPE_3GP_AMR_WB)) {\n\t\tfprintf(stderr, \"\\t3GPP AMR%s stream - Sample Rate %d - %d channel(s) %d bps\\n\", (msub_type == GF_ISOM_SUBTYPE_3GP_AMR_WB) ? \" Wide Band\" : \"\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_EVRC) {\n\t\tfprintf(stderr, \"\\t3GPP EVRC stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_QCELP) {\n\t\tfprintf(stderr, \"\\t3GPP QCELP stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_MP3) {\n\t\tfprintf(stderr, \"\\tMPEG 1/2 Audio stream - Sample Rate %d - %d channel(s) %d bps\\n\", sr, nb_ch, (u32) bps);\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_AC3) || (msub_type == GF_ISOM_SUBTYPE_EC3)) {\n\t\tu32 br = 0;\n\t\tconst char *lfe = \"\";\n\t\tBool is_ec3 = (msub_type == GF_ISOM_SUBTYPE_EC3) ? GF_TRUE : GF_FALSE;\n#ifndef GPAC_DISABLE_AV_PARSERS\n\t\tGF_AC3Config *ac3 = gf_isom_ac3_config_get(file, trackNum, 1);\n\t\tif (ac3) {\n\t\t\tnb_ch = gf_ac3_get_channels(ac3->streams[0].acmod);\n\t\t\tfor (i=0; istreams[0].nb_dep_sub; ++i) {\n\t\t\t\tassert(ac3->streams[0].nb_dep_sub == 1);\n\t\t\t\tnb_ch += gf_ac3_get_channels(ac3->streams[0].chan_loc);\n\t\t\t}\n\t\t\tif (ac3->streams[0].lfon) lfe = \".1\";\n\t\t\tbr = ac3->is_ec3 ? ac3->brcode : gf_ac3_get_bitrate(ac3->brcode);\n\t\t\tis_ec3 = ac3->is_ec3;\n\t\t\tgf_free(ac3);\n\t\t}\n#endif\n\t\tfprintf(stderr, \"\\t%s stream - Sample Rate %d - %d%s channel(s) - bitrate %d\\n\", is_ec3 ? \"EC-3\" : \"AC-3\", sr, nb_ch, lfe, br);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_SMV) {\n\t\tfprintf(stderr, \"\\t3GPP SMV stream - Sample Rate %d - %d channel(s) %d bits per samples\\n\", sr, nb_ch, (u32) bps);\n\t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_DIMS) {\n\t\tu32 w, h;\n\t\tGF_DIMSDescription dims;\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\n\t\tgf_isom_get_dims_description(file, trackNum, 1, &dims);\n\t\tfprintf(stderr, \"\\t3GPP DIMS stream - size %d x %d - Profile %d - Level %d\\n\", w, h, dims.profile, dims.level);\n\t\tfprintf(stderr, \"\\tpathComponents: %d - useFullRequestHost: %s\\n\", dims.pathComponents, dims.fullRequestHost ? \"yes\" : \"no\");\n\t\tfprintf(stderr, \"\\tstream type: %s - redundant: %s\\n\", dims.streamType ? \"primary\" : \"secondary\", (dims.containsRedundant==1) ? \"main\" : ((dims.containsRedundant==2) ? \"redundant\" : \"main+redundant\") );\n\t\tif (dims.textEncoding[0]) fprintf(stderr, \"\\ttext encoding %s\\n\", dims.textEncoding);\n\t\tif (dims.contentEncoding[0]) fprintf(stderr, \"\\tcontent encoding %s\\n\", dims.contentEncoding);\n\t\tif (dims.content_script_types) fprintf(stderr, \"\\tscript languages %s\\n\", dims.content_script_types);\n\t} else if (mtype==GF_ISOM_MEDIA_HINT) {\n\t\tu32 refTrack;\n\t\ts32 refCount = gf_isom_get_reference_count(file, trackNum, GF_ISOM_REF_HINT);\n\t\tif (refCount>0) {\n\t\t\tfprintf(stderr, \"Streaming Hint Track for track%s \", (refCount>1) ? \"s\" :\"\");\n\t\t\tfor (i=0; i<(u32) refCount; i++) {\n\t\t\t\tgf_isom_get_reference(file, trackNum, GF_ISOM_REF_HINT, i+1, &refTrack);\n\t\t\t\tif (i) fprintf(stderr, \" - \");\n\t\t\t\tfprintf(stderr, \"ID %d\", gf_isom_get_track_id(file, refTrack));\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Streaming Hint Track (no refs)\\n\");\n\t\t}\n#ifndef GPAC_DISABLE_ISOM_HINTING\n\t\trefCount = gf_isom_get_payt_count(file, trackNum);\n\t\tif (refCount>0) {\n\t\t\tfor (i=0; i<(u32) refCount; i++) {\n\t\t\t\tconst char *name = gf_isom_get_payt_info(file, trackNum, i+1, &refTrack);\n\t\t\t\tfprintf(stderr, \"\\tPayload ID %d: type %s\\n\", refTrack, name);\n\t\t\t}\n\t\t}\n#endif\n\t} else if (mtype==GF_ISOM_MEDIA_FLASH) {\n\t\tfprintf(stderr, \"Macromedia Flash Movie\\n\");\n\t} else if ((mtype==GF_ISOM_MEDIA_TEXT) || (mtype==GF_ISOM_MEDIA_SUBT) || (mtype==GF_ISOM_MEDIA_MPEG_SUBT)) {\n\t\tu32 w, h;\n\t\ts16 l;\n\t\ts32 tx, ty;\n\t\tconst char *content_encoding = NULL;\n\t\tconst char *mime = NULL;\n\t\tconst char *config = NULL;\n\t\tconst char *_namespace = NULL;\n\t\tconst char *schema_loc = NULL;\n\t\tconst char *auxiliary_mimes = NULL;\n\t\tgf_isom_get_track_layout_info(file, trackNum, &w, &h, &tx, &ty, &l);\n\t\tif (msub_type == GF_ISOM_SUBTYPE_SBTT) {\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Textual Subtitle Stream \");\n\t\t\tfprintf(stderr, \"- mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_STXT) {\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Simple Timed Text Stream \");\n\t\t\tfprintf(stderr, \"- mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_STPP) {\n\t\t\tgf_isom_xml_subtitle_get_description(file, trackNum, 1, &_namespace, &schema_loc, &auxiliary_mimes);\n\t\t\tfprintf(stderr, \"XML Subtitle Stream \");\n\t\t\tfprintf(stderr, \"- namespace %s\", _namespace);\n\t\t\tif (schema_loc != NULL) {\n\t\t\t\tfprintf(stderr, \" - schema-location %s\", schema_loc);\n\t\t\t}\n\t\t\tif (auxiliary_mimes != NULL) {\n\t\t\t\tfprintf(stderr, \" - auxiliary-mime-types %s\", auxiliary_mimes);\n\t\t\t}\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown Text Stream\");\n\t\t}\n\t\tfprintf(stderr, \"\\n Size %d x %d - Translation X=%d Y=%d - Layer %d\\n\", w, h, tx, ty, l);\n\t} else if (mtype == GF_ISOM_MEDIA_META) {\n\t\tconst char *content_encoding = NULL;\n\t\tif (msub_type == GF_ISOM_SUBTYPE_METT) {\n\t\t\tconst char *mime = NULL;\n\t\t\tconst char *config = NULL;\n\t\t\tgf_isom_stxt_get_description(file, trackNum, 1, &mime, &content_encoding, &config);\n\t\t\tfprintf(stderr, \"Textual Metadata Stream - mime %s\", mime);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (config != NULL) {\n\t\t\t\tfprintf(stderr, \" - %d bytes config\", (u32) strlen(config));\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else if (msub_type == GF_ISOM_SUBTYPE_METX) {\n\t\t\tconst char *_namespace = NULL;\n\t\t\tconst char *schema_loc = NULL;\n\t\t\tgf_isom_get_xml_metadata_description(file, trackNum, 1, &_namespace, &schema_loc, &content_encoding);\n\t\t\tfprintf(stderr, \"XML Metadata Stream - namespace %s\", _namespace);\n\t\t\tif (content_encoding != NULL) {\n\t\t\t\tfprintf(stderr, \" - encoding %s\", content_encoding);\n\t\t\t}\n\t\t\tif (schema_loc != NULL) {\n\t\t\t\tfprintf(stderr, \" - schema-location %s\", schema_loc);\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown Metadata Stream\\n\");\n\t\t}\n\t} else if ((msub_type==GF_ISOM_SUBTYPE_VVC1) || (msub_type==GF_ISOM_SUBTYPE_VVI1)) {\n\t\tGF_VVCConfig *vvccfg;\n\t\tu32 w, h;\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\tVVCState *vvc_state;\n\t\tGF_SAFEALLOC(vvc_state, VVCState);\n\t\tif (vvc_state) vvc_state->sps_active_idx = -1;\n#endif\n\n\t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);\n\t\tif (full_dump) fprintf(stderr, \"\\t\");\n\t\tfprintf(stderr, \"VVC Video - Visual Size %d x %d\\n\", w, h);\n\t\tvvccfg = gf_isom_vvc_config_get(file, trackNum, 1);\n\n\t\tif (!vvccfg) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Non-compliant VVC track: No vvcC found in sample description\\n\"));\n\t\t} else {\n\t\t\tdump_vvc_track_info(file, trackNum, vvccfg\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\t\t\t, vvc_state\n#endif\n\t\t\t);\n\t\t\tgf_odf_vvc_cfg_del(vvccfg);\n\t\t\tfprintf(stderr, \"\\n\");\n\t\t}\n#if !defined(GPAC_DISABLE_AV_PARSERS)\n\t\tif (vvc_state) gf_free(vvc_state);\n#endif\n\t} else if ((msub_type == GF_ISOM_SUBTYPE_MH3D_MHA1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHA2)\n\t\t\t|| (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM2)\n\t) {\n\t\tconst u8 *compat_profiles;\n\t\tu32 nb_compat_profiles;\n\t\tBool valid = GF_FALSE;\n\t\tBool allow_inband = GF_FALSE;\n\t\tif ( (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM1) || (msub_type == GF_ISOM_SUBTYPE_MH3D_MHM2))\n\t\t\tallow_inband = GF_TRUE;\n\n\t\tfprintf(stderr, \"\\tMPEG-H Audio stream - Sample Rate %d\\n\", sr);\n\n\t\tesd = gf_media_map_esd(file, trackNum, 1);\n\t\tif (!esd || !esd->decoderConfig || !esd->decoderConfig->decoderSpecificInfo\n\t\t\t|| !esd->decoderConfig->decoderSpecificInfo->data\n\t\t) {\n\t\t\tif (allow_inband) {\n\t\t\t\tGF_ISOSample *samp = gf_isom_get_sample(file, trackNum, 1, NULL);\n\t\t\t\tif (samp) {\n\t\t\t\t\tu64 ch_layout=0;\n\t\t\t\t\ts32 PL = gf_mpegh_get_mhas_pl(samp->data, samp->dataLength, &ch_layout);\n\t\t\t\t\tif (PL>=0) {\n\t\t\t\t\t\tfprintf(stderr, \"\\tProfileLevelIndication: 0x%02X\", PL);\n\t\t\t\t\t\tif (ch_layout)\n\t\t\t\t\t\t\tfprintf(stderr, \" - Reference Channel Layout %s\", gf_audio_fmt_get_layout_name(ch_layout) );\n\t\t\t\t\t\tfprintf(stderr, \"\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t\t}\n\t\t\t\tvalid = GF_TRUE;\n\t\t\t}\n\t\t} else if (esd->decoderConfig->decoderSpecificInfo->dataLength>=5) {\n\t\t\tfprintf(stderr, \"\\tProfileLevelIndication: 0x%02X - Reference Channel Layout %s\\n\", esd->decoderConfig->decoderSpecificInfo->data[1]\n\t\t\t\t, gf_audio_fmt_get_layout_name_from_cicp(esd->decoderConfig->decoderSpecificInfo->data[2])\n\t\t\t);\n\t\t\tvalid = GF_TRUE;\n\t\t}\n\t\tif (!valid) {\n\t\t\tM4_LOG(GF_LOG_ERROR, (\"Invalid MPEG-H audio config\\n\"));\n\t\t}\n\t\tif (esd) gf_odf_desc_del((GF_Descriptor *)esd);\n\t\tcompat_profiles = gf_isom_get_mpegh_compatible_profiles(file, trackNum, 1, &nb_compat_profiles);\n\t\tfor (i=0; idata, sample->dataLength, tmcd_flags, tmcd_num, tmcd_den, tmcd_fpt, szTimecode);\n\n\t\t\tgf_isom_sample_del(&sample);\n\t\t\tfprintf(stderr, \"\\tFirst timecode: %s\\n\", szTimecode);\n\t\t}\n\t} else {\n\t\tGF_GenericSampleDescription *udesc;\n\n\t\tudesc = gf_isom_get_generic_sample_description(file, trackNum, 1);\n\t\tif (udesc) {\n\t\t\tif (gf_isom_is_video_handler_type(mtype) ) {\n fprintf(stderr, \"%s - Compressor \\\"%s\\\" - Resolution %d x %d\\n\",\n\t\t\t\t\t\t( (mtype == GF_ISOM_MEDIA_VISUAL ? \"Visual\" : \"Auxiliary Video\") ),\n udesc->compressor_name, udesc->width, udesc->height);\n\t\t\t} else if (mtype==GF_ISOM_MEDIA_AUDIO) {\n\t\t\t\tfprintf(stderr, \"Audio - Sample Rate %d - %d channel(s)\\n\", udesc->samplerate, udesc->nb_channels);\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Unknown media type\\n\");\n\t\t\t}\n\t\t\tif (udesc->vendor_code)\n\t\t\t\tfprintf(stderr, \"\\tVendor code \\\"%s\\\" - Version %d - revision %d\\n\", gf_4cc_to_str(udesc->vendor_code), udesc->version, udesc->revision);\n\n\t\t\tif (udesc->extension_buf) {\n\t\t\t\tfprintf(stderr, \"\\tCodec configuration data size: %d bytes\\n\", udesc->extension_buf_size);\n\t\t\t\tgf_free(udesc->extension_buf);\n\t\t\t}\n\t\t\tgf_free(udesc);\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown track type\\n\");\n\t\t}\n\t}\n\n\n\t/*Crypto info*/\n\tif (gf_isom_is_track_encrypted(file, trackNum)) {\n\t\tconst char *scheme_URI, *KMS_URI;\n\t\tu32 scheme_type, version;\n\t\tu32 IV_size;\n\t\tBool use_sel_enc;\n\n\t\tif (gf_isom_is_ismacryp_media(file, trackNum, 1)) {\n\t\t\tgf_isom_get_ismacryp_info(file, trackNum, 1, NULL, &scheme_type, &version, &scheme_URI, &KMS_URI, &use_sel_enc, &IV_size, NULL);\n\t\t\tfprintf(stderr, \"\\n\\tProtected by ISMA E&A scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t\tif (scheme_URI) fprintf(stderr, \"scheme location: %s\\n\", scheme_URI);\n\t\t\tif (KMS_URI) {\n\t\t\t\tif (!strnicmp(KMS_URI, \"(key)\", 5)) fprintf(stderr, \"\\tKMS location: key in file\\n\");\n\t\t\t\telse fprintf(stderr, \"\\tKMS location: %s\\n\", KMS_URI);\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\tSelective Encryption: %s\\n\", use_sel_enc ? \"Yes\" : \"No\");\n\t\t\tif (IV_size) fprintf(stderr, \"\\tInitialization Vector size: %d bits\\n\", IV_size*8);\n\t\t} else if (gf_isom_is_omadrm_media(file, trackNum, 1)) {\n\t\t\tconst char *textHdrs;\n\t\t\tu32 enc_type, hdr_len;\n\t\t\tu64 orig_len;\n\t\t\tgf_isom_get_omadrm_info(file, trackNum, 1, NULL, &scheme_type, &version, &scheme_URI, &KMS_URI, &textHdrs, &hdr_len, &orig_len, &enc_type, &use_sel_enc, &IV_size, NULL);\n\t\t\tfprintf(stderr, \"\\n\\tProtected by OMA DRM scheme %s (version %d)\\n\", gf_4cc_to_str(scheme_type), version);\n\t\t\tfprintf(stderr, \"\\tRights Issuer: %s\\n\", KMS_URI);\n\t\t\tfprintf(stderr, \"\\tContent ID: %s\\n\", scheme_URI);\n\t\t\tif (textHdrs) {\n\t\t\t\tu32 offset;\n\t\t\t\tconst char *start = textHdrs;\n\t\t\t\tfprintf(stderr, \"\\tOMA Textual Headers:\\n\");\n\t\t\t\ti=0;\n\t\t\t\toffset=0;\n\t\t\t\twhile (iDTS+samp->CTS_Offset;\n\t\t\tsize += samp->dataLength;\n\t\t\trate += samp->dataLength;\n\t\t\tif (samp->DTS - time_slice > ts) {\n\t\t\t\tDouble max_tmp = rate * ts / (samp->DTS - time_slice);\n\t\t\t\tif (max_rate < max_tmp )\n\t\t\t\t\tmax_rate = max_tmp;\n\n\t\t\t\trate = 0;\n\t\t\t\ttime_slice = samp->DTS;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t}\n\tfprintf(stderr, \"\\nComputed info from media:\\n\");\n\tif (csize && cdur) {\n\t\tfprintf(stderr, \"\\tConstant sample size %d bytes and dur %d / %d\\n\", csize, cdur, ts);\n\t}\n\tscale = 1000.0 / ts;\n\tdur = (u64) (scale * dur);\n\tfprintf(stderr, \"\\tTotal size \"LLU\" bytes - Total samples duration \"LLU\" ms\\n\", size, dur);\n\tif (!dur) {\n\t\tfprintf(stderr, \"\\n\");\n\t\treturn;\n\t}\n\t/*rate in byte, dur is in ms*/\n\trate = 8000.0 * size / dur;\n\n\tif (!max_rate)\n\t\tmax_rate = rate;\n\telse\n\t\tmax_rate *= 8.0;\n\n\tif (rate >= 1500) {\n\t\tfprintf(stderr, \"\\tAverage rate %.2f kbps - Max Rate %.2f kbps\\n\", rate/1000, max_rate/1000);\n\t} else {\n\t\tfprintf(stderr, \"\\tAverage rate %.2f bps - Max Rate %.2f bps\\n\", rate, max_rate);\n\t}\n\n\t{\n\t\tu32 dmin, dmax, davg, smin, smax, savg;\n\t\tgf_isom_get_chunks_infos(file, trackNum, &dmin, &davg, &dmax, &smin, &savg, &smax);\n\t\tfprintf(stderr, \"\\tChunk durations: min %d ms - max %d ms - average %d ms\\n\", (1000*dmin)/ts, (1000*dmax)/ts, (1000*davg)/ts);\n\t\tfprintf(stderr, \"\\tChunk sizes (bytes): min %d - max %d - average %d\\n\", smin, smax, savg);\n\t}\n\tfprintf(stderr, \"\\n\");\n\n\tcount = gf_isom_get_chapter_count(file, trackNum);\n\tif (count) {\n\t\tconst char *name;\n\t\tu64 time;\n\t\tfprintf(stderr, \"\\nChapters:\\n\");\n\t\tfor (j=0; jinput(0);\n auto flat_in = input.flat();\n\n int fixed_length;\n const auto& length_input = context->input(1);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(length_input.shape()),\n errors::InvalidArgument(\"k must be scalar, got shape \",\n length_input.shape().DebugString()));\n fixed_length = length_input.scalar()();\n\n OP_REQUIRES(\n context, fixed_length % sizeof(T) == 0,\n errors::InvalidArgument(\n \"fixed_length (\", fixed_length,\n \") must be a multiple of the size of out_type (\", sizeof(T), \")\"));\n\n OP_REQUIRES(context, fixed_length > 0,\n errors::InvalidArgument(\"fixed_length (\", fixed_length,\n \") must be greater than zero.\"));\n\n int width = fixed_length / sizeof(T);\n\n TensorShape out_shape = input.shape();\n out_shape.AddDim(width);\n Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(\n context, context->allocate_output(\"output\", out_shape, &output_tensor));\n\n if (flat_in.size() == 0) { // Empty input\n return;\n }\n\n auto out = output_tensor->flat_inner_dims();\n T* out_data = out.data();\n\n // Forcibly clear memory - we're going to copy variable length strings in,\n // and need to ensure that if we don't write to byte N when we copy, that\n // we're not getting random data.\n memset(out_data, 0, fixed_length * flat_in.size());\n\n // If the data is already in the host's byte order, or if the width of the\n // output type is a single byte (meaning the ordering doesn't matter), we\n // can copy the memory directly.\n if (!convert_data_endianness_ || sizeof(T) == 1) {\n for (int64 i = 0; i < flat_in.size(); ++i) {\n const T* in_data = reinterpret_cast(flat_in(i).data());\n\n if (flat_in(i).size() > fixed_length) {\n memcpy(out_data, in_data, fixed_length);\n } else {\n memcpy(out_data, in_data, flat_in(i).size());\n }\n out_data += fixed_length;\n }\n } else {\n // Otherwise, the data is not in the host's byte order, and rather than a\n // direct copy, we need to reverse the byte ordering of each element.\n for (int64 i = 0; i < flat_in.size(); ++i) {\n const char* in_data_bytes =\n reinterpret_cast(flat_in(i).data());\n char* out_data_bytes = reinterpret_cast(out_data);\n const char* p_in = in_data_bytes;\n char* p_out = out_data_bytes;\n for (; p_in < in_data_bytes + fixed_length;\n p_in += sizeof(T), p_out += sizeof(T)) {\n std::reverse_copy(p_in, p_in + sizeof(T), p_out);\n }\n out_data += fixed_length;\n }\n }\n }", "project": "tensorflow", "hash": 146552813611946796478012198860441040266, "size": 72, "commit_id": "698e01511f62a3c185754db78ebce0eee1f0184d", "message": "Fix `tf.io.decode_raw` bugs and update documentation.\n\nFixes cases where specifying `fixed_length` resulted in data loss and even segfault and corruption of the Python interpreter. The fix is subtle but needed due to pointer arithmetic rules.\n\nMakes sure that `fixed_length` does not change the output when present but not needed.\n\nEliminates needless copy and cast in the main codepath.\n\nPiperOrigin-RevId: 371322725\nChange-Id: I514ef67a2961c86422f69d05122d31615e87896c", "target": 1, "dataset": "other", "idx": 196739} {"func": " void Compute(OpKernelContext* context) override {\n const auto& input = context->input(0);\n auto flat_in = input.flat();\n\n int fixed_length;\n const auto& length_input = context->input(1);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(length_input.shape()),\n errors::InvalidArgument(\"k must be scalar, got shape \",\n length_input.shape().DebugString()));\n fixed_length = length_input.scalar()();\n\n OP_REQUIRES(\n context, fixed_length % sizeof(T) == 0,\n errors::InvalidArgument(\n \"fixed_length (\", fixed_length,\n \") must be a multiple of the size of out_type (\", sizeof(T), \")\"));\n\n OP_REQUIRES(context, fixed_length > 0,\n errors::InvalidArgument(\"fixed_length (\", fixed_length,\n \") must be greater than zero.\"));\n\n int width = fixed_length / sizeof(T);\n\n TensorShape out_shape = input.shape();\n out_shape.AddDim(width);\n Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(\n context, context->allocate_output(\"output\", out_shape, &output_tensor));\n\n if (flat_in.size() == 0) { // Empty input\n return;\n }\n\n auto out = output_tensor->flat_inner_dims();\n T* out_data = out.data();\n\n // Forcibly clear memory - we're going to copy variable length strings in,\n // and need to ensure that if we don't write to byte N when we copy, that\n // we're not getting random data.\n memset(out_data, 0, fixed_length * flat_in.size());\n\n // If the data is already in the host's byte order, or if the width of the\n // output type is a single byte (meaning the ordering doesn't matter), we\n // can copy the memory directly.\n if (!convert_data_endianness_ || sizeof(T) == 1) {\n for (int64 i = 0; i < flat_in.size(); ++i) {\n const auto to_copy =\n std::min(flat_in(i).size(), static_cast(fixed_length));\n memcpy(out_data, flat_in(i).data(), to_copy);\n // Note: increase out_data by width since it's already of type T* so\n // each shift amount is implicitly multiplied by sizeof(T) according to\n // pointer arithmetic rules.\n out_data += width;\n }\n } else {\n // Otherwise, the data is not in the host's byte order, and rather than a\n // direct copy, we need to reverse the byte ordering of each element.\n for (int64 i = 0; i < flat_in.size(); ++i) {\n const char* in_data_bytes =\n reinterpret_cast(flat_in(i).data());\n char* out_data_bytes = reinterpret_cast(out_data);\n const char* p_in = in_data_bytes;\n char* p_out = out_data_bytes;\n for (; p_in < in_data_bytes + fixed_length;\n p_in += sizeof(T), p_out += sizeof(T)) {\n std::reverse_copy(p_in, p_in + sizeof(T), p_out);\n }\n // Note: increase out_data by width since it's already of type T* so\n // each shift amount is implicitly multiplied by sizeof(T) according to\n // pointer arithmetic rules.\n out_data += width;\n }\n }\n }", "project": "tensorflow", "hash": 126932864429790550515712824205640725368, "size": 74, "commit_id": "698e01511f62a3c185754db78ebce0eee1f0184d", "message": "Fix `tf.io.decode_raw` bugs and update documentation.\n\nFixes cases where specifying `fixed_length` resulted in data loss and even segfault and corruption of the Python interpreter. The fix is subtle but needed due to pointer arithmetic rules.\n\nMakes sure that `fixed_length` does not change the output when present but not needed.\n\nEliminates needless copy and cast in the main codepath.\n\nPiperOrigin-RevId: 371322725\nChange-Id: I514ef67a2961c86422f69d05122d31615e87896c", "target": 0, "dataset": "other", "idx": 243619} {"func": "static int insert_pin(\n\tsc_pkcs15_card_t *p15card,\n\tconst char *path,\n\tunsigned char id,\n\tunsigned char auth_id,\n\tunsigned char pin_reference,\n\tint min_length,\n\tconst char *label,\n\tint pin_flags\n){\n\tsc_card_t *card=p15card->card;\n\tsc_context_t *ctx=p15card->card->ctx;\n\tsc_file_t *f = NULL;\n\tstruct sc_pkcs15_auth_info pin_info;\n\tstruct sc_pkcs15_object pin_obj;\n\tint r;\n\n\tmemset(&pin_info, 0, sizeof(pin_info));\n\tpin_info.auth_id.len = 1;\n\tpin_info.auth_id.value[0] = id;\n\tpin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;\n\tpin_info.attrs.pin.reference = pin_reference;\n\tpin_info.attrs.pin.flags = pin_flags;\n\tpin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;\n\tpin_info.attrs.pin.min_length = min_length;\n\tpin_info.attrs.pin.stored_length = 16;\n\tpin_info.attrs.pin.max_length = 16;\n\tpin_info.attrs.pin.pad_char = '\\0';\n\tpin_info.logged_in = SC_PIN_STATE_UNKNOWN;\n\tsc_format_path(path, &pin_info.path);\n\n\tmemset(&pin_obj, 0, sizeof(pin_obj));\n\tstrlcpy(pin_obj.label, label, sizeof(pin_obj.label));\n\tpin_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE;\n\tpin_obj.auth_id.len = auth_id ? 0 : 1;\n\tpin_obj.auth_id.value[0] = auth_id;\n\n\tif(card->type == SC_CARD_TYPE_TCOS_V3) {\n\t\tunsigned char buf[256];\n\t\tint i, rec_no=0;\n\t\tif (pin_info.path.len >= 2) {\n\t\t\tpin_info.path.len -= 2;\n\t\t}\n\t\tsc_append_file_id(&pin_info.path, 0x5049);\n\t\tif (sc_select_file(card, &pin_info.path, NULL) != SC_SUCCESS) {\n\t\t\tsc_log(ctx, \n\t\t\t\t\"Select(%s) failed\\n\",\n\t\t\t\tsc_print_path(&pin_info.path));\n\t\t\treturn 1;\n\t\t}\n\t\tsc_log(ctx, \n\t\t\t\"Searching for PIN-Ref %02X\\n\", pin_reference);\n\t\twhile ((r = sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR)) > 0) {\n\t\t\tint found = 0, fbz = -1;\n\t\t\tif (buf[0] != 0xA0)\n\t\t\t\tcontinue;\n\t\t\tfor (i = 2; i < buf[1] + 2; i += 2 + buf[i + 1]) {\n\t\t\t\tif (buf[i] == 0x83 && buf[i + 1] == 1 && buf[i + 2] == pin_reference) {\n\t\t\t\t\t++found;\n\t\t\t\t}\n\t\t\t\tif (buf[i] == 0x90) {\n\t\t\t\t\tfbz = buf[i + 1 + buf[i + 1]];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (found) {\n\t\t\t\tpin_info.tries_left = fbz;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (r <= 0) {\n\t\t\tsc_log(ctx, \"No EF_PWDD-Record found\\n\");\n\t\t\treturn 1;\n\t\t}\n\t} else {\n\t\tif (sc_select_file(card, &pin_info.path, &f) != SC_SUCCESS\n\t\t\t \t|| !f->prop_attr || f->prop_attr_len < 4){\n\t\t\tsc_log(ctx, \"Select(%s) failed\\n\", path);\n\t\t\tsc_file_free(f);\n\t\t\treturn 1;\n\t\t}\n\t\tpin_info.tries_left = f->prop_attr[3];\n\t\tsc_file_free(f);\n\t}\n\n\tr=sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);\n\tif(r!=SC_SUCCESS){\n\t\tsc_log(ctx, \"sc_pkcs15emu_add_pin_obj(%s) failed\\n\", path);\n\t\treturn 4;\n\t}\n\tsc_log(ctx, \"%s: OK, FBZ=%d\\n\", path, pin_info.tries_left);\n\treturn 0;\n}", "project": "OpenSC", "hash": 106837843557221778698667602114311306154, "size": 92, "commit_id": "5df913b7f57ad89b9832555d24c08d23a534311e", "message": "tcos: Check bounds in insert_pin()\n\nThanks oss-fuzz\n\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=28383", "target": 1, "dataset": "other", "idx": 196754} {"func": "static int insert_pin(\n\tsc_pkcs15_card_t *p15card,\n\tconst char *path,\n\tunsigned char id,\n\tunsigned char auth_id,\n\tunsigned char pin_reference,\n\tint min_length,\n\tconst char *label,\n\tint pin_flags\n){\n\tsc_card_t *card=p15card->card;\n\tsc_context_t *ctx=p15card->card->ctx;\n\tsc_file_t *f = NULL;\n\tstruct sc_pkcs15_auth_info pin_info;\n\tstruct sc_pkcs15_object pin_obj;\n\tint r;\n\n\tmemset(&pin_info, 0, sizeof(pin_info));\n\tpin_info.auth_id.len = 1;\n\tpin_info.auth_id.value[0] = id;\n\tpin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;\n\tpin_info.attrs.pin.reference = pin_reference;\n\tpin_info.attrs.pin.flags = pin_flags;\n\tpin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;\n\tpin_info.attrs.pin.min_length = min_length;\n\tpin_info.attrs.pin.stored_length = 16;\n\tpin_info.attrs.pin.max_length = 16;\n\tpin_info.attrs.pin.pad_char = '\\0';\n\tpin_info.logged_in = SC_PIN_STATE_UNKNOWN;\n\tsc_format_path(path, &pin_info.path);\n\n\tmemset(&pin_obj, 0, sizeof(pin_obj));\n\tstrlcpy(pin_obj.label, label, sizeof(pin_obj.label));\n\tpin_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE;\n\tpin_obj.auth_id.len = auth_id ? 0 : 1;\n\tpin_obj.auth_id.value[0] = auth_id;\n\n\tif(card->type == SC_CARD_TYPE_TCOS_V3) {\n\t\tunsigned char buf[256];\n\t\tint i, rec_no=0;\n\t\tif (pin_info.path.len >= 2) {\n\t\t\tpin_info.path.len -= 2;\n\t\t}\n\t\tsc_append_file_id(&pin_info.path, 0x5049);\n\t\tif (sc_select_file(card, &pin_info.path, NULL) != SC_SUCCESS) {\n\t\t\tsc_log(ctx, \n\t\t\t\t\"Select(%s) failed\\n\",\n\t\t\t\tsc_print_path(&pin_info.path));\n\t\t\treturn 1;\n\t\t}\n\t\tsc_log(ctx, \n\t\t\t\"Searching for PIN-Ref %02X\\n\", pin_reference);\n\t\twhile ((r = sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR)) > 0) {\n\t\t\tint found = 0, fbz = -1;\n\t\t\tif (r < 2 || buf[0] != 0xA0)\n\t\t\t\tcontinue;\n\t\t\tfor (i = 2; i < buf[1] + 2 && (i + 2) < r; i += 2 + buf[i + 1]) {\n\t\t\t\tif (buf[i] == 0x83 && buf[i + 1] == 1 && buf[i + 2] == pin_reference) {\n\t\t\t\t\t++found;\n\t\t\t\t}\n\t\t\t\tif (buf[i] == 0x90 && (i + 1 + buf[i + 1]) < r) {\n\t\t\t\t\tfbz = buf[i + 1 + buf[i + 1]];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (found) {\n\t\t\t\tpin_info.tries_left = fbz;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (r <= 0) {\n\t\t\tsc_log(ctx, \"No EF_PWDD-Record found\\n\");\n\t\t\treturn 1;\n\t\t}\n\t} else {\n\t\tif (sc_select_file(card, &pin_info.path, &f) != SC_SUCCESS\n\t\t\t \t|| !f->prop_attr || f->prop_attr_len < 4){\n\t\t\tsc_log(ctx, \"Select(%s) failed\\n\", path);\n\t\t\tsc_file_free(f);\n\t\t\treturn 1;\n\t\t}\n\t\tpin_info.tries_left = f->prop_attr[3];\n\t\tsc_file_free(f);\n\t}\n\n\tr=sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);\n\tif(r!=SC_SUCCESS){\n\t\tsc_log(ctx, \"sc_pkcs15emu_add_pin_obj(%s) failed\\n\", path);\n\t\treturn 4;\n\t}\n\tsc_log(ctx, \"%s: OK, FBZ=%d\\n\", path, pin_info.tries_left);\n\treturn 0;\n}", "project": "OpenSC", "hash": 53450176173982244017827403871002445488, "size": 92, "commit_id": "5df913b7f57ad89b9832555d24c08d23a534311e", "message": "tcos: Check bounds in insert_pin()\n\nThanks oss-fuzz\n\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=28383", "target": 0, "dataset": "other", "idx": 243958} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& indices_tensor = ctx->input(0);\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(indices_tensor.shape()) ||\n TensorShapeUtils::IsScalar(indices_tensor.shape()),\n errors::InvalidArgument(\n \"The indices can only be scalar or vector, got \\\"\",\n indices_tensor.shape().DebugString(), \"\\\"\"));\n\n const Tensor& dims_tensor = ctx->input(1);\n OP_REQUIRES(\n ctx, TensorShapeUtils::IsVector(dims_tensor.shape()),\n errors::InvalidArgument(\"The indices can only be 1-D, got \\\"\",\n dims_tensor.shape().DebugString(), \"\\\"\"));\n\n auto dims = dims_tensor.vec();\n\n // Chek to make sure indices is not out of boundary\n Eigen::Tensor dims_prod_eigen = dims.prod();\n Tidx dims_prod = dims_prod_eigen();\n const Tidx* indices = indices_tensor.flat().data();\n int64 size = indices_tensor.NumElements();\n bool check = std::all_of(indices, indices + size,\n [&](Tidx index) { return index < dims_prod; });\n OP_REQUIRES(ctx, check,\n errors::InvalidArgument(\"index is out of bound as with dims\"));\n\n Eigen::array reverse({true});\n\n Tensor strides_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_temp(DataTypeToEnum::value,\n TensorShape({dims_tensor.NumElements()}),\n &strides_tensor));\n\n auto strides = strides_tensor.vec();\n strides = dims.reverse(reverse)\n .scan(0, Eigen::internal::ProdReducer(), false)\n .reverse(reverse);\n\n Tensor strides_shifted_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_temp(DataTypeToEnum::value,\n TensorShape({dims_tensor.NumElements()}),\n &strides_shifted_tensor));\n\n auto strides_shifted = strides_shifted_tensor.vec();\n strides_shifted = dims.reverse(reverse)\n .scan(0, Eigen::internal::ProdReducer(), true)\n .reverse(reverse);\n\n Tensor* output_tensor = nullptr;\n if (TensorShapeUtils::IsScalar(indices_tensor.shape())) {\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, TensorShape({dims_tensor.NumElements()}),\n &output_tensor));\n\n auto output = output_tensor->vec();\n\n output = output.constant(indices_tensor.scalar()());\n output = output.binaryExpr(strides, mod_op()) / strides_shifted;\n } else {\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0,\n TensorShape({dims_tensor.NumElements(),\n indices_tensor.NumElements()}),\n &output_tensor));\n\n auto output = output_tensor->matrix();\n\n Eigen::array reshape{\n {static_cast(dims_tensor.NumElements()), 1}};\n Eigen::array bcast(\n {1, static_cast(indices_tensor.NumElements())});\n Eigen::array indices_reshape{\n {1, static_cast(indices_tensor.NumElements())}};\n Eigen::array indices_bcast(\n {static_cast(dims_tensor.NumElements()), 1});\n\n output = indices_tensor.vec()\n .reshape(indices_reshape)\n .broadcast(indices_bcast);\n output = output.binaryExpr(strides.reshape(reshape).broadcast(bcast),\n mod_op()) /\n strides_shifted.reshape(reshape).broadcast(bcast);\n }\n }", "project": "tensorflow", "hash": 264158770569740569963092041338700970996, "size": 87, "commit_id": "a776040a5e7ebf76eeb7eb923bf1ae417dd4d233", "message": "Disallow dims input of 0 in tf.raw_ops.UnravelIndex\n\nPiperOrigin-RevId: 384284198\nChange-Id: Ia1804ef1aec57b4d857ea507e6891bcccde18e9b", "target": 1, "dataset": "other", "idx": 196763} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& indices_tensor = ctx->input(0);\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(indices_tensor.shape()) ||\n TensorShapeUtils::IsScalar(indices_tensor.shape()),\n errors::InvalidArgument(\n \"The indices can only be scalar or vector, got \\\"\",\n indices_tensor.shape().DebugString(), \"\\\"\"));\n\n const Tensor& dims_tensor = ctx->input(1);\n OP_REQUIRES(\n ctx, TensorShapeUtils::IsVector(dims_tensor.shape()),\n errors::InvalidArgument(\"The indices can only be 1-D, got \\\"\",\n dims_tensor.shape().DebugString(), \"\\\"\"));\n\n auto dims = dims_tensor.vec();\n // Make sure dims does not contain a zero\n for (int i = 0; i < dims.size(); i++) {\n OP_REQUIRES(\n ctx, dims(i) != 0,\n errors::InvalidArgument(\"Input dims cannot contain a dim of zero, \"\n \"but dims contains zero at index \",\n i));\n }\n\n // Chek to make sure indices is not out of boundary\n Eigen::Tensor dims_prod_eigen = dims.prod();\n Tidx dims_prod = dims_prod_eigen();\n const Tidx* indices = indices_tensor.flat().data();\n int64 size = indices_tensor.NumElements();\n bool check = std::all_of(indices, indices + size,\n [&](Tidx index) { return index < dims_prod; });\n OP_REQUIRES(ctx, check,\n errors::InvalidArgument(\"index is out of bound as with dims\"));\n\n Eigen::array reverse({true});\n\n Tensor strides_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_temp(DataTypeToEnum::value,\n TensorShape({dims_tensor.NumElements()}),\n &strides_tensor));\n\n auto strides = strides_tensor.vec();\n strides = dims.reverse(reverse)\n .scan(0, Eigen::internal::ProdReducer(), false)\n .reverse(reverse);\n\n Tensor strides_shifted_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_temp(DataTypeToEnum::value,\n TensorShape({dims_tensor.NumElements()}),\n &strides_shifted_tensor));\n\n auto strides_shifted = strides_shifted_tensor.vec();\n strides_shifted = dims.reverse(reverse)\n .scan(0, Eigen::internal::ProdReducer(), true)\n .reverse(reverse);\n\n Tensor* output_tensor = nullptr;\n if (TensorShapeUtils::IsScalar(indices_tensor.shape())) {\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, TensorShape({dims_tensor.NumElements()}),\n &output_tensor));\n\n auto output = output_tensor->vec();\n\n output = output.constant(indices_tensor.scalar()());\n output = output.binaryExpr(strides, mod_op()) / strides_shifted;\n } else {\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0,\n TensorShape({dims_tensor.NumElements(),\n indices_tensor.NumElements()}),\n &output_tensor));\n\n auto output = output_tensor->matrix();\n\n Eigen::array reshape{\n {static_cast(dims_tensor.NumElements()), 1}};\n Eigen::array bcast(\n {1, static_cast(indices_tensor.NumElements())});\n Eigen::array indices_reshape{\n {1, static_cast(indices_tensor.NumElements())}};\n Eigen::array indices_bcast(\n {static_cast(dims_tensor.NumElements()), 1});\n\n output = indices_tensor.vec()\n .reshape(indices_reshape)\n .broadcast(indices_bcast);\n output = output.binaryExpr(strides.reshape(reshape).broadcast(bcast),\n mod_op()) /\n strides_shifted.reshape(reshape).broadcast(bcast);\n }\n }", "project": "tensorflow", "hash": 190979480133558515936234630943195362228, "size": 95, "commit_id": "a776040a5e7ebf76eeb7eb923bf1ae417dd4d233", "message": "Disallow dims input of 0 in tf.raw_ops.UnravelIndex\n\nPiperOrigin-RevId: 384284198\nChange-Id: Ia1804ef1aec57b4d857ea507e6891bcccde18e9b", "target": 0, "dataset": "other", "idx": 243980} {"func": "static void nhmldump_send_header(GF_NHMLDumpCtx *ctx)\n{\n\tGF_FilterPacket *dst_pck;\n\tchar nhml[1024];\n\tu32 size;\n\tu8 *output;\n\tconst GF_PropertyValue *p;\n\n\tctx->szRootName = \"NHNTStream\";\n\tif (ctx->dims) {\n\t\tctx->szRootName = \"DIMSStream\";\n\t}\n\n\tif (!ctx->filep) {\n\t\tsprintf(nhml, \"\\n\");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\t/*write header*/\n\tsprintf(nhml, \"<%s version=\\\"1.0\\\" \", ctx->szRootName);\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\n\tNHML_PRINT_UINT(GF_PROP_PID_ID, NULL, \"trackID\")\n\tNHML_PRINT_UINT(GF_PROP_PID_TIMESCALE, NULL, \"timeScale\")\n\n\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_IN_IOD);\n\tif (p && p->value.boolean) {\n\t\tsprintf(nhml, \"inRootOD=\\\"yes\\\" \");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\tif (ctx->oti && (ctx->otistreamtype, ctx->oti);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32)strlen(nhml));\n\t} else {\n\t\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_SUBTYPE);\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"%s=\\\"%s\\\" \", \"mediaType\", gf_4cc_to_str(p->value.uint));\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\t\tNHML_PRINT_4CC(GF_PROP_PID_ISOM_SUBTYPE, \"mediaSubType\", \"mediaSubType\")\n\t\t} else {\n\t\t\tNHML_PRINT_4CC(GF_PROP_PID_CODECID, NULL, \"codecID\")\n\t\t}\n\t}\n\n\tif (ctx->w && ctx->h) {\n\t\t//compatibility with old arch, we might want to remove this\n\t\tswitch (ctx->streamtype) {\n\t\tcase GF_STREAM_VISUAL:\n\t\tcase GF_STREAM_SCENE:\n\t\t\tsprintf(nhml, \"width=\\\"%d\\\" height=\\\"%d\\\" \", ctx->w, ctx->h);\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\telse if (ctx->sr && ctx->chan) {\n\t\tsprintf(nhml, \"sampleRate=\\\"%d\\\" numChannels=\\\"%d\\\" \", ctx->sr, ctx->chan);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\tsprintf(nhml, \"sampleRate=\\\"%d\\\" numChannels=\\\"%d\\\" \", ctx->sr, ctx->chan);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_AUDIO_FORMAT);\n\t\tsprintf(nhml, \"bitsPerSample=\\\"%d\\\" \", gf_audio_fmt_bit_depth(p->value.uint));\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\tNHML_PRINT_4CC(0, \"codec_vendor\", \"codecVendor\")\n\tNHML_PRINT_UINT(0, \"codec_version\", \"codecVersion\")\n\tNHML_PRINT_UINT(0, \"codec_revision\", \"codecRevision\")\n\tNHML_PRINT_STRING(0, \"compressor_name\", \"compressorName\")\n\tNHML_PRINT_UINT(0, \"temporal_quality\", \"temporalQuality\")\n\tNHML_PRINT_UINT(0, \"spatial_quality\", \"spatialQuality\")\n\tNHML_PRINT_UINT(0, \"hres\", \"horizontalResolution\")\n\tNHML_PRINT_UINT(0, \"vres\", \"verticalResolution\")\n\tNHML_PRINT_UINT(GF_PROP_PID_BIT_DEPTH_Y, NULL, \"bitDepth\")\n\n\tNHML_PRINT_STRING(0, \"meta:xmlns\", \"xml_namespace\")\n\tNHML_PRINT_STRING(0, \"meta:schemaloc\", \"xml_schema_location\")\n\tNHML_PRINT_STRING(0, \"meta:mime\", \"mime_type\")\n\n\tNHML_PRINT_STRING(0, \"meta:config\", \"config\")\n\tNHML_PRINT_STRING(0, \"meta:aux_mimes\", \"aux_mime_type\")\n\n\tif (ctx->codecid == GF_CODECID_DIMS) {\n\t\tif (gf_filter_pid_get_property_str(ctx->ipid, \"meta:xmlns\")==NULL) {\n\t\t\tsprintf(nhml, \"xmlns=\\\"http://www.3gpp.org/richmedia\\\" \");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\n\t\tNHML_PRINT_UINT(0, \"dims:profile\", \"profile\")\n\t\tNHML_PRINT_UINT(0, \"dims:level\", \"level\")\n\t\tNHML_PRINT_UINT(0, \"dims:pathComponents\", \"pathComponents\")\n\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:fullRequestHost\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"useFullRequestHost=\\\"%s\\\" \", p->value.boolean ? \"yes\" : \"no\");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:streamType\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"stream_type=\\\"%s\\\" \", p->value.boolean ? \"primary\" : \"secondary\");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:redundant\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"contains_redundant=\\\"%s\\\" \", (p->value.uint==1) ? \"main\" : ((p->value.uint==1) ? \"redundant\" : \"main+redundant\") );\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tNHML_PRINT_UINT(0, \"dims:scriptTypes\", \"scriptTypes\")\n\t}\n\n\t//send DCD\n\tif (ctx->opid_info) {\n\t\tsprintf(nhml, \"specificInfoFile=\\\"%s\\\" \", gf_file_basename(ctx->info_file) );\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\tdst_pck = gf_filter_pck_new_shared(ctx->opid_info, ctx->dcfg, ctx->dcfg_size, NULL);\n\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\t\tgf_filter_pck_set_readonly(dst_pck);\n\t\tgf_filter_pck_send(dst_pck);\n\t}\n\n\tNHML_PRINT_STRING(0, \"meta:encoding\", \"encoding\")\n\tNHML_PRINT_STRING(0, \"meta:contentEncoding\", \"content_encoding\")\n\tctx->uncompress = GF_FALSE;\n\tif (p) {\n\t\tif (!strcmp(p->value.string, \"deflate\")) ctx->uncompress = GF_TRUE;\n\t\telse {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[NHMLMx] content_encoding %s not supported\\n\", p->value.string ));\n\t\t}\n\t}\n\n\tif (ctx->opid_mdia) {\n\t\tsprintf(nhml, \"baseMediaFile=\\\"%s\\\" \", gf_file_basename(ctx->media_file) );\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\tsprintf(nhml, \">\\n\");\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\tgf_bs_get_content_no_truncate(ctx->bs_w, &ctx->nhml_buffer, &size, &ctx->nhml_buffer_size);\n\n\tif (ctx->filep) {\n\t\tgf_fwrite(ctx->nhml_buffer, size, ctx->filep);\n\t\treturn;\n\t}\n\n\tdst_pck = gf_filter_pck_new_alloc(ctx->opid_nhml, size, &output);\n\tmemcpy(output, ctx->nhml_buffer, size);\n\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_FALSE);\n\tgf_filter_pck_send(dst_pck);\n}", "project": "gpac", "hash": 171851966591827362626279278095562125748, "size": 154, "commit_id": "9eeac00b38348c664dfeae2525bba0cf1bc32349", "message": "fixed #1565", "target": 1, "dataset": "other", "idx": 196766} {"func": "static void nhmldump_send_header(GF_NHMLDumpCtx *ctx)\n{\n\tGF_FilterPacket *dst_pck;\n\tchar nhml[1024];\n\tu32 size;\n\tu8 *output;\n\tconst GF_PropertyValue *p;\n\n\tctx->szRootName = \"NHNTStream\";\n\tif (ctx->dims) {\n\t\tctx->szRootName = \"DIMSStream\";\n\t}\n\n\tif (!ctx->filep) {\n\t\tsprintf(nhml, \"\\n\");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\t/*write header*/\n\tsprintf(nhml, \"<%s version=\\\"1.0\\\" \", ctx->szRootName);\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\n\tNHML_PRINT_UINT(GF_PROP_PID_ID, NULL, \"trackID\")\n\tNHML_PRINT_UINT(GF_PROP_PID_TIMESCALE, NULL, \"timeScale\")\n\n\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_IN_IOD);\n\tif (p && p->value.boolean) {\n\t\tsprintf(nhml, \"inRootOD=\\\"yes\\\" \");\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\tif (ctx->oti && (ctx->otistreamtype, ctx->oti);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32)strlen(nhml));\n\t} else {\n\t\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_SUBTYPE);\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"%s=\\\"%s\\\" \", \"mediaType\", gf_4cc_to_str(p->value.uint));\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\t\tNHML_PRINT_4CC(GF_PROP_PID_ISOM_SUBTYPE, \"mediaSubType\", \"mediaSubType\")\n\t\t} else {\n\t\t\tNHML_PRINT_4CC(GF_PROP_PID_CODECID, NULL, \"codecID\")\n\t\t}\n\t}\n\n\tif (ctx->w && ctx->h) {\n\t\t//compatibility with old arch, we might want to remove this\n\t\tswitch (ctx->streamtype) {\n\t\tcase GF_STREAM_VISUAL:\n\t\tcase GF_STREAM_SCENE:\n\t\t\tsprintf(nhml, \"width=\\\"%d\\\" height=\\\"%d\\\" \", ctx->w, ctx->h);\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\telse if (ctx->sr && ctx->chan) {\n\t\tsprintf(nhml, \"sampleRate=\\\"%d\\\" numChannels=\\\"%d\\\" \", ctx->sr, ctx->chan);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\tsprintf(nhml, \"sampleRate=\\\"%d\\\" numChannels=\\\"%d\\\" \", ctx->sr, ctx->chan);\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\tp = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_AUDIO_FORMAT);\n\t\tif (p)\n\t\t\tsprintf(nhml, \"bitsPerSample=\\\"%d\\\" \", gf_audio_fmt_bit_depth(p->value.uint));\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\n\tNHML_PRINT_4CC(0, \"codec_vendor\", \"codecVendor\")\n\tNHML_PRINT_UINT(0, \"codec_version\", \"codecVersion\")\n\tNHML_PRINT_UINT(0, \"codec_revision\", \"codecRevision\")\n\tNHML_PRINT_STRING(0, \"compressor_name\", \"compressorName\")\n\tNHML_PRINT_UINT(0, \"temporal_quality\", \"temporalQuality\")\n\tNHML_PRINT_UINT(0, \"spatial_quality\", \"spatialQuality\")\n\tNHML_PRINT_UINT(0, \"hres\", \"horizontalResolution\")\n\tNHML_PRINT_UINT(0, \"vres\", \"verticalResolution\")\n\tNHML_PRINT_UINT(GF_PROP_PID_BIT_DEPTH_Y, NULL, \"bitDepth\")\n\n\tNHML_PRINT_STRING(0, \"meta:xmlns\", \"xml_namespace\")\n\tNHML_PRINT_STRING(0, \"meta:schemaloc\", \"xml_schema_location\")\n\tNHML_PRINT_STRING(0, \"meta:mime\", \"mime_type\")\n\n\tNHML_PRINT_STRING(0, \"meta:config\", \"config\")\n\tNHML_PRINT_STRING(0, \"meta:aux_mimes\", \"aux_mime_type\")\n\n\tif (ctx->codecid == GF_CODECID_DIMS) {\n\t\tif (gf_filter_pid_get_property_str(ctx->ipid, \"meta:xmlns\")==NULL) {\n\t\t\tsprintf(nhml, \"xmlns=\\\"http://www.3gpp.org/richmedia\\\" \");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\n\t\tNHML_PRINT_UINT(0, \"dims:profile\", \"profile\")\n\t\tNHML_PRINT_UINT(0, \"dims:level\", \"level\")\n\t\tNHML_PRINT_UINT(0, \"dims:pathComponents\", \"pathComponents\")\n\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:fullRequestHost\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"useFullRequestHost=\\\"%s\\\" \", p->value.boolean ? \"yes\" : \"no\");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:streamType\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"stream_type=\\\"%s\\\" \", p->value.boolean ? \"primary\" : \"secondary\");\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tp = gf_filter_pid_get_property_str(ctx->ipid, \"dims:redundant\");\n\t\tif (p) {\n\t\t\tsprintf(nhml, \"contains_redundant=\\\"%s\\\" \", (p->value.uint==1) ? \"main\" : ((p->value.uint==1) ? \"redundant\" : \"main+redundant\") );\n\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t\t}\n\t\tNHML_PRINT_UINT(0, \"dims:scriptTypes\", \"scriptTypes\")\n\t}\n\n\t//send DCD\n\tif (ctx->opid_info) {\n\t\tsprintf(nhml, \"specificInfoFile=\\\"%s\\\" \", gf_file_basename(ctx->info_file) );\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\tdst_pck = gf_filter_pck_new_shared(ctx->opid_info, ctx->dcfg, ctx->dcfg_size, NULL);\n\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\t\tgf_filter_pck_set_readonly(dst_pck);\n\t\tgf_filter_pck_send(dst_pck);\n\t}\n\n\tNHML_PRINT_STRING(0, \"meta:encoding\", \"encoding\")\n\tNHML_PRINT_STRING(0, \"meta:contentEncoding\", \"content_encoding\")\n\tctx->uncompress = GF_FALSE;\n\tif (p) {\n\t\tif (!strcmp(p->value.string, \"deflate\")) ctx->uncompress = GF_TRUE;\n\t\telse {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (\"[NHMLMx] content_encoding %s not supported\\n\", p->value.string ));\n\t\t}\n\t}\n\n\tif (ctx->opid_mdia) {\n\t\tsprintf(nhml, \"baseMediaFile=\\\"%s\\\" \", gf_file_basename(ctx->media_file) );\n\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\t}\n\tsprintf(nhml, \">\\n\");\n\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\tgf_bs_get_content_no_truncate(ctx->bs_w, &ctx->nhml_buffer, &size, &ctx->nhml_buffer_size);\n\n\tif (ctx->filep) {\n\t\tgf_fwrite(ctx->nhml_buffer, size, ctx->filep);\n\t\treturn;\n\t}\n\n\tdst_pck = gf_filter_pck_new_alloc(ctx->opid_nhml, size, &output);\n\tmemcpy(output, ctx->nhml_buffer, size);\n\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_FALSE);\n\tgf_filter_pck_send(dst_pck);\n}", "project": "gpac", "hash": 192488898754254972476380860269472215022, "size": 155, "commit_id": "9eeac00b38348c664dfeae2525bba0cf1bc32349", "message": "fixed #1565", "target": 0, "dataset": "other", "idx": 244385} {"func": "static int track_header(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, int size)\n{\n int i, j, ret;\n int64_t off;\n int val_1;\n int num_video;\n AVIOContext pb0, *pb = &pb0;\n\n ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL);\n\n ffio_read_varlen(pb); // track_header_len\n avio_r8(pb); // '1'\n\n val_1 = ffio_read_varlen(pb);\n\n for (i=0;iid = i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;\n st->codecpar->codec_id = AV_CODEC_ID_VP6;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb);\n avio_r8(pb); // '3'\n avio_r8(pb); // val_7\n num = avio_rl32(pb); // frame_time\n den = avio_rl32(pb); // time_base\n avpriv_set_pts_info(st, 64, num, den);\n st->nb_frames = avio_rl32(pb); // n frames\n st->codecpar->width = avio_rl16(pb); // width\n st->codecpar->height = avio_rl16(pb); // height\n avio_r8(pb); // val_8\n avio_rl32(pb); // val_9\n\n avio_seek(pb, off, SEEK_SET);\n }\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // val_10\n avio_r8(pb); // '4'\n viv->num_audio = avio_r8(pb);\n avio_seek(pb, off, SEEK_SET);\n\n if (viv->num_audio != 1)\n av_log(s, AV_LOG_WARNING, \"number of audio tracks %d is not 1\\n\", viv->num_audio);\n\n for(i=0;inum_audio;i++) {\n int q;\n AVStream *st = avformat_new_stream(s, NULL);\n if (!st)\n return AVERROR(ENOMEM);\n\n st->id = num_video + i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;\n st->codecpar->codec_id = AV_CODEC_ID_VORBIS;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // length\n avio_r8(pb); // '5'\n avio_r8(pb); //codec_id\n avio_rl16(pb); //codec_subid\n st->codecpar->channels = avio_rl16(pb); // channels\n st->codecpar->sample_rate = avio_rl32(pb); // sample_rate\n avio_seek(pb, 10, SEEK_CUR); // data_1\n q = avio_r8(pb);\n avio_seek(pb, q, SEEK_CUR); // data_2\n avio_r8(pb); // zeropad\n\n if (avio_tell(pb) < off) {\n int num_data;\n int xd_size = 0;\n int data_len[256];\n int offset = 1;\n uint8_t *p;\n ffio_read_varlen(pb); // val_13\n avio_r8(pb); // '19'\n ffio_read_varlen(pb); // len_3\n num_data = avio_r8(pb);\n for (j = 0; j < num_data; j++) {\n uint64_t len = ffio_read_varlen(pb);\n if (len > INT_MAX/2 - xd_size) {\n return AVERROR_INVALIDDATA;\n }\n data_len[j] = len;\n xd_size += len;\n }\n\n ret = ff_alloc_extradata(st->codecpar, 64 + xd_size + xd_size / 255);\n if (ret < 0)\n return ret;\n\n p = st->codecpar->extradata;\n p[0] = 2;\n\n for (j = 0; j < num_data - 1; j++) {\n unsigned delta = av_xiphlacing(&p[offset], data_len[j]);\n if (delta > data_len[j]) {\n return AVERROR_INVALIDDATA;\n }\n offset += delta;\n }\n\n for (j = 0; j < num_data; j++) {\n int ret = avio_read(pb, &p[offset], data_len[j]);\n if (ret < data_len[j]) {\n st->codecpar->extradata_size = 0;\n av_freep(&st->codecpar->extradata);\n break;\n }\n offset += data_len[j];\n }\n\n if (offset < st->codecpar->extradata_size)\n st->codecpar->extradata_size = offset;\n }\n }\n\n return 0;\n}", "project": "FFmpeg", "hash": 206145715012219860741644177051309694139, "size": 152, "commit_id": "27a99e2c7d450fef15594671eef4465c8a166bd7", "message": "avformat/vividas: improve extradata packing checks in track_header()\n\nFixes: out of array accesses\nFixes: 26622/clusterfuzz-testcase-minimized-ffmpeg_dem_VIVIDAS_fuzzer-6581200338288640\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nSigned-off-by: Michael Niedermayer ", "target": 1, "dataset": "other", "idx": 196768} {"func": "static int track_header(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, int size)\n{\n int i, j, ret;\n int64_t off;\n int val_1;\n int num_video;\n AVIOContext pb0, *pb = &pb0;\n\n ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL);\n\n ffio_read_varlen(pb); // track_header_len\n avio_r8(pb); // '1'\n\n val_1 = ffio_read_varlen(pb);\n\n for (i=0;iid = i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;\n st->codecpar->codec_id = AV_CODEC_ID_VP6;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb);\n avio_r8(pb); // '3'\n avio_r8(pb); // val_7\n num = avio_rl32(pb); // frame_time\n den = avio_rl32(pb); // time_base\n avpriv_set_pts_info(st, 64, num, den);\n st->nb_frames = avio_rl32(pb); // n frames\n st->codecpar->width = avio_rl16(pb); // width\n st->codecpar->height = avio_rl16(pb); // height\n avio_r8(pb); // val_8\n avio_rl32(pb); // val_9\n\n avio_seek(pb, off, SEEK_SET);\n }\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // val_10\n avio_r8(pb); // '4'\n viv->num_audio = avio_r8(pb);\n avio_seek(pb, off, SEEK_SET);\n\n if (viv->num_audio != 1)\n av_log(s, AV_LOG_WARNING, \"number of audio tracks %d is not 1\\n\", viv->num_audio);\n\n for(i=0;inum_audio;i++) {\n int q;\n AVStream *st = avformat_new_stream(s, NULL);\n if (!st)\n return AVERROR(ENOMEM);\n\n st->id = num_video + i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;\n st->codecpar->codec_id = AV_CODEC_ID_VORBIS;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // length\n avio_r8(pb); // '5'\n avio_r8(pb); //codec_id\n avio_rl16(pb); //codec_subid\n st->codecpar->channels = avio_rl16(pb); // channels\n st->codecpar->sample_rate = avio_rl32(pb); // sample_rate\n avio_seek(pb, 10, SEEK_CUR); // data_1\n q = avio_r8(pb);\n avio_seek(pb, q, SEEK_CUR); // data_2\n avio_r8(pb); // zeropad\n\n if (avio_tell(pb) < off) {\n int num_data;\n int xd_size = 1;\n int data_len[256];\n int offset = 1;\n uint8_t *p;\n ffio_read_varlen(pb); // val_13\n avio_r8(pb); // '19'\n ffio_read_varlen(pb); // len_3\n num_data = avio_r8(pb);\n for (j = 0; j < num_data; j++) {\n uint64_t len = ffio_read_varlen(pb);\n if (len > INT_MAX/2 - xd_size) {\n return AVERROR_INVALIDDATA;\n }\n data_len[j] = len;\n xd_size += len + 1 + len/255;\n }\n\n ret = ff_alloc_extradata(st->codecpar, xd_size);\n if (ret < 0)\n return ret;\n\n p = st->codecpar->extradata;\n p[0] = 2;\n\n for (j = 0; j < num_data - 1; j++) {\n unsigned delta = av_xiphlacing(&p[offset], data_len[j]);\n av_assert0(delta <= xd_size - offset);\n offset += delta;\n }\n\n for (j = 0; j < num_data; j++) {\n int ret = avio_read(pb, &p[offset], data_len[j]);\n if (ret < data_len[j]) {\n st->codecpar->extradata_size = 0;\n av_freep(&st->codecpar->extradata);\n break;\n }\n av_assert0(data_len[j] <= xd_size - offset);\n offset += data_len[j];\n }\n\n if (offset < st->codecpar->extradata_size)\n st->codecpar->extradata_size = offset;\n }\n }\n\n return 0;\n}", "project": "FFmpeg", "hash": 221246914153953907748437805686154036081, "size": 151, "commit_id": "27a99e2c7d450fef15594671eef4465c8a166bd7", "message": "avformat/vividas: improve extradata packing checks in track_header()\n\nFixes: out of array accesses\nFixes: 26622/clusterfuzz-testcase-minimized-ffmpeg_dem_VIVIDAS_fuzzer-6581200338288640\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nSigned-off-by: Michael Niedermayer ", "target": 0, "dataset": "other", "idx": 244426} {"func": "static int process_base_block(struct archive_read* a,\n struct archive_entry* entry)\n{\n\tstruct rar5* rar = get_context(a);\n\tuint32_t hdr_crc, computed_crc;\n\tsize_t raw_hdr_size = 0, hdr_size_len, hdr_size;\n\tsize_t header_id = 0;\n\tsize_t header_flags = 0;\n\tconst uint8_t* p;\n\tint ret;\n\n\tenum HEADER_TYPE {\n\t\tHEAD_MARK = 0x00, HEAD_MAIN = 0x01, HEAD_FILE = 0x02,\n\t\tHEAD_SERVICE = 0x03, HEAD_CRYPT = 0x04, HEAD_ENDARC = 0x05,\n\t\tHEAD_UNKNOWN = 0xff,\n\t};\n\n\t/* Skip any unprocessed data for this file. */\n\tret = skip_unprocessed_bytes(a);\n\tif(ret != ARCHIVE_OK)\n\t\treturn ret;\n\n\t/* Read the expected CRC32 checksum. */\n\tif(!read_u32(a, &hdr_crc)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\t/* Read header size. */\n\tif(!read_var_sized(a, &raw_hdr_size, &hdr_size_len)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\t/* Sanity check, maximum header size for RAR5 is 2MB. */\n\tif(raw_hdr_size > (2 * 1024 * 1024)) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t \"Base block header is too large\");\n\n\t\treturn ARCHIVE_FATAL;\n\t}\n\n\thdr_size = raw_hdr_size + hdr_size_len;\n\n\t/* Read the whole header data into memory, maximum memory use here is\n\t * 2MB. */\n\tif(!read_ahead(a, hdr_size, &p)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\t/* Verify the CRC32 of the header data. */\n\tcomputed_crc = (uint32_t) crc32(0, p, (int) hdr_size);\n\tif(computed_crc != hdr_crc) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t \"Header CRC error\");\n\n\t\treturn ARCHIVE_FATAL;\n\t}\n\n\t/* If the checksum is OK, we proceed with parsing. */\n\tif(ARCHIVE_OK != consume(a, hdr_size_len)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\tif(!read_var_sized(a, &header_id, NULL))\n\t\treturn ARCHIVE_EOF;\n\n\tif(!read_var_sized(a, &header_flags, NULL))\n\t\treturn ARCHIVE_EOF;\n\n\trar->generic.split_after = (header_flags & HFL_SPLIT_AFTER) > 0;\n\trar->generic.split_before = (header_flags & HFL_SPLIT_BEFORE) > 0;\n\trar->generic.size = (int)hdr_size;\n\trar->generic.last_header_id = (int)header_id;\n\trar->main.endarc = 0;\n\n\t/* Those are possible header ids in RARv5. */\n\tswitch(header_id) {\n\t\tcase HEAD_MAIN:\n\t\t\tret = process_head_main(a, rar, entry, header_flags);\n\n\t\t\t/* Main header doesn't have any files in it, so it's\n\t\t\t * pointless to return to the caller. Retry to next\n\t\t\t * header, which should be HEAD_FILE/HEAD_SERVICE. */\n\t\t\tif(ret == ARCHIVE_OK)\n\t\t\t\treturn ARCHIVE_RETRY;\n\n\t\t\treturn ret;\n\t\tcase HEAD_SERVICE:\n\t\t\tret = process_head_service(a, rar, entry, header_flags);\n\t\t\treturn ret;\n\t\tcase HEAD_FILE:\n\t\t\tret = process_head_file(a, rar, entry, header_flags);\n\t\t\treturn ret;\n\t\tcase HEAD_CRYPT:\n\t\t\tarchive_set_error(&a->archive,\n\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t \"Encryption is not supported\");\n\t\t\treturn ARCHIVE_FATAL;\n\t\tcase HEAD_ENDARC:\n\t\t\trar->main.endarc = 1;\n\n\t\t\t/* After encountering an end of file marker, we need\n\t\t\t * to take into consideration if this archive is\n\t\t\t * continued in another file (i.e. is it part01.rar:\n\t\t\t * is there a part02.rar?) */\n\t\t\tif(rar->main.volume) {\n\t\t\t\t/* In case there is part02.rar, position the\n\t\t\t\t * read pointer in a proper place, so we can\n\t\t\t\t * resume parsing. */\n\t\t\t\tret = scan_for_signature(a);\n\t\t\t\tif(ret == ARCHIVE_FATAL) {\n\t\t\t\t\treturn ARCHIVE_EOF;\n\t\t\t\t} else {\n\t\t\t\t\tif(rar->vol.expected_vol_no ==\n\t\t\t\t\t UINT_MAX) {\n\t\t\t\t\t\tarchive_set_error(&a->archive,\n\t\t\t\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t\t\t\t \"Header error\");\n\t\t\t\t\t\t\treturn ARCHIVE_FATAL;\n\t\t\t\t\t}\n\n\t\t\t\t\trar->vol.expected_vol_no =\n\t\t\t\t\t rar->main.vol_no + 1;\n\t\t\t\t\treturn ARCHIVE_OK;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn ARCHIVE_EOF;\n\t\t\t}\n\t\tcase HEAD_MARK:\n\t\t\treturn ARCHIVE_EOF;\n\t\tdefault:\n\t\t\tif((header_flags & HFL_SKIP_IF_UNKNOWN) == 0) {\n\t\t\t\tarchive_set_error(&a->archive,\n\t\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t\t \"Header type error\");\n\t\t\t\treturn ARCHIVE_FATAL;\n\t\t\t} else {\n\t\t\t\t/* If the block is marked as 'skip if unknown',\n\t\t\t\t * do as the flag says: skip the block\n\t\t\t\t * instead on failing on it. */\n\t\t\t\treturn ARCHIVE_RETRY;\n\t\t\t}\n\t}\n\n#if !defined WIN32\n\t// Not reached.\n\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,\n\t \"Internal unpacker error\");\n\treturn ARCHIVE_FATAL;\n#endif\n}", "project": "libarchive", "hash": 100291370177792498743783572399624603579, "size": 150, "commit_id": "94821008d6eea81e315c5881cdf739202961040a", "message": "RAR5 reader: reject files that declare invalid header flags\n\nOne of the fields in RAR5's base block structure is the size of the\nheader. Some invalid files declare a 0 header size setting, which can\nconfuse the unpacker. Minimum header size for RAR5 base blocks is 7\nbytes (4 bytes for CRC, and 3 bytes for the rest), so block size of 0\nbytes should be rejected at header parsing stage.\n\nThe fix adds an error condition if header size of 0 bytes is detected.\nIn this case, the unpacker will not attempt to unpack the file, as the\nheader is corrupted.\n\nThe commit also adds OSSFuzz #20459 sample to test further regressions\nin this area.", "target": 1, "dataset": "other", "idx": 196781} {"func": "static int process_base_block(struct archive_read* a,\n struct archive_entry* entry)\n{\n\tconst size_t SMALLEST_RAR5_BLOCK_SIZE = 3;\n\n\tstruct rar5* rar = get_context(a);\n\tuint32_t hdr_crc, computed_crc;\n\tsize_t raw_hdr_size = 0, hdr_size_len, hdr_size;\n\tsize_t header_id = 0;\n\tsize_t header_flags = 0;\n\tconst uint8_t* p;\n\tint ret;\n\n\tenum HEADER_TYPE {\n\t\tHEAD_MARK = 0x00, HEAD_MAIN = 0x01, HEAD_FILE = 0x02,\n\t\tHEAD_SERVICE = 0x03, HEAD_CRYPT = 0x04, HEAD_ENDARC = 0x05,\n\t\tHEAD_UNKNOWN = 0xff,\n\t};\n\n\t/* Skip any unprocessed data for this file. */\n\tret = skip_unprocessed_bytes(a);\n\tif(ret != ARCHIVE_OK)\n\t\treturn ret;\n\n\t/* Read the expected CRC32 checksum. */\n\tif(!read_u32(a, &hdr_crc)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\t/* Read header size. */\n\tif(!read_var_sized(a, &raw_hdr_size, &hdr_size_len)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\thdr_size = raw_hdr_size + hdr_size_len;\n\n\t/* Sanity check, maximum header size for RAR5 is 2MB. */\n\tif(hdr_size > (2 * 1024 * 1024)) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t \"Base block header is too large\");\n\n\t\treturn ARCHIVE_FATAL;\n\t}\n\n\t/* Additional sanity checks to weed out invalid files. */\n\tif(raw_hdr_size == 0 || hdr_size_len == 0 ||\n\t\thdr_size < SMALLEST_RAR5_BLOCK_SIZE)\n\t{\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t \"Too small block encountered (%ld bytes)\",\n\t\t raw_hdr_size);\n\n\t\treturn ARCHIVE_FATAL;\n\t}\n\n\t/* Read the whole header data into memory, maximum memory use here is\n\t * 2MB. */\n\tif(!read_ahead(a, hdr_size, &p)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\t/* Verify the CRC32 of the header data. */\n\tcomputed_crc = (uint32_t) crc32(0, p, (int) hdr_size);\n\tif(computed_crc != hdr_crc) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t \"Header CRC error\");\n\n\t\treturn ARCHIVE_FATAL;\n\t}\n\n\t/* If the checksum is OK, we proceed with parsing. */\n\tif(ARCHIVE_OK != consume(a, hdr_size_len)) {\n\t\treturn ARCHIVE_EOF;\n\t}\n\n\tif(!read_var_sized(a, &header_id, NULL))\n\t\treturn ARCHIVE_EOF;\n\n\tif(!read_var_sized(a, &header_flags, NULL))\n\t\treturn ARCHIVE_EOF;\n\n\trar->generic.split_after = (header_flags & HFL_SPLIT_AFTER) > 0;\n\trar->generic.split_before = (header_flags & HFL_SPLIT_BEFORE) > 0;\n\trar->generic.size = (int)hdr_size;\n\trar->generic.last_header_id = (int)header_id;\n\trar->main.endarc = 0;\n\n\t/* Those are possible header ids in RARv5. */\n\tswitch(header_id) {\n\t\tcase HEAD_MAIN:\n\t\t\tret = process_head_main(a, rar, entry, header_flags);\n\n\t\t\t/* Main header doesn't have any files in it, so it's\n\t\t\t * pointless to return to the caller. Retry to next\n\t\t\t * header, which should be HEAD_FILE/HEAD_SERVICE. */\n\t\t\tif(ret == ARCHIVE_OK)\n\t\t\t\treturn ARCHIVE_RETRY;\n\n\t\t\treturn ret;\n\t\tcase HEAD_SERVICE:\n\t\t\tret = process_head_service(a, rar, entry, header_flags);\n\t\t\treturn ret;\n\t\tcase HEAD_FILE:\n\t\t\tret = process_head_file(a, rar, entry, header_flags);\n\t\t\treturn ret;\n\t\tcase HEAD_CRYPT:\n\t\t\tarchive_set_error(&a->archive,\n\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t \"Encryption is not supported\");\n\t\t\treturn ARCHIVE_FATAL;\n\t\tcase HEAD_ENDARC:\n\t\t\trar->main.endarc = 1;\n\n\t\t\t/* After encountering an end of file marker, we need\n\t\t\t * to take into consideration if this archive is\n\t\t\t * continued in another file (i.e. is it part01.rar:\n\t\t\t * is there a part02.rar?) */\n\t\t\tif(rar->main.volume) {\n\t\t\t\t/* In case there is part02.rar, position the\n\t\t\t\t * read pointer in a proper place, so we can\n\t\t\t\t * resume parsing. */\n\t\t\t\tret = scan_for_signature(a);\n\t\t\t\tif(ret == ARCHIVE_FATAL) {\n\t\t\t\t\treturn ARCHIVE_EOF;\n\t\t\t\t} else {\n\t\t\t\t\tif(rar->vol.expected_vol_no ==\n\t\t\t\t\t UINT_MAX) {\n\t\t\t\t\t\tarchive_set_error(&a->archive,\n\t\t\t\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t\t\t\t \"Header error\");\n\t\t\t\t\t\t\treturn ARCHIVE_FATAL;\n\t\t\t\t\t}\n\n\t\t\t\t\trar->vol.expected_vol_no =\n\t\t\t\t\t rar->main.vol_no + 1;\n\t\t\t\t\treturn ARCHIVE_OK;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn ARCHIVE_EOF;\n\t\t\t}\n\t\tcase HEAD_MARK:\n\t\t\treturn ARCHIVE_EOF;\n\t\tdefault:\n\t\t\tif((header_flags & HFL_SKIP_IF_UNKNOWN) == 0) {\n\t\t\t\tarchive_set_error(&a->archive,\n\t\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t\t \"Header type error\");\n\t\t\t\treturn ARCHIVE_FATAL;\n\t\t\t} else {\n\t\t\t\t/* If the block is marked as 'skip if unknown',\n\t\t\t\t * do as the flag says: skip the block\n\t\t\t\t * instead on failing on it. */\n\t\t\t\treturn ARCHIVE_RETRY;\n\t\t\t}\n\t}\n\n#if !defined WIN32\n\t// Not reached.\n\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,\n\t \"Internal unpacker error\");\n\treturn ARCHIVE_FATAL;\n#endif\n}", "project": "libarchive", "hash": 7503224727997862368510784011625765002, "size": 163, "commit_id": "94821008d6eea81e315c5881cdf739202961040a", "message": "RAR5 reader: reject files that declare invalid header flags\n\nOne of the fields in RAR5's base block structure is the size of the\nheader. Some invalid files declare a 0 header size setting, which can\nconfuse the unpacker. Minimum header size for RAR5 base blocks is 7\nbytes (4 bytes for CRC, and 3 bytes for the rest), so block size of 0\nbytes should be rejected at header parsing stage.\n\nThe fix adds an error condition if header size of 0 bytes is detected.\nIn this case, the unpacker will not attempt to unpack the file, as the\nheader is corrupted.\n\nThe commit also adds OSSFuzz #20459 sample to test further regressions\nin this area.", "target": 0, "dataset": "other", "idx": 244730} {"func": " void Compute(OpKernelContext* context) override {\n // Get inputs\n const Tensor& input_tensor = context->input(0);\n const auto input_tensor_flat = input_tensor.flat();\n const Tensor& input_splits = context->input(1);\n const auto input_splits_flat = input_splits.flat();\n\n // Since we limit to a 2-D input (flat_values of rank 1 and a single splits\n // tensor), our output dimension will be 1 with it's size equal to the\n // number of splits (outer dimension or ragged tensor).\n TensorShape output_shape({input_splits.dim_size(0) - 1});\n Tensor* output_tensor;\n OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n &output_tensor));\n auto output_tensor_flat = output_tensor->flat();\n\n // Use a single index over the flattened input values tensor.\n int idx = 0;\n // Loop through our split dimension to create a new string at each split.\n for (int i = 1; i < input_splits_flat.size(); ++i) {\n icu::UnicodeString unicode_string;\n icu::UnicodeStringAppendable appendable_unicode_string(unicode_string);\n for (; idx < input_splits_flat(i); ++idx) {\n int32 code_point = input_tensor_flat(idx);\n // Check for invalid code point\n if (!U_IS_UNICODE_CHAR(code_point)) {\n if (error_options_.error_on_malformatting) {\n context->CtxFailure(errors::InvalidArgument(\n \"Code point is out of range for Unicode, or a noncharacter.\"));\n return;\n } else if (!error_options_.elide_replacement) {\n code_point = error_options_.subst;\n }\n }\n appendable_unicode_string.appendCodePoint(code_point);\n }\n // Encode our string and save in the output.\n tstring result;\n Encode(encoding_, unicode_string, &result);\n output_tensor_flat(i - 1) = std::move(result);\n }\n }", "project": "tensorflow", "hash": 446394916603269042647737762256325608, "size": 42, "commit_id": "51300ba1cc2f487aefec6e6631fef03b0e08b298", "message": "Fix heap buffer overflow in tf.raw_ops.UnicodeEncode.\n\nPiperOrigin-RevId: 371717714\nChange-Id: If33443b28f158e58078f1268f6b92f2728d219e0", "target": 1, "dataset": "other", "idx": 196791} {"func": " void Compute(OpKernelContext* context) override {\n // Get inputs\n const Tensor& input_tensor = context->input(0);\n const auto input_tensor_flat = input_tensor.flat();\n const Tensor& input_splits = context->input(1);\n const auto input_splits_flat = input_splits.flat();\n\n // Operation will treat first argument in input_splits as if it were zero\n // regardless of its actual value since splits should begin with zero and\n // end with the length of the input values vector.\n OP_REQUIRES(\n context, input_splits_flat(0) == 0,\n errors::InvalidArgument(\"First value in input_splits must be zero.\"));\n OP_REQUIRES(context,\n input_splits_flat(input_splits_flat.size() - 1) ==\n input_tensor_flat.size(),\n errors::InvalidArgument(\"Last value in input_splits must be \"\n \"equal to length of input_tensor.\"));\n // Since we limit to a 2-D input (flat_values of rank 1 and a single splits\n // tensor), our output dimension will be 1 with it's size equal to the\n // number of splits (outer dimension or ragged tensor).\n TensorShape output_shape({input_splits.dim_size(0) - 1});\n Tensor* output_tensor;\n OP_REQUIRES_OK(context, context->allocate_output(\"output\", output_shape,\n &output_tensor));\n auto output_tensor_flat = output_tensor->flat();\n\n // Use a single index over the flattened input values tensor.\n int idx = 0;\n // Loop through our split dimension to create a new string at each split.\n for (int i = 1; i < input_splits_flat.size(); ++i) {\n icu::UnicodeString unicode_string;\n icu::UnicodeStringAppendable appendable_unicode_string(unicode_string);\n OP_REQUIRES(\n context, input_splits_flat(i - 1) <= input_splits_flat(i),\n errors::InvalidArgument(\n \"Values in input_splits must be equal or in ascending order.\"));\n OP_REQUIRES(\n context, input_splits_flat(i) <= input_tensor_flat.size(),\n errors::InvalidArgument(\"Values in input_splits must be less than or \"\n \"equal to input_tensor length.\"));\n for (; idx < input_splits_flat(i); ++idx) {\n int32 code_point = input_tensor_flat(idx);\n // Check for invalid code point\n if (!U_IS_UNICODE_CHAR(code_point)) {\n if (error_options_.error_on_malformatting) {\n context->CtxFailure(errors::InvalidArgument(\n \"Code point is out of range for Unicode, or a noncharacter.\"));\n return;\n } else if (!error_options_.elide_replacement) {\n code_point = error_options_.subst;\n }\n }\n appendable_unicode_string.appendCodePoint(code_point);\n }\n // Encode our string and save in the output.\n tstring result;\n Encode(encoding_, unicode_string, &result);\n output_tensor_flat(i - 1) = std::move(result);\n }\n }", "project": "tensorflow", "hash": 337772719006525180924147964884184973162, "size": 61, "commit_id": "51300ba1cc2f487aefec6e6631fef03b0e08b298", "message": "Fix heap buffer overflow in tf.raw_ops.UnicodeEncode.\n\nPiperOrigin-RevId: 371717714\nChange-Id: If33443b28f158e58078f1268f6b92f2728d219e0", "target": 0, "dataset": "other", "idx": 245150} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n Tensor input_min_tensor;\n Tensor input_max_tensor;\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n if (range_given_) {\n input_min_tensor = ctx->input(1);\n input_max_tensor = ctx->input(2);\n if (axis_ == -1) {\n auto min_val = input_min_tensor.scalar()();\n auto max_val = input_max_tensor.scalar()();\n OP_REQUIRES(ctx, min_val <= max_val,\n errors::InvalidArgument(\"Invalid range: input_min \",\n min_val, \" > input_max \", max_val));\n } else {\n OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_min_tensor has incorrect size, was \",\n input_min_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_min_tensor.shape()));\n OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_max_tensor has incorrect size, was \",\n input_max_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_max_tensor.shape()));\n }\n } else {\n auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth});\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value,\n range_shape, &input_min_tensor));\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value,\n range_shape, &input_max_tensor));\n }\n\n if (axis_ == -1) {\n functor::QuantizeAndDequantizeOneScaleFunctor f;\n f(ctx->eigen_device(), input.flat(), signed_input_, num_bits_,\n range_given_, &input_min_tensor, &input_max_tensor, round_mode_,\n narrow_range_, output->flat());\n } else {\n functor::QuantizeAndDequantizePerChannelFunctor f;\n f(ctx->eigen_device(),\n input.template flat_inner_outer_dims(axis_ - 1), signed_input_,\n num_bits_, range_given_, &input_min_tensor, &input_max_tensor,\n round_mode_, narrow_range_,\n output->template flat_inner_outer_dims(axis_ - 1));\n }\n }", "project": "tensorflow", "hash": 293324771546003032170952415326365543811, "size": 52, "commit_id": "eccb7ec454e6617738554a255d77f08e60ee0808", "message": "Prevent segfault in `quantize_and_dequantize`\n\nFixes #42105.\n\nIf `tf.quantization.quantize_and_dequantize` is called with `axis` argument pointing to outside of the input tensor, we obtain a `CHECK` fail which then aborts the application/interpreter. This change adds a condition check and returns a `Status` instead of crashing.\n\nPiperOrigin-RevId: 337972243\nChange-Id: I71ec32c00a87266e364fb017f0ad5dfd3e23542f", "target": 1, "dataset": "other", "idx": 196800} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n\n // One global scale.\n Tensor input_min_tensor(DataTypeToEnum::value, TensorShape());\n Tensor input_max_tensor(DataTypeToEnum::value, TensorShape());\n // Initialize the tensors with the values in the Attrs.\n input_min_tensor.template scalar()() = static_cast(input_min_);\n input_max_tensor.template scalar()() = static_cast(input_max_);\n\n functor::QuantizeAndDequantizeOneScaleFunctor functor;\n functor(ctx->eigen_device(), input.flat(), signed_input_,\n num_bits_, range_given_, &input_min_tensor, &input_max_tensor,\n ROUND_HALF_TO_EVEN, /*narrow_range=*/false, output->flat());\n }", "project": "tensorflow", "hash": 34025787901370453152773493086761626349, "size": 18, "commit_id": "eccb7ec454e6617738554a255d77f08e60ee0808", "message": "Prevent segfault in `quantize_and_dequantize`\n\nFixes #42105.\n\nIf `tf.quantization.quantize_and_dequantize` is called with `axis` argument pointing to outside of the input tensor, we obtain a `CHECK` fail which then aborts the application/interpreter. This change adds a condition check and returns a `Status` instead of crashing.\n\nPiperOrigin-RevId: 337972243\nChange-Id: I71ec32c00a87266e364fb017f0ad5dfd3e23542f", "target": 0, "dataset": "other", "idx": 245427} {"func": " static void launch(OpKernelContext* context, const PoolParameters& params,\n const Tensor& grad_in, const Tensor& argmax,\n Tensor* grad_out, const bool include_batch_in_index) {\n const DeviceBase::CpuWorkerThreads& worker_threads =\n *(context->device()->tensorflow_cpu_worker_threads());\n\n auto shard = [&grad_in, &argmax, &grad_out, include_batch_in_index](\n int64 start, int64 limit) {\n const int64 batch_size =\n GetTensorDim(grad_out->shape(), FORMAT_NHWC, 'N');\n const int64 output_size_per_batch = grad_out->NumElements() / batch_size;\n const int64 input_size_per_batch = grad_in.NumElements() / batch_size;\n\n {\n auto grad_out_flat = grad_out->flat();\n auto argmax_flat = argmax.flat();\n auto grad_in_flat = grad_in.flat();\n\n const int64 output_start = start * output_size_per_batch;\n const int64 output_end = limit * output_size_per_batch;\n EigenMatrixMap inputShard(grad_out_flat.data() + output_start, 1,\n output_end - output_start);\n inputShard.setConstant(T(0));\n\n const int input_start = start * input_size_per_batch;\n const int input_end = limit * input_size_per_batch;\n for (int64 index = input_start; index < input_end; index++) {\n int64 grad_out_index = argmax_flat(index);\n if (!include_batch_in_index) {\n const int64 cur_batch = index / input_size_per_batch;\n grad_out_index += cur_batch * output_size_per_batch;\n }\n CHECK(grad_out_index >= output_start && grad_out_index < output_end)\n << \"Invalid output gradient index: \" << grad_out_index << \", \"\n << output_start << \", \" << output_end;\n grad_out_flat(grad_out_index) += grad_in_flat(index);\n }\n }\n };\n\n const int64 batch_size = GetTensorDim(grad_out->shape(), FORMAT_NHWC, 'N');\n const int64 shard_cost = grad_out->NumElements() / batch_size;\n Shard(worker_threads.num_threads, worker_threads.workers, batch_size,\n shard_cost, shard);\n }", "project": "tensorflow", "hash": 251209108610120812809202532236756676128, "size": 45, "commit_id": "dcd7867de0fea4b72a2b34bd41eb74548dc23886", "message": "Fix heap buffer overflow\n\nPiperOrigin-RevId: 372132844\nChange-Id: Idef9895efaf145f2b1c23d31983601ec980cd5e4", "target": 1, "dataset": "other", "idx": 196802} {"func": " static void launch(OpKernelContext* context, const PoolParameters& params,\n const Tensor& grad_in, const Tensor& argmax,\n Tensor* grad_out, const bool include_batch_in_index) {\n const DeviceBase::CpuWorkerThreads& worker_threads =\n *(context->device()->tensorflow_cpu_worker_threads());\n\n auto shard = [&grad_in, &argmax, &grad_out, include_batch_in_index](\n int64 start, int64 limit) {\n const int64 batch_size =\n GetTensorDim(grad_out->shape(), FORMAT_NHWC, 'N');\n const int64 output_size_per_batch = grad_out->NumElements() / batch_size;\n const int64 input_size_per_batch = grad_in.NumElements() / batch_size;\n\n {\n auto grad_out_flat = grad_out->flat();\n auto argmax_flat = argmax.flat();\n auto grad_in_flat = grad_in.flat();\n\n const int64 output_start = start * output_size_per_batch;\n const int64 output_end = limit * output_size_per_batch;\n EigenMatrixMap inputShard(grad_out_flat.data() + output_start, 1,\n output_end - output_start);\n inputShard.setConstant(T(0));\n\n const int input_start = start * input_size_per_batch;\n const int input_end = limit * input_size_per_batch;\n for (int64 index = input_start; index < input_end; index++) {\n if (index >= argmax.NumElements()) {\n break;\n }\n int64 grad_out_index = argmax_flat(index);\n if (!include_batch_in_index) {\n const int64 cur_batch = index / input_size_per_batch;\n grad_out_index += cur_batch * output_size_per_batch;\n }\n CHECK(grad_out_index >= output_start && grad_out_index < output_end)\n << \"Invalid output gradient index: \" << grad_out_index << \", \"\n << output_start << \", \" << output_end;\n grad_out_flat(grad_out_index) += grad_in_flat(index);\n }\n }\n };\n\n const int64 batch_size = GetTensorDim(grad_out->shape(), FORMAT_NHWC, 'N');\n const int64 shard_cost = grad_out->NumElements() / batch_size;\n Shard(worker_threads.num_threads, worker_threads.workers, batch_size,\n shard_cost, shard);\n }", "project": "tensorflow", "hash": 118757592964186460200476445367138932686, "size": 48, "commit_id": "dcd7867de0fea4b72a2b34bd41eb74548dc23886", "message": "Fix heap buffer overflow\n\nPiperOrigin-RevId: 372132844\nChange-Id: Idef9895efaf145f2b1c23d31983601ec980cd5e4", "target": 0, "dataset": "other", "idx": 245438} {"func": "void UncompressElementOp::Compute(OpKernelContext* ctx) {\n Tensor tensor = ctx->input(0);\n const Variant& variant = tensor.scalar()();\n const CompressedElement* compressed = variant.get();\n\n std::vector components;\n OP_REQUIRES_OK(ctx, UncompressElement(*compressed, &components));\n OP_REQUIRES(ctx, components.size() == output_types_.size(),\n errors::FailedPrecondition(\"Expected \", output_types_.size(),\n \" outputs from uncompress, but got \",\n components.size()));\n for (int i = 0; i < components.size(); ++i) {\n OP_REQUIRES(\n ctx, components[i].dtype() == output_types_[i],\n errors::FailedPrecondition(\"Expected a tensor of type \",\n DataTypeString(output_types_[i]),\n \" but got a tensor of type \",\n DataTypeString(components[i].dtype())));\n ctx->set_output(i, components[i]);\n }\n}", "project": "tensorflow", "hash": 123137112005180251715591720813780418586, "size": 21, "commit_id": "7bdf50bb4f5c54a4997c379092888546c97c3ebd", "message": "Ensure non-empty compressed input in tf.raw_ops.UncompressElement\n\nPiperOrigin-RevId: 383955815\nChange-Id: I072a84fd02738dd2f51b3f42836ed80067dba4a8", "target": 1, "dataset": "other", "idx": 196811} {"func": "void UncompressElementOp::Compute(OpKernelContext* ctx) {\n Tensor tensor = ctx->input(0);\n const Variant& variant = tensor.scalar()();\n const CompressedElement* compressed = variant.get();\n OP_REQUIRES(\n ctx, compressed != nullptr,\n errors::InvalidArgument(\n \"Input does not contain a compressed element. Instead got tensor \",\n tensor.DebugString()));\n\n std::vector components;\n OP_REQUIRES_OK(ctx, UncompressElement(*compressed, &components));\n OP_REQUIRES(ctx, components.size() == output_types_.size(),\n errors::FailedPrecondition(\"Expected \", output_types_.size(),\n \" outputs from uncompress, but got \",\n components.size()));\n for (int i = 0; i < components.size(); ++i) {\n OP_REQUIRES(\n ctx, components[i].dtype() == output_types_[i],\n errors::FailedPrecondition(\"Expected a tensor of type \",\n DataTypeString(output_types_[i]),\n \" but got a tensor of type \",\n DataTypeString(components[i].dtype())));\n ctx->set_output(i, components[i]);\n }\n}", "project": "tensorflow", "hash": 63230142722208908504743697445986676990, "size": 26, "commit_id": "7bdf50bb4f5c54a4997c379092888546c97c3ebd", "message": "Ensure non-empty compressed input in tf.raw_ops.UncompressElement\n\nPiperOrigin-RevId: 383955815\nChange-Id: I072a84fd02738dd2f51b3f42836ed80067dba4a8", "target": 0, "dataset": "other", "idx": 245642} {"func": "PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n MessageWriter *input,\n MessageReader *output) {\n int ret;\n\n UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();\n\n SgxParams *const sgx_params =\n reinterpret_cast(untrusted_cache->Malloc(sizeof(SgxParams)));\n Cleanup clean_up(\n [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });\n sgx_params->input_size = 0;\n sgx_params->input = nullptr;\n if (input) {\n sgx_params->input_size = input->MessageSize();\n if (sgx_params->input_size > 0) {\n // Allocate and copy data to |input_buffer|.\n sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);\n input->Serialize(const_cast(sgx_params->input));\n }\n }\n sgx_params->output_size = 0;\n sgx_params->output = nullptr;\n CHECK_OCALL(\n ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n if (sgx_params->input) {\n untrusted_cache->Free(const_cast(sgx_params->input));\n }\n if (sgx_params->output) {\n // For the results obtained in |output_buffer|, copy them to |output|\n // before freeing the buffer.\n output->Deserialize(sgx_params->output, sgx_params->output_size);\n TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n }\n return PrimitiveStatus::OkStatus();\n}", "project": "asylo", "hash": 261964073185143736765939860190443192174, "size": 36, "commit_id": "83036fd841d33baa7e039f842d131aa7881fdcc2", "message": "Verify UntrustedCall output is outside enclave\n\nPiperOrigin-RevId: 333781703\nChange-Id: I9df55c04dc8b04f4bf0bda8e68cc32bca81b933a", "target": 1, "dataset": "other", "idx": 196831} {"func": "PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n MessageWriter *input,\n MessageReader *output) {\n int ret;\n\n UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();\n\n SgxParams *const sgx_params =\n reinterpret_cast(untrusted_cache->Malloc(sizeof(SgxParams)));\n Cleanup clean_up(\n [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });\n sgx_params->input_size = 0;\n sgx_params->input = nullptr;\n if (input) {\n sgx_params->input_size = input->MessageSize();\n if (sgx_params->input_size > 0) {\n // Allocate and copy data to |input_buffer|.\n sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);\n input->Serialize(const_cast(sgx_params->input));\n }\n }\n sgx_params->output_size = 0;\n sgx_params->output = nullptr;\n CHECK_OCALL(\n ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n if (sgx_params->input) {\n untrusted_cache->Free(const_cast(sgx_params->input));\n }\n if (!TrustedPrimitives::IsOutsideEnclave(sgx_params->output,\n sgx_params->output_size)) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param output should be in untrusted memory\");\n }\n if (sgx_params->output) {\n // For the results obtained in |output_buffer|, copy them to |output|\n // before freeing the buffer.\n output->Deserialize(sgx_params->output, sgx_params->output_size);\n TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n }\n return PrimitiveStatus::OkStatus();\n}", "project": "asylo", "hash": 97744345373278828596253695008510711317, "size": 41, "commit_id": "83036fd841d33baa7e039f842d131aa7881fdcc2", "message": "Verify UntrustedCall output is outside enclave\n\nPiperOrigin-RevId: 333781703\nChange-Id: I9df55c04dc8b04f4bf0bda8e68cc32bca81b933a", "target": 0, "dataset": "other", "idx": 246050} {"func": "static int multiSelect(\n Parse *pParse, /* Parsing context */\n Select *p, /* The right-most of SELECTs to be coded */\n SelectDest *pDest /* What to do with query results */\n){\n int rc = SQLITE_OK; /* Success code from a subroutine */\n Select *pPrior; /* Another SELECT immediately to our left */\n Vdbe *v; /* Generate code to this VDBE */\n SelectDest dest; /* Alternative data destination */\n Select *pDelete = 0; /* Chain of simple selects to delete */\n sqlite3 *db; /* Database connection */\n\n /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only\n ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.\n */\n assert( p && p->pPrior ); /* Calling function guarantees this much */\n assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );\n assert( p->selFlags & SF_Compound );\n db = pParse->db;\n pPrior = p->pPrior;\n dest = *pDest;\n if( pPrior->pOrderBy || pPrior->pLimit ){\n sqlite3ErrorMsg(pParse,\"%s clause should come after %s not before\",\n pPrior->pOrderBy!=0 ? \"ORDER BY\" : \"LIMIT\", selectOpName(p->op));\n rc = 1;\n goto multi_select_end;\n }\n\n v = sqlite3GetVdbe(pParse);\n assert( v!=0 ); /* The VDBE already created by calling function */\n\n /* Create the destination temporary table if necessary\n */\n if( dest.eDest==SRT_EphemTab ){\n assert( p->pEList );\n sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);\n dest.eDest = SRT_Table;\n }\n\n /* Special handling for a compound-select that originates as a VALUES clause.\n */\n if( p->selFlags & SF_MultiValue ){\n rc = multiSelectValues(pParse, p, &dest);\n if( rc>=0 ) goto multi_select_end;\n rc = SQLITE_OK;\n }\n\n /* Make sure all SELECTs in the statement have the same number of elements\n ** in their result sets.\n */\n assert( p->pEList && pPrior->pEList );\n assert( p->pEList->nExpr==pPrior->pEList->nExpr );\n\n#ifndef SQLITE_OMIT_CTE\n if( p->selFlags & SF_Recursive ){\n generateWithRecursiveQuery(pParse, p, &dest);\n }else\n#endif\n\n /* Compound SELECTs that have an ORDER BY clause are handled separately.\n */\n if( p->pOrderBy ){\n return multiSelectOrderBy(pParse, p, pDest);\n }else{\n\n#ifndef SQLITE_OMIT_EXPLAIN\n if( pPrior->pPrior==0 ){\n ExplainQueryPlan((pParse, 1, \"COMPOUND QUERY\"));\n ExplainQueryPlan((pParse, 1, \"LEFT-MOST SUBQUERY\"));\n }\n#endif\n\n /* Generate code for the left and right SELECT statements.\n */\n switch( p->op ){\n case TK_ALL: {\n int addr = 0;\n int nLimit;\n assert( !pPrior->pLimit );\n pPrior->iLimit = p->iLimit;\n pPrior->iOffset = p->iOffset;\n pPrior->pLimit = p->pLimit;\n rc = sqlite3Select(pParse, pPrior, &dest);\n p->pLimit = 0;\n if( rc ){\n goto multi_select_end;\n }\n p->pPrior = 0;\n p->iLimit = pPrior->iLimit;\n p->iOffset = pPrior->iOffset;\n if( p->iLimit ){\n addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);\n VdbeComment((v, \"Jump ahead if LIMIT reached\"));\n if( p->iOffset ){\n sqlite3VdbeAddOp3(v, OP_OffsetLimit,\n p->iLimit, p->iOffset+1, p->iOffset);\n }\n }\n ExplainQueryPlan((pParse, 1, \"UNION ALL\"));\n rc = sqlite3Select(pParse, p, &dest);\n testcase( rc!=SQLITE_OK );\n pDelete = p->pPrior;\n p->pPrior = pPrior;\n p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);\n if( pPrior->pLimit\n && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)\n && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) \n ){\n p->nSelectRow = sqlite3LogEst((u64)nLimit);\n }\n if( addr ){\n sqlite3VdbeJumpHere(v, addr);\n }\n break;\n }\n case TK_EXCEPT:\n case TK_UNION: {\n int unionTab; /* Cursor number of the temp table holding result */\n u8 op = 0; /* One of the SRT_ operations to apply to self */\n int priorOp; /* The SRT_ operation to apply to prior selects */\n Expr *pLimit; /* Saved values of p->nLimit */\n int addr;\n SelectDest uniondest;\n \n testcase( p->op==TK_EXCEPT );\n testcase( p->op==TK_UNION );\n priorOp = SRT_Union;\n if( dest.eDest==priorOp ){\n /* We can reuse a temporary table generated by a SELECT to our\n ** right.\n */\n assert( p->pLimit==0 ); /* Not allowed on leftward elements */\n unionTab = dest.iSDParm;\n }else{\n /* We will need to create our own temporary table to hold the\n ** intermediate results.\n */\n unionTab = pParse->nTab++;\n assert( p->pOrderBy==0 );\n addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);\n assert( p->addrOpenEphm[0] == -1 );\n p->addrOpenEphm[0] = addr;\n findRightmost(p)->selFlags |= SF_UsesEphemeral;\n assert( p->pEList );\n }\n \n /* Code the SELECT statements to our left\n */\n assert( !pPrior->pOrderBy );\n sqlite3SelectDestInit(&uniondest, priorOp, unionTab);\n rc = sqlite3Select(pParse, pPrior, &uniondest);\n if( rc ){\n goto multi_select_end;\n }\n \n /* Code the current SELECT statement\n */\n if( p->op==TK_EXCEPT ){\n op = SRT_Except;\n }else{\n assert( p->op==TK_UNION );\n op = SRT_Union;\n }\n p->pPrior = 0;\n pLimit = p->pLimit;\n p->pLimit = 0;\n uniondest.eDest = op;\n ExplainQueryPlan((pParse, 1, \"%s USING TEMP B-TREE\",\n selectOpName(p->op)));\n rc = sqlite3Select(pParse, p, &uniondest);\n testcase( rc!=SQLITE_OK );\n /* Query flattening in sqlite3Select() might refill p->pOrderBy.\n ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */\n sqlite3ExprListDelete(db, p->pOrderBy);\n pDelete = p->pPrior;\n p->pPrior = pPrior;\n p->pOrderBy = 0;\n if( p->op==TK_UNION ){\n p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);\n }\n sqlite3ExprDelete(db, p->pLimit);\n p->pLimit = pLimit;\n p->iLimit = 0;\n p->iOffset = 0;\n \n /* Convert the data in the temporary table into whatever form\n ** it is that we currently need.\n */\n assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );\n assert( p->pEList || db->mallocFailed );\n if( dest.eDest!=priorOp && db->mallocFailed==0 ){\n int iCont, iBreak, iStart;\n iBreak = sqlite3VdbeMakeLabel(pParse);\n iCont = sqlite3VdbeMakeLabel(pParse);\n computeLimitRegisters(pParse, p, iBreak);\n sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);\n iStart = sqlite3VdbeCurrentAddr(v);\n selectInnerLoop(pParse, p, unionTab,\n 0, 0, &dest, iCont, iBreak);\n sqlite3VdbeResolveLabel(v, iCont);\n sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);\n sqlite3VdbeResolveLabel(v, iBreak);\n sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);\n }\n break;\n }\n default: assert( p->op==TK_INTERSECT ); {\n int tab1, tab2;\n int iCont, iBreak, iStart;\n Expr *pLimit;\n int addr;\n SelectDest intersectdest;\n int r1;\n \n /* INTERSECT is different from the others since it requires\n ** two temporary tables. Hence it has its own case. Begin\n ** by allocating the tables we will need.\n */\n tab1 = pParse->nTab++;\n tab2 = pParse->nTab++;\n assert( p->pOrderBy==0 );\n \n addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);\n assert( p->addrOpenEphm[0] == -1 );\n p->addrOpenEphm[0] = addr;\n findRightmost(p)->selFlags |= SF_UsesEphemeral;\n assert( p->pEList );\n \n /* Code the SELECTs to our left into temporary table \"tab1\".\n */\n sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);\n rc = sqlite3Select(pParse, pPrior, &intersectdest);\n if( rc ){\n goto multi_select_end;\n }\n \n /* Code the current SELECT into temporary table \"tab2\"\n */\n addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);\n assert( p->addrOpenEphm[1] == -1 );\n p->addrOpenEphm[1] = addr;\n p->pPrior = 0;\n pLimit = p->pLimit;\n p->pLimit = 0;\n intersectdest.iSDParm = tab2;\n ExplainQueryPlan((pParse, 1, \"%s USING TEMP B-TREE\",\n selectOpName(p->op)));\n rc = sqlite3Select(pParse, p, &intersectdest);\n testcase( rc!=SQLITE_OK );\n pDelete = p->pPrior;\n p->pPrior = pPrior;\n if( p->nSelectRow>pPrior->nSelectRow ){\n p->nSelectRow = pPrior->nSelectRow;\n }\n sqlite3ExprDelete(db, p->pLimit);\n p->pLimit = pLimit;\n \n /* Generate code to take the intersection of the two temporary\n ** tables.\n */\n assert( p->pEList );\n iBreak = sqlite3VdbeMakeLabel(pParse);\n iCont = sqlite3VdbeMakeLabel(pParse);\n computeLimitRegisters(pParse, p, iBreak);\n sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);\n r1 = sqlite3GetTempReg(pParse);\n iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);\n sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);\n VdbeCoverage(v);\n sqlite3ReleaseTempReg(pParse, r1);\n selectInnerLoop(pParse, p, tab1,\n 0, 0, &dest, iCont, iBreak);\n sqlite3VdbeResolveLabel(v, iCont);\n sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);\n sqlite3VdbeResolveLabel(v, iBreak);\n sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);\n sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);\n break;\n }\n }\n \n #ifndef SQLITE_OMIT_EXPLAIN\n if( p->pNext==0 ){\n ExplainQueryPlanPop(pParse);\n }\n #endif\n }\n if( pParse->nErr ) goto multi_select_end;\n \n /* Compute collating sequences used by \n ** temporary tables needed to implement the compound select.\n ** Attach the KeyInfo structure to all temporary tables.\n **\n ** This section is run by the right-most SELECT statement only.\n ** SELECT statements to the left always skip this part. The right-most\n ** SELECT might also skip this part if it has no ORDER BY clause and\n ** no temp tables are required.\n */\n if( p->selFlags & SF_UsesEphemeral ){\n int i; /* Loop counter */\n KeyInfo *pKeyInfo; /* Collating sequence for the result set */\n Select *pLoop; /* For looping through SELECT statements */\n CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */\n int nCol; /* Number of columns in result set */\n\n assert( p->pNext==0 );\n nCol = p->pEList->nExpr;\n pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);\n if( !pKeyInfo ){\n rc = SQLITE_NOMEM_BKPT;\n goto multi_select_end;\n }\n for(i=0, apColl=pKeyInfo->aColl; ipDfltColl;\n }\n }\n\n for(pLoop=p; pLoop; pLoop=pLoop->pPrior){\n for(i=0; i<2; i++){\n int addr = pLoop->addrOpenEphm[i];\n if( addr<0 ){\n /* If [0] is unused then [1] is also unused. So we can\n ** always safely abort as soon as the first unused slot is found */\n assert( pLoop->addrOpenEphm[1]<0 );\n break;\n }\n sqlite3VdbeChangeP2(v, addr, nCol);\n sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),\n P4_KEYINFO);\n pLoop->addrOpenEphm[i] = -1;\n }\n }\n sqlite3KeyInfoUnref(pKeyInfo);\n }\n\nmulti_select_end:\n pDest->iSdst = dest.iSdst;\n pDest->nSdst = dest.nSdst;\n sqlite3SelectDelete(db, pDelete);\n return rc;\n}", "project": "sqlite", "hash": 200791527881523564389362957209573506757, "size": 343, "commit_id": "5f69512404cd2e5153ddf90ea277fbba6dd58ab7", "message": "Early-out on the INTERSECT query processing following an error.\n\nFossilOrigin-Name: a67cf5b7d37d5b1484be32092635faafd8f76e5881898cd9435517c4b287d663", "target": 1, "dataset": "other", "idx": 196833} {"func": "static int multiSelect(\n Parse *pParse, /* Parsing context */\n Select *p, /* The right-most of SELECTs to be coded */\n SelectDest *pDest /* What to do with query results */\n){\n int rc = SQLITE_OK; /* Success code from a subroutine */\n Select *pPrior; /* Another SELECT immediately to our left */\n Vdbe *v; /* Generate code to this VDBE */\n SelectDest dest; /* Alternative data destination */\n Select *pDelete = 0; /* Chain of simple selects to delete */\n sqlite3 *db; /* Database connection */\n\n /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only\n ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.\n */\n assert( p && p->pPrior ); /* Calling function guarantees this much */\n assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );\n assert( p->selFlags & SF_Compound );\n db = pParse->db;\n pPrior = p->pPrior;\n dest = *pDest;\n if( pPrior->pOrderBy || pPrior->pLimit ){\n sqlite3ErrorMsg(pParse,\"%s clause should come after %s not before\",\n pPrior->pOrderBy!=0 ? \"ORDER BY\" : \"LIMIT\", selectOpName(p->op));\n rc = 1;\n goto multi_select_end;\n }\n\n v = sqlite3GetVdbe(pParse);\n assert( v!=0 ); /* The VDBE already created by calling function */\n\n /* Create the destination temporary table if necessary\n */\n if( dest.eDest==SRT_EphemTab ){\n assert( p->pEList );\n sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);\n dest.eDest = SRT_Table;\n }\n\n /* Special handling for a compound-select that originates as a VALUES clause.\n */\n if( p->selFlags & SF_MultiValue ){\n rc = multiSelectValues(pParse, p, &dest);\n if( rc>=0 ) goto multi_select_end;\n rc = SQLITE_OK;\n }\n\n /* Make sure all SELECTs in the statement have the same number of elements\n ** in their result sets.\n */\n assert( p->pEList && pPrior->pEList );\n assert( p->pEList->nExpr==pPrior->pEList->nExpr );\n\n#ifndef SQLITE_OMIT_CTE\n if( p->selFlags & SF_Recursive ){\n generateWithRecursiveQuery(pParse, p, &dest);\n }else\n#endif\n\n /* Compound SELECTs that have an ORDER BY clause are handled separately.\n */\n if( p->pOrderBy ){\n return multiSelectOrderBy(pParse, p, pDest);\n }else{\n\n#ifndef SQLITE_OMIT_EXPLAIN\n if( pPrior->pPrior==0 ){\n ExplainQueryPlan((pParse, 1, \"COMPOUND QUERY\"));\n ExplainQueryPlan((pParse, 1, \"LEFT-MOST SUBQUERY\"));\n }\n#endif\n\n /* Generate code for the left and right SELECT statements.\n */\n switch( p->op ){\n case TK_ALL: {\n int addr = 0;\n int nLimit;\n assert( !pPrior->pLimit );\n pPrior->iLimit = p->iLimit;\n pPrior->iOffset = p->iOffset;\n pPrior->pLimit = p->pLimit;\n rc = sqlite3Select(pParse, pPrior, &dest);\n p->pLimit = 0;\n if( rc ){\n goto multi_select_end;\n }\n p->pPrior = 0;\n p->iLimit = pPrior->iLimit;\n p->iOffset = pPrior->iOffset;\n if( p->iLimit ){\n addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);\n VdbeComment((v, \"Jump ahead if LIMIT reached\"));\n if( p->iOffset ){\n sqlite3VdbeAddOp3(v, OP_OffsetLimit,\n p->iLimit, p->iOffset+1, p->iOffset);\n }\n }\n ExplainQueryPlan((pParse, 1, \"UNION ALL\"));\n rc = sqlite3Select(pParse, p, &dest);\n testcase( rc!=SQLITE_OK );\n pDelete = p->pPrior;\n p->pPrior = pPrior;\n p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);\n if( pPrior->pLimit\n && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)\n && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) \n ){\n p->nSelectRow = sqlite3LogEst((u64)nLimit);\n }\n if( addr ){\n sqlite3VdbeJumpHere(v, addr);\n }\n break;\n }\n case TK_EXCEPT:\n case TK_UNION: {\n int unionTab; /* Cursor number of the temp table holding result */\n u8 op = 0; /* One of the SRT_ operations to apply to self */\n int priorOp; /* The SRT_ operation to apply to prior selects */\n Expr *pLimit; /* Saved values of p->nLimit */\n int addr;\n SelectDest uniondest;\n \n testcase( p->op==TK_EXCEPT );\n testcase( p->op==TK_UNION );\n priorOp = SRT_Union;\n if( dest.eDest==priorOp ){\n /* We can reuse a temporary table generated by a SELECT to our\n ** right.\n */\n assert( p->pLimit==0 ); /* Not allowed on leftward elements */\n unionTab = dest.iSDParm;\n }else{\n /* We will need to create our own temporary table to hold the\n ** intermediate results.\n */\n unionTab = pParse->nTab++;\n assert( p->pOrderBy==0 );\n addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);\n assert( p->addrOpenEphm[0] == -1 );\n p->addrOpenEphm[0] = addr;\n findRightmost(p)->selFlags |= SF_UsesEphemeral;\n assert( p->pEList );\n }\n \n /* Code the SELECT statements to our left\n */\n assert( !pPrior->pOrderBy );\n sqlite3SelectDestInit(&uniondest, priorOp, unionTab);\n rc = sqlite3Select(pParse, pPrior, &uniondest);\n if( rc ){\n goto multi_select_end;\n }\n \n /* Code the current SELECT statement\n */\n if( p->op==TK_EXCEPT ){\n op = SRT_Except;\n }else{\n assert( p->op==TK_UNION );\n op = SRT_Union;\n }\n p->pPrior = 0;\n pLimit = p->pLimit;\n p->pLimit = 0;\n uniondest.eDest = op;\n ExplainQueryPlan((pParse, 1, \"%s USING TEMP B-TREE\",\n selectOpName(p->op)));\n rc = sqlite3Select(pParse, p, &uniondest);\n testcase( rc!=SQLITE_OK );\n /* Query flattening in sqlite3Select() might refill p->pOrderBy.\n ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */\n sqlite3ExprListDelete(db, p->pOrderBy);\n pDelete = p->pPrior;\n p->pPrior = pPrior;\n p->pOrderBy = 0;\n if( p->op==TK_UNION ){\n p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);\n }\n sqlite3ExprDelete(db, p->pLimit);\n p->pLimit = pLimit;\n p->iLimit = 0;\n p->iOffset = 0;\n \n /* Convert the data in the temporary table into whatever form\n ** it is that we currently need.\n */\n assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );\n assert( p->pEList || db->mallocFailed );\n if( dest.eDest!=priorOp && db->mallocFailed==0 ){\n int iCont, iBreak, iStart;\n iBreak = sqlite3VdbeMakeLabel(pParse);\n iCont = sqlite3VdbeMakeLabel(pParse);\n computeLimitRegisters(pParse, p, iBreak);\n sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);\n iStart = sqlite3VdbeCurrentAddr(v);\n selectInnerLoop(pParse, p, unionTab,\n 0, 0, &dest, iCont, iBreak);\n sqlite3VdbeResolveLabel(v, iCont);\n sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);\n sqlite3VdbeResolveLabel(v, iBreak);\n sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);\n }\n break;\n }\n default: assert( p->op==TK_INTERSECT ); {\n int tab1, tab2;\n int iCont, iBreak, iStart;\n Expr *pLimit;\n int addr;\n SelectDest intersectdest;\n int r1;\n \n /* INTERSECT is different from the others since it requires\n ** two temporary tables. Hence it has its own case. Begin\n ** by allocating the tables we will need.\n */\n tab1 = pParse->nTab++;\n tab2 = pParse->nTab++;\n assert( p->pOrderBy==0 );\n \n addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);\n assert( p->addrOpenEphm[0] == -1 );\n p->addrOpenEphm[0] = addr;\n findRightmost(p)->selFlags |= SF_UsesEphemeral;\n assert( p->pEList );\n \n /* Code the SELECTs to our left into temporary table \"tab1\".\n */\n sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);\n rc = sqlite3Select(pParse, pPrior, &intersectdest);\n if( rc ){\n goto multi_select_end;\n }\n \n /* Code the current SELECT into temporary table \"tab2\"\n */\n addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);\n assert( p->addrOpenEphm[1] == -1 );\n p->addrOpenEphm[1] = addr;\n p->pPrior = 0;\n pLimit = p->pLimit;\n p->pLimit = 0;\n intersectdest.iSDParm = tab2;\n ExplainQueryPlan((pParse, 1, \"%s USING TEMP B-TREE\",\n selectOpName(p->op)));\n rc = sqlite3Select(pParse, p, &intersectdest);\n testcase( rc!=SQLITE_OK );\n pDelete = p->pPrior;\n p->pPrior = pPrior;\n if( p->nSelectRow>pPrior->nSelectRow ){\n p->nSelectRow = pPrior->nSelectRow;\n }\n sqlite3ExprDelete(db, p->pLimit);\n p->pLimit = pLimit;\n \n /* Generate code to take the intersection of the two temporary\n ** tables.\n */\n if( rc ) break;\n assert( p->pEList );\n iBreak = sqlite3VdbeMakeLabel(pParse);\n iCont = sqlite3VdbeMakeLabel(pParse);\n computeLimitRegisters(pParse, p, iBreak);\n sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);\n r1 = sqlite3GetTempReg(pParse);\n iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);\n sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);\n VdbeCoverage(v);\n sqlite3ReleaseTempReg(pParse, r1);\n selectInnerLoop(pParse, p, tab1,\n 0, 0, &dest, iCont, iBreak);\n sqlite3VdbeResolveLabel(v, iCont);\n sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);\n sqlite3VdbeResolveLabel(v, iBreak);\n sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);\n sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);\n break;\n }\n }\n \n #ifndef SQLITE_OMIT_EXPLAIN\n if( p->pNext==0 ){\n ExplainQueryPlanPop(pParse);\n }\n #endif\n }\n if( pParse->nErr ) goto multi_select_end;\n \n /* Compute collating sequences used by \n ** temporary tables needed to implement the compound select.\n ** Attach the KeyInfo structure to all temporary tables.\n **\n ** This section is run by the right-most SELECT statement only.\n ** SELECT statements to the left always skip this part. The right-most\n ** SELECT might also skip this part if it has no ORDER BY clause and\n ** no temp tables are required.\n */\n if( p->selFlags & SF_UsesEphemeral ){\n int i; /* Loop counter */\n KeyInfo *pKeyInfo; /* Collating sequence for the result set */\n Select *pLoop; /* For looping through SELECT statements */\n CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */\n int nCol; /* Number of columns in result set */\n\n assert( p->pNext==0 );\n nCol = p->pEList->nExpr;\n pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);\n if( !pKeyInfo ){\n rc = SQLITE_NOMEM_BKPT;\n goto multi_select_end;\n }\n for(i=0, apColl=pKeyInfo->aColl; ipDfltColl;\n }\n }\n\n for(pLoop=p; pLoop; pLoop=pLoop->pPrior){\n for(i=0; i<2; i++){\n int addr = pLoop->addrOpenEphm[i];\n if( addr<0 ){\n /* If [0] is unused then [1] is also unused. So we can\n ** always safely abort as soon as the first unused slot is found */\n assert( pLoop->addrOpenEphm[1]<0 );\n break;\n }\n sqlite3VdbeChangeP2(v, addr, nCol);\n sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),\n P4_KEYINFO);\n pLoop->addrOpenEphm[i] = -1;\n }\n }\n sqlite3KeyInfoUnref(pKeyInfo);\n }\n\nmulti_select_end:\n pDest->iSdst = dest.iSdst;\n pDest->nSdst = dest.nSdst;\n sqlite3SelectDelete(db, pDelete);\n return rc;\n}", "project": "sqlite", "hash": 222304138699688756475020408719005629756, "size": 344, "commit_id": "5f69512404cd2e5153ddf90ea277fbba6dd58ab7", "message": "Early-out on the INTERSECT query processing following an error.\n\nFossilOrigin-Name: a67cf5b7d37d5b1484be32092635faafd8f76e5881898cd9435517c4b287d663", "target": 0, "dataset": "other", "idx": 246169} {"func": " StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes,\r\n size_t xTriggerLevelBytes,\r\n BaseType_t xIsMessageBuffer )\r\n {\r\n uint8_t * pucAllocatedMemory;\r\n uint8_t ucFlags;\r\n\r\n /* In case the stream buffer is going to be used as a message buffer\r\n * (that is, it will hold discrete messages with a little meta data that\r\n * says how big the next message is) check the buffer will be large enough\r\n * to hold at least one message. */\r\n if( xIsMessageBuffer == pdTRUE )\r\n {\r\n /* Is a message buffer but not statically allocated. */\r\n ucFlags = sbFLAGS_IS_MESSAGE_BUFFER;\r\n configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH );\r\n }\r\n else\r\n {\r\n /* Not a message buffer and not statically allocated. */\r\n ucFlags = 0;\r\n configASSERT( xBufferSizeBytes > 0 );\r\n }\r\n\r\n configASSERT( xTriggerLevelBytes <= xBufferSizeBytes );\r\n\r\n /* A trigger level of 0 would cause a waiting task to unblock even when\r\n * the buffer was empty. */\r\n if( xTriggerLevelBytes == ( size_t ) 0 )\r\n {\r\n xTriggerLevelBytes = ( size_t ) 1;\r\n }\r\n\r\n /* A stream buffer requires a StreamBuffer_t structure and a buffer.\r\n * Both are allocated in a single call to pvPortMalloc(). The\r\n * StreamBuffer_t structure is placed at the start of the allocated memory\r\n * and the buffer follows immediately after. The requested size is\r\n * incremented so the free space is returned as the user would expect -\r\n * this is a quirk of the implementation that means otherwise the free\r\n * space would be reported as one byte smaller than would be logically\r\n * expected. */\r\n xBufferSizeBytes++;\r\n pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */\r\n\r\n if( pucAllocatedMemory != NULL )\r\n {\r\n prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */\r\n pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */\r\n xBufferSizeBytes,\r\n xTriggerLevelBytes,\r\n ucFlags );\r\n\r\n traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer );\r\n }\r\n else\r\n {\r\n traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer );\r\n }\r\n\r\n return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */\r\n }\r", "project": "FreeRTOS-Kernel", "hash": 218343301167279592040435651791165811, "size": 61, "commit_id": "d05b9c123f2bf9090bce386a244fc934ae44db5b", "message": "Add addition overflow check for stream buffer (#226)", "target": 1, "dataset": "other", "idx": 196843} {"func": " StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes,\r\n size_t xTriggerLevelBytes,\r\n BaseType_t xIsMessageBuffer )\r\n {\r\n uint8_t * pucAllocatedMemory;\r\n uint8_t ucFlags;\r\n\r\n /* In case the stream buffer is going to be used as a message buffer\r\n * (that is, it will hold discrete messages with a little meta data that\r\n * says how big the next message is) check the buffer will be large enough\r\n * to hold at least one message. */\r\n if( xIsMessageBuffer == pdTRUE )\r\n {\r\n /* Is a message buffer but not statically allocated. */\r\n ucFlags = sbFLAGS_IS_MESSAGE_BUFFER;\r\n configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH );\r\n }\r\n else\r\n {\r\n /* Not a message buffer and not statically allocated. */\r\n ucFlags = 0;\r\n configASSERT( xBufferSizeBytes > 0 );\r\n }\r\n\r\n configASSERT( xTriggerLevelBytes <= xBufferSizeBytes );\r\n\r\n /* A trigger level of 0 would cause a waiting task to unblock even when\r\n * the buffer was empty. */\r\n if( xTriggerLevelBytes == ( size_t ) 0 )\r\n {\r\n xTriggerLevelBytes = ( size_t ) 1;\r\n }\r\n\r\n /* A stream buffer requires a StreamBuffer_t structure and a buffer.\r\n * Both are allocated in a single call to pvPortMalloc(). The\r\n * StreamBuffer_t structure is placed at the start of the allocated memory\r\n * and the buffer follows immediately after. The requested size is\r\n * incremented so the free space is returned as the user would expect -\r\n * this is a quirk of the implementation that means otherwise the free\r\n * space would be reported as one byte smaller than would be logically\r\n * expected. */\r\n if( xBufferSizeBytes < ( xBufferSizeBytes + 1 + sizeof( StreamBuffer_t ) ) )\r\n {\r\n xBufferSizeBytes++;\r\n pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */\r\n }\r\n else\r\n {\r\n pucAllocatedMemory = NULL;\r\n }\r\n \r\n\r\n if( pucAllocatedMemory != NULL )\r\n {\r\n prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */\r\n pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */\r\n xBufferSizeBytes,\r\n xTriggerLevelBytes,\r\n ucFlags );\r\n\r\n traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer );\r\n }\r\n else\r\n {\r\n traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer );\r\n }\r\n\r\n return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */\r\n }\r", "project": "FreeRTOS-Kernel", "hash": 8256987615210769350257310115874004097, "size": 69, "commit_id": "d05b9c123f2bf9090bce386a244fc934ae44db5b", "message": "Add addition overflow check for stream buffer (#226)", "target": 0, "dataset": "other", "idx": 246422} {"func": "Status CompressElement(const std::vector& element,\n CompressedElement* out) {\n // Step 1: Determine the total uncompressed size. This requires serializing\n // non-memcopyable tensors, which we save to use again later.\n std::vector non_memcpy_components;\n int64 total_size = 0;\n for (auto& component : element) {\n if (DataTypeCanUseMemcpy(component.dtype())) {\n // Some datatypes can be memcopied, allowing us to save two copies\n // (AsProtoTensorContent and SerializeToArray).\n total_size += DMAHelper::buffer(&component)->size();\n } else {\n non_memcpy_components.emplace_back();\n component.AsProtoTensorContent(&non_memcpy_components.back());\n total_size += non_memcpy_components.back().ByteSizeLong();\n }\n }\n\n // Step 2: Write the tensor data to a buffer, and compress that buffer.\n // We use tstring for access to resize_uninitialized.\n tstring uncompressed;\n uncompressed.resize_uninitialized(total_size);\n // Position in `uncompressed` to write the next component.\n char* position = uncompressed.mdata();\n int non_memcpy_component_index = 0;\n for (auto& component : element) {\n CompressedComponentMetadata* metadata =\n out->mutable_component_metadata()->Add();\n metadata->set_dtype(component.dtype());\n component.shape().AsProto(metadata->mutable_tensor_shape());\n if (DataTypeCanUseMemcpy(component.dtype())) {\n const TensorBuffer* buffer = DMAHelper::buffer(&component);\n memcpy(position, buffer->data(), buffer->size());\n metadata->set_tensor_size_bytes(buffer->size());\n } else {\n TensorProto& proto = non_memcpy_components[non_memcpy_component_index++];\n proto.SerializeToArray(position, proto.ByteSizeLong());\n metadata->set_tensor_size_bytes(proto.ByteSizeLong());\n }\n position += metadata->tensor_size_bytes();\n }\n DCHECK_EQ(position, uncompressed.mdata() + total_size);\n\n if (!port::Snappy_Compress(uncompressed.mdata(), total_size,\n out->mutable_data())) {\n return errors::Internal(\"Failed to compress using snappy.\");\n }\n VLOG(3) << \"Compressed element from \" << total_size << \" bytes to \"\n << out->data().size() << \" bytes\";\n return Status::OK();\n}", "project": "tensorflow", "hash": 221515392574513944494740423419101303962, "size": 51, "commit_id": "5dc7f6981fdaf74c8c5be41f393df705841fb7c5", "message": "Fix accessing possible nullptr in tensorflow::data::CompressElement and UncompressElement which are used in tf.data.service.\n\nPiperOrigin-RevId: 373920841\nChange-Id: Ia88d78aee09fa19bb53a0f163fd19620d0c68743", "target": 1, "dataset": "other", "idx": 196856} {"func": "Status CompressElement(const std::vector& element,\n CompressedElement* out) {\n // Step 1: Determine the total uncompressed size. This requires serializing\n // non-memcopyable tensors, which we save to use again later.\n std::vector non_memcpy_components;\n int64 total_size = 0;\n for (auto& component : element) {\n if (DataTypeCanUseMemcpy(component.dtype())) {\n const TensorBuffer* buffer = DMAHelper::buffer(&component);\n if (buffer) {\n total_size += buffer->size();\n }\n } else {\n non_memcpy_components.emplace_back();\n component.AsProtoTensorContent(&non_memcpy_components.back());\n total_size += non_memcpy_components.back().ByteSizeLong();\n }\n }\n\n // Step 2: Write the tensor data to a buffer, and compress that buffer.\n // We use tstring for access to resize_uninitialized.\n tstring uncompressed;\n uncompressed.resize_uninitialized(total_size);\n // Position in `uncompressed` to write the next component.\n char* position = uncompressed.mdata();\n int non_memcpy_component_index = 0;\n for (auto& component : element) {\n CompressedComponentMetadata* metadata =\n out->mutable_component_metadata()->Add();\n metadata->set_dtype(component.dtype());\n component.shape().AsProto(metadata->mutable_tensor_shape());\n if (DataTypeCanUseMemcpy(component.dtype())) {\n const TensorBuffer* buffer = DMAHelper::buffer(&component);\n if (buffer) {\n memcpy(position, buffer->data(), buffer->size());\n metadata->set_tensor_size_bytes(buffer->size());\n }\n } else {\n TensorProto& proto = non_memcpy_components[non_memcpy_component_index++];\n proto.SerializeToArray(position, proto.ByteSizeLong());\n metadata->set_tensor_size_bytes(proto.ByteSizeLong());\n }\n position += metadata->tensor_size_bytes();\n }\n DCHECK_EQ(position, uncompressed.mdata() + total_size);\n\n if (!port::Snappy_Compress(uncompressed.mdata(), total_size,\n out->mutable_data())) {\n return errors::Internal(\"Failed to compress using snappy.\");\n }\n VLOG(3) << \"Compressed element from \" << total_size << \" bytes to \"\n << out->data().size() << \" bytes\";\n return Status::OK();\n}", "project": "tensorflow", "hash": 20244254151554116869938450542850593726, "size": 54, "commit_id": "5dc7f6981fdaf74c8c5be41f393df705841fb7c5", "message": "Fix accessing possible nullptr in tensorflow::data::CompressElement and UncompressElement which are used in tf.data.service.\n\nPiperOrigin-RevId: 373920841\nChange-Id: Ia88d78aee09fa19bb53a0f163fd19620d0c68743", "target": 0, "dataset": "other", "idx": 246589} {"func": " void Compute(OpKernelContext *ctx) override {\n const Tensor *a_indices_t, *a_values_t, *a_shape_t, *b_indices_t,\n *b_values_t, *b_shape_t;\n OP_REQUIRES_OK(ctx, ctx->input(\"a_indices\", &a_indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"a_values\", &a_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"a_shape\", &a_shape_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_indices\", &b_indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_values\", &b_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_shape\", &b_shape_t));\n\n // Validations.\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsMatrix(a_indices_t->shape()) &&\n TensorShapeUtils::IsMatrix(b_indices_t->shape()),\n errors::InvalidArgument(\"Inputs a_indices and b_indices should be \"\n \"matrices but received shapes: \",\n a_indices_t->shape().DebugString(), \", \",\n b_indices_t->shape().DebugString()));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_values_t->shape()) &&\n TensorShapeUtils::IsVector(b_values_t->shape()),\n errors::InvalidArgument(\n \"Inputs a_values and b_values should be vectors \"\n \"but received shapes: \",\n a_values_t->shape().DebugString(), \" and \",\n b_values_t->shape().DebugString()));\n\n const int64 a_nnz = a_indices_t->dim_size(0);\n const int64 b_nnz = b_indices_t->dim_size(0);\n const auto a_values = a_values_t->vec();\n const auto b_values = b_values_t->vec();\n\n OP_REQUIRES(\n ctx, a_values.size() == a_nnz && b_values.size() == b_nnz,\n errors::InvalidArgument(\"Expected \", a_nnz, \" and \", b_nnz,\n \" non-empty input values, got \",\n a_values.size(), \" and \", b_values.size()));\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_shape_t->shape()) &&\n TensorShapeUtils::IsVector(b_shape_t->shape()),\n errors::InvalidArgument(\n \"Input shapes should be a vector but received shapes \",\n a_shape_t->shape().DebugString(), \" and \",\n b_shape_t->shape().DebugString()));\n OP_REQUIRES(ctx, a_shape_t->IsSameSize(*b_shape_t),\n errors::InvalidArgument(\n \"Operands do not have the same ranks; got shapes: \",\n a_shape_t->SummarizeValue(10), \" and \",\n b_shape_t->SummarizeValue(10)));\n const auto a_shape = a_shape_t->flat();\n const auto b_shape = b_shape_t->flat();\n for (int i = 0; i < a_shape_t->NumElements(); ++i) {\n OP_REQUIRES(ctx, a_shape(i) == b_shape(i),\n errors::InvalidArgument(\"Operands' shapes do not match: got \",\n a_shape(i), \" and \", b_shape(i),\n \" for dimension \", i));\n }\n\n OP_REQUIRES(\n ctx, a_indices_t->dim_size(1) == b_indices_t->dim_size(1),\n errors::InvalidArgument(\n \"Indices' dimensions do not match: got \", a_indices_t->dim_size(1),\n \" and \", b_indices_t->dim_size(1), \" for the second dimension.\"));\n const int num_dims = a_indices_t->dim_size(1);\n const auto a_indices_mat = a_indices_t->matrix();\n const auto b_indices_mat = b_indices_t->matrix();\n std::vector a_augmented_values, b_augmented_values;\n std::vector> entries_to_copy; // from_a?, idx\n UnionSparseIndicesAndValues(a_indices_mat, a_values, a_nnz, b_indices_mat,\n b_values, b_nnz, num_dims, &a_augmented_values,\n &b_augmented_values, &entries_to_copy);\n\n // Allocates and fills output tensors.\n const int64 sum_nnz = a_augmented_values.size();\n Tensor *output_indices_t, *output_values_t;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}),\n &output_indices_t));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &output_values_t));\n auto output_indices_mat = output_indices_t->matrix();\n\n for (int64 i = 0; i < sum_nnz; ++i) {\n const bool from_a = entries_to_copy[i].first;\n const int64 idx = entries_to_copy[i].second;\n output_indices_mat.chip<0>(i) =\n from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx);\n }\n\n // Performs the functor operation using Eigen.\n //\n // Note that the two stack-allocated std::vector's may not be aligned. Using\n // allocate_temp() would've given us aligned storage, but we do not know\n // their sizes in advance, so we couldn't use allocate_temp() anyway.\n //\n // TODO(zongheng): measure if it's worthwhile to somehow force alignment.\n using UnalignedTensorMap =\n Eigen::TensorMap,\n Eigen::Unaligned>;\n auto a_augmented_values_t =\n UnalignedTensorMap(a_augmented_values.data(), sum_nnz);\n auto b_augmented_values_t =\n UnalignedTensorMap(b_augmented_values.data(), sum_nnz);\n output_values_t->flat().device(ctx->eigen_device()) =\n a_augmented_values_t.binaryExpr(b_augmented_values_t,\n typename Functor::func());\n }", "project": "tensorflow", "hash": 294501462862477461576591658344805884704, "size": 109, "commit_id": "f6fde895ef9c77d848061c0517f19d0ec2682f3a", "message": "Validate that a and b are proper sparse tensors\n\nPiperOrigin-RevId: 373274848\nChange-Id: I3a665ac3a29dee9fb69bdf408a939330cb93ea75", "target": 1, "dataset": "other", "idx": 196857} {"func": " void Compute(OpKernelContext *ctx) override {\n const Tensor *a_indices_t, *a_values_t, *a_shape_t, *b_indices_t,\n *b_values_t, *b_shape_t;\n OP_REQUIRES_OK(ctx, ctx->input(\"a_indices\", &a_indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"a_values\", &a_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"a_shape\", &a_shape_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_indices\", &b_indices_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_values\", &b_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_shape\", &b_shape_t));\n\n // Validations.\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsMatrix(a_indices_t->shape()) &&\n TensorShapeUtils::IsMatrix(b_indices_t->shape()),\n errors::InvalidArgument(\"Inputs a_indices and b_indices should be \"\n \"matrices but received shapes: \",\n a_indices_t->shape().DebugString(), \", \",\n b_indices_t->shape().DebugString()));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_values_t->shape()) &&\n TensorShapeUtils::IsVector(b_values_t->shape()),\n errors::InvalidArgument(\n \"Inputs a_values and b_values should be vectors \"\n \"but received shapes: \",\n a_values_t->shape().DebugString(), \" and \",\n b_values_t->shape().DebugString()));\n\n const int64 a_nnz = a_indices_t->dim_size(0);\n const int64 b_nnz = b_indices_t->dim_size(0);\n\n const auto a_values = a_values_t->vec();\n const auto b_values = b_values_t->vec();\n\n OP_REQUIRES(\n ctx, a_values.size() == a_nnz && b_values.size() == b_nnz,\n errors::InvalidArgument(\"Expected \", a_nnz, \" and \", b_nnz,\n \" non-empty input values, got \",\n a_values.size(), \" and \", b_values.size()));\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_shape_t->shape()) &&\n TensorShapeUtils::IsVector(b_shape_t->shape()),\n errors::InvalidArgument(\n \"Input shapes should be a vector but received shapes \",\n a_shape_t->shape().DebugString(), \" and \",\n b_shape_t->shape().DebugString()));\n const int num_dims = a_indices_t->dim_size(1);\n OP_REQUIRES(\n ctx, a_shape_t->NumElements() == num_dims,\n errors::InvalidArgument(\"Second dimension of a_indices and length of \"\n \"a_shape must match, got \",\n num_dims, \" and \", a_shape_t->NumElements()));\n OP_REQUIRES(ctx, num_dims > 0,\n errors::InvalidArgument(\"Tensors must not be empty\"));\n OP_REQUIRES(ctx, a_shape_t->IsSameSize(*b_shape_t),\n errors::InvalidArgument(\n \"Operands do not have the same ranks; got shapes: \",\n a_shape_t->SummarizeValue(10), \" and \",\n b_shape_t->SummarizeValue(10)));\n const auto a_shape = a_shape_t->flat();\n const auto b_shape = b_shape_t->flat();\n for (int i = 0; i < a_shape_t->NumElements(); ++i) {\n OP_REQUIRES(ctx, a_shape(i) == b_shape(i),\n errors::InvalidArgument(\"Operands' shapes do not match: got \",\n a_shape(i), \" and \", b_shape(i),\n \" for dimension \", i));\n }\n\n const auto a_indices_mat = a_indices_t->matrix();\n const auto b_indices_mat = b_indices_t->matrix();\n std::vector a_augmented_values, b_augmented_values;\n std::vector> entries_to_copy; // from_a?, idx\n UnionSparseIndicesAndValues(a_indices_mat, a_values, a_nnz, b_indices_mat,\n b_values, b_nnz, num_dims, &a_augmented_values,\n &b_augmented_values, &entries_to_copy);\n\n // Allocates and fills output tensors.\n const int64 sum_nnz = a_augmented_values.size();\n Tensor *output_indices_t, *output_values_t;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}),\n &output_indices_t));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &output_values_t));\n auto output_indices_mat = output_indices_t->matrix();\n\n for (int64 i = 0; i < sum_nnz; ++i) {\n const bool from_a = entries_to_copy[i].first;\n const int64 idx = entries_to_copy[i].second;\n output_indices_mat.chip<0>(i) =\n from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx);\n }\n\n // Performs the functor operation using Eigen.\n //\n // Note that the two stack-allocated std::vector's may not be aligned. Using\n // allocate_temp() would've given us aligned storage, but we do not know\n // their sizes in advance, so we couldn't use allocate_temp() anyway.\n //\n // TODO(zongheng): measure if it's worthwhile to somehow force alignment.\n using UnalignedTensorMap =\n Eigen::TensorMap,\n Eigen::Unaligned>;\n auto a_augmented_values_t =\n UnalignedTensorMap(a_augmented_values.data(), sum_nnz);\n auto b_augmented_values_t =\n UnalignedTensorMap(b_augmented_values.data(), sum_nnz);\n output_values_t->flat().device(ctx->eigen_device()) =\n a_augmented_values_t.binaryExpr(b_augmented_values_t,\n typename Functor::func());\n }", "project": "tensorflow", "hash": 146102284664006539274854620186945524131, "size": 112, "commit_id": "f6fde895ef9c77d848061c0517f19d0ec2682f3a", "message": "Validate that a and b are proper sparse tensors\n\nPiperOrigin-RevId: 373274848\nChange-Id: I3a665ac3a29dee9fb69bdf408a939330cb93ea75", "target": 0, "dataset": "other", "idx": 246590} {"func": " bool matches(const Http::RequestHeaderMap& headers) const override {\n if (BaseMatcherImpl::matchRoute(headers)) {\n const Http::HeaderString& path = headers.Path()->value();\n const absl::string_view query_string = Http::Utility::findQueryStringStart(path);\n absl::string_view path_view = path.getStringView();\n path_view.remove_suffix(query_string.length());\n if (path_matcher_->match(path_view)) {\n ENVOY_LOG(debug, \"Regex requirement '{}' matched.\", regex_str_);\n return true;\n }\n }\n return false;\n }", "project": "envoy", "hash": 76257563614559165334076596514064335521, "size": 13, "commit_id": "9371333230b1a6e1be2eccf4868771e11af6253a", "message": "CVE-2021-43824\n\njwt_atuhn: fixed the crash when a CONNECT request is sent to JWT filter\nconfigured with regex match.\n\nSigned-off-by: Yan Avlasov ", "target": 1, "dataset": "other", "idx": 196858} {"func": " bool matches(const Http::RequestHeaderMap& headers) const override {\n if (BaseMatcherImpl::matchRoute(headers)) {\n if (headers.Path() == nullptr) {\n return false;\n }\n const Http::HeaderString& path = headers.Path()->value();\n const absl::string_view query_string = Http::Utility::findQueryStringStart(path);\n absl::string_view path_view = path.getStringView();\n path_view.remove_suffix(query_string.length());\n if (path_matcher_->match(path_view)) {\n ENVOY_LOG(debug, \"Regex requirement '{}' matched.\", regex_str_);\n return true;\n }\n }\n return false;\n }", "project": "envoy", "hash": 234200888989403949850149389072672312631, "size": 16, "commit_id": "9371333230b1a6e1be2eccf4868771e11af6253a", "message": "CVE-2021-43824\n\njwt_atuhn: fixed the crash when a CONNECT request is sent to JWT filter\nconfigured with regex match.\n\nSigned-off-by: Yan Avlasov ", "target": 0, "dataset": "other", "idx": 246616} {"func": "void M_LoadDefaults (void)\n{\n int\t\ti;\n int\t\tlen;\n FILE*\tf;\n char\tdef[80];\n char\tstrparm[100];\n char*\tnewstring;\n int\t\tparm;\n boolean\tisstring;\n \n // set everything to base values\n numdefaults = sizeof(defaults)/sizeof(defaults[0]);\n for (i=0 ; i>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenMatrixMap;\n\n constexpr int tensor_in_and_out_dims = 4;\n\n const Tensor& tensor_in = context->input(0);\n OP_REQUIRES(context, tensor_in.dims() == tensor_in_and_out_dims,\n errors::InvalidArgument(\"tensor_in must be 4-dimensional\"));\n\n std::vector input_size(tensor_in_and_out_dims);\n std::vector output_size(tensor_in_and_out_dims);\n for (int i = 0; i < tensor_in_and_out_dims; ++i) {\n input_size[i] = tensor_in.dim_size(i);\n }\n // Output size.\n for (int i = 0; i < tensor_in_and_out_dims; ++i) {\n output_size[i] =\n static_cast(std::floor(input_size[i] / pooling_ratio_[i]));\n DCHECK_GT(output_size[i], 0);\n }\n\n // Generate pooling sequence.\n std::vector row_cum_seq;\n std::vector col_cum_seq;\n GuardedPhiloxRandom generator;\n generator.Init(seed_, seed2_);\n row_cum_seq = GeneratePoolingSequence(input_size[1], output_size[1],\n &generator, pseudo_random_);\n col_cum_seq = GeneratePoolingSequence(input_size[2], output_size[2],\n &generator, pseudo_random_);\n\n // Prepare output.\n Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0,\n TensorShape({output_size[0], output_size[1],\n output_size[2], output_size[3]}),\n &output_tensor));\n Tensor* output_row_seq_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 1, TensorShape({static_cast(row_cum_seq.size())}),\n &output_row_seq_tensor));\n Tensor* output_col_seq_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 2, TensorShape({static_cast(col_cum_seq.size())}),\n &output_col_seq_tensor));\n\n ConstEigenMatrixMap in_mat(tensor_in.flat().data(), input_size[3],\n input_size[2] * input_size[1] * input_size[0]);\n\n EigenMatrixMap out_mat(output_tensor->flat().data(), output_size[3],\n output_size[2] * output_size[1] * output_size[0]);\n // out_count corresponds to number of elements in each pooling cell.\n Eigen::Matrix out_count(out_mat.cols());\n\n // Initializes the output tensor and out_count with 0.\n out_mat.setZero();\n out_count.setZero();\n\n auto output_row_seq_flat = output_row_seq_tensor->flat();\n auto output_col_seq_flat = output_col_seq_tensor->flat();\n\n // Set output tensors.\n for (int i = 0; i < row_cum_seq.size(); ++i) {\n output_row_seq_flat(i) = row_cum_seq[i];\n }\n\n for (int i = 0; i < col_cum_seq.size(); ++i) {\n output_col_seq_flat(i) = col_cum_seq[i];\n }\n\n // For both input and output,\n // 0: batch\n // 1: row / row\n // 2: col / col\n // 3: depth / channel\n const int64 row_max = input_size[1] - 1;\n const int64 col_max = input_size[2] - 1;\n for (int64 b = 0; b < input_size[0]; ++b) {\n // row sequence.\n for (int64 hs = 0; hs < row_cum_seq.size() - 1; ++hs) {\n // row start and end.\n const int64 row_start = row_cum_seq[hs];\n int64 row_end =\n overlapping_ ? row_cum_seq[hs + 1] : row_cum_seq[hs + 1] - 1;\n row_end = std::min(row_end, row_max);\n\n // col sequence.\n for (int64 ws = 0; ws < col_cum_seq.size() - 1; ++ws) {\n const int64 out_offset =\n (b * output_size[1] + hs) * output_size[2] + ws;\n // col start and end.\n const int64 col_start = col_cum_seq[ws];\n int64 col_end =\n overlapping_ ? col_cum_seq[ws + 1] : col_cum_seq[ws + 1] - 1;\n col_end = std::min(col_end, col_max);\n for (int64 h = row_start; h <= row_end; ++h) {\n for (int64 w = col_start; w <= col_end; ++w) {\n const int64 in_offset =\n (b * input_size[1] + h) * input_size[2] + w;\n out_mat.col(out_offset) += in_mat.col(in_offset);\n out_count(out_offset)++;\n }\n }\n }\n }\n }\n DCHECK_GT(out_count.minCoeff(), 0);\n out_mat.array().rowwise() /= out_count.transpose().array();\n }", "project": "tensorflow", "hash": 65175645890002238093586777553466908304, "size": 115, "commit_id": "548b5eaf23685d86f722233d8fbc21d0a4aecb96", "message": "Fix divide by zero error in `fractional_pool_common.cc`.\n\nPiperOrigin-RevId: 371126221\nChange-Id: Iea4b2f363aaeb116ab460e3bc592c687484af344", "target": 1, "dataset": "other", "idx": 196921} {"func": " void Compute(OpKernelContext* context) override {\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenMatrixMap;\n\n constexpr int tensor_in_and_out_dims = 4;\n\n const Tensor& tensor_in = context->input(0);\n OP_REQUIRES(context, tensor_in.dims() == tensor_in_and_out_dims,\n errors::InvalidArgument(\"tensor_in must be 4-dimensional\"));\n\n std::vector input_size(tensor_in_and_out_dims);\n std::vector output_size(tensor_in_and_out_dims);\n for (int i = 0; i < tensor_in_and_out_dims; ++i) {\n input_size[i] = tensor_in.dim_size(i);\n OP_REQUIRES(\n context, pooling_ratio_[i] <= input_size[i],\n errors::InvalidArgument(\n \"Pooling ratio cannot be bigger than input tensor dim size.\"));\n }\n // Output size.\n for (int i = 0; i < tensor_in_and_out_dims; ++i) {\n output_size[i] =\n static_cast(std::floor(input_size[i] / pooling_ratio_[i]));\n DCHECK_GT(output_size[i], 0);\n }\n\n // Generate pooling sequence.\n std::vector row_cum_seq;\n std::vector col_cum_seq;\n GuardedPhiloxRandom generator;\n generator.Init(seed_, seed2_);\n row_cum_seq = GeneratePoolingSequence(input_size[1], output_size[1],\n &generator, pseudo_random_);\n col_cum_seq = GeneratePoolingSequence(input_size[2], output_size[2],\n &generator, pseudo_random_);\n\n // Prepare output.\n Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0,\n TensorShape({output_size[0], output_size[1],\n output_size[2], output_size[3]}),\n &output_tensor));\n Tensor* output_row_seq_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 1, TensorShape({static_cast(row_cum_seq.size())}),\n &output_row_seq_tensor));\n Tensor* output_col_seq_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\n 2, TensorShape({static_cast(col_cum_seq.size())}),\n &output_col_seq_tensor));\n\n ConstEigenMatrixMap in_mat(tensor_in.flat().data(), input_size[3],\n input_size[2] * input_size[1] * input_size[0]);\n\n EigenMatrixMap out_mat(output_tensor->flat().data(), output_size[3],\n output_size[2] * output_size[1] * output_size[0]);\n // out_count corresponds to number of elements in each pooling cell.\n Eigen::Matrix out_count(out_mat.cols());\n\n // Initializes the output tensor and out_count with 0.\n out_mat.setZero();\n out_count.setZero();\n\n auto output_row_seq_flat = output_row_seq_tensor->flat();\n auto output_col_seq_flat = output_col_seq_tensor->flat();\n\n // Set output tensors.\n for (int i = 0; i < row_cum_seq.size(); ++i) {\n output_row_seq_flat(i) = row_cum_seq[i];\n }\n\n for (int i = 0; i < col_cum_seq.size(); ++i) {\n output_col_seq_flat(i) = col_cum_seq[i];\n }\n\n // For both input and output,\n // 0: batch\n // 1: row / row\n // 2: col / col\n // 3: depth / channel\n const int64 row_max = input_size[1] - 1;\n const int64 col_max = input_size[2] - 1;\n for (int64 b = 0; b < input_size[0]; ++b) {\n // row sequence.\n for (int64 hs = 0; hs < row_cum_seq.size() - 1; ++hs) {\n // row start and end.\n const int64 row_start = row_cum_seq[hs];\n int64 row_end =\n overlapping_ ? row_cum_seq[hs + 1] : row_cum_seq[hs + 1] - 1;\n row_end = std::min(row_end, row_max);\n\n // col sequence.\n for (int64 ws = 0; ws < col_cum_seq.size() - 1; ++ws) {\n const int64 out_offset =\n (b * output_size[1] + hs) * output_size[2] + ws;\n // col start and end.\n const int64 col_start = col_cum_seq[ws];\n int64 col_end =\n overlapping_ ? col_cum_seq[ws + 1] : col_cum_seq[ws + 1] - 1;\n col_end = std::min(col_end, col_max);\n for (int64 h = row_start; h <= row_end; ++h) {\n for (int64 w = col_start; w <= col_end; ++w) {\n const int64 in_offset =\n (b * input_size[1] + h) * input_size[2] + w;\n out_mat.col(out_offset) += in_mat.col(in_offset);\n out_count(out_offset)++;\n }\n }\n }\n }\n }\n DCHECK_GT(out_count.minCoeff(), 0);\n out_mat.array().rowwise() /= out_count.transpose().array();\n }", "project": "tensorflow", "hash": 290851511414157159746753067138127604859, "size": 119, "commit_id": "548b5eaf23685d86f722233d8fbc21d0a4aecb96", "message": "Fix divide by zero error in `fractional_pool_common.cc`.\n\nPiperOrigin-RevId: 371126221\nChange-Id: Iea4b2f363aaeb116ab460e3bc592c687484af344", "target": 0, "dataset": "other", "idx": 248336} {"func": "static void hash_search(int f,struct sum_struct *s,\n\t\t\tstruct map_struct *buf, OFF_T len)\n{\n\tOFF_T offset, aligned_offset, end;\n\tint32 k, want_i, backup;\n\tchar sum2[SUM_LENGTH];\n\tuint32 s1, s2, sum;\n\tint more;\n\tschar *map;\n\n\t/* want_i is used to encourage adjacent matches, allowing the RLL\n\t * coding of the output to work more efficiently. */\n\twant_i = 0;\n\n\tif (verbose > 2) {\n\t\trprintf(FINFO, \"hash search b=%ld len=%.0f\\n\",\n\t\t\t(long)s->blength, (double)len);\n\t}\n\n\tk = (int32)MIN(len, (OFF_T)s->blength);\n\n\tmap = (schar *)map_ptr(buf, 0, k);\n\n\tsum = get_checksum1((char *)map, k);\n\ts1 = sum & 0xFFFF;\n\ts2 = sum >> 16;\n\tif (verbose > 3)\n\t\trprintf(FINFO, \"sum=%.8x k=%ld\\n\", sum, (long)k);\n\n\toffset = aligned_offset = 0;\n\n\tend = len + 1 - s->sums[s->count-1].len;\n\n\tif (verbose > 3) {\n\t\trprintf(FINFO, \"hash search s->blength=%ld len=%.0f count=%.0f\\n\",\n\t\t\t(long)s->blength, (double)len, (double)s->count);\n\t}\n\n\tdo {\n\t\tint done_csum2 = 0;\n\t\tint32 i;\n\n\t\tif (verbose > 4) {\n\t\t\trprintf(FINFO, \"offset=%.0f sum=%04x%04x\\n\",\n\t\t\t\t(double)offset, s2 & 0xFFFF, s1 & 0xFFFF);\n\t\t}\n\n\t\tif (tablesize == TRADITIONAL_TABLESIZE) {\n\t\t\tif ((i = hash_table[SUM2HASH2(s1,s2)]) < 0)\n\t\t\t\tgoto null_hash;\n\t\t\tsum = (s1 & 0xffff) | (s2 << 16);\n\t\t} else {\n\t\t\tsum = (s1 & 0xffff) | (s2 << 16);\n\t\t\tif ((i = hash_table[BIG_SUM2HASH(sum)]) < 0)\n\t\t\t\tgoto null_hash;\n\t\t}\n\n\t\thash_hits++;\n\t\tdo {\n\t\t\tint32 l;\n\n\t\t\tif (sum != s->sums[i].sum1)\n\t\t\t\tcontinue;\n\n\t\t\t/* also make sure the two blocks are the same length */\n\t\t\tl = (int32)MIN((OFF_T)s->blength, len-offset);\n\t\t\tif (l != s->sums[i].len)\n\t\t\t\tcontinue;\n\n\t\t\t/* in-place: ensure chunk's offset is either >= our\n\t\t\t * offset or that the data didn't move. */\n\t\t\tif (updating_basis_file && s->sums[i].offset < offset\n\t\t\t && !(s->sums[i].flags & SUMFLG_SAME_OFFSET))\n\t\t\t\tcontinue;\n\n\t\t\tif (verbose > 3) {\n\t\t\t\trprintf(FINFO,\n\t\t\t\t\t\"potential match at %.0f i=%ld sum=%08x\\n\",\n\t\t\t\t\t(double)offset, (long)i, sum);\n\t\t\t}\n\n\t\t\tif (!done_csum2) {\n\t\t\t\tmap = (schar *)map_ptr(buf,offset,l);\n\t\t\t\tget_checksum2((char *)map,l,sum2);\n\t\t\t\tdone_csum2 = 1;\n\t\t\t}\n\n\t\t\tif (memcmp(sum2,s->sums[i].sum2,s->s2length) != 0) {\n\t\t\t\tfalse_alarms++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* When updating in-place, the best possible match is\n\t\t\t * one with an identical offset, so we prefer that over\n\t\t\t * the adjacent want_i optimization. */\n\t\t\tif (updating_basis_file) {\n\t\t\t\t/* All the generator's chunks start at blength boundaries. */\n\t\t\t\twhile (aligned_offset < offset)\n\t\t\t\t\taligned_offset += s->blength;\n\t\t\t\tif (offset == aligned_offset) {\n\t\t\t\t\tint32 i2;\n\t\t\t\t\tfor (i2 = i; i2 >= 0; i2 = s->sums[i2].chain) {\n\t\t\t\t\t\tif (s->sums[i2].offset != offset)\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tif (i2 != i) {\n\t\t\t\t\t\t\tif (sum != s->sums[i2].sum1\n\t\t\t\t\t\t\t || l != s->sums[i2].len\n\t\t\t\t\t\t\t || memcmp(sum2, s->sums[i2].sum2, s->s2length) != 0)\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\ti = i2;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* This chunk remained in the same spot in the old and new file. */\n\t\t\t\t\t\ts->sums[i].flags |= SUMFLG_SAME_OFFSET;\n\t\t\t\t\t\twant_i = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* we've found a match, but now check to see\n\t\t\t * if want_i can hint at a better match. */\n\t\t\tif (i != want_i && want_i < s->count\n\t\t\t && (!updating_basis_file || s->sums[want_i].offset >= offset\n\t\t\t || s->sums[want_i].flags & SUMFLG_SAME_OFFSET)\n\t\t\t && sum == s->sums[want_i].sum1\n\t\t\t && memcmp(sum2, s->sums[want_i].sum2, s->s2length) == 0) {\n\t\t\t\t/* we've found an adjacent match - the RLL coder\n\t\t\t\t * will be happy */\n\t\t\t\ti = want_i;\n\t\t\t}\n\t\t\twant_i = i + 1;\n\n\t\t\tmatched(f,s,buf,offset,i);\n\t\t\toffset += s->sums[i].len - 1;\n\t\t\tk = (int32)MIN((OFF_T)s->blength, len-offset);\n\t\t\tmap = (schar *)map_ptr(buf, offset, k);\n\t\t\tsum = get_checksum1((char *)map, k);\n\t\t\ts1 = sum & 0xFFFF;\n\t\t\ts2 = sum >> 16;\n\t\t\tmatches++;\n\t\t\tbreak;\n\t\t} while ((i = s->sums[i].chain) >= 0);\n\n\t null_hash:\n\t\tbackup = (int32)(offset - last_match);\n\t\t/* We sometimes read 1 byte prior to last_match... */\n\t\tif (backup < 0)\n\t\t\tbackup = 0;\n\n\t\t/* Trim off the first byte from the checksum */\n\t\tmore = offset + k < len;\n\t\tmap = (schar *)map_ptr(buf, offset - backup, k + more + backup)\n\t\t + backup;\n\t\ts1 -= map[0] + CHAR_OFFSET;\n\t\ts2 -= k * (map[0]+CHAR_OFFSET);\n\n\t\t/* Add on the next byte (if there is one) to the checksum */\n\t\tif (more) {\n\t\t\ts1 += map[k] + CHAR_OFFSET;\n\t\t\ts2 += s1;\n\t\t} else\n\t\t\t--k;\n\n\t\t/* By matching early we avoid re-reading the\n\t\t data 3 times in the case where a token\n\t\t match comes a long way after last\n\t\t match. The 3 reads are caused by the\n\t\t running match, the checksum update and the\n\t\t literal send. */\n\t\tif (backup >= s->blength+CHUNK_SIZE && end-offset > CHUNK_SIZE)\n\t\t\tmatched(f, s, buf, offset - s->blength, -2);\n\t} while (++offset < end);\n\n\tmatched(f, s, buf, len, -1);\n\tmap_ptr(buf, len-1, 1);\n}", "project": "rsync", "hash": 13269351929661258568831239064102968322, "size": 176, "commit_id": "c8255147b06b74dad940d32f9cef5fbe17595239", "message": "Optimize finding the sum that matches our --inplace position.", "target": 1, "dataset": "other", "idx": 196927} {"func": "static void hash_search(int f,struct sum_struct *s,\n\t\t\tstruct map_struct *buf, OFF_T len)\n{\n\tOFF_T offset, aligned_offset, end;\n\tint32 k, want_i, aligned_i, backup;\n\tchar sum2[SUM_LENGTH];\n\tuint32 s1, s2, sum;\n\tint more;\n\tschar *map;\n\n\t/* want_i is used to encourage adjacent matches, allowing the RLL\n\t * coding of the output to work more efficiently. */\n\twant_i = 0;\n\n\tif (verbose > 2) {\n\t\trprintf(FINFO, \"hash search b=%ld len=%.0f\\n\",\n\t\t\t(long)s->blength, (double)len);\n\t}\n\n\tk = (int32)MIN(len, (OFF_T)s->blength);\n\n\tmap = (schar *)map_ptr(buf, 0, k);\n\n\tsum = get_checksum1((char *)map, k);\n\ts1 = sum & 0xFFFF;\n\ts2 = sum >> 16;\n\tif (verbose > 3)\n\t\trprintf(FINFO, \"sum=%.8x k=%ld\\n\", sum, (long)k);\n\n\toffset = aligned_offset = aligned_i = 0;\n\n\tend = len + 1 - s->sums[s->count-1].len;\n\n\tif (verbose > 3) {\n\t\trprintf(FINFO, \"hash search s->blength=%ld len=%.0f count=%.0f\\n\",\n\t\t\t(long)s->blength, (double)len, (double)s->count);\n\t}\n\n\tdo {\n\t\tint done_csum2 = 0;\n\t\tint32 i;\n\n\t\tif (verbose > 4) {\n\t\t\trprintf(FINFO, \"offset=%.0f sum=%04x%04x\\n\",\n\t\t\t\t(double)offset, s2 & 0xFFFF, s1 & 0xFFFF);\n\t\t}\n\n\t\tif (tablesize == TRADITIONAL_TABLESIZE) {\n\t\t\tif ((i = hash_table[SUM2HASH2(s1,s2)]) < 0)\n\t\t\t\tgoto null_hash;\n\t\t\tsum = (s1 & 0xffff) | (s2 << 16);\n\t\t} else {\n\t\t\tsum = (s1 & 0xffff) | (s2 << 16);\n\t\t\tif ((i = hash_table[BIG_SUM2HASH(sum)]) < 0)\n\t\t\t\tgoto null_hash;\n\t\t}\n\n\t\thash_hits++;\n\t\tdo {\n\t\t\tint32 l;\n\n\t\t\tif (sum != s->sums[i].sum1)\n\t\t\t\tcontinue;\n\n\t\t\t/* also make sure the two blocks are the same length */\n\t\t\tl = (int32)MIN((OFF_T)s->blength, len-offset);\n\t\t\tif (l != s->sums[i].len)\n\t\t\t\tcontinue;\n\n\t\t\t/* in-place: ensure chunk's offset is either >= our\n\t\t\t * offset or that the data didn't move. */\n\t\t\tif (updating_basis_file && s->sums[i].offset < offset\n\t\t\t && !(s->sums[i].flags & SUMFLG_SAME_OFFSET))\n\t\t\t\tcontinue;\n\n\t\t\tif (verbose > 3) {\n\t\t\t\trprintf(FINFO,\n\t\t\t\t\t\"potential match at %.0f i=%ld sum=%08x\\n\",\n\t\t\t\t\t(double)offset, (long)i, sum);\n\t\t\t}\n\n\t\t\tif (!done_csum2) {\n\t\t\t\tmap = (schar *)map_ptr(buf,offset,l);\n\t\t\t\tget_checksum2((char *)map,l,sum2);\n\t\t\t\tdone_csum2 = 1;\n\t\t\t}\n\n\t\t\tif (memcmp(sum2,s->sums[i].sum2,s->s2length) != 0) {\n\t\t\t\tfalse_alarms++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* When updating in-place, the best possible match is\n\t\t\t * one with an identical offset, so we prefer that over\n\t\t\t * the adjacent want_i optimization. */\n\t\t\tif (updating_basis_file) {\n\t\t\t\t/* All the generator's chunks start at blength boundaries. */\n\t\t\t\twhile (aligned_offset < offset) {\n\t\t\t\t\taligned_offset += s->blength;\n\t\t\t\t\taligned_i++;\n\t\t\t\t}\n\t\t\t\tif (offset == aligned_offset) {\n\t\t\t\t\tif (i != aligned_i) {\n\t\t\t\t\t\tif (sum != s->sums[aligned_i].sum1\n\t\t\t\t\t\t || l != s->sums[aligned_i].len\n\t\t\t\t\t\t || memcmp(sum2, s->sums[aligned_i].sum2, s->s2length) != 0)\n\t\t\t\t\t\t\tgoto check_want_i;\n\t\t\t\t\t\ti = aligned_i;\n\t\t\t\t\t}\n\t\t\t\t\t/* This identical chunk is in the same spot in the old and new file. */\n\t\t\t\t\ts->sums[i].flags |= SUMFLG_SAME_OFFSET;\n\t\t\t\t\twant_i = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t check_want_i:\n\t\t\t/* we've found a match, but now check to see\n\t\t\t * if want_i can hint at a better match. */\n\t\t\tif (i != want_i && want_i < s->count\n\t\t\t && (!updating_basis_file || s->sums[want_i].offset >= offset\n\t\t\t || s->sums[want_i].flags & SUMFLG_SAME_OFFSET)\n\t\t\t && sum == s->sums[want_i].sum1\n\t\t\t && memcmp(sum2, s->sums[want_i].sum2, s->s2length) == 0) {\n\t\t\t\t/* we've found an adjacent match - the RLL coder\n\t\t\t\t * will be happy */\n\t\t\t\ti = want_i;\n\t\t\t}\n\t\t\twant_i = i + 1;\n\n\t\t\tmatched(f,s,buf,offset,i);\n\t\t\toffset += s->sums[i].len - 1;\n\t\t\tk = (int32)MIN((OFF_T)s->blength, len-offset);\n\t\t\tmap = (schar *)map_ptr(buf, offset, k);\n\t\t\tsum = get_checksum1((char *)map, k);\n\t\t\ts1 = sum & 0xFFFF;\n\t\t\ts2 = sum >> 16;\n\t\t\tmatches++;\n\t\t\tbreak;\n\t\t} while ((i = s->sums[i].chain) >= 0);\n\n\t null_hash:\n\t\tbackup = (int32)(offset - last_match);\n\t\t/* We sometimes read 1 byte prior to last_match... */\n\t\tif (backup < 0)\n\t\t\tbackup = 0;\n\n\t\t/* Trim off the first byte from the checksum */\n\t\tmore = offset + k < len;\n\t\tmap = (schar *)map_ptr(buf, offset - backup, k + more + backup)\n\t\t + backup;\n\t\ts1 -= map[0] + CHAR_OFFSET;\n\t\ts2 -= k * (map[0]+CHAR_OFFSET);\n\n\t\t/* Add on the next byte (if there is one) to the checksum */\n\t\tif (more) {\n\t\t\ts1 += map[k] + CHAR_OFFSET;\n\t\t\ts2 += s1;\n\t\t} else\n\t\t\t--k;\n\n\t\t/* By matching early we avoid re-reading the\n\t\t data 3 times in the case where a token\n\t\t match comes a long way after last\n\t\t match. The 3 reads are caused by the\n\t\t running match, the checksum update and the\n\t\t literal send. */\n\t\tif (backup >= s->blength+CHUNK_SIZE && end-offset > CHUNK_SIZE)\n\t\t\tmatched(f, s, buf, offset - s->blength, -2);\n\t} while (++offset < end);\n\n\tmatched(f, s, buf, len, -1);\n\tmap_ptr(buf, len-1, 1);\n}", "project": "rsync", "hash": 282231606510893388476838486510622012833, "size": 173, "commit_id": "c8255147b06b74dad940d32f9cef5fbe17595239", "message": "Optimize finding the sum that matches our --inplace position.", "target": 0, "dataset": "other", "idx": 248548} {"func": "static void SpatialMaxPoolWithArgMaxHelper(\n OpKernelContext* context, Tensor* output, Tensor* output_arg_max,\n Tensor* input_backprop, const Tensor& tensor_in, const Tensor& out_backprop,\n const PoolParameters& params, const bool include_batch_in_index) {\n if (input_backprop != nullptr) {\n OP_REQUIRES(\n context, include_batch_in_index,\n errors::Internal(\n \"SpatialMaxPoolWithArgMaxHelper requires include_batch_in_index \"\n \"to be True when input_backprop != nullptr\"));\n OP_REQUIRES(\n context, (std::is_same::value),\n errors::Internal(\"SpatialMaxPoolWithArgMaxHelper requires Targmax \"\n \"to be int64 when input_backprop != nullptr\"));\n }\n\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenMatrixMap;\n typedef Eigen::Map>\n EigenIndexMatrixMap;\n\n ConstEigenMatrixMap in_mat(\n tensor_in.flat().data(), params.depth,\n params.tensor_in_cols * params.tensor_in_rows * params.tensor_in_batch);\n EigenMatrixMap out_mat(\n output->flat().data(), params.depth,\n params.out_width * params.out_height * params.tensor_in_batch);\n EigenIndexMatrixMap out_arg_max_mat(\n output_arg_max->flat().data(), params.depth,\n params.out_width * params.out_height * params.tensor_in_batch);\n\n const DeviceBase::CpuWorkerThreads& worker_threads =\n *(context->device()->tensorflow_cpu_worker_threads());\n\n // The following code basically does the following:\n // 1. Flattens the input and output tensors into two dimensional arrays.\n // tensor_in_as_matrix:\n // depth by (tensor_in_cols * tensor_in_rows * tensor_in_batch)\n // output_as_matrix:\n // depth by (out_width * out_height * tensor_in_batch)\n //\n // 2. Walks through the set of columns in the flattened tensor_in_as_matrix,\n // and updates the corresponding column(s) in output_as_matrix with the\n // max value.\n auto shard = [¶ms, &in_mat, &out_mat, &out_arg_max_mat, &input_backprop,\n &output_arg_max, &out_backprop,\n include_batch_in_index](int64 start, int64 limit) {\n const int32 depth = params.depth;\n const int32 in_rows = params.tensor_in_rows;\n const int32 in_cols = params.tensor_in_cols;\n const int32 pad_top = params.pad_top;\n const int32 pad_left = params.pad_left;\n const int32 window_rows = params.window_rows;\n const int32 window_cols = params.window_cols;\n const int32 row_stride = params.row_stride;\n const int32 col_stride = params.col_stride;\n const int32 out_height = params.out_height;\n const int32 out_width = params.out_width;\n\n {\n // Initializes the output tensor with MIN.\n const int32 output_image_size = out_height * out_width * depth;\n EigenMatrixMap out_shard(out_mat.data() + start * output_image_size, 1,\n (limit - start) * output_image_size);\n out_shard.setConstant(Eigen::NumTraits::lowest());\n EigenIndexMatrixMap out_arg_max_shard(\n out_arg_max_mat.data() + start * output_image_size, 1,\n (limit - start) * output_image_size);\n out_arg_max_shard.setConstant(kInvalidMaxPoolingIndex);\n }\n\n for (int64 b = start; b < limit; ++b) {\n for (int h = 0; h < in_rows; ++h) {\n for (int w = 0; w < in_cols; ++w) {\n // (h_start, h_end) * (w_start, w_end) is the range that the input\n // vector projects to.\n const int hpad = h + pad_top;\n const int wpad = w + pad_left;\n const int h_start =\n (hpad < window_rows) ? 0 : (hpad - window_rows) / row_stride + 1;\n const int h_end = std::min(hpad / row_stride + 1, out_height);\n const int w_start =\n (wpad < window_cols) ? 0 : (wpad - window_cols) / col_stride + 1;\n const int w_end = std::min(wpad / col_stride + 1, out_width);\n // compute elementwise max\n const int64 in_index = (b * in_rows + h) * in_cols + w;\n for (int ph = h_start; ph < h_end; ++ph) {\n const int64 out_index_base = (b * out_height + ph) * out_width;\n for (int pw = w_start; pw < w_end; ++pw) {\n const int64 out_index = out_index_base + pw;\n /// NOTES(zhengxq): not using the eigen matrix operation for\n /// now.\n for (int d = 0; d < depth; ++d) {\n const T& input_ref = in_mat.coeffRef(d, in_index);\n T& output_ref = out_mat.coeffRef(d, out_index);\n Targmax& out_arg_max_ref =\n out_arg_max_mat.coeffRef(d, out_index);\n if (output_ref < input_ref ||\n out_arg_max_ref == kInvalidMaxPoolingIndex) {\n output_ref = input_ref;\n if (include_batch_in_index) {\n out_arg_max_ref = in_index * depth + d;\n } else {\n out_arg_max_ref = (h * in_cols + w) * depth + d;\n }\n }\n }\n }\n }\n }\n }\n }\n\n if (input_backprop != nullptr) {\n auto input_backprop_flat = input_backprop->flat();\n auto out_arg_max_flat = output_arg_max->flat();\n auto out_backprop_flat = out_backprop.flat();\n\n // Initialize output to 0.\n const int64 in_size = in_rows * in_cols * depth;\n const int64 in_start = start * in_size;\n const int64 in_end = limit * in_size;\n EigenMatrixMap in_shard(input_backprop_flat.data() + in_start, 1,\n in_end - in_start);\n in_shard.setConstant(T(0));\n\n // Backpropagate.\n const int out_size = out_height * out_width * depth;\n const int out_start = start * out_size;\n const int out_end = limit * out_size;\n for (int index = out_start; index < out_end; ++index) {\n int input_backprop_index = out_arg_max_flat(index);\n // Although this check is in the inner loop, it is worth its value\n // so we don't end up with memory corruptions. Our benchmark shows that\n // the performance impact is quite small\n // CHECK(input_backprop_index >= in_start && input_backprop_index <\n // in_end)\n FastBoundsCheck(input_backprop_index - in_start, in_end - in_start);\n input_backprop_flat(input_backprop_index) += out_backprop_flat(index);\n }\n }\n };\n\n const int64 shard_cost = params.tensor_in_rows * params.tensor_in_cols *\n params.depth * params.window_rows *\n params.window_cols;\n Shard(worker_threads.num_threads, worker_threads.workers,\n params.tensor_in_batch, shard_cost, shard);\n}", "project": "tensorflow", "hash": 68179409679570044569453067278368921696, "size": 151, "commit_id": "a74768f8e4efbda4def9f16ee7e13cf3922ac5f7", "message": "Prevent heap OOB error in `MaxPoolGrad`\n\nPiperOrigin-RevId: 372424854\nChange-Id: Idac0f23867ad8b0601cafbaaa52d5e64269e63a7", "target": 1, "dataset": "other", "idx": 196935} {"func": "static void SpatialMaxPoolWithArgMaxHelper(\n OpKernelContext* context, Tensor* output, Tensor* output_arg_max,\n Tensor* input_backprop, const Tensor& tensor_in, const Tensor& out_backprop,\n const PoolParameters& params, const bool include_batch_in_index) {\n if (input_backprop != nullptr) {\n OP_REQUIRES(\n context, include_batch_in_index,\n errors::Internal(\n \"SpatialMaxPoolWithArgMaxHelper requires include_batch_in_index \"\n \"to be True when input_backprop != nullptr\"));\n OP_REQUIRES(\n context, (std::is_same::value),\n errors::Internal(\"SpatialMaxPoolWithArgMaxHelper requires Targmax \"\n \"to be int64 when input_backprop != nullptr\"));\n }\n\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenMatrixMap;\n typedef Eigen::Map>\n EigenIndexMatrixMap;\n\n ConstEigenMatrixMap in_mat(\n tensor_in.flat().data(), params.depth,\n params.tensor_in_cols * params.tensor_in_rows * params.tensor_in_batch);\n EigenMatrixMap out_mat(\n output->flat().data(), params.depth,\n params.out_width * params.out_height * params.tensor_in_batch);\n EigenIndexMatrixMap out_arg_max_mat(\n output_arg_max->flat().data(), params.depth,\n params.out_width * params.out_height * params.tensor_in_batch);\n\n const DeviceBase::CpuWorkerThreads& worker_threads =\n *(context->device()->tensorflow_cpu_worker_threads());\n\n // The following code basically does the following:\n // 1. Flattens the input and output tensors into two dimensional arrays.\n // tensor_in_as_matrix:\n // depth by (tensor_in_cols * tensor_in_rows * tensor_in_batch)\n // output_as_matrix:\n // depth by (out_width * out_height * tensor_in_batch)\n //\n // 2. Walks through the set of columns in the flattened tensor_in_as_matrix,\n // and updates the corresponding column(s) in output_as_matrix with the\n // max value.\n auto shard = [¶ms, &in_mat, &out_mat, &out_arg_max_mat, &input_backprop,\n &output_arg_max, &out_backprop,\n include_batch_in_index](int64 start, int64 limit) {\n const int32 depth = params.depth;\n const int32 in_rows = params.tensor_in_rows;\n const int32 in_cols = params.tensor_in_cols;\n const int32 pad_top = params.pad_top;\n const int32 pad_left = params.pad_left;\n const int32 window_rows = params.window_rows;\n const int32 window_cols = params.window_cols;\n const int32 row_stride = params.row_stride;\n const int32 col_stride = params.col_stride;\n const int32 out_height = params.out_height;\n const int32 out_width = params.out_width;\n\n {\n // Initializes the output tensor with MIN.\n const int32 output_image_size = out_height * out_width * depth;\n EigenMatrixMap out_shard(out_mat.data() + start * output_image_size, 1,\n (limit - start) * output_image_size);\n out_shard.setConstant(Eigen::NumTraits::lowest());\n EigenIndexMatrixMap out_arg_max_shard(\n out_arg_max_mat.data() + start * output_image_size, 1,\n (limit - start) * output_image_size);\n out_arg_max_shard.setConstant(kInvalidMaxPoolingIndex);\n }\n\n for (int64 b = start; b < limit; ++b) {\n for (int h = 0; h < in_rows; ++h) {\n for (int w = 0; w < in_cols; ++w) {\n // (h_start, h_end) * (w_start, w_end) is the range that the input\n // vector projects to.\n const int hpad = h + pad_top;\n const int wpad = w + pad_left;\n const int h_start =\n (hpad < window_rows) ? 0 : (hpad - window_rows) / row_stride + 1;\n const int h_end = std::min(hpad / row_stride + 1, out_height);\n const int w_start =\n (wpad < window_cols) ? 0 : (wpad - window_cols) / col_stride + 1;\n const int w_end = std::min(wpad / col_stride + 1, out_width);\n // compute elementwise max\n const int64 in_index = (b * in_rows + h) * in_cols + w;\n for (int ph = h_start; ph < h_end; ++ph) {\n const int64 out_index_base = (b * out_height + ph) * out_width;\n for (int pw = w_start; pw < w_end; ++pw) {\n const int64 out_index = out_index_base + pw;\n /// NOTES(zhengxq): not using the eigen matrix operation for\n /// now.\n for (int d = 0; d < depth; ++d) {\n const T& input_ref = in_mat.coeffRef(d, in_index);\n T& output_ref = out_mat.coeffRef(d, out_index);\n Targmax& out_arg_max_ref =\n out_arg_max_mat.coeffRef(d, out_index);\n if (output_ref < input_ref ||\n out_arg_max_ref == kInvalidMaxPoolingIndex) {\n output_ref = input_ref;\n if (include_batch_in_index) {\n out_arg_max_ref = in_index * depth + d;\n } else {\n out_arg_max_ref = (h * in_cols + w) * depth + d;\n }\n }\n }\n }\n }\n }\n }\n }\n\n if (input_backprop != nullptr) {\n auto input_backprop_flat = input_backprop->flat();\n auto out_arg_max_flat = output_arg_max->flat();\n auto out_backprop_flat = out_backprop.flat();\n\n // Initialize output to 0.\n const int64 in_size = in_rows * in_cols * depth;\n const int64 in_start = start * in_size;\n const int64 in_end = limit * in_size;\n EigenMatrixMap in_shard(input_backprop_flat.data() + in_start, 1,\n in_end - in_start);\n in_shard.setConstant(T(0));\n\n // Backpropagate.\n const int out_size = out_height * out_width * depth;\n const int out_start = start * out_size;\n const int out_end = limit * out_size;\n for (int index = out_start; index < out_end; ++index) {\n int input_backprop_index = out_arg_max_flat(index);\n // Although this check is in the inner loop, it is worth its value\n // so we don't end up with memory corruptions. Our benchmark shows that\n // the performance impact is quite small\n // CHECK(input_backprop_index >= in_start && input_backprop_index <\n // in_end)\n FastBoundsCheck(input_backprop_index - in_start, in_end - in_start);\n if (index < out_backprop.NumElements()) {\n input_backprop_flat(input_backprop_index) += out_backprop_flat(index);\n }\n }\n }\n };\n\n const int64 shard_cost = params.tensor_in_rows * params.tensor_in_cols *\n params.depth * params.window_rows *\n params.window_cols;\n Shard(worker_threads.num_threads, worker_threads.workers,\n params.tensor_in_batch, shard_cost, shard);\n}", "project": "tensorflow", "hash": 19671573270094211449128076626686963676, "size": 153, "commit_id": "a74768f8e4efbda4def9f16ee7e13cf3922ac5f7", "message": "Prevent heap OOB error in `MaxPoolGrad`\n\nPiperOrigin-RevId: 372424854\nChange-Id: Idac0f23867ad8b0601cafbaaa52d5e64269e63a7", "target": 0, "dataset": "other", "idx": 248727} {"func": "extern \"C\" int64_t enc_untrusted_syscall(int sysno, ...) {\n if (!enc_is_error_handler_set()) {\n enc_set_error_handler(default_error_handler);\n }\n\n asylo::system_call::SystemCallDescriptor descriptor{sysno};\n if (!descriptor.is_valid()) {\n error_handler(\"system_call.cc: Invalid SystemCallDescriptor encountered.\");\n }\n\n // Collect the passed parameter list into an array.\n std::array parameters;\n va_list args;\n va_start(args, sysno);\n for (int i = 0; i < descriptor.parameter_count(); i++) {\n parameters[i] = va_arg(args, uint64_t);\n }\n va_end(args);\n\n // Allocate a buffer for the serialized request.\n asylo::primitives::Extent request;\n asylo::primitives::PrimitiveStatus status;\n status = asylo::system_call::SerializeRequest(sysno, parameters, &request);\n if (!status.ok()) {\n error_handler(\n \"system_call.cc: Encountered serialization error when serializing \"\n \"syscall parameters.\");\n }\n\n std::unique_ptr request_owner(request.As());\n\n // Invoke the system call dispatch callback to execute the system call.\n uint8_t *response_buffer;\n size_t response_size;\n\n if (!enc_is_syscall_dispatcher_set()) {\n error_handler(\"system_.cc: system call dispatcher not set.\");\n }\n status = global_syscall_callback(request.As(), request.size(),\n &response_buffer, &response_size);\n if (!status.ok()) {\n error_handler(\n \"system_call.cc: Callback from syscall dispatcher was unsuccessful.\");\n }\n\n std::unique_ptr response_owner(response_buffer);\n\n if (!response_buffer) {\n error_handler(\n \"system_call.cc: null response buffer received for the syscall.\");\n }\n\n // Copy outputs back into pointer parameters.\n auto response_reader =\n asylo::system_call::MessageReader({response_buffer, response_size});\n const asylo::primitives::PrimitiveStatus response_status =\n response_reader.Validate();\n if (!response_status.ok()) {\n error_handler(\n \"system_call.cc: Error deserializing response buffer into response \"\n \"reader.\");\n }\n\n for (int i = 0; i < asylo::system_call::kParameterMax; i++) {\n asylo::system_call::ParameterDescriptor parameter = descriptor.parameter(i);\n if (parameter.is_out()) {\n size_t size;\n if (parameter.is_fixed()) {\n size = parameter.size();\n } else {\n size = parameters[parameter.size()] * parameter.element_size();\n }\n const void *src = response_reader.parameter_address(i);\n void *dst = reinterpret_cast(parameters[i]);\n if (dst != nullptr) {\n memcpy(dst, src, size);\n }\n }\n }\n\n uint64_t result = response_reader.header()->result;\n if (static_cast(result) == -1) {\n int klinux_errno = response_reader.header()->error_number;\n\n // Simply having a return value of -1 from a syscall is not a necessary\n // condition that the syscall failed. Some syscalls can return -1 when\n // successful (eg., lseek). The reliable way to check for syscall failure is\n // to therefore check both return value and presence of a non-zero errno.\n if (klinux_errno != 0) {\n errno = FromkLinuxErrno(klinux_errno);\n }\n }\n return result;\n}", "project": "asylo", "hash": 130310869398981487889556909042186639572, "size": 94, "commit_id": "90d7619e9dd99bcdb6cd28c7649d741d254d9a1a", "message": "Add sysno check in MessageReader\n\nThe sysno in MessageReader is interpreted from the Message header passed\nfrom the host. A malicious Message header may provide a modified sysno\nto bypass the validation, and overwrites enclave memory. This change\nadds a check for sysno to make sure it matches the expected value.\n\nThis issue was reported by Qinkun Bao, Zhaofeng Chen, Mingshen Sun, and\nKang Li from Baidu Security.\n\nPiperOrigin-RevId: 377328054\nChange-Id: I3ff6f60694d3390f66da89d139cf7cc7b49abaea", "target": 1, "dataset": "other", "idx": 196939} {"func": "extern \"C\" int64_t enc_untrusted_syscall(int sysno, ...) {\n if (!enc_is_error_handler_set()) {\n enc_set_error_handler(default_error_handler);\n }\n\n asylo::system_call::SystemCallDescriptor descriptor{sysno};\n if (!descriptor.is_valid()) {\n error_handler(\"system_call.cc: Invalid SystemCallDescriptor encountered.\");\n }\n\n // Collect the passed parameter list into an array.\n std::array parameters;\n va_list args;\n va_start(args, sysno);\n for (int i = 0; i < descriptor.parameter_count(); i++) {\n parameters[i] = va_arg(args, uint64_t);\n }\n va_end(args);\n\n // Allocate a buffer for the serialized request.\n asylo::primitives::Extent request;\n asylo::primitives::PrimitiveStatus status;\n status = asylo::system_call::SerializeRequest(sysno, parameters, &request);\n if (!status.ok()) {\n error_handler(\n \"system_call.cc: Encountered serialization error when serializing \"\n \"syscall parameters.\");\n }\n\n std::unique_ptr request_owner(request.As());\n\n // Invoke the system call dispatch callback to execute the system call.\n uint8_t *response_buffer;\n size_t response_size;\n\n if (!enc_is_syscall_dispatcher_set()) {\n error_handler(\"system_.cc: system call dispatcher not set.\");\n }\n status = global_syscall_callback(request.As(), request.size(),\n &response_buffer, &response_size);\n if (!status.ok()) {\n error_handler(\n \"system_call.cc: Callback from syscall dispatcher was unsuccessful.\");\n }\n\n std::unique_ptr response_owner(response_buffer);\n\n if (!response_buffer) {\n error_handler(\n \"system_call.cc: null response buffer received for the syscall.\");\n }\n\n // Copy outputs back into pointer parameters.\n auto response_reader =\n asylo::system_call::MessageReader({response_buffer, response_size});\n if (response_reader.sysno() != sysno) {\n error_handler(\"system_call.cc: Unexpected sysno in response\");\n }\n const asylo::primitives::PrimitiveStatus response_status =\n response_reader.Validate();\n if (!response_status.ok()) {\n error_handler(\n \"system_call.cc: Error deserializing response buffer into response \"\n \"reader.\");\n }\n\n for (int i = 0; i < asylo::system_call::kParameterMax; i++) {\n asylo::system_call::ParameterDescriptor parameter = descriptor.parameter(i);\n if (parameter.is_out()) {\n size_t size;\n if (parameter.is_fixed()) {\n size = parameter.size();\n } else {\n size = parameters[parameter.size()] * parameter.element_size();\n }\n const void *src = response_reader.parameter_address(i);\n void *dst = reinterpret_cast(parameters[i]);\n if (dst != nullptr) {\n memcpy(dst, src, size);\n }\n }\n }\n\n uint64_t result = response_reader.header()->result;\n if (static_cast(result) == -1) {\n int klinux_errno = response_reader.header()->error_number;\n\n // Simply having a return value of -1 from a syscall is not a necessary\n // condition that the syscall failed. Some syscalls can return -1 when\n // successful (eg., lseek). The reliable way to check for syscall failure is\n // to therefore check both return value and presence of a non-zero errno.\n if (klinux_errno != 0) {\n errno = FromkLinuxErrno(klinux_errno);\n }\n }\n return result;\n}", "project": "asylo", "hash": 301481568949052192969768700409775374312, "size": 97, "commit_id": "90d7619e9dd99bcdb6cd28c7649d741d254d9a1a", "message": "Add sysno check in MessageReader\n\nThe sysno in MessageReader is interpreted from the Message header passed\nfrom the host. A malicious Message header may provide a modified sysno\nto bypass the validation, and overwrites enclave memory. This change\nadds a check for sysno to make sure it matches the expected value.\n\nThis issue was reported by Qinkun Bao, Zhaofeng Chen, Mingshen Sun, and\nKang Li from Baidu Security.\n\nPiperOrigin-RevId: 377328054\nChange-Id: I3ff6f60694d3390f66da89d139cf7cc7b49abaea", "target": 0, "dataset": "other", "idx": 248772} {"func": "parseNormalModeParameters(IsoPresentation* self, uint8_t* buffer, int totalLength, int bufPos)\n{\n int endPos = bufPos + totalLength;\n\n self->calledPresentationSelector.size = 0;\n self->callingPresentationSelector.size = 0;\n\n bool hasUserData = false;\n\n while (bufPos < endPos) {\n uint8_t tag = buffer[bufPos++];\n int len;\n\n if (bufPos == endPos) {\n if (DEBUG_PRES)\n printf(\"PRES: invalid message\\n\");\n return -1;\n }\n\n bufPos = BerDecoder_decodeLength(buffer, &len, bufPos, endPos);\n\n if (bufPos < 0) {\n if (DEBUG_PRES)\n printf(\"PRES: wrong parameter length\\n\");\n return -1;\n }\n\n switch (tag) {\n case 0x81: /* calling-presentation-selector */\n\n if (len > 16) {\n if (DEBUG_PRES)\n printf(\"PRES: calling-presentation-sel too large\\n\");\n }\n else {\n self->callingPresentationSelector.size = len;\n int i;\n for (i = 0; i < len; i++)\n self->callingPresentationSelector.value[i] = buffer[bufPos + i];\n }\n\n bufPos += len;\n break;\n\n case 0x82: /* called-presentation-selector */\n\n if (len > 16) {\n if (DEBUG_PRES)\n printf(\"PRES: called-presentation-sel too large\\n\");\n }\n else {\n self->calledPresentationSelector.size = len;\n int i;\n for (i = 0; i < len; i++)\n self->calledPresentationSelector.value[i] = buffer[bufPos + i];\n }\n\n bufPos += len;\n break;\n\n case 0x83: /* responding-presentation-selector */\n\n if (len > 16) {\n if (DEBUG_PRES)\n printf(\"PRES: responding-presentation-sel too large\\n\");\n }\n\n bufPos += len;\n break;\n\n case 0xa4: /* presentation-context-definition list */\n if (DEBUG_PRES)\n printf(\"PRES: pcd list\\n\");\n bufPos = parsePresentationContextDefinitionList(self, buffer, len, bufPos);\n break;\n\n case 0xa5: /* context-definition-result-list */\n\n bufPos += len;\n break;\n\n case 0x61: /* user data */\n if (DEBUG_PRES)\n printf(\"PRES: user-data\\n\");\n\n bufPos = parseFullyEncodedData(self, buffer, len, bufPos);\n\n if (bufPos < 0)\n return -1;\n\n if (self->nextPayload.size > 0)\n hasUserData = true;\n\n break;\n\n case 0x00: /* indefinite length end tag -> ignore */\n break;\n\n default:\n if (DEBUG_PRES)\n printf(\"PRES: unknown tag in normal-mode\\n\");\n bufPos += len;\n break;\n }\n }\n\n if (hasUserData == false) {\n if (DEBUG_PRES)\n printf(\"PRES: user-data is missing\\n\");\n\n return -1;\n }\n\n return bufPos;\n}", "project": "libiec61850", "hash": 331339374126968299932527563528983733700, "size": 115, "commit_id": "cfa94cbf10302bedc779703f874ee2e8387a0721", "message": "- fixed - Bug in presentation layer parser can cause infinite loop (LIB61850-302)", "target": 1, "dataset": "other", "idx": 196991} {"func": "parseNormalModeParameters(IsoPresentation* self, uint8_t* buffer, int totalLength, int bufPos)\n{\n int endPos = bufPos + totalLength;\n\n self->calledPresentationSelector.size = 0;\n self->callingPresentationSelector.size = 0;\n\n bool hasUserData = false;\n\n while (bufPos < endPos) {\n uint8_t tag = buffer[bufPos++];\n int len;\n\n if (bufPos == endPos) {\n if (DEBUG_PRES)\n printf(\"PRES: invalid message\\n\");\n return -1;\n }\n\n bufPos = BerDecoder_decodeLength(buffer, &len, bufPos, endPos);\n\n if (bufPos < 0) {\n if (DEBUG_PRES)\n printf(\"PRES: wrong parameter length\\n\");\n return -1;\n }\n\n switch (tag) {\n case 0x81: /* calling-presentation-selector */\n\n if (len > 16) {\n if (DEBUG_PRES)\n printf(\"PRES: calling-presentation-sel too large\\n\");\n }\n else {\n self->callingPresentationSelector.size = len;\n int i;\n for (i = 0; i < len; i++)\n self->callingPresentationSelector.value[i] = buffer[bufPos + i];\n }\n\n bufPos += len;\n break;\n\n case 0x82: /* called-presentation-selector */\n\n if (len > 16) {\n if (DEBUG_PRES)\n printf(\"PRES: called-presentation-sel too large\\n\");\n }\n else {\n self->calledPresentationSelector.size = len;\n int i;\n for (i = 0; i < len; i++)\n self->calledPresentationSelector.value[i] = buffer[bufPos + i];\n }\n\n bufPos += len;\n break;\n\n case 0x83: /* responding-presentation-selector */\n\n if (len > 16) {\n if (DEBUG_PRES)\n printf(\"PRES: responding-presentation-sel too large\\n\");\n }\n\n bufPos += len;\n break;\n\n case 0xa4: /* presentation-context-definition list */\n if (DEBUG_PRES)\n printf(\"PRES: pcd list\\n\");\n bufPos = parsePresentationContextDefinitionList(self, buffer, len, bufPos);\n\n if (bufPos < 0)\n return -1;\n\n break;\n\n case 0xa5: /* context-definition-result-list */\n\n bufPos += len;\n break;\n\n case 0x61: /* user data */\n if (DEBUG_PRES)\n printf(\"PRES: user-data\\n\");\n\n bufPos = parseFullyEncodedData(self, buffer, len, bufPos);\n\n if (bufPos < 0)\n return -1;\n\n if (self->nextPayload.size > 0)\n hasUserData = true;\n\n break;\n\n case 0x00: /* indefinite length end tag -> ignore */\n break;\n\n default:\n if (DEBUG_PRES)\n printf(\"PRES: unknown tag in normal-mode\\n\");\n bufPos += len;\n break;\n }\n }\n\n if (hasUserData == false) {\n if (DEBUG_PRES)\n printf(\"PRES: user-data is missing\\n\");\n\n return -1;\n }\n\n return bufPos;\n}", "project": "libiec61850", "hash": 100266899328047651441631665278404681002, "size": 119, "commit_id": "cfa94cbf10302bedc779703f874ee2e8387a0721", "message": "- fixed - Bug in presentation layer parser can cause infinite loop (LIB61850-302)", "target": 0, "dataset": "other", "idx": 249484} {"func": "#ifndef GPAC_DISABLE_ISOM_HINTING\n\nvoid dump_isom_sdp(GF_ISOFile *file, char *inName, Bool is_final_name)\n{\n\tconst char *sdp;\n\tu32 size, i;\n\tFILE *dump;\n\n\tif (inName) {\n\t\tchar szBuf[1024];\n\t\tstrcpy(szBuf, inName);\n\t\tif (!is_final_name) {\n\t\t\tchar *ext = strchr(szBuf, '.');\n\t\t\tif (ext) ext[0] = 0;\n\t\t\tstrcat(szBuf, \"_sdp.txt\");\n\t\t}\n\t\tdump = gf_fopen(szBuf, \"wt\");\n\t\tif (!dump) {\n\t\t\tfprintf(stderr, \"Failed to open %s for dumping\\n\", szBuf);\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tdump = stdout;\n\t\tfprintf(dump, \"* File SDP content *\\n\\n\");\n\t}\n\t//get the movie SDP\n\tgf_isom_sdp_get(file, &sdp, &size);\n\tfprintf(dump, \"%s\", sdp);\n\tfprintf(dump, \"\\r\\n\");\n\n\t//then tracks\n\tfor (i=0; ihttp_version == HTTP_VERSION_2) return NULL;*/\n /*(However, new connections over TLS may become HTTP/2 connections via ALPN\n * and return from this routine with r->http_version == HTTP_VERSION_2) */\n\n if ((NULL == c || NULL == c->next) && con->is_readable > 0) {\n con->read_idle_ts = log_epoch_secs;\n if (0 != con->network_read(con, cq, MAX_READ_LIMIT)) {\n request_st * const r = &con->request;\n connection_set_state_error(r, CON_STATE_ERROR);\n }\n /* check if switched to HTTP/2 (ALPN \"h2\" during TLS negotiation) */\n request_st * const r = &con->request;\n if (r->http_version == HTTP_VERSION_2) return NULL;\n }\n\n if (cq->first != cq->last && 0 != olen) {\n const size_t clen = chunkqueue_length(cq);\n size_t block = (olen + (16384-1)) & (16384-1);\n block += (block - olen > 1024 ? 0 : 16384);\n chunkqueue_compact_mem(cq, block > clen ? clen : block);\n }\n\n /* detect if data is added to chunk */\n c = cq->first;\n return (c && (size_t)c->offset + olen < buffer_string_length(c->mem))\n ? c\n : NULL;\n}", "project": "lighttpd1.4", "hash": 58630683850731888391551309485472068258, "size": 30, "commit_id": "b03b86f47b0d5a553137f081fadc482b4af1372d", "message": "[core] fix merging large headers across mult reads (fixes #3059)\n\n(thx mitd)\n\nx-ref:\n \"Connections stuck in Close_Wait causing 100% cpu usage\"\n https://redmine.lighttpd.net/issues/3059", "target": 1, "dataset": "other", "idx": 197066} {"func": "static chunk * connection_read_header_more(connection *con, chunkqueue *cq, chunk *c, const size_t olen) {\n /*(should not be reached by HTTP/2 streams)*/\n /*if (r->http_version == HTTP_VERSION_2) return NULL;*/\n /*(However, new connections over TLS may become HTTP/2 connections via ALPN\n * and return from this routine with r->http_version == HTTP_VERSION_2) */\n\n if ((NULL == c || NULL == c->next) && con->is_readable > 0) {\n con->read_idle_ts = log_epoch_secs;\n if (0 != con->network_read(con, cq, MAX_READ_LIMIT)) {\n request_st * const r = &con->request;\n connection_set_state_error(r, CON_STATE_ERROR);\n }\n /* check if switched to HTTP/2 (ALPN \"h2\" during TLS negotiation) */\n request_st * const r = &con->request;\n if (r->http_version == HTTP_VERSION_2) return NULL;\n }\n\n if (cq->first != cq->last && 0 != olen) {\n const size_t clen = chunkqueue_length(cq);\n size_t block = (olen + (16384-1)) & ~(16384-1);\n block += (block - olen > 1024 ? 0 : 16384);\n chunkqueue_compact_mem(cq, block > clen ? clen : block);\n }\n\n /* detect if data is added to chunk */\n c = cq->first;\n return (c && (size_t)c->offset + olen < buffer_string_length(c->mem))\n ? c\n : NULL;\n}", "project": "lighttpd1.4", "hash": 161459326522428992863096627223237510818, "size": 30, "commit_id": "b03b86f47b0d5a553137f081fadc482b4af1372d", "message": "[core] fix merging large headers across mult reads (fixes #3059)\n\n(thx mitd)\n\nx-ref:\n \"Connections stuck in Close_Wait causing 100% cpu usage\"\n https://redmine.lighttpd.net/issues/3059", "target": 0, "dataset": "other", "idx": 251461} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& shape_tensor = ctx->input(0);\n const Tensor& means_tensor = ctx->input(1);\n const Tensor& stddevs_tensor = ctx->input(2);\n const Tensor& minvals_tensor = ctx->input(3);\n const Tensor& maxvals_tensor = ctx->input(4);\n\n OP_REQUIRES(\n ctx, TensorShapeUtils::IsVector(shape_tensor.shape()),\n errors::InvalidArgument(\"Input shape should be a vector, got shape: \",\n shape_tensor.shape().DebugString()));\n int32 num_batches = shape_tensor.flat()(0);\n\n int32 samples_per_batch = 1;\n const int32 num_dims = shape_tensor.dim_size(0);\n for (int32 i = 1; i < num_dims; i++) {\n samples_per_batch *= shape_tensor.flat()(i);\n }\n const int32 num_elements = num_batches * samples_per_batch;\n\n // Allocate the output before fudging num_batches and samples_per_batch.\n auto shape_vec = shape_tensor.flat();\n TensorShape tensor_shape;\n OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(\n shape_vec.data(), shape_vec.size(), &tensor_shape));\n Tensor* samples_tensor;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, tensor_shape, &samples_tensor));\n\n // Parameters must be 0-d or 1-d.\n OP_REQUIRES(ctx, means_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input means should be a scalar or vector, got shape: \",\n means_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, stddevs_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input stddevs should be a scalar or vector, got shape: \",\n stddevs_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, minvals_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input minvals should be a scalar or vector, got shape: \",\n minvals_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, maxvals_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input maxvals should be a scalar or vector, got shape: \",\n maxvals_tensor.shape().DebugString()));\n\n if ((means_tensor.dims() == 0 || means_tensor.dim_size(0) == 1) &&\n (stddevs_tensor.dims() == 0 || stddevs_tensor.dim_size(0) == 1) &&\n minvals_tensor.dims() == 0 && maxvals_tensor.dims() == 0) {\n // All batches have the same parameters, so we can update the batch size\n // to a reasonable value to improve parallelism (ensure enough batches,\n // and no very small batches which have high overhead).\n int32 size = num_batches * samples_per_batch;\n int32 adjusted_samples = kDesiredBatchSize;\n // Ensure adjusted_batches * adjusted_samples >= size.\n int32 adjusted_batches = Eigen::divup(size, adjusted_samples);\n num_batches = adjusted_batches;\n samples_per_batch = adjusted_samples;\n } else {\n // Parameters must be broadcastable to the shape [num_batches].\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(means_tensor.shape()) ||\n means_tensor.dim_size(0) == 1 ||\n means_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input means should have length 1 or shape[0], got shape: \",\n means_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(stddevs_tensor.shape()) ||\n stddevs_tensor.dim_size(0) == 1 ||\n stddevs_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input stddevs should have length 1 or shape[0], got shape: \",\n stddevs_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(minvals_tensor.shape()) ||\n minvals_tensor.dim_size(0) == 1 ||\n minvals_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input minvals should have length 1 or shape[0], got shape: \",\n minvals_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(maxvals_tensor.shape()) ||\n maxvals_tensor.dim_size(0) == 1 ||\n maxvals_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input maxvals should have length 1 or shape[0], got shape: \",\n maxvals_tensor.shape().DebugString()));\n }\n\n auto truncFunctor = functor::TruncatedNormalFunctor();\n // Each worker has the fudge factor for samples_per_batch, so use it here.\n random::PhiloxRandom rng =\n generator_.ReserveSamples128(num_batches * 2 * functor::kMaxIterations *\n (samples_per_batch + 3) / 4);\n truncFunctor(ctx, ctx->eigen_device(), num_batches,\n samples_per_batch, num_elements, means_tensor.flat(),\n stddevs_tensor.flat(), minvals_tensor.flat(),\n maxvals_tensor.flat(), rng, samples_tensor->flat());\n }", "project": "tensorflow", "hash": 148108695542733870828908833256506778307, "size": 104, "commit_id": "5e52ef5a461570cfb68f3bdbbebfe972cb4e0fd8", "message": "Fix breakage in parameterized_truncated_normal_op.cc\n\nPiperOrigin-RevId: 372041718\nChange-Id: Iff79e77a2bb27032423eefcb84211627b27dfe81", "target": 1, "dataset": "other", "idx": 197084} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& shape_tensor = ctx->input(0);\n const Tensor& means_tensor = ctx->input(1);\n const Tensor& stddevs_tensor = ctx->input(2);\n const Tensor& minvals_tensor = ctx->input(3);\n const Tensor& maxvals_tensor = ctx->input(4);\n\n OP_REQUIRES(\n ctx, TensorShapeUtils::IsVector(shape_tensor.shape()),\n errors::InvalidArgument(\"Input shape should be a vector, got shape: \",\n shape_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, shape_tensor.NumElements() > 0,\n errors::InvalidArgument(\"Shape tensor must not be empty, got \",\n shape_tensor.DebugString()));\n int32 num_batches = shape_tensor.flat()(0);\n\n int32 samples_per_batch = 1;\n const int32 num_dims = shape_tensor.dim_size(0);\n for (int32 i = 1; i < num_dims; i++) {\n samples_per_batch *= shape_tensor.flat()(i);\n }\n const int32 num_elements = num_batches * samples_per_batch;\n\n // Allocate the output before fudging num_batches and samples_per_batch.\n auto shape_vec = shape_tensor.flat();\n TensorShape tensor_shape;\n OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(\n shape_vec.data(), shape_vec.size(), &tensor_shape));\n Tensor* samples_tensor;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, tensor_shape, &samples_tensor));\n\n // Parameters must be 0-d or 1-d.\n OP_REQUIRES(ctx, means_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input means should be a scalar or vector, got shape: \",\n means_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, stddevs_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input stddevs should be a scalar or vector, got shape: \",\n stddevs_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, minvals_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input minvals should be a scalar or vector, got shape: \",\n minvals_tensor.shape().DebugString()));\n OP_REQUIRES(ctx, maxvals_tensor.dims() <= 1,\n errors::InvalidArgument(\n \"Input maxvals should be a scalar or vector, got shape: \",\n maxvals_tensor.shape().DebugString()));\n\n if ((means_tensor.dims() == 0 || means_tensor.dim_size(0) == 1) &&\n (stddevs_tensor.dims() == 0 || stddevs_tensor.dim_size(0) == 1) &&\n minvals_tensor.dims() == 0 && maxvals_tensor.dims() == 0) {\n // All batches have the same parameters, so we can update the batch size\n // to a reasonable value to improve parallelism (ensure enough batches,\n // and no very small batches which have high overhead).\n int32 size = num_batches * samples_per_batch;\n int32 adjusted_samples = kDesiredBatchSize;\n // Ensure adjusted_batches * adjusted_samples >= size.\n int32 adjusted_batches = Eigen::divup(size, adjusted_samples);\n num_batches = adjusted_batches;\n samples_per_batch = adjusted_samples;\n } else {\n // Parameters must be broadcastable to the shape [num_batches].\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(means_tensor.shape()) ||\n means_tensor.dim_size(0) == 1 ||\n means_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input means should have length 1 or shape[0], got shape: \",\n means_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(stddevs_tensor.shape()) ||\n stddevs_tensor.dim_size(0) == 1 ||\n stddevs_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input stddevs should have length 1 or shape[0], got shape: \",\n stddevs_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(minvals_tensor.shape()) ||\n minvals_tensor.dim_size(0) == 1 ||\n minvals_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input minvals should have length 1 or shape[0], got shape: \",\n minvals_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx,\n TensorShapeUtils::IsScalar(maxvals_tensor.shape()) ||\n maxvals_tensor.dim_size(0) == 1 ||\n maxvals_tensor.dim_size(0) == num_batches,\n errors::InvalidArgument(\n \"Input maxvals should have length 1 or shape[0], got shape: \",\n maxvals_tensor.shape().DebugString()));\n }\n\n auto truncFunctor = functor::TruncatedNormalFunctor();\n // Each worker has the fudge factor for samples_per_batch, so use it here.\n random::PhiloxRandom rng =\n generator_.ReserveSamples128(num_batches * 2 * functor::kMaxIterations *\n (samples_per_batch + 3) / 4);\n truncFunctor(ctx, ctx->eigen_device(), num_batches,\n samples_per_batch, num_elements, means_tensor.flat(),\n stddevs_tensor.flat(), minvals_tensor.flat(),\n maxvals_tensor.flat(), rng, samples_tensor->flat());\n }", "project": "tensorflow", "hash": 320463600272774049798784249056358162496, "size": 107, "commit_id": "5e52ef5a461570cfb68f3bdbbebfe972cb4e0fd8", "message": "Fix breakage in parameterized_truncated_normal_op.cc\n\nPiperOrigin-RevId: 372041718\nChange-Id: Iff79e77a2bb27032423eefcb84211627b27dfe81", "target": 0, "dataset": "other", "idx": 251872} {"func": "static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)\n{\n#ifndef PB_ENABLE_MALLOC\n PB_UNUSED(wire_type);\n PB_UNUSED(iter);\n PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n pb_type_t type;\n pb_decoder_t func;\n \n type = iter->pos->type;\n func = PB_DECODERS[PB_LTYPE(type)];\n \n switch (PB_HTYPE(type))\n {\n case PB_HTYPE_REQUIRED:\n case PB_HTYPE_OPTIONAL:\n case PB_HTYPE_ONEOF:\n if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&\n *(void**)iter->pData != NULL)\n {\n /* Duplicate field, have to release the old allocation first. */\n pb_release_single_field(iter);\n }\n \n if (PB_HTYPE(type) == PB_HTYPE_ONEOF)\n {\n *(pb_size_t*)iter->pSize = iter->pos->tag;\n }\n\n if (PB_LTYPE(type) == PB_LTYPE_STRING ||\n PB_LTYPE(type) == PB_LTYPE_BYTES)\n {\n return func(stream, iter->pos, iter->pData);\n }\n else\n {\n if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))\n return false;\n \n initialize_pointer_field(*(void**)iter->pData, iter);\n return func(stream, iter->pos, *(void**)iter->pData);\n }\n \n case PB_HTYPE_REPEATED:\n if (wire_type == PB_WT_STRING\n && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)\n {\n /* Packed array, multiple items come in at once. */\n bool status = true;\n pb_size_t *size = (pb_size_t*)iter->pSize;\n size_t allocated_size = *size;\n void *pItem;\n pb_istream_t substream;\n \n if (!pb_make_string_substream(stream, &substream))\n return false;\n \n while (substream.bytes_left)\n {\n if ((size_t)*size + 1 > allocated_size)\n {\n /* Allocate more storage. This tries to guess the\n * number of remaining entries. Round the division\n * upwards. */\n allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;\n \n if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))\n {\n status = false;\n break;\n }\n }\n\n /* Decode the array entry */\n pItem = *(char**)iter->pData + iter->pos->data_size * (*size);\n initialize_pointer_field(pItem, iter);\n if (!func(&substream, iter->pos, pItem))\n {\n status = false;\n break;\n }\n \n if (*size == PB_SIZE_MAX)\n {\n#ifndef PB_NO_ERRMSG\n stream->errmsg = \"too many array entries\";\n#endif\n status = false;\n break;\n }\n \n (*size)++;\n }\n if (!pb_close_string_substream(stream, &substream))\n return false;\n \n return status;\n }\n else\n {\n /* Normal repeated field, i.e. only one item at a time. */\n pb_size_t *size = (pb_size_t*)iter->pSize;\n void *pItem;\n \n if (*size == PB_SIZE_MAX)\n PB_RETURN_ERROR(stream, \"too many array entries\");\n \n (*size)++;\n if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size))\n return false;\n \n pItem = *(char**)iter->pData + iter->pos->data_size * (*size - 1);\n initialize_pointer_field(pItem, iter);\n return func(stream, iter->pos, pItem);\n }\n\n default:\n PB_RETURN_ERROR(stream, \"invalid field type\");\n }\n#endif\n}", "project": "nanopb", "hash": 213075198701079106378906571658903743081, "size": 122, "commit_id": "aa9d0d1ca78d6adec3adfeecf3a706c7f9df81f2", "message": "Fix invalid free() after failed realloc() (GHSA-gcx3-7m76-287p)", "target": 1, "dataset": "other", "idx": 197114} {"func": "static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)\n{\n#ifndef PB_ENABLE_MALLOC\n PB_UNUSED(wire_type);\n PB_UNUSED(iter);\n PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n pb_type_t type;\n pb_decoder_t func;\n \n type = iter->pos->type;\n func = PB_DECODERS[PB_LTYPE(type)];\n \n switch (PB_HTYPE(type))\n {\n case PB_HTYPE_REQUIRED:\n case PB_HTYPE_OPTIONAL:\n case PB_HTYPE_ONEOF:\n if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&\n *(void**)iter->pData != NULL)\n {\n /* Duplicate field, have to release the old allocation first. */\n pb_release_single_field(iter);\n }\n \n if (PB_HTYPE(type) == PB_HTYPE_ONEOF)\n {\n *(pb_size_t*)iter->pSize = iter->pos->tag;\n }\n\n if (PB_LTYPE(type) == PB_LTYPE_STRING ||\n PB_LTYPE(type) == PB_LTYPE_BYTES)\n {\n return func(stream, iter->pos, iter->pData);\n }\n else\n {\n if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))\n return false;\n \n initialize_pointer_field(*(void**)iter->pData, iter);\n return func(stream, iter->pos, *(void**)iter->pData);\n }\n \n case PB_HTYPE_REPEATED:\n if (wire_type == PB_WT_STRING\n && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)\n {\n /* Packed array, multiple items come in at once. */\n bool status = true;\n pb_size_t *size = (pb_size_t*)iter->pSize;\n size_t allocated_size = *size;\n void *pItem;\n pb_istream_t substream;\n \n if (!pb_make_string_substream(stream, &substream))\n return false;\n \n while (substream.bytes_left)\n {\n if ((size_t)*size + 1 > allocated_size)\n {\n /* Allocate more storage. This tries to guess the\n * number of remaining entries. Round the division\n * upwards. */\n allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;\n \n if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))\n {\n status = false;\n break;\n }\n }\n\n /* Decode the array entry */\n pItem = *(char**)iter->pData + iter->pos->data_size * (*size);\n initialize_pointer_field(pItem, iter);\n if (!func(&substream, iter->pos, pItem))\n {\n status = false;\n break;\n }\n \n if (*size == PB_SIZE_MAX)\n {\n#ifndef PB_NO_ERRMSG\n stream->errmsg = \"too many array entries\";\n#endif\n status = false;\n break;\n }\n \n (*size)++;\n }\n if (!pb_close_string_substream(stream, &substream))\n return false;\n \n return status;\n }\n else\n {\n /* Normal repeated field, i.e. only one item at a time. */\n pb_size_t *size = (pb_size_t*)iter->pSize;\n void *pItem;\n \n if (*size == PB_SIZE_MAX)\n PB_RETURN_ERROR(stream, \"too many array entries\");\n \n if (!allocate_field(stream, iter->pData, iter->pos->data_size, (size_t)(*size + 1)))\n return false;\n \n pItem = *(char**)iter->pData + iter->pos->data_size * (*size);\n (*size)++;\n initialize_pointer_field(pItem, iter);\n return func(stream, iter->pos, pItem);\n }\n\n default:\n PB_RETURN_ERROR(stream, \"invalid field type\");\n }\n#endif\n}", "project": "nanopb", "hash": 105540620865014349806580074661016441612, "size": 122, "commit_id": "aa9d0d1ca78d6adec3adfeecf3a706c7f9df81f2", "message": "Fix invalid free() after failed realloc() (GHSA-gcx3-7m76-287p)", "target": 0, "dataset": "other", "idx": 252505} {"func": " void Compute(OpKernelContext* context) override {\n // Here's the basic idea:\n // Batch and depth dimension are independent from row and col dimension. And\n // because FractionalAvgPool currently only support pooling along row and\n // col, we can basically think of this 4D tensor backpropagation as\n // operation of a series of 2D planes.\n //\n // For each element of a 'slice' (2D plane) of output_backprop, we need to\n // figure out its contributors when doing FractionalAvgPool operation. This\n // can be done based on row_pooling_sequence, col_pooling_seq and\n // overlapping.\n // Once we figure out the original contributors, we just need to evenly\n // divide the value of this element among these contributors.\n //\n // Internally, we divide the out_backprop tensor and store it in a temporary\n // tensor of double type. And cast it to the corresponding type.\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenDoubleMatrixMap;\n\n // Grab the inputs.\n const Tensor& orig_input_tensor_shape = context->input(0);\n OP_REQUIRES(context,\n orig_input_tensor_shape.dims() == 1 &&\n orig_input_tensor_shape.NumElements() == 4,\n errors::InvalidArgument(\"original input tensor shape must be\"\n \"1-dimensional and 4 elements\"));\n const Tensor& out_backprop = context->input(1);\n const Tensor& row_seq_tensor = context->input(2);\n const Tensor& col_seq_tensor = context->input(3);\n\n const int64 out_batch = out_backprop.dim_size(0);\n const int64 out_rows = out_backprop.dim_size(1);\n const int64 out_cols = out_backprop.dim_size(2);\n const int64 out_depth = out_backprop.dim_size(3);\n\n auto row_seq_tensor_flat = row_seq_tensor.flat();\n auto col_seq_tensor_flat = col_seq_tensor.flat();\n auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat();\n\n const int64 in_batch = orig_input_tensor_shape_flat(0);\n const int64 in_rows = orig_input_tensor_shape_flat(1);\n const int64 in_cols = orig_input_tensor_shape_flat(2);\n const int64 in_depth = orig_input_tensor_shape_flat(3);\n\n constexpr int tensor_in_and_out_dims = 4;\n // Transform orig_input_tensor_shape into TensorShape\n TensorShape in_shape;\n for (auto i = 0; i < tensor_in_and_out_dims; ++i) {\n in_shape.AddDim(orig_input_tensor_shape_flat(i));\n }\n\n // Create intermediate in_backprop.\n Tensor in_backprop_tensor_temp;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(\n {0}, DataTypeToEnum::v(), in_shape,\n &in_backprop_tensor_temp));\n in_backprop_tensor_temp.flat().setZero();\n // Transform 4D tensor to 2D matrix.\n EigenDoubleMatrixMap in_backprop_tensor_temp_mat(\n in_backprop_tensor_temp.flat().data(), in_depth,\n in_cols * in_rows * in_batch);\n ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(),\n out_depth,\n out_cols * out_rows * out_batch);\n // Loop through each element of out_backprop and evenly distribute the\n // element to the corresponding pooling cell.\n const int64 in_max_row_index = in_rows - 1;\n const int64 in_max_col_index = in_cols - 1;\n for (int64 b = 0; b < out_batch; ++b) {\n for (int64 r = 0; r < out_rows; ++r) {\n const int64 in_row_start = row_seq_tensor_flat(r);\n int64 in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)\n : row_seq_tensor_flat(r + 1) - 1;\n in_row_end = std::min(in_row_end, in_max_row_index);\n for (int64 c = 0; c < out_cols; ++c) {\n const int64 in_col_start = col_seq_tensor_flat(c);\n int64 in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)\n : col_seq_tensor_flat(c + 1) - 1;\n in_col_end = std::min(in_col_end, in_max_col_index);\n\n const int64 num_elements_in_pooling_cell =\n (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);\n const int64 out_index = (b * out_rows + r) * out_cols + c;\n // Now we can evenly distribute out_backprop(b, h, w, *) to\n // in_backprop(b, hs:he, ws:we, *).\n for (int64 in_r = in_row_start; in_r <= in_row_end; ++in_r) {\n for (int64 in_c = in_col_start; in_c <= in_col_end; ++in_c) {\n const int64 in_index = (b * in_rows + in_r) * in_cols + in_c;\n // Walk through each channel (depth).\n for (int64 d = 0; d < out_depth; ++d) {\n const double out_backprop_element = static_cast(\n out_backprop_mat.coeffRef(d, out_index));\n double& in_backprop_ref =\n in_backprop_tensor_temp_mat.coeffRef(d, in_index);\n in_backprop_ref +=\n out_backprop_element / num_elements_in_pooling_cell;\n }\n }\n }\n }\n }\n }\n\n // Depending on the type, cast double to type T.\n Tensor* in_backprop_tensor = nullptr;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {0}, 0, in_shape, &in_backprop_tensor));\n auto in_backprop_tensor_flat = in_backprop_tensor->flat();\n auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat();\n for (int64 i = 0; i < in_backprop_tensor_flat.size(); ++i) {\n in_backprop_tensor_flat(i) =\n static_cast(in_backprop_tensor_temp_flat(i));\n }\n }", "project": "tensorflow", "hash": 220832190112288234713294919372485684625, "size": 116, "commit_id": "12c727cee857fa19be717f336943d95fca4ffe4f", "message": "Validate inputs of `FractionalAvgPoolGrad`.\n\nPiperOrigin-RevId: 372420640\nChange-Id: Icc583928e6cdc3062e12498e4d2337a8fe3da016", "target": 1, "dataset": "other", "idx": 197133} {"func": " void Compute(OpKernelContext* context) override {\n // Here's the basic idea:\n // Batch and depth dimension are independent from row and col dimension. And\n // because FractionalAvgPool currently only support pooling along row and\n // col, we can basically think of this 4D tensor backpropagation as\n // operation of a series of 2D planes.\n //\n // For each element of a 'slice' (2D plane) of output_backprop, we need to\n // figure out its contributors when doing FractionalAvgPool operation. This\n // can be done based on row_pooling_sequence, col_pooling_seq and\n // overlapping.\n // Once we figure out the original contributors, we just need to evenly\n // divide the value of this element among these contributors.\n //\n // Internally, we divide the out_backprop tensor and store it in a temporary\n // tensor of double type. And cast it to the corresponding type.\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>\n EigenDoubleMatrixMap;\n\n // Grab the inputs.\n const Tensor& orig_input_tensor_shape = context->input(0);\n OP_REQUIRES(context,\n orig_input_tensor_shape.dims() == 1 &&\n orig_input_tensor_shape.NumElements() == 4,\n errors::InvalidArgument(\"original input tensor shape must be\"\n \"1-dimensional and 4 elements\"));\n const Tensor& out_backprop = context->input(1);\n const Tensor& row_seq_tensor = context->input(2);\n const Tensor& col_seq_tensor = context->input(3);\n\n const int64 out_batch = out_backprop.dim_size(0);\n const int64 out_rows = out_backprop.dim_size(1);\n const int64 out_cols = out_backprop.dim_size(2);\n const int64 out_depth = out_backprop.dim_size(3);\n\n OP_REQUIRES(context, row_seq_tensor.NumElements() > out_rows,\n errors::InvalidArgument(\"Given out_backprop shape \",\n out_backprop.shape().DebugString(),\n \", row_seq_tensor must have at least \",\n out_rows + 1, \" elements, but got \",\n row_seq_tensor.NumElements()));\n OP_REQUIRES(context, col_seq_tensor.NumElements() > out_cols,\n errors::InvalidArgument(\"Given out_backprop shape \",\n out_backprop.shape().DebugString(),\n \", col_seq_tensor must have at least \",\n out_cols + 1, \" elements, but got \",\n col_seq_tensor.NumElements()));\n\n auto row_seq_tensor_flat = row_seq_tensor.flat();\n auto col_seq_tensor_flat = col_seq_tensor.flat();\n auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat();\n\n const int64 in_batch = orig_input_tensor_shape_flat(0);\n const int64 in_rows = orig_input_tensor_shape_flat(1);\n const int64 in_cols = orig_input_tensor_shape_flat(2);\n const int64 in_depth = orig_input_tensor_shape_flat(3);\n\n constexpr int tensor_in_and_out_dims = 4;\n // Transform orig_input_tensor_shape into TensorShape\n TensorShape in_shape;\n for (auto i = 0; i < tensor_in_and_out_dims; ++i) {\n in_shape.AddDim(orig_input_tensor_shape_flat(i));\n }\n\n // Create intermediate in_backprop.\n Tensor in_backprop_tensor_temp;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp(\n {0}, DataTypeToEnum::v(), in_shape,\n &in_backprop_tensor_temp));\n in_backprop_tensor_temp.flat().setZero();\n // Transform 4D tensor to 2D matrix.\n EigenDoubleMatrixMap in_backprop_tensor_temp_mat(\n in_backprop_tensor_temp.flat().data(), in_depth,\n in_cols * in_rows * in_batch);\n ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(),\n out_depth,\n out_cols * out_rows * out_batch);\n // Loop through each element of out_backprop and evenly distribute the\n // element to the corresponding pooling cell.\n const int64 in_max_row_index = in_rows - 1;\n const int64 in_max_col_index = in_cols - 1;\n for (int64 b = 0; b < out_batch; ++b) {\n for (int64 r = 0; r < out_rows; ++r) {\n const int64 in_row_start = row_seq_tensor_flat(r);\n int64 in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1)\n : row_seq_tensor_flat(r + 1) - 1;\n in_row_end = std::min(in_row_end, in_max_row_index);\n for (int64 c = 0; c < out_cols; ++c) {\n const int64 in_col_start = col_seq_tensor_flat(c);\n int64 in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1)\n : col_seq_tensor_flat(c + 1) - 1;\n in_col_end = std::min(in_col_end, in_max_col_index);\n\n const int64 num_elements_in_pooling_cell =\n (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1);\n const int64 out_index = (b * out_rows + r) * out_cols + c;\n // Now we can evenly distribute out_backprop(b, h, w, *) to\n // in_backprop(b, hs:he, ws:we, *).\n for (int64 in_r = in_row_start; in_r <= in_row_end; ++in_r) {\n for (int64 in_c = in_col_start; in_c <= in_col_end; ++in_c) {\n const int64 in_index = (b * in_rows + in_r) * in_cols + in_c;\n // Walk through each channel (depth).\n for (int64 d = 0; d < out_depth; ++d) {\n const double out_backprop_element = static_cast(\n out_backprop_mat.coeffRef(d, out_index));\n double& in_backprop_ref =\n in_backprop_tensor_temp_mat.coeffRef(d, in_index);\n in_backprop_ref +=\n out_backprop_element / num_elements_in_pooling_cell;\n }\n }\n }\n }\n }\n }\n\n // Depending on the type, cast double to type T.\n Tensor* in_backprop_tensor = nullptr;\n OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(\n {0}, 0, in_shape, &in_backprop_tensor));\n auto in_backprop_tensor_flat = in_backprop_tensor->flat();\n auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat();\n for (int64 i = 0; i < in_backprop_tensor_flat.size(); ++i) {\n in_backprop_tensor_flat(i) =\n static_cast(in_backprop_tensor_temp_flat(i));\n }\n }", "project": "tensorflow", "hash": 41801048919539989826079311137357489877, "size": 129, "commit_id": "12c727cee857fa19be717f336943d95fca4ffe4f", "message": "Validate inputs of `FractionalAvgPoolGrad`.\n\nPiperOrigin-RevId: 372420640\nChange-Id: Icc583928e6cdc3062e12498e4d2337a8fe3da016", "target": 0, "dataset": "other", "idx": 253652} {"func": "int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,\n\t\t char * const exc_prop[], int exc_prop_count,\n\t\t struct fdt_region region[], int max_regions,\n\t\t char *path, int path_len, int add_string_tab)\n{\n\tint stack[FDT_MAX_DEPTH] = { 0 };\n\tchar *end;\n\tint nextoffset = 0;\n\tuint32_t tag;\n\tint count = 0;\n\tint start = -1;\n\tint depth = -1;\n\tint want = 0;\n\tint base = fdt_off_dt_struct(fdt);\n\n\tend = path;\n\t*end = '\\0';\n\tdo {\n\t\tconst struct fdt_property *prop;\n\t\tconst char *name;\n\t\tconst char *str;\n\t\tint include = 0;\n\t\tint stop_at = 0;\n\t\tint offset;\n\t\tint len;\n\n\t\toffset = nextoffset;\n\t\ttag = fdt_next_tag(fdt, offset, &nextoffset);\n\t\tstop_at = nextoffset;\n\n\t\tswitch (tag) {\n\t\tcase FDT_PROP:\n\t\t\tinclude = want >= 2;\n\t\t\tstop_at = offset;\n\t\t\tprop = fdt_get_property_by_offset(fdt, offset, NULL);\n\t\t\tstr = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));\n\t\t\tif (!str)\n\t\t\t\treturn -FDT_ERR_BADSTRUCTURE;\n\t\t\tif (str_in_list(str, exc_prop, exc_prop_count))\n\t\t\t\tinclude = 0;\n\t\t\tbreak;\n\n\t\tcase FDT_NOP:\n\t\t\tinclude = want >= 2;\n\t\t\tstop_at = offset;\n\t\t\tbreak;\n\n\t\tcase FDT_BEGIN_NODE:\n\t\t\tdepth++;\n\t\t\tif (depth == FDT_MAX_DEPTH)\n\t\t\t\treturn -FDT_ERR_BADSTRUCTURE;\n\t\t\tname = fdt_get_name(fdt, offset, &len);\n\t\t\tif (end - path + 2 + len >= path_len)\n\t\t\t\treturn -FDT_ERR_NOSPACE;\n\t\t\tif (end != path + 1)\n\t\t\t\t*end++ = '/';\n\t\t\tstrcpy(end, name);\n\t\t\tend += len;\n\t\t\tstack[depth] = want;\n\t\t\tif (want == 1)\n\t\t\t\tstop_at = offset;\n\t\t\tif (str_in_list(path, inc, inc_count))\n\t\t\t\twant = 2;\n\t\t\telse if (want)\n\t\t\t\twant--;\n\t\t\telse\n\t\t\t\tstop_at = offset;\n\t\t\tinclude = want;\n\t\t\tbreak;\n\n\t\tcase FDT_END_NODE:\n\t\t\t/* Depth must never go below -1 */\n\t\t\tif (depth < 0)\n\t\t\t\treturn -FDT_ERR_BADSTRUCTURE;\n\t\t\tinclude = want;\n\t\t\twant = stack[depth--];\n\t\t\twhile (end > path && *--end != '/')\n\t\t\t\t;\n\t\t\t*end = '\\0';\n\t\t\tbreak;\n\n\t\tcase FDT_END:\n\t\t\tinclude = 1;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (include && start == -1) {\n\t\t\t/* Should we merge with previous? */\n\t\t\tif (count && count <= max_regions &&\n\t\t\t offset == region[count - 1].offset +\n\t\t\t\t\tregion[count - 1].size - base)\n\t\t\t\tstart = region[--count].offset - base;\n\t\t\telse\n\t\t\t\tstart = offset;\n\t\t}\n\n\t\tif (!include && start != -1) {\n\t\t\tif (count < max_regions) {\n\t\t\t\tregion[count].offset = base + start;\n\t\t\t\tregion[count].size = stop_at - start;\n\t\t\t}\n\t\t\tcount++;\n\t\t\tstart = -1;\n\t\t}\n\t} while (tag != FDT_END);\n\n\tif (nextoffset != fdt_size_dt_struct(fdt))\n\t\treturn -FDT_ERR_BADLAYOUT;\n\n\t/* Add a region for the END tag and the string table */\n\tif (count < max_regions) {\n\t\tregion[count].offset = base + start;\n\t\tregion[count].size = nextoffset - start;\n\t\tif (add_string_tab)\n\t\t\tregion[count].size += fdt_size_dt_strings(fdt);\n\t}\n\tcount++;\n\n\treturn count;\n}", "project": "u-boot", "hash": 43916771152843850774133375533513142058, "size": 120, "commit_id": "8a7d4cf9820ea16fabd25a6379351b4dc291204b", "message": "fdt_region: Check for a single root node of the correct name\n\nAt present fdt_find_regions() assumes that the FIT is a valid devicetree.\nIf the FIT has two root nodes this is currently not detected in this\nfunction, nor does libfdt's fdt_check_full() notice. Also it is possible\nfor the root node to have a name even though it should not.\n\nAdd checks for these and return -FDT_ERR_BADSTRUCTURE if a problem is\ndetected.\n\nCVE-2021-27097\n\nSigned-off-by: Simon Glass \nReported-by: Bruce Monroe \nReported-by: Arie Haenel \nReported-by: Julien Lenoir ", "target": 1, "dataset": "other", "idx": 197162} {"func": "int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,\n\t\t char * const exc_prop[], int exc_prop_count,\n\t\t struct fdt_region region[], int max_regions,\n\t\t char *path, int path_len, int add_string_tab)\n{\n\tint stack[FDT_MAX_DEPTH] = { 0 };\n\tchar *end;\n\tint nextoffset = 0;\n\tuint32_t tag;\n\tint count = 0;\n\tint start = -1;\n\tint depth = -1;\n\tint want = 0;\n\tint base = fdt_off_dt_struct(fdt);\n\tbool expect_end = false;\n\n\tend = path;\n\t*end = '\\0';\n\tdo {\n\t\tconst struct fdt_property *prop;\n\t\tconst char *name;\n\t\tconst char *str;\n\t\tint include = 0;\n\t\tint stop_at = 0;\n\t\tint offset;\n\t\tint len;\n\n\t\toffset = nextoffset;\n\t\ttag = fdt_next_tag(fdt, offset, &nextoffset);\n\t\tstop_at = nextoffset;\n\n\t\t/* If we see two root nodes, something is wrong */\n\t\tif (expect_end && tag != FDT_END)\n\t\t\treturn -FDT_ERR_BADLAYOUT;\n\n\t\tswitch (tag) {\n\t\tcase FDT_PROP:\n\t\t\tinclude = want >= 2;\n\t\t\tstop_at = offset;\n\t\t\tprop = fdt_get_property_by_offset(fdt, offset, NULL);\n\t\t\tstr = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));\n\t\t\tif (!str)\n\t\t\t\treturn -FDT_ERR_BADSTRUCTURE;\n\t\t\tif (str_in_list(str, exc_prop, exc_prop_count))\n\t\t\t\tinclude = 0;\n\t\t\tbreak;\n\n\t\tcase FDT_NOP:\n\t\t\tinclude = want >= 2;\n\t\t\tstop_at = offset;\n\t\t\tbreak;\n\n\t\tcase FDT_BEGIN_NODE:\n\t\t\tdepth++;\n\t\t\tif (depth == FDT_MAX_DEPTH)\n\t\t\t\treturn -FDT_ERR_BADSTRUCTURE;\n\t\t\tname = fdt_get_name(fdt, offset, &len);\n\n\t\t\t/* The root node must have an empty name */\n\t\t\tif (!depth && *name)\n\t\t\t\treturn -FDT_ERR_BADLAYOUT;\n\t\t\tif (end - path + 2 + len >= path_len)\n\t\t\t\treturn -FDT_ERR_NOSPACE;\n\t\t\tif (end != path + 1)\n\t\t\t\t*end++ = '/';\n\t\t\tstrcpy(end, name);\n\t\t\tend += len;\n\t\t\tstack[depth] = want;\n\t\t\tif (want == 1)\n\t\t\t\tstop_at = offset;\n\t\t\tif (str_in_list(path, inc, inc_count))\n\t\t\t\twant = 2;\n\t\t\telse if (want)\n\t\t\t\twant--;\n\t\t\telse\n\t\t\t\tstop_at = offset;\n\t\t\tinclude = want;\n\t\t\tbreak;\n\n\t\tcase FDT_END_NODE:\n\t\t\t/* Depth must never go below -1 */\n\t\t\tif (depth < 0)\n\t\t\t\treturn -FDT_ERR_BADSTRUCTURE;\n\t\t\tinclude = want;\n\t\t\twant = stack[depth--];\n\t\t\twhile (end > path && *--end != '/')\n\t\t\t\t;\n\t\t\t*end = '\\0';\n\t\t\tif (depth == -1)\n\t\t\t\texpect_end = true;\n\t\t\tbreak;\n\n\t\tcase FDT_END:\n\t\t\tinclude = 1;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (include && start == -1) {\n\t\t\t/* Should we merge with previous? */\n\t\t\tif (count && count <= max_regions &&\n\t\t\t offset == region[count - 1].offset +\n\t\t\t\t\tregion[count - 1].size - base)\n\t\t\t\tstart = region[--count].offset - base;\n\t\t\telse\n\t\t\t\tstart = offset;\n\t\t}\n\n\t\tif (!include && start != -1) {\n\t\t\tif (count < max_regions) {\n\t\t\t\tregion[count].offset = base + start;\n\t\t\t\tregion[count].size = stop_at - start;\n\t\t\t}\n\t\t\tcount++;\n\t\t\tstart = -1;\n\t\t}\n\t} while (tag != FDT_END);\n\n\tif (nextoffset != fdt_size_dt_struct(fdt))\n\t\treturn -FDT_ERR_BADLAYOUT;\n\n\t/* Add a region for the END tag and the string table */\n\tif (count < max_regions) {\n\t\tregion[count].offset = base + start;\n\t\tregion[count].size = nextoffset - start;\n\t\tif (add_string_tab)\n\t\t\tregion[count].size += fdt_size_dt_strings(fdt);\n\t}\n\tcount++;\n\n\treturn count;\n}", "project": "u-boot", "hash": 238752706778527509335520424068219469599, "size": 131, "commit_id": "8a7d4cf9820ea16fabd25a6379351b4dc291204b", "message": "fdt_region: Check for a single root node of the correct name\n\nAt present fdt_find_regions() assumes that the FIT is a valid devicetree.\nIf the FIT has two root nodes this is currently not detected in this\nfunction, nor does libfdt's fdt_check_full() notice. Also it is possible\nfor the root node to have a name even though it should not.\n\nAdd checks for these and return -FDT_ERR_BADSTRUCTURE if a problem is\ndetected.\n\nCVE-2021-27097\n\nSigned-off-by: Simon Glass \nReported-by: Bruce Monroe \nReported-by: Arie Haenel \nReported-by: Julien Lenoir ", "target": 0, "dataset": "other", "idx": 254234} {"func": "static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *field)\n{\n pb_field_iter_t old_field = *field;\n pb_size_t old_tag = *(pb_size_t*)field->pSize; /* Previous which_ value */\n pb_size_t new_tag = field->tag; /* New which_ value */\n\n if (old_tag == 0)\n return true; /* Ok, no old data in union */\n\n if (old_tag == new_tag)\n return true; /* Ok, old data is of same type => merge */\n\n /* Release old data. The find can fail if the message struct contains\n * invalid data. */\n if (!pb_field_iter_find(&old_field, old_tag))\n PB_RETURN_ERROR(stream, \"invalid union tag\");\n\n pb_release_single_field(&old_field);\n\n return true;\n}", "project": "nanopb", "hash": 112412675508427426387109317948700128093, "size": 21, "commit_id": "e2f0ccf939d9f82931d085acb6df8e9a182a4261", "message": "Fix invalid free() with oneof (#647)\n\nNanopb would call free() or realloc() on an invalid\n(attacker controlled) pointer value when all the following\nconditions are true:\n\n- PB_ENABLE_MALLOC is defined at the compile time\n- Message definition contains an oneof field, and the oneof\n contains at least one pointer type field and at least one\n non-pointer type field.\n- Data being decoded first contains a non-pointer value for\n the oneof field, and later contains an overwriting pointer\n value.\n\nDepending on message layout, the bug may not be exploitable in all\ncases, but it is known to be exploitable at least with string and\nbytes fields. Actual security impact will also depend on the heap\nimplementation used.", "target": 1, "dataset": "other", "idx": 197172} {"func": "static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *field)\n{\n pb_field_iter_t old_field = *field;\n pb_size_t old_tag = *(pb_size_t*)field->pSize; /* Previous which_ value */\n pb_size_t new_tag = field->tag; /* New which_ value */\n\n if (old_tag == 0)\n return true; /* Ok, no old data in union */\n\n if (old_tag == new_tag)\n return true; /* Ok, old data is of same type => merge */\n\n /* Release old data. The find can fail if the message struct contains\n * invalid data. */\n if (!pb_field_iter_find(&old_field, old_tag))\n PB_RETURN_ERROR(stream, \"invalid union tag\");\n\n pb_release_single_field(&old_field);\n\n if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)\n {\n /* Initialize the pointer to NULL to make sure it is valid\n * even in case of error return. */\n *(void**)field->pField = NULL;\n field->pData = NULL;\n }\n\n return true;\n}", "project": "nanopb", "hash": 141020607398662900410401211462596595087, "size": 29, "commit_id": "e2f0ccf939d9f82931d085acb6df8e9a182a4261", "message": "Fix invalid free() with oneof (#647)\n\nNanopb would call free() or realloc() on an invalid\n(attacker controlled) pointer value when all the following\nconditions are true:\n\n- PB_ENABLE_MALLOC is defined at the compile time\n- Message definition contains an oneof field, and the oneof\n contains at least one pointer type field and at least one\n non-pointer type field.\n- Data being decoded first contains a non-pointer value for\n the oneof field, and later contains an overwriting pointer\n value.\n\nDepending on message layout, the bug may not be exploitable in all\ncases, but it is known to be exploitable at least with string and\nbytes fields. Actual security impact will also depend on the heap\nimplementation used.", "target": 0, "dataset": "other", "idx": 254699} {"func": "void ndpi_search_h323(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow)\n{\n struct ndpi_packet_struct *packet = &flow->packet;\n u_int16_t dport = 0, sport = 0;\n\n NDPI_LOG_DBG(ndpi_struct, \"search H323\\n\");\n\n /*\n The TPKT protocol is used by ISO 8072 (on port 102)\n and H.323. So this check below is to avoid ambiguities\n */\n if((packet->tcp != NULL) && (packet->tcp->dest != ntohs(102))) {\n NDPI_LOG_DBG2(ndpi_struct, \"calculated dport over tcp\\n\");\n\n /* H323 */\n if(packet->payload_packet_len >= 4\n && (packet->payload[0] == 0x03)\n && (packet->payload[1] == 0x00)) {\n\tstruct tpkt *t = (struct tpkt*)packet->payload;\n\tu_int16_t len = ntohs(t->len);\n\n\tif(packet->payload_packet_len == len) {\n\t /*\n\t We need to check if this packet is in reality\n\t a RDP (Remote Desktop) packet encapsulated on TPTK\n\t */\n\n\t if(packet->payload[4] == (packet->payload_packet_len - sizeof(struct tpkt) - 1)) {\n\t /* ISO 8073/X.224 */\n\t if((packet->payload[5] == 0xE0 /* CC Connect Request */)\n\t || (packet->payload[5] == 0xD0 /* CC Connect Confirm */)) {\n\t NDPI_LOG_INFO(ndpi_struct, \"found RDP\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_RDP, NDPI_PROTOCOL_UNKNOWN);\n\t return;\n\t }\n\t }\n\n\t flow->l4.tcp.h323_valid_packets++;\n\n\t if(flow->l4.tcp.h323_valid_packets >= 2) {\n\t NDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\t }\n\t} else {\n\t /* This is not H.323 */\n\t NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n\t return;\n\t}\n }\n } else if(packet->udp != NULL) {\n sport = ntohs(packet->udp->source), dport = ntohs(packet->udp->dest);\n NDPI_LOG_DBG2(ndpi_struct, \"calculated dport over udp\\n\");\n\n if(packet->payload_packet_len >= 6 && packet->payload[0] == 0x80 && packet->payload[1] == 0x08 &&\n (packet->payload[2] == 0xe7 || packet->payload[2] == 0x26) &&\n packet->payload[4] == 0x00 && packet->payload[5] == 0x00)\n {\n\tNDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\tndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\treturn;\n }\n /* H323 */\n if(sport == 1719 || dport == 1719)\n {\n if(packet->payload[0] == 0x16 && packet->payload[1] == 0x80 && packet->payload[4] == 0x06 && packet->payload[5] == 0x00)\n\t {\n\t NDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\t return;\n\t }\n else if(packet->payload_packet_len >= 20 && packet->payload_packet_len <= 117)\n\t {\n\t NDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\t return;\n\t }\n else\n\t {\n\t NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n\t return;\n\t }\n }\n }\n\n}", "project": "nDPI", "hash": 239776547736060222158186732995430716218, "size": 85, "commit_id": "b7e666e465f138ae48ab81976726e67deed12701", "message": "Added fix to avoid potential heap buffer overflow in H.323 dissector\nModified HTTP report information to make it closer to the HTTP field names", "target": 1, "dataset": "other", "idx": 197178} {"func": "void ndpi_search_h323(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow)\n{\n struct ndpi_packet_struct *packet = &flow->packet;\n u_int16_t dport = 0, sport = 0;\n\n NDPI_LOG_DBG(ndpi_struct, \"search H323\\n\");\n\n /*\n The TPKT protocol is used by ISO 8072 (on port 102)\n and H.323. So this check below is to avoid ambiguities\n */\n if((packet->tcp != NULL) && (packet->tcp->dest != ntohs(102))) {\n NDPI_LOG_DBG2(ndpi_struct, \"calculated dport over tcp\\n\");\n\n /* H323 */\n if(packet->payload_packet_len >= 4\n && (packet->payload[0] == 0x03)\n && (packet->payload[1] == 0x00)) {\n struct tpkt *t = (struct tpkt*)packet->payload;\n u_int16_t len = ntohs(t->len);\n\n if(packet->payload_packet_len == len) {\n\t/*\n\t We need to check if this packet is in reality\n\t a RDP (Remote Desktop) packet encapsulated on TPTK\n\t*/\n\n\tif(packet->payload[4] == (packet->payload_packet_len - sizeof(struct tpkt) - 1)) {\n\t /* ISO 8073/X.224 */\n\t if((packet->payload[5] == 0xE0 /* CC Connect Request */)\n\t || (packet->payload[5] == 0xD0 /* CC Connect Confirm */)) {\n\t NDPI_LOG_INFO(ndpi_struct, \"found RDP\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_RDP, NDPI_PROTOCOL_UNKNOWN);\n\t return;\n\t }\n\t}\n\n\tflow->l4.tcp.h323_valid_packets++;\n\n\tif(flow->l4.tcp.h323_valid_packets >= 2) {\n\t NDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\t ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\t}\n } else {\n\t/* This is not H.323 */\n\tNDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n\treturn;\n }\n }\n } else if(packet->udp != NULL) {\n sport = ntohs(packet->udp->source), dport = ntohs(packet->udp->dest);\n NDPI_LOG_DBG2(ndpi_struct, \"calculated dport over udp\\n\");\n\n if(packet->payload_packet_len >= 6 && packet->payload[0] == 0x80 && packet->payload[1] == 0x08 &&\n (packet->payload[2] == 0xe7 || packet->payload[2] == 0x26) &&\n packet->payload[4] == 0x00 && packet->payload[5] == 0x00)\n {\n\tNDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\tndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\treturn;\n }\n /* H323 */\n if(sport == 1719 || dport == 1719) {\n if((packet->payload_packet_len >= 5)\n\t && (packet->payload[0] == 0x16)\n\t && (packet->payload[1] == 0x80)\n\t && (packet->payload[4] == 0x06)\n\t && (packet->payload[5] == 0x00)) {\n\tNDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\tndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\treturn;\n } else if(packet->payload_packet_len >= 20 && packet->payload_packet_len <= 117) {\n\tNDPI_LOG_INFO(ndpi_struct, \"found H323 broadcast\\n\");\n\tndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN);\n\treturn;\n } else {\n\tNDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n\treturn;\n }\n }\n }\n}", "project": "nDPI", "hash": 333094768327408050308949731073671429220, "size": 82, "commit_id": "b7e666e465f138ae48ab81976726e67deed12701", "message": "Added fix to avoid potential heap buffer overflow in H.323 dissector\nModified HTTP report information to make it closer to the HTTP field names", "target": 0, "dataset": "other", "idx": 254869} {"func": "Status ConvBackpropComputeDimensionsV2(\n StringPiece label, int num_spatial_dims, const TensorShape& input_shape,\n const TensorShape& filter_shape, const TensorShape& out_backprop_shape,\n const gtl::ArraySlice& dilations, const std::vector& strides,\n Padding padding, absl::Span explicit_paddings,\n TensorFormat data_format, ConvBackpropDimensions* dims) {\n // The + 2 in the following line is for the batch and feature dimensions.\n const int num_dims = num_spatial_dims + 2;\n if (input_shape.dims() != num_dims) {\n return errors::InvalidArgument(label, \": input must be \", num_dims,\n \"-dimensional\");\n }\n if (filter_shape.dims() != num_dims) {\n return errors::InvalidArgument(label, \": filter must be \", num_dims,\n \"-dimensional\");\n }\n if (out_backprop_shape.dims() != num_dims) {\n return errors::InvalidArgument(label, \": out_backprop must be \", num_dims,\n \"-dimensional\");\n }\n int batch_dim = GetTensorBatchDimIndex(num_dims, data_format);\n dims->batch_size = input_shape.dim_size(batch_dim);\n if (dims->batch_size != out_backprop_shape.dim_size(batch_dim)) {\n return errors::InvalidArgument(\n label, \": input and out_backprop must have the same batch size.\",\n \" Input batch: \", dims->batch_size,\n \", outbackprop batch: \", out_backprop_shape.dim_size(batch_dim),\n \", batch_dim: \", batch_dim);\n }\n\n int feature_dim = GetTensorFeatureDimIndex(num_dims, data_format);\n dims->in_depth = input_shape.dim_size(feature_dim);\n // The input and output feature dimensions are the second last and last\n // dimensions of the filter Tensor.\n VLOG(2) << \"input vs filter_in depth \" << dims->in_depth << \" \"\n << filter_shape.dim_size(num_dims - 2);\n if (dims->in_depth % filter_shape.dim_size(num_dims - 2)) {\n return errors::InvalidArgument(\n label, \": input depth must be evenly divisible by filter depth\");\n }\n dims->out_depth = filter_shape.dim_size(num_dims - 1);\n if (dims->out_depth != out_backprop_shape.dim_size(feature_dim)) {\n return errors::InvalidArgument(\n label, \": filter and out_backprop must have the same out_depth\");\n }\n dims->spatial_dims.resize(num_spatial_dims);\n for (int i = 0; i < num_spatial_dims; ++i) {\n int image_dim = GetTensorSpatialDimIndex(num_dims, data_format, i);\n int64 padding_before = -1, padding_after = -1;\n if (padding == EXPLICIT) {\n padding_before = explicit_paddings[2 * image_dim];\n padding_after = explicit_paddings[2 * image_dim + 1];\n }\n TF_RETURN_IF_ERROR(ConvBackpropExtractAndVerifyDimension(\n label, input_shape, filter_shape, out_backprop_shape, dilations,\n strides, padding, padding_before, padding_after, image_dim, i,\n &dims->spatial_dims[i]));\n }\n return Status::OK();\n}", "project": "tensorflow", "hash": 320799004957211890798176933281449360794, "size": 60, "commit_id": "fca9874a9b42a2134f907d2fb46ab774a831404a", "message": "Prevent another division by zero.\n\nPiperOrigin-RevId: 369338598\nChange-Id: I55471d363e401fdcf8d259670ad4eef672b731e2", "target": 1, "dataset": "other", "idx": 197183} {"func": "Status ConvBackpropComputeDimensionsV2(\n StringPiece label, int num_spatial_dims, const TensorShape& input_shape,\n const TensorShape& filter_shape, const TensorShape& out_backprop_shape,\n const gtl::ArraySlice& dilations, const std::vector& strides,\n Padding padding, absl::Span explicit_paddings,\n TensorFormat data_format, ConvBackpropDimensions* dims) {\n // The + 2 in the following line is for the batch and feature dimensions.\n const int num_dims = num_spatial_dims + 2;\n if (input_shape.dims() != num_dims) {\n return errors::InvalidArgument(label, \": input must be \", num_dims,\n \"-dimensional\");\n }\n if (filter_shape.dims() != num_dims) {\n return errors::InvalidArgument(label, \": filter must be \", num_dims,\n \"-dimensional\");\n }\n if (out_backprop_shape.dims() != num_dims) {\n return errors::InvalidArgument(label, \": out_backprop must be \", num_dims,\n \"-dimensional\");\n }\n int batch_dim = GetTensorBatchDimIndex(num_dims, data_format);\n dims->batch_size = input_shape.dim_size(batch_dim);\n if (dims->batch_size != out_backprop_shape.dim_size(batch_dim)) {\n return errors::InvalidArgument(\n label, \": input and out_backprop must have the same batch size.\",\n \" Input batch: \", dims->batch_size,\n \", outbackprop batch: \", out_backprop_shape.dim_size(batch_dim),\n \", batch_dim: \", batch_dim);\n }\n\n int feature_dim = GetTensorFeatureDimIndex(num_dims, data_format);\n dims->in_depth = input_shape.dim_size(feature_dim);\n // The input and output feature dimensions are the second last and last\n // dimensions of the filter Tensor.\n VLOG(2) << \"input vs filter_in depth \" << dims->in_depth << \" \"\n << filter_shape.dim_size(num_dims - 2);\n if (filter_shape.dim_size(num_dims - 2) <= 0) {\n return errors ::InvalidArgument(\n label, \": filter depth must be strictly greated than zero\");\n }\n if (dims->in_depth % filter_shape.dim_size(num_dims - 2)) {\n return errors::InvalidArgument(\n label, \": input depth must be evenly divisible by filter depth\");\n }\n dims->out_depth = filter_shape.dim_size(num_dims - 1);\n if (dims->out_depth != out_backprop_shape.dim_size(feature_dim)) {\n return errors::InvalidArgument(\n label, \": filter and out_backprop must have the same out_depth\");\n }\n dims->spatial_dims.resize(num_spatial_dims);\n for (int i = 0; i < num_spatial_dims; ++i) {\n int image_dim = GetTensorSpatialDimIndex(num_dims, data_format, i);\n int64 padding_before = -1, padding_after = -1;\n if (padding == EXPLICIT) {\n padding_before = explicit_paddings[2 * image_dim];\n padding_after = explicit_paddings[2 * image_dim + 1];\n }\n TF_RETURN_IF_ERROR(ConvBackpropExtractAndVerifyDimension(\n label, input_shape, filter_shape, out_backprop_shape, dilations,\n strides, padding, padding_before, padding_after, image_dim, i,\n &dims->spatial_dims[i]));\n }\n return Status::OK();\n}", "project": "tensorflow", "hash": 287077448679940441968460163872429604572, "size": 64, "commit_id": "fca9874a9b42a2134f907d2fb46ab774a831404a", "message": "Prevent another division by zero.\n\nPiperOrigin-RevId: 369338598\nChange-Id: I55471d363e401fdcf8d259670ad4eef672b731e2", "target": 0, "dataset": "other", "idx": 255022} {"func": "std::vector CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target)\n{\n\tstd::vector results;\n\tGetLengthType retval;\n\tretval.startOrder = target.startOrder;\n\tretval.startRow = target.startRow;\n\n\t// Are we trying to reach a certain pattern position?\n\tconst bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget;\n\tconst bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions;\n\n\tSEQUENCEINDEX sequence = target.sequence;\n\tif(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex();\n\tconst ModSequence &orderList = Order(sequence);\n\n\tGetLengthMemory memory(*this);\n\tCSoundFile::PlayState &playState = *memory.state;\n\t// Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time)\n\tRowVisitor visitedRows(*this, sequence);\n\n\tplayState.m_nNextRow = playState.m_nRow = target.startRow;\n\tplayState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder;\n\n\t// Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode.\n\tstd::bitset forbiddenCommands;\n\tstd::bitset forbiddenVolCommands;\n\n\tif(adjustSamplePos)\n\t{\n\t\tforbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP);\n\t\tforbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN);\n\t\tforbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG);\n\t\tforbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG);\n\t\tforbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN);\n\n\t\t// Optimize away channels for which it's pointless to adjust sample positions\n\t\tfor(CHANNELINDEX i = 0; i < GetNumChannels(); i++)\n\t\t{\n\t\t\tif(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;\n\t\t}\n\t\tif(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size())\n\t\t{\n\t\t\t// If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start.\n\t\t\tconst PATTERNINDEX seekPat = orderList[target.pos.order];\n\t\t\tif(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row))\n\t\t\t{\n\t\t\t\tconst ModCommand *m = Patterns[seekPat].GetRow(target.pos.row);\n\t\t\t\tfor(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++)\n\t\t\t\t{\n\t\t\t\t\tif(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments())\n\t\t\t\t\t\t|| (m->IsNote() && !m->IsPortamento()))\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// If samples are being synced, force them to resync if tick duration changes\n\tuint32 oldTickDuration = 0;\n\n\tfor (;;)\n\t{\n\t\t// Time target reached.\n\t\tif(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time)\n\t\t{\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tuint32 rowDelay = 0, tickDelay = 0;\n\t\tplayState.m_nRow = playState.m_nNextRow;\n\t\tplayState.m_nCurrentOrder = playState.m_nNextOrder;\n\n\t\tif(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows())\n\t\t{\n\t\t\tplayState.m_nRow = 0;\n\t\t\tif(m_playBehaviour[kFT2LoopE60Restart])\n\t\t\t{\n\t\t\t\tplayState.m_nRow = playState.m_nNextPatStartRow;\n\t\t\t\tplayState.m_nNextPatStartRow = 0;\n\t\t\t}\n\t\t\tplayState.m_nCurrentOrder = ++playState.m_nNextOrder;\n\t\t}\n\n\t\t// Check if pattern is valid\n\t\tplayState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();\n\t\tbool positionJumpOnThisRow = false;\n\t\tbool patternBreakOnThisRow = false;\n\t\tbool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false;\n\n\t\tif(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order)\n\t\t{\n\t\t\t// Early test: Target is inside +++ or non-existing pattern\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\twhile(playState.m_nPattern >= Patterns.Size())\n\t\t{\n\t\t\t// End of song?\n\t\t\tif((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size()))\n\t\t\t{\n\t\t\t\tif(playState.m_nCurrentOrder == orderList.GetRestartPos())\n\t\t\t\t\tbreak;\n\t\t\t\telse\n\t\t\t\t\tplayState.m_nCurrentOrder = orderList.GetRestartPos();\n\t\t\t} else\n\t\t\t{\n\t\t\t\tplayState.m_nCurrentOrder++;\n\t\t\t}\n\t\t\tplayState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();\n\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder;\n\t\t\tif((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true))\n\t\t\t{\n\t\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t\t{\n\t\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\t\tbreak;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\t\tresults.push_back(retval);\n\t\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\t\tmemory.Reset();\n\n\t\t\t\t\tplayState.m_nCurrentOrder = playState.m_nNextOrder;\n\t\t\t\t\tplayState.m_nPattern = orderList[playState.m_nCurrentOrder];\n\t\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(playState.m_nNextOrder == ORDERINDEX_INVALID)\n\t\t{\n\t\t\t// GetFirstUnvisitedRow failed, so there is nothing more to play\n\t\t\tbreak;\n\t\t}\n\n\t\t// Skip non-existing patterns\n\t\tif(!Patterns.IsValidPat(playState.m_nPattern))\n\t\t{\n\t\t\t// If there isn't even a tune, we should probably stop here.\n\t\t\tif(playState.m_nCurrentOrder == orderList.GetRestartPos())\n\t\t\t{\n\t\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t\t{\n\t\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\t\tbreak;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\t\tresults.push_back(retval);\n\t\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\t\tmemory.Reset();\n\t\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder + 1;\n\t\t\tcontinue;\n\t\t}\n\t\t// Should never happen\n\t\tif(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())\n\t\t\tplayState.m_nRow = 0;\n\n\t\t// Check whether target was reached.\n\t\tif(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row)\n\t\t{\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true))\n\t\t{\n\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t{\n\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\tbreak;\n\t\t\t} else\n\t\t\t{\n\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\tresults.push_back(retval);\n\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\tmemory.Reset();\n\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tretval.endOrder = playState.m_nCurrentOrder;\n\t\tretval.endRow = playState.m_nRow;\n\n\t\t// Update next position\n\t\tplayState.m_nNextRow = playState.m_nRow + 1;\n\n\t\t// Jumped to invalid pattern row?\n\t\tif(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())\n\t\t{\n\t\t\tplayState.m_nRow = 0;\n\t\t}\n\t\t// New pattern?\n\t\tif(!playState.m_nRow)\n\t\t{\n\t\t\tfor(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)\n\t\t\t{\n\t\t\t\tmemory.chnSettings[chn].patLoop = memory.elapsedTime;\n\t\t\t\tmemory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t}\n\t\t}\n\n\t\tModChannel *pChn = playState.Chn;\n\t\t\n\t\t// For various effects, we need to know first how many ticks there are in this row.\n\t\tconst ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0);\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++)\n\t\t{\n\t\t\tif(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])\t// not even effects are processed on muted S3M channels\n\t\t\t\tcontinue;\n\t\t\tif(p->IsPcNote())\n\t\t\t{\n#ifndef NO_PLUGINS\n\t\t\t\tif((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS)\n\t\t\t\t{\n\t\t\t\t\tmemory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol();\n\t\t\t\t}\n#endif // NO_PLUGINS\n\t\t\t\tpChn[nChn].rowCommand.Clear();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpChn[nChn].rowCommand = *p;\n\t\t\tswitch(p->command)\n\t\t\t{\n\t\t\tcase CMD_SPEED:\n\t\t\t\tSetSpeed(playState, p->param);\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_TEMPO:\n\t\t\t\tif(m_playBehaviour[kMODVBlankTiming])\n\t\t\t\t{\n\t\t\t\t\t// ProTracker MODs with VBlank timing: All Fxx parameters set the tick count.\n\t\t\t\t\tif(p->param != 0) SetSpeed(playState, p->param);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tif((p->param & 0xF0) == 0x60)\n\t\t\t\t{\n\t\t\t\t\t// Fine Pattern Delay\n\t\t\t\t\ttickDelay += (p->param & 0x0F);\n\t\t\t\t} else if((p->param & 0xF0) == 0xE0 && !rowDelay)\n\t\t\t\t{\n\t\t\t\t\t// Pattern Delay\n\t\t\t\t\tif(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t// While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right),\n\t\t\t\t\t\t// Scream Tracker 3 simply ignores such commands.\n\t\t\t\t\t\trowDelay = 1 + (p->param & 0x0F);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tif((p->param & 0xF0) == 0xE0)\n\t\t\t\t{\n\t\t\t\t\t// Pattern Delay\n\t\t\t\t\trowDelay = 1 + (p->param & 0x0F);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(rowDelay == 0) rowDelay = 1;\n\t\tconst uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay;\n\t\tconst uint32 nonRowTicks = numTicks - rowDelay;\n\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty())\n\t\t{\n\t\t\tif(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])\t// not even effects are processed on muted S3M channels\n\t\t\t\tcontinue;\n\t\t\tModCommand::COMMAND command = pChn->rowCommand.command;\n\t\t\tModCommand::PARAM param = pChn->rowCommand.param;\n\t\t\tModCommand::NOTE note = pChn->rowCommand.note;\n\n\t\t\tif (pChn->rowCommand.instr)\n\t\t\t{\n\t\t\t\tpChn->nNewIns = pChn->rowCommand.instr;\n\t\t\t\tpChn->nLastNote = NOTE_NONE;\n\t\t\t\tmemory.chnSettings[nChn].vol = 0xFF;\n\t\t\t}\n\t\t\tif (pChn->rowCommand.IsNote()) pChn->nLastNote = note;\n\n\t\t\t// Update channel panning\n\t\t\tif(pChn->rowCommand.IsNote() || pChn->rowCommand.instr)\n\t\t\t{\n\t\t\t\tSAMPLEINDEX smp = 0;\n\t\t\t\tif(GetNumInstruments())\n\t\t\t\t{\n\t\t\t\t\tModInstrument *pIns;\n\t\t\t\t\tif(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(pIns->dwFlags[INS_SETPANNING])\n\t\t\t\t\t\t\tpChn->nPan = pIns->nPan;\n\t\t\t\t\t\tif(ModCommand::IsNote(note))\n\t\t\t\t\t\t\tsmp = pIns->Keyboard[note - NOTE_MIN];\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tsmp = pChn->nNewIns;\n\t\t\t\t}\n\t\t\t\tif(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING])\n\t\t\t\t{\n\t\t\t\t\tpChn->nPan = Samples[smp].nPan;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch(pChn->rowCommand.volcmd)\n\t\t\t{\n\t\t\tcase VOLCMD_VOLUME:\n\t\t\t\tmemory.chnSettings[nChn].vol = pChn->rowCommand.vol;\n\t\t\t\tbreak;\n\t\t\tcase VOLCMD_VOLSLIDEUP:\n\t\t\tcase VOLCMD_VOLSLIDEDOWN:\n\t\t\t\tif(pChn->rowCommand.vol != 0)\n\t\t\t\t\tpChn->nOldVolParam = pChn->rowCommand.vol;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch(command)\n\t\t\t{\n\t\t\t// Position Jump\n\t\t\tcase CMD_POSITIONJUMP:\n\t\t\t\tpositionJumpOnThisRow = true;\n\t\t\t\tplayState.m_nNextOrder = static_cast(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn));\n\t\t\t\tplayState.m_nNextPatStartRow = 0; // FT2 E60 bug\n\t\t\t\t// see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx\n\t\t\t\t// Test case: PatternJump.mod\n\t\t\t\tif(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM)))\n\t\t\t\t\tplayState.m_nNextRow = 0;\n\n\t\t\t\tif (adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tpChn->nPatternLoopCount = 0;\n\t\t\t\t\tpChn->nPatternLoop = 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Pattern Break\n\t\t\tcase CMD_PATTERNBREAK:\n\t\t\t\t{\n\t\t\t\t\tROWINDEX row = PatternBreak(playState, nChn, param);\n\t\t\t\t\tif(row != ROWINDEX_INVALID)\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternBreakOnThisRow = true;\n\t\t\t\t\t\tplayState.m_nNextRow = row;\n\n\t\t\t\t\t\tif(!positionJumpOnThisRow)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpChn->nPatternLoopCount = 0;\n\t\t\t\t\t\t\tpChn->nPatternLoop = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Set Tempo\n\t\t\tcase CMD_TEMPO:\n\t\t\t\tif(!m_playBehaviour[kMODVBlankTiming])\n\t\t\t\t{\n\t\t\t\t\tTEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0);\n\t\t\t\t\tif ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (tempo.GetInt()) pChn->nOldTempo = static_cast(tempo.GetInt()); else tempo.Set(pChn->nOldTempo);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// Tempo Slide\n\t\t\t\t\t\tTEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0);\n\t\t\t\t\t\tif ((tempo.GetInt() & 0xF0) == 0x10)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tplayState.m_nMusicTempo += tempoDiff;\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(tempoDiff < playState.m_nMusicTempo)\n\t\t\t\t\t\t\t\tplayState.m_nMusicTempo -= tempoDiff;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tplayState.m_nMusicTempo.Set(0);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tTEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax();\n\t\t\t\t\tif(m_playBehaviour[kTempoClamp])\t// clamp tempo correctly in compatible mode\n\t\t\t\t\t{\n\t\t\t\t\t\ttempoMax.Set(255);\n\t\t\t\t\t}\n\t\t\t\t\tLimit(playState.m_nMusicTempo, tempoMin, tempoMax);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tswitch(param & 0xF0)\n\t\t\t\t{\n\t\t\t\tcase 0x90:\n\t\t\t\t\tif(param <= 0x91)\n\t\t\t\t\t{\n\t\t\t\t\t\tpChn->dwFlags.set(CHN_SURROUND, param == 0x91);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xA0:\n\t\t\t\t\t// High sample offset\n\t\t\t\t\tpChn->nOldHiOffset = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t\n\t\t\t\tcase 0xB0:\n\t\t\t\t\t// Pattern Loop\n\t\t\t\t\tif (param & 0x0F)\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternLoopEndedOnThisRow = true;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tCHANNELINDEX firstChn = nChn, lastChn = nChn;\n\t\t\t\t\t\tif(GetType() == MOD_TYPE_S3M)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// ST3 has only one global loop memory.\n\t\t\t\t\t\t\tfirstChn = 0;\n\t\t\t\t\t\t\tlastChn = GetNumChannels() - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor(CHANNELINDEX c = firstChn; c <= lastChn; c++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoop = memory.elapsedTime;\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoopStart = playState.m_nRow;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpatternLoopStartedOnThisRow = true;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xF0:\n\t\t\t\t\t// Active macro\n\t\t\t\t\tpChn->nActiveMacro = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tswitch(param & 0xF0)\n\t\t\t\t{\n\t\t\t\tcase 0x60:\n\t\t\t\t\t// Pattern Loop\n\t\t\t\t\tif (param & 0x0F)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug\n\t\t\t\t\t\tpatternLoopEndedOnThisRow = true;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternLoopStartedOnThisRow = true;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopStart = playState.m_nRow;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xF0:\n\t\t\t\t\t// Active macro\n\t\t\t\t\tpChn->nActiveMacro = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_XFINEPORTAUPDOWN:\n\t\t\t\t// ignore high offset in compatible mode\n\t\t\t\tif(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// The following calculations are not interesting if we just want to get the song length.\n\t\t\tif (!(adjustMode & eAdjust)) continue;\n\t\t\tswitch(command)\n\t\t\t{\n\t\t\t// Portamento Up/Down\n\t\t\tcase CMD_PORTAMENTOUP:\n\t\t\t\tif(param)\n\t\t\t\t{\n\t\t\t\t\t// FT2 compatibility: Separate effect memory for all portamento commands\n\t\t\t\t\t// Test case: Porta-LinkMem.xm\n\t\t\t\t\tif(!m_playBehaviour[kFT2PortaUpDownMemory])\n\t\t\t\t\t\tpChn->nOldPortaDown = param;\n\t\t\t\t\tpChn->nOldPortaUp = param;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CMD_PORTAMENTODOWN:\n\t\t\t\tif(param)\n\t\t\t\t{\n\t\t\t\t\t// FT2 compatibility: Separate effect memory for all portamento commands\n\t\t\t\t\t// Test case: Porta-LinkMem.xm\n\t\t\t\t\tif(!m_playBehaviour[kFT2PortaUpDownMemory])\n\t\t\t\t\t\tpChn->nOldPortaUp = param;\n\t\t\t\t\tpChn->nOldPortaDown = param;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Tone-Portamento\n\t\t\tcase CMD_TONEPORTAMENTO:\n\t\t\t\tif (param) pChn->nPortamentoSlide = param << 2;\n\t\t\t\tbreak;\n\t\t\t// Offset\n\t\t\tcase CMD_OFFSET:\n\t\t\t\tif (param) pChn->oldOffset = param << 8;\n\t\t\t\tbreak;\n\t\t\t// Volume Slide\n\t\t\tcase CMD_VOLUMESLIDE:\n\t\t\tcase CMD_TONEPORTAVOL:\n\t\t\t\tif (param) pChn->nOldVolumeSlide = param;\n\t\t\t\tbreak;\n\t\t\t// Set Volume\n\t\t\tcase CMD_VOLUME:\n\t\t\t\tmemory.chnSettings[nChn].vol = param;\n\t\t\t\tbreak;\n\t\t\t// Global Volume\n\t\t\tcase CMD_GLOBALVOLUME:\n\t\t\t\tif(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2;\n\t\t\t\t// IT compatibility 16. ST3 and IT ignore out-of-range values\n\t\t\t\tif(param <= 128)\n\t\t\t\t{\n\t\t\t\t\tplayState.m_nGlobalVolume = param * 2;\n\t\t\t\t} else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M)))\n\t\t\t\t{\n\t\t\t\t\tplayState.m_nGlobalVolume = 256;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Global Volume Slide\n\t\t\tcase CMD_GLOBALVOLSLIDE:\n\t\t\t\tif(m_playBehaviour[kPerChannelGlobalVolSlide])\n\t\t\t\t{\n\t\t\t\t\t// IT compatibility 16. Global volume slide params are stored per channel (FT2/IT)\n\t\t\t\t\tif (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide;\n\t\t\t\t}\n\t\t\t\tif (((param & 0x0F) == 0x0F) && (param & 0xF0))\n\t\t\t\t{\n\t\t\t\t\tparam >>= 4;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume += param << 1;\n\t\t\t\t} else if (((param & 0xF0) == 0xF0) && (param & 0x0F))\n\t\t\t\t{\n\t\t\t\t\tparam = (param & 0x0F) << 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume -= param;\n\t\t\t\t} else if (param & 0xF0)\n\t\t\t\t{\n\t\t\t\t\tparam >>= 4;\n\t\t\t\t\tparam <<= 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume += param * nonRowTicks;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tparam = (param & 0x0F) << 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume -= param * nonRowTicks;\n\t\t\t\t}\n\t\t\t\tLimit(playState.m_nGlobalVolume, 0, 256);\n\t\t\t\tbreak;\n\t\t\tcase CMD_CHANNELVOLUME:\n\t\t\t\tif (param <= 64) pChn->nGlobalVol = param;\n\t\t\t\tbreak;\n\t\t\tcase CMD_CHANNELVOLSLIDE:\n\t\t\t\t{\n\t\t\t\t\tif (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide;\n\t\t\t\t\tint32 volume = pChn->nGlobalVol;\n\t\t\t\t\tif((param & 0x0F) == 0x0F && (param & 0xF0))\n\t\t\t\t\t\tvolume += (param >> 4);\t\t// Fine Up\n\t\t\t\t\telse if((param & 0xF0) == 0xF0 && (param & 0x0F))\n\t\t\t\t\t\tvolume -= (param & 0x0F);\t// Fine Down\n\t\t\t\t\telse if(param & 0x0F)\t\t\t// Down\n\t\t\t\t\t\tvolume -= (param & 0x0F) * nonRowTicks;\n\t\t\t\t\telse\t\t\t\t\t\t\t// Up\n\t\t\t\t\t\tvolume += ((param & 0xF0) >> 4) * nonRowTicks;\n\t\t\t\t\tLimit(volume, 0, 64);\n\t\t\t\t\tpChn->nGlobalVol = volume;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CMD_PANNING8:\n\t\t\t\tPanning(pChn, param, Pan8bit);\n\t\t\t\tbreak;\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tif(param < 0x10)\n\t\t\t\t{\n\t\t\t\t\t// LED filter\n\t\t\t\t\tfor(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tMPT_FALLTHROUGH;\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tif((param & 0xF0) == 0x80)\n\t\t\t\t{\n\t\t\t\t\tPanning(pChn, (param & 0x0F), Pan4bit);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\tif (param) pChn->nOldVolumeSlide = param;\n\t\t\t\tparam = 0;\n\t\t\t\tMPT_FALLTHROUGH;\n\t\t\tcase CMD_VIBRATO:\n\t\t\t\tVibrato(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_FINEVIBRATO:\n\t\t\t\tFineVibrato(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_TREMOLO:\n\t\t\t\tTremolo(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_PANBRELLO:\n\t\t\t\tPanbrello(pChn, param);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch(pChn->rowCommand.volcmd)\n\t\t\t{\n\t\t\tcase VOLCMD_PANNING:\n\t\t\t\tPanning(pChn, pChn->rowCommand.vol, Pan6bit);\n\t\t\t\tbreak;\n\n\t\t\tcase VOLCMD_VIBRATOSPEED:\n\t\t\t\t// FT2 does not automatically enable vibrato with the \"set vibrato speed\" command\n\t\t\t\tif(m_playBehaviour[kFT2VolColVibrato])\n\t\t\t\t\tpChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F;\n\t\t\t\telse\n\t\t\t\t\tVibrato(pChn, pChn->rowCommand.vol << 4);\n\t\t\t\tbreak;\n\t\t\tcase VOLCMD_VIBRATODEPTH:\n\t\t\t\tVibrato(pChn, pChn->rowCommand.vol);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Process vibrato / tremolo / panbrello\n\t\t\tswitch(pChn->rowCommand.command)\n\t\t\t{\n\t\t\tcase CMD_VIBRATO:\n\t\t\tcase CMD_FINEVIBRATO:\n\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tuint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;\n\t\t\t\t\tuint32 inc = pChn->nVibratoSpeed * vibTicks;\n\t\t\t\t\tif(m_playBehaviour[kITVibratoTremoloPanbrello])\n\t\t\t\t\t\tinc *= 4;\n\t\t\t\t\tpChn->nVibratoPos += static_cast(inc);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_TREMOLO:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tuint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;\n\t\t\t\t\tuint32 inc = pChn->nTremoloSpeed * tremTicks;\n\t\t\t\t\tif(m_playBehaviour[kITVibratoTremoloPanbrello])\n\t\t\t\t\t\tinc *= 4;\n\t\t\t\t\tpChn->nTremoloPos += static_cast(inc);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_PANBRELLO:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\t// Panbrello effect is permanent in compatible mode, so actually apply panbrello for the last tick of this row\n\t\t\t\t\tpChn->nPanbrelloPos += static_cast(pChn->nPanbrelloSpeed * (numTicks - 1));\n\t\t\t\t\tProcessPanbrello(pChn);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Interpret F00 effect in XM files as \"stop song\"\n\t\tif(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tplayState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat;\n\t\tif(Patterns[playState.m_nPattern].GetOverrideSignature())\n\t\t{\n\t\t\tplayState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat();\n\t\t}\n\n\t\tconst uint32 tickDuration = GetTickDuration(playState);\n\t\tconst uint32 rowDuration = tickDuration * numTicks;\n\t\tmemory.elapsedTime += static_cast(rowDuration) / static_cast(m_MixerSettings.gdwMixingFreq);\n\t\tplayState.m_lTotalSampleCount += rowDuration;\n\n\t\tif(adjustSamplePos)\n\t\t{\n\t\t\t// Super experimental and dirty sample seeking\n\t\t\tpChn = playState.Chn;\n\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++)\n\t\t\t{\n\t\t\t\tif(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tuint32 startTick = 0;\n\t\t\t\tconst ModCommand &m = pChn->rowCommand;\n\t\t\t\tuint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F;\n\t\t\t\tbool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO;\n\t\t\t\tbool stopNote = patternLoopStartedOnThisRow;\t// It's too much trouble to keep those pattern loops in sync...\n\n\t\t\t\tif(m.instr) pChn->proTrackerOffset = 0;\n\t\t\t\tif(m.IsNote())\n\t\t\t\t{\n\t\t\t\t\tif(porta && memory.chnSettings[nChn].incChanged)\n\t\t\t\t\t{\n\t\t\t\t\t\t// If there's a portamento, the current channel increment mustn't be 0 in NoteChange()\n\t\t\t\t\t\tpChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0);\n\t\t\t\t\t}\n\t\t\t\t\tint32 setPan = pChn->nPan;\n\t\t\t\t\tpChn->nNewNote = pChn->nLastNote;\n\t\t\t\t\tif(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta);\n\t\t\t\t\tNoteChange(pChn, m.note, porta);\n\t\t\t\t\tmemory.chnSettings[nChn].incChanged = true;\n\n\t\t\t\t\tif((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick = paramLo;\n\t\t\t\t\t} else if(m.command == CMD_DELAYCUT && paramHi < numTicks)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick = paramHi;\n\t\t\t\t\t}\n\t\t\t\t\tif(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1);\n\t\t\t\t\t}\n\t\t\t\t\tif(!porta) memory.chnSettings[nChn].ticksToRender = 0;\n\n\t\t\t\t\t// Panning commands have to be re-applied after a note change with potential pan change.\n\t\t\t\t\tif(m.command == CMD_PANNING8\n\t\t\t\t\t\t|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8)\n\t\t\t\t\t\t|| m.volcmd == VOLCMD_PANNING)\n\t\t\t\t\t{\n\t\t\t\t\t\tpChn->nPan = setPan;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(m.command == CMD_OFFSET)\n\t\t\t\t\t{\n\t\t\t\t\t\tbool isExtended = false;\n\t\t\t\t\t\tSmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended);\n\t\t\t\t\t\tif(!isExtended)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toffset <<= 8;\n\t\t\t\t\t\t\tif(offset == 0) offset = pChn->oldOffset;\n\t\t\t\t\t\t\toffset += static_cast(pChn->nOldHiOffset) << 16;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSampleOffset(*pChn, offset);\n\t\t\t\t\t} else if(m.command == CMD_OFFSETPERCENTAGE)\n\t\t\t\t\t{\n\t\t\t\t\t\tSampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255));\n\t\t\t\t\t} else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\tReverseSampleOffset(*pChn, m.param);\n\t\t\t\t\t\tstartTick = playState.m_nMusicSpeed - 1;\n\t\t\t\t\t} else if(m.volcmd == VOLCMD_OFFSET)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSmpLength offset;\n\t\t\t\t\t\t\tif(m.vol == 0)\n\t\t\t\t\t\t\t\toffset = pChn->oldOffset;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\toffset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1];\n\t\t\t\t\t\t\tSampleOffset(*pChn, offset);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments())\n\t\t\t\t\t|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks)\n\t\t\t\t\t|| (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks))\n\t\t\t\t{\n\t\t\t\t\tstopNote = true;\n\t\t\t\t}\n\n\t\t\t\tif(m.command == CMD_VOLUME)\n\t\t\t\t{\n\t\t\t\t\tpChn->nVolume = m.param * 4;\n\t\t\t\t} else if(m.volcmd == VOLCMD_VOLUME)\n\t\t\t\t{\n\t\t\t\t\tpChn->nVolume = m.vol * 4;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(pChn->pModSample && !stopNote)\n\t\t\t\t{\n\t\t\t\t\t// Check if we don't want to emulate some effect and thus stop processing.\n\t\t\t\t\tif(m.command < MAX_EFFECTS)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(forbiddenCommands[m.command])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t\t} else if(m.command == CMD_MODCMDEX)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Special case: Slides using extended commands\n\t\t\t\t\t\t\tswitch(m.param & 0xF0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 0x10:\n\t\t\t\t\t\t\tcase 0x20:\n\t\t\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd])\n\t\t\t\t\t{\n\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(stopNote)\n\t\t\t\t{\n\t\t\t\t\tpChn->Stop();\n\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender = 0;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif(oldTickDuration != tickDuration && oldTickDuration != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t}\n\n\t\t\t\t\tswitch(m.command)\n\t\t\t\t\t{\n\t\t\t\t\tcase CMD_TONEPORTAVOL:\n\t\t\t\t\tcase CMD_VOLUMESLIDE:\n\t\t\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\t\t\tif(m.param || (GetType() != MOD_TYPE_MOD))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(uint32 i = 0; i < numTicks; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->isFirstTick = (i == 0);\n\t\t\t\t\t\t\t\tVolumeSlide(pChn, m.param);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase CMD_MODCMDEX:\n\t\t\t\t\t\tif((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpChn->isFirstTick = true;\n\t\t\t\t\t\t\tswitch(m.param & 0xF0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break;\n\t\t\t\t\t\t\tcase 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\t\t\tif(m.param == 0x9E)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Play forward\n\t\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\t\tpChn->dwFlags.reset(CHN_PINGPONGFLAG);\n\t\t\t\t\t\t} else if(m.param == 0x9F)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Reverse\n\t\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\t\tpChn->dwFlags.set(CHN_PINGPONGFLAG);\n\t\t\t\t\t\t\tif(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP]))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if((m.param & 0xF0) == 0x70)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// TODO\n\t\t\t\t\t\t\t//ExtendedS3MCommands(nChn, param);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tpChn->isFirstTick = true;\n\t\t\t\t\tswitch(m.volcmd)\n\t\t\t\t\t{\n\t\t\t\t\tcase VOLCMD_FINEVOLUP:\t\tFineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;\n\t\t\t\t\tcase VOLCMD_FINEVOLDOWN:\tFineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;\n\t\t\t\t\tcase VOLCMD_VOLSLIDEUP:\n\t\t\t\t\tcase VOLCMD_VOLSLIDEDOWN:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// IT Compatibility: Volume column volume slides have their own memory\n\t\t\t\t\t\t\t// Test case: VolColMemory.it\n\t\t\t\t\t\t\tModCommand::VOL vol = m.vol;\n\t\t\t\t\t\t\tif(vol == 0 && m_playBehaviour[kITVolColMemory])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvol = pChn->nOldVolParam;\n\t\t\t\t\t\t\t\tif(vol == 0)\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(m.volcmd == VOLCMD_VOLSLIDEUP)\n\t\t\t\t\t\t\t\tvol <<= 4;\n\t\t\t\t\t\t\tfor(uint32 i = 0; i < numTicks; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->isFirstTick = (i == 0);\n\t\t\t\t\t\t\t\tVolumeSlide(pChn, vol);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(porta)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Portamento needs immediate syncing, as the pitch changes on each tick\n\t\t\t\t\t\tuint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1;\n\t\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender += numTicks;\n\t\t\t\t\t\tmemory.RenderChannel(nChn, tickDuration, portaTick);\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender += (numTicks - startTick);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\toldTickDuration = tickDuration;\n\n\t\t// Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row.\n\t\t// Pattern loop is not executed in IT if there are any position jump commands on the same row.\n\t\t// Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm\n\t\t// Test case for IT: exception: LoopBreak.it\n\t\tif(patternLoopEndedOnThisRow\n\t\t\t&& (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow))\n\t\t\t&& (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow))\n\t\t{\n\t\t\tstd::map startTimes;\n\t\t\t// This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row.\n\t\t\t// If one of them starts or ends \"in between\", it will most likely calculate a wrong duration.\n\t\t\t// For S3M files, it's also way off.\n\t\t\tpChn = playState.Chn;\n\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n\t\t\t{\n\t\t\t\tModCommand::COMMAND command = pChn->rowCommand.command;\n\t\t\t\tModCommand::PARAM param = pChn->rowCommand.param;\n\t\t\t\tif((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF)\n\t\t\t\t\t|| (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F))\n\t\t\t\t{\n\t\t\t\t\tconst double start = memory.chnSettings[nChn].patLoop;\n\t\t\t\t\tif(!startTimes[start]) startTimes[start] = 1;\n\t\t\t\t\tstartTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F));\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(const auto &i : startTimes)\n\t\t\t{\n\t\t\t\tmemory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1);\n\t\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n\t\t\t\t{\n\t\t\t\t\tif(memory.chnSettings[nChn].patLoop == i.first)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1);\n\t\t\t\t\t\tif(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(GetType() == MOD_TYPE_IT)\n\t\t\t{\n\t\t\t\t// IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0)\n\t\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)\n\t\t\t\t{\n\t\t\t\t\tif((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF))\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now advance the sample positions for sample seeking on channels that are still playing\n\tif(adjustSamplePos)\n\t{\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)\n\t\t{\n\t\t\tif(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL)\n\t\t\t{\n\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\n\t\t\t}\n\t\t}\n\t}\n\n\tif(retval.targetReached || target.mode == GetLengthTarget::NoTarget)\n\t{\n\t\tretval.lastOrder = playState.m_nCurrentOrder;\n\t\tretval.lastRow = playState.m_nRow;\n\t}\n\tretval.duration = memory.elapsedTime;\n\tresults.push_back(retval);\n\n\t// Store final variables\n\tif(adjustMode & eAdjust)\n\t{\n\t\tif(retval.targetReached || target.mode == GetLengthTarget::NoTarget)\n\t\t{\n\t\t\t// Target found, or there is no target (i.e. play whole song)...\n\t\t\tm_PlayState = std::move(playState);\n\t\t\tm_PlayState.m_nNextRow = m_PlayState.m_nRow;\n\t\t\tm_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0;\n\t\t\tm_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1;\n\t\t\tm_PlayState.m_bPositionChanged = true;\n\t\t\tfor(CHANNELINDEX n = 0; n < GetNumChannels(); n++)\n\t\t\t{\n\t\t\t\tif(m_PlayState.Chn[n].nLastNote != NOTE_NONE)\n\t\t\t\t{\n\t\t\t\t\tm_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote;\n\t\t\t\t}\n\t\t\t\tif(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos)\n\t\t\t\t{\n\t\t\t\t\tm_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4;\n\t\t\t\t}\n\t\t\t}\n\n#ifndef NO_PLUGINS\n\t\t\t// If there were any PC events, update plugin parameters to their latest value.\n\t\t\tstd::bitset plugSetProgram;\n\t\t\tfor(const auto ¶m : memory.plugParams)\n\t\t\t{\n\t\t\t\tPLUGINDEX plug = param.first.first - 1;\n\t\t\t\tIMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin;\n\t\t\t\tif(plugin != nullptr)\n\t\t\t\t{\n\t\t\t\t\tif(!plugSetProgram[plug])\n\t\t\t\t\t{\n\t\t\t\t\t\t// Used for bridged plugins to avoid sending out individual messages for each parameter.\n\t\t\t\t\t\tplugSetProgram.set(plug);\n\t\t\t\t\t\tplugin->BeginSetProgram();\n\t\t\t\t\t}\n\t\t\t\t\tplugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(plugSetProgram.any())\n\t\t\t{\n\t\t\t\tfor(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++)\n\t\t\t\t{\n\t\t\t\t\tif(plugSetProgram[i])\n\t\t\t\t\t{\n\t\t\t\t\t\tm_MixPlugins[i].pMixPlugin->EndSetProgram();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n#endif // NO_PLUGINS\n\t\t} else if(adjustMode != eAdjustOnSuccess)\n\t\t{\n\t\t\t// Target not found (e.g. when jumping to a hidden sub song), reset global variables...\n\t\t\tm_PlayState.m_nMusicSpeed = m_nDefaultSpeed;\n\t\t\tm_PlayState.m_nMusicTempo = m_nDefaultTempo;\n\t\t\tm_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume;\n\t\t}\n\t\t// When adjusting the playback status, we will also want to update the visited rows vector according to the current position.\n\t\tif(sequence != Order.GetCurrentSequenceIndex())\n\t\t{\n\t\t\tOrder.SetSequence(sequence);\n\t\t}\n\t\tvisitedSongRows.Set(visitedRows);\n\t}\n\n\treturn results;\n\n}", "project": "openmpt", "hash": 248561327453942912572700036302541191491, "size": 1079, "commit_id": "7ebf02af2e90f03e0dbd0e18b8b3164f372fb97c", "message": "[Fix] Possible out-of-bounds read when computing length of some IT files with pattern loops (OpenMPT: formats that are converted to IT, libopenmpt: IT/ITP/MO3), caught with afl-fuzz.\n\ngit-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@10027 56274372-70c3-4bfc-bfc3-4c3a0b034d27", "target": 1, "dataset": "other", "idx": 197202} {"func": "std::vector CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target)\n{\n\tstd::vector results;\n\tGetLengthType retval;\n\tretval.startOrder = target.startOrder;\n\tretval.startRow = target.startRow;\n\n\t// Are we trying to reach a certain pattern position?\n\tconst bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget;\n\tconst bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions;\n\n\tSEQUENCEINDEX sequence = target.sequence;\n\tif(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex();\n\tconst ModSequence &orderList = Order(sequence);\n\n\tGetLengthMemory memory(*this);\n\tCSoundFile::PlayState &playState = *memory.state;\n\t// Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time)\n\tRowVisitor visitedRows(*this, sequence);\n\n\tplayState.m_nNextRow = playState.m_nRow = target.startRow;\n\tplayState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder;\n\n\t// Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode.\n\tstd::bitset forbiddenCommands;\n\tstd::bitset forbiddenVolCommands;\n\n\tif(adjustSamplePos)\n\t{\n\t\tforbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP);\n\t\tforbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN);\n\t\tforbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG);\n\t\tforbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG);\n\t\tforbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN);\n\n\t\t// Optimize away channels for which it's pointless to adjust sample positions\n\t\tfor(CHANNELINDEX i = 0; i < GetNumChannels(); i++)\n\t\t{\n\t\t\tif(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;\n\t\t}\n\t\tif(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size())\n\t\t{\n\t\t\t// If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start.\n\t\t\tconst PATTERNINDEX seekPat = orderList[target.pos.order];\n\t\t\tif(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row))\n\t\t\t{\n\t\t\t\tconst ModCommand *m = Patterns[seekPat].GetRow(target.pos.row);\n\t\t\t\tfor(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++)\n\t\t\t\t{\n\t\t\t\t\tif(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments())\n\t\t\t\t\t\t|| (m->IsNote() && !m->IsPortamento()))\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// If samples are being synced, force them to resync if tick duration changes\n\tuint32 oldTickDuration = 0;\n\n\tfor (;;)\n\t{\n\t\t// Time target reached.\n\t\tif(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time)\n\t\t{\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tuint32 rowDelay = 0, tickDelay = 0;\n\t\tplayState.m_nRow = playState.m_nNextRow;\n\t\tplayState.m_nCurrentOrder = playState.m_nNextOrder;\n\n\t\tif(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows())\n\t\t{\n\t\t\tplayState.m_nRow = 0;\n\t\t\tif(m_playBehaviour[kFT2LoopE60Restart])\n\t\t\t{\n\t\t\t\tplayState.m_nRow = playState.m_nNextPatStartRow;\n\t\t\t\tplayState.m_nNextPatStartRow = 0;\n\t\t\t}\n\t\t\tplayState.m_nCurrentOrder = ++playState.m_nNextOrder;\n\t\t}\n\n\t\t// Check if pattern is valid\n\t\tplayState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();\n\t\tbool positionJumpOnThisRow = false;\n\t\tbool patternBreakOnThisRow = false;\n\t\tbool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false;\n\n\t\tif(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order)\n\t\t{\n\t\t\t// Early test: Target is inside +++ or non-existing pattern\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\twhile(playState.m_nPattern >= Patterns.Size())\n\t\t{\n\t\t\t// End of song?\n\t\t\tif((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size()))\n\t\t\t{\n\t\t\t\tif(playState.m_nCurrentOrder == orderList.GetRestartPos())\n\t\t\t\t\tbreak;\n\t\t\t\telse\n\t\t\t\t\tplayState.m_nCurrentOrder = orderList.GetRestartPos();\n\t\t\t} else\n\t\t\t{\n\t\t\t\tplayState.m_nCurrentOrder++;\n\t\t\t}\n\t\t\tplayState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex();\n\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder;\n\t\t\tif((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true))\n\t\t\t{\n\t\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t\t{\n\t\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\t\tbreak;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\t\tresults.push_back(retval);\n\t\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\t\tmemory.Reset();\n\n\t\t\t\t\tplayState.m_nCurrentOrder = playState.m_nNextOrder;\n\t\t\t\t\tplayState.m_nPattern = orderList[playState.m_nCurrentOrder];\n\t\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(playState.m_nNextOrder == ORDERINDEX_INVALID)\n\t\t{\n\t\t\t// GetFirstUnvisitedRow failed, so there is nothing more to play\n\t\t\tbreak;\n\t\t}\n\n\t\t// Skip non-existing patterns\n\t\tif(!Patterns.IsValidPat(playState.m_nPattern))\n\t\t{\n\t\t\t// If there isn't even a tune, we should probably stop here.\n\t\t\tif(playState.m_nCurrentOrder == orderList.GetRestartPos())\n\t\t\t{\n\t\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t\t{\n\t\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\t\tbreak;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\t\tresults.push_back(retval);\n\t\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\t\tmemory.Reset();\n\t\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder + 1;\n\t\t\tcontinue;\n\t\t}\n\t\t// Should never happen\n\t\tif(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())\n\t\t\tplayState.m_nRow = 0;\n\n\t\t// Check whether target was reached.\n\t\tif(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row)\n\t\t{\n\t\t\tretval.targetReached = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true))\n\t\t{\n\t\t\tif(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true))\n\t\t\t{\n\t\t\t\t// We aren't searching for a specific row, or we couldn't find any more unvisited rows.\n\t\t\t\tbreak;\n\t\t\t} else\n\t\t\t{\n\t\t\t\t// We haven't found the target row yet, but we found some other unplayed row... continue searching from here.\n\t\t\t\tretval.duration = memory.elapsedTime;\n\t\t\t\tresults.push_back(retval);\n\t\t\t\tretval.startRow = playState.m_nRow;\n\t\t\t\tretval.startOrder = playState.m_nNextOrder;\n\t\t\t\tmemory.Reset();\n\t\t\t\tplayState.m_nNextRow = playState.m_nRow;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tretval.endOrder = playState.m_nCurrentOrder;\n\t\tretval.endRow = playState.m_nRow;\n\n\t\t// Update next position\n\t\tplayState.m_nNextRow = playState.m_nRow + 1;\n\n\t\t// Jumped to invalid pattern row?\n\t\tif(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows())\n\t\t{\n\t\t\tplayState.m_nRow = 0;\n\t\t}\n\t\t// New pattern?\n\t\tif(!playState.m_nRow)\n\t\t{\n\t\t\tfor(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)\n\t\t\t{\n\t\t\t\tmemory.chnSettings[chn].patLoop = memory.elapsedTime;\n\t\t\t\tmemory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t}\n\t\t}\n\n\t\tModChannel *pChn = playState.Chn;\n\t\t\n\t\t// For various effects, we need to know first how many ticks there are in this row.\n\t\tconst ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0);\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++)\n\t\t{\n\t\t\tif(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])\t// not even effects are processed on muted S3M channels\n\t\t\t\tcontinue;\n\t\t\tif(p->IsPcNote())\n\t\t\t{\n#ifndef NO_PLUGINS\n\t\t\t\tif((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS)\n\t\t\t\t{\n\t\t\t\t\tmemory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol();\n\t\t\t\t}\n#endif // NO_PLUGINS\n\t\t\t\tpChn[nChn].rowCommand.Clear();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpChn[nChn].rowCommand = *p;\n\t\t\tswitch(p->command)\n\t\t\t{\n\t\t\tcase CMD_SPEED:\n\t\t\t\tSetSpeed(playState, p->param);\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_TEMPO:\n\t\t\t\tif(m_playBehaviour[kMODVBlankTiming])\n\t\t\t\t{\n\t\t\t\t\t// ProTracker MODs with VBlank timing: All Fxx parameters set the tick count.\n\t\t\t\t\tif(p->param != 0) SetSpeed(playState, p->param);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tif((p->param & 0xF0) == 0x60)\n\t\t\t\t{\n\t\t\t\t\t// Fine Pattern Delay\n\t\t\t\t\ttickDelay += (p->param & 0x0F);\n\t\t\t\t} else if((p->param & 0xF0) == 0xE0 && !rowDelay)\n\t\t\t\t{\n\t\t\t\t\t// Pattern Delay\n\t\t\t\t\tif(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t// While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right),\n\t\t\t\t\t\t// Scream Tracker 3 simply ignores such commands.\n\t\t\t\t\t\trowDelay = 1 + (p->param & 0x0F);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tif((p->param & 0xF0) == 0xE0)\n\t\t\t\t{\n\t\t\t\t\t// Pattern Delay\n\t\t\t\t\trowDelay = 1 + (p->param & 0x0F);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(rowDelay == 0) rowDelay = 1;\n\t\tconst uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay;\n\t\tconst uint32 nonRowTicks = numTicks - rowDelay;\n\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty())\n\t\t{\n\t\t\tif(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])\t// not even effects are processed on muted S3M channels\n\t\t\t\tcontinue;\n\t\t\tModCommand::COMMAND command = pChn->rowCommand.command;\n\t\t\tModCommand::PARAM param = pChn->rowCommand.param;\n\t\t\tModCommand::NOTE note = pChn->rowCommand.note;\n\n\t\t\tif (pChn->rowCommand.instr)\n\t\t\t{\n\t\t\t\tpChn->nNewIns = pChn->rowCommand.instr;\n\t\t\t\tpChn->nLastNote = NOTE_NONE;\n\t\t\t\tmemory.chnSettings[nChn].vol = 0xFF;\n\t\t\t}\n\t\t\tif (pChn->rowCommand.IsNote()) pChn->nLastNote = note;\n\n\t\t\t// Update channel panning\n\t\t\tif(pChn->rowCommand.IsNote() || pChn->rowCommand.instr)\n\t\t\t{\n\t\t\t\tSAMPLEINDEX smp = 0;\n\t\t\t\tif(GetNumInstruments())\n\t\t\t\t{\n\t\t\t\t\tModInstrument *pIns;\n\t\t\t\t\tif(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(pIns->dwFlags[INS_SETPANNING])\n\t\t\t\t\t\t\tpChn->nPan = pIns->nPan;\n\t\t\t\t\t\tif(ModCommand::IsNote(note))\n\t\t\t\t\t\t\tsmp = pIns->Keyboard[note - NOTE_MIN];\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tsmp = pChn->nNewIns;\n\t\t\t\t}\n\t\t\t\tif(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING])\n\t\t\t\t{\n\t\t\t\t\tpChn->nPan = Samples[smp].nPan;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch(pChn->rowCommand.volcmd)\n\t\t\t{\n\t\t\tcase VOLCMD_VOLUME:\n\t\t\t\tmemory.chnSettings[nChn].vol = pChn->rowCommand.vol;\n\t\t\t\tbreak;\n\t\t\tcase VOLCMD_VOLSLIDEUP:\n\t\t\tcase VOLCMD_VOLSLIDEDOWN:\n\t\t\t\tif(pChn->rowCommand.vol != 0)\n\t\t\t\t\tpChn->nOldVolParam = pChn->rowCommand.vol;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch(command)\n\t\t\t{\n\t\t\t// Position Jump\n\t\t\tcase CMD_POSITIONJUMP:\n\t\t\t\tpositionJumpOnThisRow = true;\n\t\t\t\tplayState.m_nNextOrder = static_cast(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn));\n\t\t\t\tplayState.m_nNextPatStartRow = 0; // FT2 E60 bug\n\t\t\t\t// see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx\n\t\t\t\t// Test case: PatternJump.mod\n\t\t\t\tif(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM)))\n\t\t\t\t\tplayState.m_nNextRow = 0;\n\n\t\t\t\tif (adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tpChn->nPatternLoopCount = 0;\n\t\t\t\t\tpChn->nPatternLoop = 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Pattern Break\n\t\t\tcase CMD_PATTERNBREAK:\n\t\t\t\t{\n\t\t\t\t\tROWINDEX row = PatternBreak(playState, nChn, param);\n\t\t\t\t\tif(row != ROWINDEX_INVALID)\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternBreakOnThisRow = true;\n\t\t\t\t\t\tplayState.m_nNextRow = row;\n\n\t\t\t\t\t\tif(!positionJumpOnThisRow)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tplayState.m_nNextOrder = playState.m_nCurrentOrder + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpChn->nPatternLoopCount = 0;\n\t\t\t\t\t\t\tpChn->nPatternLoop = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Set Tempo\n\t\t\tcase CMD_TEMPO:\n\t\t\t\tif(!m_playBehaviour[kMODVBlankTiming])\n\t\t\t\t{\n\t\t\t\t\tTEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0);\n\t\t\t\t\tif ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (tempo.GetInt()) pChn->nOldTempo = static_cast(tempo.GetInt()); else tempo.Set(pChn->nOldTempo);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// Tempo Slide\n\t\t\t\t\t\tTEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0);\n\t\t\t\t\t\tif ((tempo.GetInt() & 0xF0) == 0x10)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tplayState.m_nMusicTempo += tempoDiff;\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(tempoDiff < playState.m_nMusicTempo)\n\t\t\t\t\t\t\t\tplayState.m_nMusicTempo -= tempoDiff;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tplayState.m_nMusicTempo.Set(0);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tTEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax();\n\t\t\t\t\tif(m_playBehaviour[kTempoClamp])\t// clamp tempo correctly in compatible mode\n\t\t\t\t\t{\n\t\t\t\t\t\ttempoMax.Set(255);\n\t\t\t\t\t}\n\t\t\t\t\tLimit(playState.m_nMusicTempo, tempoMin, tempoMax);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tswitch(param & 0xF0)\n\t\t\t\t{\n\t\t\t\tcase 0x90:\n\t\t\t\t\tif(param <= 0x91)\n\t\t\t\t\t{\n\t\t\t\t\t\tpChn->dwFlags.set(CHN_SURROUND, param == 0x91);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xA0:\n\t\t\t\t\t// High sample offset\n\t\t\t\t\tpChn->nOldHiOffset = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t\n\t\t\t\tcase 0xB0:\n\t\t\t\t\t// Pattern Loop\n\t\t\t\t\tif (param & 0x0F)\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternLoopEndedOnThisRow = true;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tCHANNELINDEX firstChn = nChn, lastChn = nChn;\n\t\t\t\t\t\tif(GetType() == MOD_TYPE_S3M)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// ST3 has only one global loop memory.\n\t\t\t\t\t\t\tfirstChn = 0;\n\t\t\t\t\t\t\tlastChn = GetNumChannels() - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor(CHANNELINDEX c = firstChn; c <= lastChn; c++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoop = memory.elapsedTime;\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\t\tmemory.chnSettings[c].patLoopStart = playState.m_nRow;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpatternLoopStartedOnThisRow = true;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xF0:\n\t\t\t\t\t// Active macro\n\t\t\t\t\tpChn->nActiveMacro = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tswitch(param & 0xF0)\n\t\t\t\t{\n\t\t\t\tcase 0x60:\n\t\t\t\t\t// Pattern Loop\n\t\t\t\t\tif (param & 0x0F)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug\n\t\t\t\t\t\tpatternLoopEndedOnThisRow = true;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tpatternLoopStartedOnThisRow = true;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopStart = playState.m_nRow;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0xF0:\n\t\t\t\t\t// Active macro\n\t\t\t\t\tpChn->nActiveMacro = param & 0x0F;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_XFINEPORTAUPDOWN:\n\t\t\t\t// ignore high offset in compatible mode\n\t\t\t\tif(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// The following calculations are not interesting if we just want to get the song length.\n\t\t\tif (!(adjustMode & eAdjust)) continue;\n\t\t\tswitch(command)\n\t\t\t{\n\t\t\t// Portamento Up/Down\n\t\t\tcase CMD_PORTAMENTOUP:\n\t\t\t\tif(param)\n\t\t\t\t{\n\t\t\t\t\t// FT2 compatibility: Separate effect memory for all portamento commands\n\t\t\t\t\t// Test case: Porta-LinkMem.xm\n\t\t\t\t\tif(!m_playBehaviour[kFT2PortaUpDownMemory])\n\t\t\t\t\t\tpChn->nOldPortaDown = param;\n\t\t\t\t\tpChn->nOldPortaUp = param;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CMD_PORTAMENTODOWN:\n\t\t\t\tif(param)\n\t\t\t\t{\n\t\t\t\t\t// FT2 compatibility: Separate effect memory for all portamento commands\n\t\t\t\t\t// Test case: Porta-LinkMem.xm\n\t\t\t\t\tif(!m_playBehaviour[kFT2PortaUpDownMemory])\n\t\t\t\t\t\tpChn->nOldPortaUp = param;\n\t\t\t\t\tpChn->nOldPortaDown = param;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Tone-Portamento\n\t\t\tcase CMD_TONEPORTAMENTO:\n\t\t\t\tif (param) pChn->nPortamentoSlide = param << 2;\n\t\t\t\tbreak;\n\t\t\t// Offset\n\t\t\tcase CMD_OFFSET:\n\t\t\t\tif (param) pChn->oldOffset = param << 8;\n\t\t\t\tbreak;\n\t\t\t// Volume Slide\n\t\t\tcase CMD_VOLUMESLIDE:\n\t\t\tcase CMD_TONEPORTAVOL:\n\t\t\t\tif (param) pChn->nOldVolumeSlide = param;\n\t\t\t\tbreak;\n\t\t\t// Set Volume\n\t\t\tcase CMD_VOLUME:\n\t\t\t\tmemory.chnSettings[nChn].vol = param;\n\t\t\t\tbreak;\n\t\t\t// Global Volume\n\t\t\tcase CMD_GLOBALVOLUME:\n\t\t\t\tif(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2;\n\t\t\t\t// IT compatibility 16. ST3 and IT ignore out-of-range values\n\t\t\t\tif(param <= 128)\n\t\t\t\t{\n\t\t\t\t\tplayState.m_nGlobalVolume = param * 2;\n\t\t\t\t} else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M)))\n\t\t\t\t{\n\t\t\t\t\tplayState.m_nGlobalVolume = 256;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// Global Volume Slide\n\t\t\tcase CMD_GLOBALVOLSLIDE:\n\t\t\t\tif(m_playBehaviour[kPerChannelGlobalVolSlide])\n\t\t\t\t{\n\t\t\t\t\t// IT compatibility 16. Global volume slide params are stored per channel (FT2/IT)\n\t\t\t\t\tif (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide;\n\t\t\t\t}\n\t\t\t\tif (((param & 0x0F) == 0x0F) && (param & 0xF0))\n\t\t\t\t{\n\t\t\t\t\tparam >>= 4;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume += param << 1;\n\t\t\t\t} else if (((param & 0xF0) == 0xF0) && (param & 0x0F))\n\t\t\t\t{\n\t\t\t\t\tparam = (param & 0x0F) << 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume -= param;\n\t\t\t\t} else if (param & 0xF0)\n\t\t\t\t{\n\t\t\t\t\tparam >>= 4;\n\t\t\t\t\tparam <<= 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume += param * nonRowTicks;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tparam = (param & 0x0F) << 1;\n\t\t\t\t\tif (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1;\n\t\t\t\t\tplayState.m_nGlobalVolume -= param * nonRowTicks;\n\t\t\t\t}\n\t\t\t\tLimit(playState.m_nGlobalVolume, 0, 256);\n\t\t\t\tbreak;\n\t\t\tcase CMD_CHANNELVOLUME:\n\t\t\t\tif (param <= 64) pChn->nGlobalVol = param;\n\t\t\t\tbreak;\n\t\t\tcase CMD_CHANNELVOLSLIDE:\n\t\t\t\t{\n\t\t\t\t\tif (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide;\n\t\t\t\t\tint32 volume = pChn->nGlobalVol;\n\t\t\t\t\tif((param & 0x0F) == 0x0F && (param & 0xF0))\n\t\t\t\t\t\tvolume += (param >> 4);\t\t// Fine Up\n\t\t\t\t\telse if((param & 0xF0) == 0xF0 && (param & 0x0F))\n\t\t\t\t\t\tvolume -= (param & 0x0F);\t// Fine Down\n\t\t\t\t\telse if(param & 0x0F)\t\t\t// Down\n\t\t\t\t\t\tvolume -= (param & 0x0F) * nonRowTicks;\n\t\t\t\t\telse\t\t\t\t\t\t\t// Up\n\t\t\t\t\t\tvolume += ((param & 0xF0) >> 4) * nonRowTicks;\n\t\t\t\t\tLimit(volume, 0, 64);\n\t\t\t\t\tpChn->nGlobalVol = volume;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase CMD_PANNING8:\n\t\t\t\tPanning(pChn, param, Pan8bit);\n\t\t\t\tbreak;\n\t\t\tcase CMD_MODCMDEX:\n\t\t\t\tif(param < 0x10)\n\t\t\t\t{\n\t\t\t\t\t// LED filter\n\t\t\t\t\tfor(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tMPT_FALLTHROUGH;\n\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\tif((param & 0xF0) == 0x80)\n\t\t\t\t{\n\t\t\t\t\tPanning(pChn, (param & 0x0F), Pan4bit);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\tif (param) pChn->nOldVolumeSlide = param;\n\t\t\t\tparam = 0;\n\t\t\t\tMPT_FALLTHROUGH;\n\t\t\tcase CMD_VIBRATO:\n\t\t\t\tVibrato(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_FINEVIBRATO:\n\t\t\t\tFineVibrato(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_TREMOLO:\n\t\t\t\tTremolo(pChn, param);\n\t\t\t\tbreak;\n\t\t\tcase CMD_PANBRELLO:\n\t\t\t\tPanbrello(pChn, param);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch(pChn->rowCommand.volcmd)\n\t\t\t{\n\t\t\tcase VOLCMD_PANNING:\n\t\t\t\tPanning(pChn, pChn->rowCommand.vol, Pan6bit);\n\t\t\t\tbreak;\n\n\t\t\tcase VOLCMD_VIBRATOSPEED:\n\t\t\t\t// FT2 does not automatically enable vibrato with the \"set vibrato speed\" command\n\t\t\t\tif(m_playBehaviour[kFT2VolColVibrato])\n\t\t\t\t\tpChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F;\n\t\t\t\telse\n\t\t\t\t\tVibrato(pChn, pChn->rowCommand.vol << 4);\n\t\t\t\tbreak;\n\t\t\tcase VOLCMD_VIBRATODEPTH:\n\t\t\t\tVibrato(pChn, pChn->rowCommand.vol);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Process vibrato / tremolo / panbrello\n\t\t\tswitch(pChn->rowCommand.command)\n\t\t\t{\n\t\t\tcase CMD_VIBRATO:\n\t\t\tcase CMD_FINEVIBRATO:\n\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tuint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;\n\t\t\t\t\tuint32 inc = pChn->nVibratoSpeed * vibTicks;\n\t\t\t\t\tif(m_playBehaviour[kITVibratoTremoloPanbrello])\n\t\t\t\t\t\tinc *= 4;\n\t\t\t\t\tpChn->nVibratoPos += static_cast(inc);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_TREMOLO:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\tuint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks;\n\t\t\t\t\tuint32 inc = pChn->nTremoloSpeed * tremTicks;\n\t\t\t\t\tif(m_playBehaviour[kITVibratoTremoloPanbrello])\n\t\t\t\t\t\tinc *= 4;\n\t\t\t\t\tpChn->nTremoloPos += static_cast(inc);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CMD_PANBRELLO:\n\t\t\t\tif(adjustMode & eAdjust)\n\t\t\t\t{\n\t\t\t\t\t// Panbrello effect is permanent in compatible mode, so actually apply panbrello for the last tick of this row\n\t\t\t\t\tpChn->nPanbrelloPos += static_cast(pChn->nPanbrelloSpeed * (numTicks - 1));\n\t\t\t\t\tProcessPanbrello(pChn);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Interpret F00 effect in XM files as \"stop song\"\n\t\tif(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tplayState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat;\n\t\tif(Patterns[playState.m_nPattern].GetOverrideSignature())\n\t\t{\n\t\t\tplayState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat();\n\t\t}\n\n\t\tconst uint32 tickDuration = GetTickDuration(playState);\n\t\tconst uint32 rowDuration = tickDuration * numTicks;\n\t\tmemory.elapsedTime += static_cast(rowDuration) / static_cast(m_MixerSettings.gdwMixingFreq);\n\t\tplayState.m_lTotalSampleCount += rowDuration;\n\n\t\tif(adjustSamplePos)\n\t\t{\n\t\t\t// Super experimental and dirty sample seeking\n\t\t\tpChn = playState.Chn;\n\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++)\n\t\t\t{\n\t\t\t\tif(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tuint32 startTick = 0;\n\t\t\t\tconst ModCommand &m = pChn->rowCommand;\n\t\t\t\tuint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F;\n\t\t\t\tbool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO;\n\t\t\t\tbool stopNote = patternLoopStartedOnThisRow;\t// It's too much trouble to keep those pattern loops in sync...\n\n\t\t\t\tif(m.instr) pChn->proTrackerOffset = 0;\n\t\t\t\tif(m.IsNote())\n\t\t\t\t{\n\t\t\t\t\tif(porta && memory.chnSettings[nChn].incChanged)\n\t\t\t\t\t{\n\t\t\t\t\t\t// If there's a portamento, the current channel increment mustn't be 0 in NoteChange()\n\t\t\t\t\t\tpChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0);\n\t\t\t\t\t}\n\t\t\t\t\tint32 setPan = pChn->nPan;\n\t\t\t\t\tpChn->nNewNote = pChn->nLastNote;\n\t\t\t\t\tif(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta);\n\t\t\t\t\tNoteChange(pChn, m.note, porta);\n\t\t\t\t\tmemory.chnSettings[nChn].incChanged = true;\n\n\t\t\t\t\tif((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick = paramLo;\n\t\t\t\t\t} else if(m.command == CMD_DELAYCUT && paramHi < numTicks)\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick = paramHi;\n\t\t\t\t\t}\n\t\t\t\t\tif(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)))\n\t\t\t\t\t{\n\t\t\t\t\t\tstartTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1);\n\t\t\t\t\t}\n\t\t\t\t\tif(!porta) memory.chnSettings[nChn].ticksToRender = 0;\n\n\t\t\t\t\t// Panning commands have to be re-applied after a note change with potential pan change.\n\t\t\t\t\tif(m.command == CMD_PANNING8\n\t\t\t\t\t\t|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8)\n\t\t\t\t\t\t|| m.volcmd == VOLCMD_PANNING)\n\t\t\t\t\t{\n\t\t\t\t\t\tpChn->nPan = setPan;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(m.command == CMD_OFFSET)\n\t\t\t\t\t{\n\t\t\t\t\t\tbool isExtended = false;\n\t\t\t\t\t\tSmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended);\n\t\t\t\t\t\tif(!isExtended)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toffset <<= 8;\n\t\t\t\t\t\t\tif(offset == 0) offset = pChn->oldOffset;\n\t\t\t\t\t\t\toffset += static_cast(pChn->nOldHiOffset) << 16;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSampleOffset(*pChn, offset);\n\t\t\t\t\t} else if(m.command == CMD_OFFSETPERCENTAGE)\n\t\t\t\t\t{\n\t\t\t\t\t\tSampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255));\n\t\t\t\t\t} else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr)\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\tReverseSampleOffset(*pChn, m.param);\n\t\t\t\t\t\tstartTick = playState.m_nMusicSpeed - 1;\n\t\t\t\t\t} else if(m.volcmd == VOLCMD_OFFSET)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSmpLength offset;\n\t\t\t\t\t\t\tif(m.vol == 0)\n\t\t\t\t\t\t\t\toffset = pChn->oldOffset;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\toffset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1];\n\t\t\t\t\t\t\tSampleOffset(*pChn, offset);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments())\n\t\t\t\t\t|| ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks)\n\t\t\t\t\t|| (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks))\n\t\t\t\t{\n\t\t\t\t\tstopNote = true;\n\t\t\t\t}\n\n\t\t\t\tif(m.command == CMD_VOLUME)\n\t\t\t\t{\n\t\t\t\t\tpChn->nVolume = m.param * 4;\n\t\t\t\t} else if(m.volcmd == VOLCMD_VOLUME)\n\t\t\t\t{\n\t\t\t\t\tpChn->nVolume = m.vol * 4;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(pChn->pModSample && !stopNote)\n\t\t\t\t{\n\t\t\t\t\t// Check if we don't want to emulate some effect and thus stop processing.\n\t\t\t\t\tif(m.command < MAX_EFFECTS)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(forbiddenCommands[m.command])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t\t} else if(m.command == CMD_MODCMDEX)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Special case: Slides using extended commands\n\t\t\t\t\t\t\tswitch(m.param & 0xF0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 0x10:\n\t\t\t\t\t\t\tcase 0x20:\n\t\t\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd])\n\t\t\t\t\t{\n\t\t\t\t\t\tstopNote = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(stopNote)\n\t\t\t\t{\n\t\t\t\t\tpChn->Stop();\n\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender = 0;\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif(oldTickDuration != tickDuration && oldTickDuration != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t}\n\n\t\t\t\t\tswitch(m.command)\n\t\t\t\t\t{\n\t\t\t\t\tcase CMD_TONEPORTAVOL:\n\t\t\t\t\tcase CMD_VOLUMESLIDE:\n\t\t\t\t\tcase CMD_VIBRATOVOL:\n\t\t\t\t\t\tif(m.param || (GetType() != MOD_TYPE_MOD))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(uint32 i = 0; i < numTicks; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->isFirstTick = (i == 0);\n\t\t\t\t\t\t\t\tVolumeSlide(pChn, m.param);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase CMD_MODCMDEX:\n\t\t\t\t\t\tif((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpChn->isFirstTick = true;\n\t\t\t\t\t\t\tswitch(m.param & 0xF0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break;\n\t\t\t\t\t\t\tcase 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase CMD_S3MCMDEX:\n\t\t\t\t\t\tif(m.param == 0x9E)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Play forward\n\t\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\t\tpChn->dwFlags.reset(CHN_PINGPONGFLAG);\n\t\t\t\t\t\t} else if(m.param == 0x9F)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Reverse\n\t\t\t\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\t// Re-sync what we've got so far\n\t\t\t\t\t\t\tpChn->dwFlags.set(CHN_PINGPONGFLAG);\n\t\t\t\t\t\t\tif(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP]))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if((m.param & 0xF0) == 0x70)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// TODO\n\t\t\t\t\t\t\t//ExtendedS3MCommands(nChn, param);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tpChn->isFirstTick = true;\n\t\t\t\t\tswitch(m.volcmd)\n\t\t\t\t\t{\n\t\t\t\t\tcase VOLCMD_FINEVOLUP:\t\tFineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;\n\t\t\t\t\tcase VOLCMD_FINEVOLDOWN:\tFineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break;\n\t\t\t\t\tcase VOLCMD_VOLSLIDEUP:\n\t\t\t\t\tcase VOLCMD_VOLSLIDEDOWN:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// IT Compatibility: Volume column volume slides have their own memory\n\t\t\t\t\t\t\t// Test case: VolColMemory.it\n\t\t\t\t\t\t\tModCommand::VOL vol = m.vol;\n\t\t\t\t\t\t\tif(vol == 0 && m_playBehaviour[kITVolColMemory])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvol = pChn->nOldVolParam;\n\t\t\t\t\t\t\t\tif(vol == 0)\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(m.volcmd == VOLCMD_VOLSLIDEUP)\n\t\t\t\t\t\t\t\tvol <<= 4;\n\t\t\t\t\t\t\tfor(uint32 i = 0; i < numTicks; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpChn->isFirstTick = (i == 0);\n\t\t\t\t\t\t\t\tVolumeSlide(pChn, vol);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(porta)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Portamento needs immediate syncing, as the pitch changes on each tick\n\t\t\t\t\t\tuint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1;\n\t\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender += numTicks;\n\t\t\t\t\t\tmemory.RenderChannel(nChn, tickDuration, portaTick);\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[nChn].ticksToRender += (numTicks - startTick);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\toldTickDuration = tickDuration;\n\n\t\t// Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row.\n\t\t// Pattern loop is not executed in IT if there are any position jump commands on the same row.\n\t\t// Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm\n\t\t// Test case for IT: exception: LoopBreak.it\n\t\tif(patternLoopEndedOnThisRow\n\t\t\t&& (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow))\n\t\t\t&& (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow))\n\t\t{\n\t\t\tstd::map startTimes;\n\t\t\t// This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row.\n\t\t\t// If one of them starts or ends \"in between\", it will most likely calculate a wrong duration.\n\t\t\t// For S3M files, it's also way off.\n\t\t\tpChn = playState.Chn;\n\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n\t\t\t{\n\t\t\t\tModCommand::COMMAND command = pChn->rowCommand.command;\n\t\t\t\tModCommand::PARAM param = pChn->rowCommand.param;\n\t\t\t\tif((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF)\n\t\t\t\t\t|| (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F))\n\t\t\t\t{\n\t\t\t\t\tconst double start = memory.chnSettings[nChn].patLoop;\n\t\t\t\t\tif(!startTimes[start]) startTimes[start] = 1;\n\t\t\t\t\tstartTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F));\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(const auto &i : startTimes)\n\t\t\t{\n\t\t\t\tmemory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1);\n\t\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n\t\t\t\t{\n\t\t\t\t\tif(memory.chnSettings[nChn].patLoop == i.first)\n\t\t\t\t\t{\n\t\t\t\t\t\tplayState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1);\n\t\t\t\t\t\tif(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(GetType() == MOD_TYPE_IT)\n\t\t\t{\n\t\t\t\t// IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0)\n\t\t\t\tpChn = playState.Chn;\n\t\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n\t\t\t\t{\n\t\t\t\t\tif((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF))\n\t\t\t\t\t{\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoop = memory.elapsedTime;\n\t\t\t\t\t\tmemory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now advance the sample positions for sample seeking on channels that are still playing\n\tif(adjustSamplePos)\n\t{\n\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)\n\t\t{\n\t\t\tif(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL)\n\t\t\t{\n\t\t\t\tmemory.RenderChannel(nChn, oldTickDuration);\n\t\t\t}\n\t\t}\n\t}\n\n\tif(retval.targetReached || target.mode == GetLengthTarget::NoTarget)\n\t{\n\t\tretval.lastOrder = playState.m_nCurrentOrder;\n\t\tretval.lastRow = playState.m_nRow;\n\t}\n\tretval.duration = memory.elapsedTime;\n\tresults.push_back(retval);\n\n\t// Store final variables\n\tif(adjustMode & eAdjust)\n\t{\n\t\tif(retval.targetReached || target.mode == GetLengthTarget::NoTarget)\n\t\t{\n\t\t\t// Target found, or there is no target (i.e. play whole song)...\n\t\t\tm_PlayState = std::move(playState);\n\t\t\tm_PlayState.m_nNextRow = m_PlayState.m_nRow;\n\t\t\tm_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0;\n\t\t\tm_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1;\n\t\t\tm_PlayState.m_bPositionChanged = true;\n\t\t\tfor(CHANNELINDEX n = 0; n < GetNumChannels(); n++)\n\t\t\t{\n\t\t\t\tif(m_PlayState.Chn[n].nLastNote != NOTE_NONE)\n\t\t\t\t{\n\t\t\t\t\tm_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote;\n\t\t\t\t}\n\t\t\t\tif(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos)\n\t\t\t\t{\n\t\t\t\t\tm_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4;\n\t\t\t\t}\n\t\t\t}\n\n#ifndef NO_PLUGINS\n\t\t\t// If there were any PC events, update plugin parameters to their latest value.\n\t\t\tstd::bitset plugSetProgram;\n\t\t\tfor(const auto ¶m : memory.plugParams)\n\t\t\t{\n\t\t\t\tPLUGINDEX plug = param.first.first - 1;\n\t\t\t\tIMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin;\n\t\t\t\tif(plugin != nullptr)\n\t\t\t\t{\n\t\t\t\t\tif(!plugSetProgram[plug])\n\t\t\t\t\t{\n\t\t\t\t\t\t// Used for bridged plugins to avoid sending out individual messages for each parameter.\n\t\t\t\t\t\tplugSetProgram.set(plug);\n\t\t\t\t\t\tplugin->BeginSetProgram();\n\t\t\t\t\t}\n\t\t\t\t\tplugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(plugSetProgram.any())\n\t\t\t{\n\t\t\t\tfor(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++)\n\t\t\t\t{\n\t\t\t\t\tif(plugSetProgram[i])\n\t\t\t\t\t{\n\t\t\t\t\t\tm_MixPlugins[i].pMixPlugin->EndSetProgram();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n#endif // NO_PLUGINS\n\t\t} else if(adjustMode != eAdjustOnSuccess)\n\t\t{\n\t\t\t// Target not found (e.g. when jumping to a hidden sub song), reset global variables...\n\t\t\tm_PlayState.m_nMusicSpeed = m_nDefaultSpeed;\n\t\t\tm_PlayState.m_nMusicTempo = m_nDefaultTempo;\n\t\t\tm_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume;\n\t\t}\n\t\t// When adjusting the playback status, we will also want to update the visited rows vector according to the current position.\n\t\tif(sequence != Order.GetCurrentSequenceIndex())\n\t\t{\n\t\t\tOrder.SetSequence(sequence);\n\t\t}\n\t\tvisitedSongRows.Set(visitedRows);\n\t}\n\n\treturn results;\n\n}", "project": "openmpt", "hash": 82247471402509974896295465140162503884, "size": 1080, "commit_id": "7ebf02af2e90f03e0dbd0e18b8b3164f372fb97c", "message": "[Fix] Possible out-of-bounds read when computing length of some IT files with pattern loops (OpenMPT: formats that are converted to IT, libopenmpt: IT/ITP/MO3), caught with afl-fuzz.\n\ngit-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@10027 56274372-70c3-4bfc-bfc3-4c3a0b034d27", "target": 0, "dataset": "other", "idx": 255181} {"func": "static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)\n{\n#ifndef PB_ENABLE_MALLOC\n UNUSED(wire_type);\n UNUSED(iter);\n PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n pb_type_t type;\n pb_decoder_t func;\n \n type = iter->pos->type;\n func = PB_DECODERS[PB_LTYPE(type)];\n \n switch (PB_HTYPE(type))\n {\n case PB_HTYPE_REQUIRED:\n case PB_HTYPE_OPTIONAL:\n if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&\n *(void**)iter->pData != NULL)\n {\n /* Duplicate field, have to release the old allocation first. */\n pb_release_single_field(iter);\n }\n \n if (PB_LTYPE(type) == PB_LTYPE_STRING ||\n PB_LTYPE(type) == PB_LTYPE_BYTES)\n {\n return func(stream, iter->pos, iter->pData);\n }\n else\n {\n if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))\n return false;\n \n initialize_pointer_field(*(void**)iter->pData, iter);\n return func(stream, iter->pos, *(void**)iter->pData);\n }\n \n case PB_HTYPE_REPEATED:\n if (wire_type == PB_WT_STRING\n && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)\n {\n /* Packed array, multiple items come in at once. */\n bool status = true;\n size_t *size = (size_t*)iter->pSize;\n size_t allocated_size = *size;\n void *pItem;\n pb_istream_t substream;\n \n if (!pb_make_string_substream(stream, &substream))\n return false;\n \n while (substream.bytes_left)\n {\n if (*size + 1 > allocated_size)\n {\n /* Allocate more storage. This tries to guess the\n * number of remaining entries. Round the division\n * upwards. */\n allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;\n \n if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))\n {\n status = false;\n break;\n }\n }\n\n /* Decode the array entry */\n pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size);\n initialize_pointer_field(pItem, iter);\n if (!func(&substream, iter->pos, pItem))\n {\n status = false;\n break;\n }\n (*size)++;\n }\n pb_close_string_substream(stream, &substream);\n \n return status;\n }\n else\n {\n /* Normal repeated field, i.e. only one item at a time. */\n size_t *size = (size_t*)iter->pSize;\n void *pItem;\n \n (*size)++;\n if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size))\n return false;\n \n pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size - 1);\n initialize_pointer_field(pItem, iter);\n return func(stream, iter->pos, pItem);\n }\n \n default:\n PB_RETURN_ERROR(stream, \"invalid field type\");\n }\n#endif\n}", "project": "nanopb", "hash": 44925250467000600069522886101534959296, "size": 102, "commit_id": "7b396821ddd06df8e39143f16e1dc0a4645b89a3", "message": "Fix invalid free() after failed realloc() (GHSA-gcx3-7m76-287p)", "target": 1, "dataset": "other", "idx": 197204} {"func": "static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)\n{\n#ifndef PB_ENABLE_MALLOC\n UNUSED(wire_type);\n UNUSED(iter);\n PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n pb_type_t type;\n pb_decoder_t func;\n \n type = iter->pos->type;\n func = PB_DECODERS[PB_LTYPE(type)];\n \n switch (PB_HTYPE(type))\n {\n case PB_HTYPE_REQUIRED:\n case PB_HTYPE_OPTIONAL:\n if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&\n *(void**)iter->pData != NULL)\n {\n /* Duplicate field, have to release the old allocation first. */\n pb_release_single_field(iter);\n }\n \n if (PB_LTYPE(type) == PB_LTYPE_STRING ||\n PB_LTYPE(type) == PB_LTYPE_BYTES)\n {\n return func(stream, iter->pos, iter->pData);\n }\n else\n {\n if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))\n return false;\n \n initialize_pointer_field(*(void**)iter->pData, iter);\n return func(stream, iter->pos, *(void**)iter->pData);\n }\n \n case PB_HTYPE_REPEATED:\n if (wire_type == PB_WT_STRING\n && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)\n {\n /* Packed array, multiple items come in at once. */\n bool status = true;\n size_t *size = (size_t*)iter->pSize;\n size_t allocated_size = *size;\n void *pItem;\n pb_istream_t substream;\n \n if (!pb_make_string_substream(stream, &substream))\n return false;\n \n while (substream.bytes_left)\n {\n if (*size + 1 > allocated_size)\n {\n /* Allocate more storage. This tries to guess the\n * number of remaining entries. Round the division\n * upwards. */\n allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;\n \n if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))\n {\n status = false;\n break;\n }\n }\n\n /* Decode the array entry */\n pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size);\n initialize_pointer_field(pItem, iter);\n if (!func(&substream, iter->pos, pItem))\n {\n status = false;\n break;\n }\n (*size)++;\n }\n pb_close_string_substream(stream, &substream);\n \n return status;\n }\n else\n {\n /* Normal repeated field, i.e. only one item at a time. */\n size_t *size = (size_t*)iter->pSize;\n void *pItem;\n \n if (!allocate_field(stream, iter->pData, iter->pos->data_size, (size_t)(*size + 1)))\n return false;\n \n pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size);\n (*size)++;\n initialize_pointer_field(pItem, iter);\n return func(stream, iter->pos, pItem);\n }\n \n default:\n PB_RETURN_ERROR(stream, \"invalid field type\");\n }\n#endif\n}", "project": "nanopb", "hash": 123490975432721035768232801290650758429, "size": 102, "commit_id": "7b396821ddd06df8e39143f16e1dc0a4645b89a3", "message": "Fix invalid free() after failed realloc() (GHSA-gcx3-7m76-287p)", "target": 0, "dataset": "other", "idx": 255326} {"func": "GF_Err flac_dmx_process(GF_Filter *filter)\n{\n\tGF_FLACDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck, *dst_pck;\n\tu8 *output;\n\tu8 *start;\n\tBool final_flush=GF_FALSE;\n\tu32 pck_size, remain, prev_pck_size;\n\tu64 cts = GF_FILTER_NO_TS;\n\tFLACHeader hdr;\n\n\t//always reparse duration\n\tif (!ctx->duration.num)\n\t\tflac_dmx_check_dur(filter, ctx);\n\n\tif (ctx->opid && !ctx->is_playing)\n\t\treturn GF_OK;\n\n\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tif (!ctx->flac_buffer_size) {\n\t\t\t\tif (ctx->opid)\n\t\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = NULL;\n\t\t\t\treturn GF_EOS;\n\t\t\t}\n\t\t\tfinal_flush = GF_TRUE;\n\t\t} else {\n\t\t\treturn GF_OK;\n\t\t}\n\t}\n\n\tprev_pck_size = ctx->flac_buffer_size;\n\tif (pck && !ctx->resume_from) {\n\t\tu8 *data = (u8 *) gf_filter_pck_get_data(pck, &pck_size);\n\n\t\tif (ctx->byte_offset != GF_FILTER_NO_BO) {\n\t\t\tu64 byte_offset = gf_filter_pck_get_byte_offset(pck);\n\t\t\tif (!ctx->flac_buffer_size) {\n\t\t\t\tctx->byte_offset = byte_offset;\n\t\t\t} else if (ctx->byte_offset + ctx->flac_buffer_size != byte_offset) {\n\t\t\t\tctx->byte_offset = GF_FILTER_NO_BO;\n\t\t\t\tif ((byte_offset != GF_FILTER_NO_BO) && (byte_offset>ctx->flac_buffer_size) ) {\n\t\t\t\t\tctx->byte_offset = byte_offset - ctx->flac_buffer_size;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (ctx->flac_buffer_size + pck_size > ctx->flac_buffer_alloc) {\n\t\t\tctx->flac_buffer_alloc = ctx->flac_buffer_size + pck_size;\n\t\t\tctx->flac_buffer = gf_realloc(ctx->flac_buffer, ctx->flac_buffer_alloc);\n\t\t}\n\t\tmemcpy(ctx->flac_buffer + ctx->flac_buffer_size, data, pck_size);\n\t\tctx->flac_buffer_size += pck_size;\n\t}\n\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (ctx->timescale && pck) {\n\t\tcts = gf_filter_pck_get_cts(pck);\n\t}\n\n\tif (cts == GF_FILTER_NO_TS) {\n\t\t//avoids updating cts\n\t\tprev_pck_size = 0;\n\t}\n\n\tremain = ctx->flac_buffer_size;\n\tstart = ctx->flac_buffer;\n\n\tif (ctx->resume_from) {\n\t\tstart += ctx->resume_from - 1;\n\t\tremain -= ctx->resume_from - 1;\n\t\tctx->resume_from = 0;\n\t}\n\n\twhile (remain>2) {\n\t\tu32 next_frame=0, nb_samp;\n\t\tu32 cur_size = remain-2;\n\t\tu8 *cur_buf = start+2;\n\t\tu8 *hdr_start = NULL;\n\n\t\tif (final_flush) {\n\t\t\tnext_frame = remain;\n\t\t} else {\n\t\t\twhile (cur_size) {\n\t\t\t\t//wait till we have a frame header\n\t\t\t\thdr_start = memchr(cur_buf, 0xFF, cur_size);\n\t\t\t\tif (!hdr_start) break;\n\t\t\t\tnext_frame = (u32) (hdr_start-start);\n\t\t\t\tif (next_frame == remain)\n\t\t\t\t\tbreak;\n\n\t\t\t\tif ((hdr_start[1]&0xFC) == 0xF8) {\n\t\t\t\t\tif (flac_parse_header(ctx, hdr_start, (u32) remain - next_frame, &hdr))\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcur_buf = hdr_start+1;\n\t\t\t\tcur_size = (u32) (cur_buf - start);\n\t\t\t\tassert(cur_size<=remain);\n\t\t\t\tcur_size = remain - cur_size;\n\t\t\t\thdr_start = NULL;\n\t\t\t}\n\t\t\tif (!hdr_start) break;\n\t\t\tif (next_frame == remain)\n\t\t\t\tbreak;\n\t\t}\n\n\n\t\tif (!ctx->initialized) {\n\t\t\tu32 size = next_frame;\n\t\t\tu32 dsi_end = 0;\n\t\t\t//we have a header\n\t\t\tgf_bs_reassign_buffer(ctx->bs, ctx->flac_buffer, size);\n\t\t\tu32 magic = gf_bs_read_u32(ctx->bs);\n\t\t\tif (magic != GF_4CC('f','L','a','C')) {\n\n\t\t\t}\n\t\t\twhile (gf_bs_available(ctx->bs)) {\n\t\t\t\tBool last = gf_bs_read_int(ctx->bs, 1);\n\t\t\t\tu32 type = gf_bs_read_int(ctx->bs, 7);\n\t\t\t\tu32 len = gf_bs_read_int(ctx->bs, 24);\n\n\t\t\t\tif (type==0) {\n\t\t\t\t\tu16 min_block_size = gf_bs_read_u16(ctx->bs);\n\t\t\t\t\tu16 max_block_size = gf_bs_read_u16(ctx->bs);\n\t\t\t\t\t/*u32 min_frame_size = */gf_bs_read_u24(ctx->bs);\n\t\t\t\t\t/*u32 max_frame_size = */gf_bs_read_u24(ctx->bs);\n\t\t\t\t\tctx->sample_rate = gf_bs_read_int(ctx->bs, 20);\n\t\t\t\t\tctx->nb_channels = 1 + gf_bs_read_int(ctx->bs, 3);\n\t\t\t\t\tctx->bits_per_sample = 1 + gf_bs_read_int(ctx->bs, 5);\n\t\t\t\t\tif (min_block_size==max_block_size) ctx->block_size = min_block_size;\n\t\t\t\t\telse ctx->block_size = 0;\n\n\t\t\t\t\tctx->duration.num = gf_bs_read_long_int(ctx->bs, 36);\n\t\t\t\t\tctx->duration.den = ctx->sample_rate;\n\t\t\t\t\t//ignore the rest\n\t\t\t\t\tgf_bs_skip_bytes(ctx->bs, 16);\n\t\t\t\t\tdsi_end = (u32) gf_bs_get_position(ctx->bs);\n\n\t\t\t\t} else {\n\t\t\t\t\t//ignore the rest for now\n\t\t\t\t\t//TODO: expose metadata, pictures and co\n\t\t\t\t\tgf_bs_skip_bytes(ctx->bs, len);\n\t\t\t\t}\n\t\t\t\tif (last) break;\n\t\t\t}\n\t\t\tflac_dmx_check_pid(filter, ctx, ctx->flac_buffer+4, dsi_end-4);\n\t\t\tremain -= size;\n\t\t\tstart += size;\n\t\t\tctx->initialized = GF_TRUE;\n\t\t\tif (!ctx->is_playing) break;\n\t\t\tcontinue;\n\t\t}\n\n\t\t//we have a next frame, check we are synchronize\n\t\tif ((start[0] != 0xFF) && ((start[1]&0xFC) != 0xF8)) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[FLACDmx] invalid frame, droping %d bytes and resyncing\\n\", next_frame));\n\t\t\tstart += next_frame;\n\t\t\tremain -= next_frame;\n\t\t\tcontinue;\n\t\t}\n\n\t\tflac_parse_header(ctx,start, next_frame, &hdr);\n\t\tif (hdr.sample_rate != ctx->sample_rate) {\n\t\t\tctx->sample_rate = hdr.sample_rate;\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_SAMPLE_RATE, & PROP_UINT(ctx->sample_rate));\n\t\t}\n\n\t\tnb_samp = hdr.block_size;\n\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_samples_at_seek = (u64) (ctx->start_range * ctx->sample_rate);\n\t\t\tif (ctx->cts + nb_samp >= nb_samples_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + nb_samp ) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}\n\n\t\tif (ctx->timescale && !prev_pck_size && (cts != GF_FILTER_NO_TS) ) {\n\t\t\tctx->cts = cts;\n\t\t\tcts = GF_FILTER_NO_TS;\n\t\t}\n\n\t\tif (!ctx->in_seek) {\n\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, next_frame, &output);\n\t\t\tmemcpy(output, start, next_frame);\n\n\t\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\t\tif (!ctx->timescale || (ctx->timescale==ctx->sample_rate) )\n\t\t\t\tgf_filter_pck_set_duration(dst_pck, nb_samp);\n\t\t\telse {\n\t\t\t\tgf_filter_pck_set_duration(dst_pck, (nb_samp * ctx->timescale) / ctx->sample_rate);\n\t\t\t}\n\t\t\tgf_filter_pck_set_sap(dst_pck, GF_FILTER_SAP_1);\n\t\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\n\t\t\tif (ctx->byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, ctx->byte_offset);\n\t\t\t}\n\t\t\tgf_filter_pck_send(dst_pck);\n\t\t}\n\t\tflac_dmx_update_cts(ctx, nb_samp);\n\n\t\tassert (start[0] == 0xFF);\n\t\tassert((start[1]&0xFC) == 0xF8);\n\n\t\tstart += next_frame;\n\t\tassert(remain >= next_frame);\n\t\tremain -= next_frame;\n\n\t}\n\n\tif (!pck) {\n\t\tctx->flac_buffer_size = 0;\n\t\treturn flac_dmx_process(filter);\n\t} else {\n\t\tif (remain < ctx->flac_buffer_size) {\n\t\t\tmemmove(ctx->flac_buffer, start, remain);\n\t\t}\n\t\tctx->flac_buffer_size = remain;\n\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t}\n\treturn GF_OK;\n}", "project": "gpac", "hash": 181202795714431631737649125597649664622, "size": 226, "commit_id": "da69ad1f970a7e17c865eaec9af98cc84df10d5b", "message": "fixed 1718", "target": 1, "dataset": "other", "idx": 197240} {"func": "GF_Err flac_dmx_process(GF_Filter *filter)\n{\n\tGF_FLACDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck, *dst_pck;\n\tu8 *output;\n\tu8 *start;\n\tBool final_flush=GF_FALSE;\n\tu32 pck_size, remain, prev_pck_size;\n\tu64 cts = GF_FILTER_NO_TS;\n\tFLACHeader hdr;\n\n\tif (ctx->in_error)\n\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\n\t//always reparse duration\n\tif (!ctx->duration.num)\n\t\tflac_dmx_check_dur(filter, ctx);\n\n\tif (ctx->opid && !ctx->is_playing)\n\t\treturn GF_OK;\n\n\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tif (!ctx->flac_buffer_size) {\n\t\t\t\tif (ctx->opid)\n\t\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = NULL;\n\t\t\t\treturn GF_EOS;\n\t\t\t}\n\t\t\tfinal_flush = GF_TRUE;\n\t\t} else {\n\t\t\treturn GF_OK;\n\t\t}\n\t}\n\n\tprev_pck_size = ctx->flac_buffer_size;\n\tif (pck && !ctx->resume_from) {\n\t\tu8 *data = (u8 *) gf_filter_pck_get_data(pck, &pck_size);\n\n\t\tif (ctx->byte_offset != GF_FILTER_NO_BO) {\n\t\t\tu64 byte_offset = gf_filter_pck_get_byte_offset(pck);\n\t\t\tif (!ctx->flac_buffer_size) {\n\t\t\t\tctx->byte_offset = byte_offset;\n\t\t\t} else if (ctx->byte_offset + ctx->flac_buffer_size != byte_offset) {\n\t\t\t\tctx->byte_offset = GF_FILTER_NO_BO;\n\t\t\t\tif ((byte_offset != GF_FILTER_NO_BO) && (byte_offset>ctx->flac_buffer_size) ) {\n\t\t\t\t\tctx->byte_offset = byte_offset - ctx->flac_buffer_size;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (ctx->flac_buffer_size + pck_size > ctx->flac_buffer_alloc) {\n\t\t\tctx->flac_buffer_alloc = ctx->flac_buffer_size + pck_size;\n\t\t\tctx->flac_buffer = gf_realloc(ctx->flac_buffer, ctx->flac_buffer_alloc);\n\t\t}\n\t\tmemcpy(ctx->flac_buffer + ctx->flac_buffer_size, data, pck_size);\n\t\tctx->flac_buffer_size += pck_size;\n\t}\n\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (ctx->timescale && pck) {\n\t\tcts = gf_filter_pck_get_cts(pck);\n\t}\n\n\tif (cts == GF_FILTER_NO_TS) {\n\t\t//avoids updating cts\n\t\tprev_pck_size = 0;\n\t}\n\n\tremain = ctx->flac_buffer_size;\n\tstart = ctx->flac_buffer;\n\n\tif (ctx->resume_from) {\n\t\tstart += ctx->resume_from - 1;\n\t\tremain -= ctx->resume_from - 1;\n\t\tctx->resume_from = 0;\n\t}\n\n\twhile (remain>2) {\n\t\tu32 next_frame=0, nb_samp;\n\t\tu32 cur_size = remain-2;\n\t\tu8 *cur_buf = start+2;\n\t\tu8 *hdr_start = NULL;\n\n\t\tif (final_flush) {\n\t\t\tnext_frame = remain;\n\t\t} else {\n\t\t\twhile (cur_size) {\n\t\t\t\t//wait till we have a frame header\n\t\t\t\thdr_start = memchr(cur_buf, 0xFF, cur_size);\n\t\t\t\tif (!hdr_start) break;\n\t\t\t\tnext_frame = (u32) (hdr_start-start);\n\t\t\t\tif (next_frame == remain)\n\t\t\t\t\tbreak;\n\n\t\t\t\tif ((hdr_start[1]&0xFC) == 0xF8) {\n\t\t\t\t\tif (flac_parse_header(ctx, hdr_start, (u32) remain - next_frame, &hdr))\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcur_buf = hdr_start+1;\n\t\t\t\tcur_size = (u32) (cur_buf - start);\n\t\t\t\tassert(cur_size<=remain);\n\t\t\t\tcur_size = remain - cur_size;\n\t\t\t\thdr_start = NULL;\n\t\t\t}\n\t\t\tif (!hdr_start) break;\n\t\t\tif (next_frame == remain)\n\t\t\t\tbreak;\n\t\t}\n\n\n\t\tif (!ctx->initialized) {\n\t\t\tu32 size = next_frame;\n\t\t\tu32 dsi_end = 0;\n\t\t\t//we have a header\n\t\t\tgf_bs_reassign_buffer(ctx->bs, ctx->flac_buffer, size);\n\t\t\tu32 magic = gf_bs_read_u32(ctx->bs);\n\t\t\tif (magic != GF_4CC('f','L','a','C')) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[FLACDmx] invalid FLAC magic\\n\"));\n\t\t\t\tctx->in_error = GF_TRUE;\n\t\t\t\tctx->flac_buffer_size = 0;\n\t\t\t\tif (pck)\n\t\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t\twhile (gf_bs_available(ctx->bs)) {\n\t\t\t\tBool last = gf_bs_read_int(ctx->bs, 1);\n\t\t\t\tu32 type = gf_bs_read_int(ctx->bs, 7);\n\t\t\t\tu32 len = gf_bs_read_int(ctx->bs, 24);\n\n\t\t\t\tif (type==0) {\n\t\t\t\t\tu16 min_block_size = gf_bs_read_u16(ctx->bs);\n\t\t\t\t\tu16 max_block_size = gf_bs_read_u16(ctx->bs);\n\t\t\t\t\t/*u32 min_frame_size = */gf_bs_read_u24(ctx->bs);\n\t\t\t\t\t/*u32 max_frame_size = */gf_bs_read_u24(ctx->bs);\n\t\t\t\t\tctx->sample_rate = gf_bs_read_int(ctx->bs, 20);\n\t\t\t\t\tctx->nb_channels = 1 + gf_bs_read_int(ctx->bs, 3);\n\t\t\t\t\tctx->bits_per_sample = 1 + gf_bs_read_int(ctx->bs, 5);\n\t\t\t\t\tif (min_block_size==max_block_size) ctx->block_size = min_block_size;\n\t\t\t\t\telse ctx->block_size = 0;\n\n\t\t\t\t\tctx->duration.num = gf_bs_read_long_int(ctx->bs, 36);\n\t\t\t\t\tctx->duration.den = ctx->sample_rate;\n\t\t\t\t\t//ignore the rest\n\t\t\t\t\tgf_bs_skip_bytes(ctx->bs, 16);\n\t\t\t\t\tdsi_end = (u32) gf_bs_get_position(ctx->bs);\n\n\t\t\t\t} else {\n\t\t\t\t\t//ignore the rest for now\n\t\t\t\t\t//TODO: expose metadata, pictures and co\n\t\t\t\t\tgf_bs_skip_bytes(ctx->bs, len);\n\t\t\t\t}\n\t\t\t\tif (last) break;\n\t\t\t}\n\t\t\tif (!dsi_end) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, (\"[FLACDmx] invalid FLAC header\\n\"));\n\t\t\t\tctx->in_error = GF_TRUE;\n\t\t\t\tctx->flac_buffer_size = 0;\n\t\t\t\tif (pck)\n\t\t\t\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\t\t\treturn GF_NON_COMPLIANT_BITSTREAM;\n\t\t\t}\n\t\t\tflac_dmx_check_pid(filter, ctx, ctx->flac_buffer+4, dsi_end-4);\n\t\t\tremain -= size;\n\t\t\tstart += size;\n\t\t\tctx->initialized = GF_TRUE;\n\t\t\tif (!ctx->is_playing) break;\n\t\t\tcontinue;\n\t\t}\n\n\t\t//we have a next frame, check we are synchronize\n\t\tif ((start[0] != 0xFF) && ((start[1]&0xFC) != 0xF8)) {\n\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (\"[FLACDmx] invalid frame, droping %d bytes and resyncing\\n\", next_frame));\n\t\t\tstart += next_frame;\n\t\t\tremain -= next_frame;\n\t\t\tcontinue;\n\t\t}\n\n\t\tflac_parse_header(ctx,start, next_frame, &hdr);\n\t\tif (hdr.sample_rate != ctx->sample_rate) {\n\t\t\tctx->sample_rate = hdr.sample_rate;\n\t\t\tgf_filter_pid_set_property(ctx->opid, GF_PROP_PID_SAMPLE_RATE, & PROP_UINT(ctx->sample_rate));\n\t\t}\n\n\t\tnb_samp = hdr.block_size;\n\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_samples_at_seek = (u64) (ctx->start_range * ctx->sample_rate);\n\t\t\tif (ctx->cts + nb_samp >= nb_samples_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + nb_samp ) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}\n\n\t\tif (ctx->timescale && !prev_pck_size && (cts != GF_FILTER_NO_TS) ) {\n\t\t\tctx->cts = cts;\n\t\t\tcts = GF_FILTER_NO_TS;\n\t\t}\n\n\t\tif (!ctx->in_seek) {\n\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, next_frame, &output);\n\t\t\tmemcpy(output, start, next_frame);\n\n\t\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\t\tif (!ctx->timescale || (ctx->timescale==ctx->sample_rate) )\n\t\t\t\tgf_filter_pck_set_duration(dst_pck, nb_samp);\n\t\t\telse {\n\t\t\t\tgf_filter_pck_set_duration(dst_pck, (nb_samp * ctx->timescale) / ctx->sample_rate);\n\t\t\t}\n\t\t\tgf_filter_pck_set_sap(dst_pck, GF_FILTER_SAP_1);\n\t\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\n\t\t\tif (ctx->byte_offset != GF_FILTER_NO_BO) {\n\t\t\t\tgf_filter_pck_set_byte_offset(dst_pck, ctx->byte_offset);\n\t\t\t}\n\t\t\tgf_filter_pck_send(dst_pck);\n\t\t}\n\t\tflac_dmx_update_cts(ctx, nb_samp);\n\n\t\tassert (start[0] == 0xFF);\n\t\tassert((start[1]&0xFC) == 0xF8);\n\n\t\tstart += next_frame;\n\t\tassert(remain >= next_frame);\n\t\tremain -= next_frame;\n\n\t}\n\n\tif (!pck) {\n\t\tctx->flac_buffer_size = 0;\n\t\treturn flac_dmx_process(filter);\n\t} else {\n\t\tif (remain < ctx->flac_buffer_size) {\n\t\t\tmemmove(ctx->flac_buffer, start, remain);\n\t\t}\n\t\tctx->flac_buffer_size = remain;\n\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t}\n\treturn GF_OK;\n}", "project": "gpac", "hash": 45890451895495219456520744515811279483, "size": 242, "commit_id": "da69ad1f970a7e17c865eaec9af98cc84df10d5b", "message": "fixed 1718", "target": 0, "dataset": "other", "idx": 255791} {"func": "export_desktop_file (const char *app,\n const char *branch,\n const char *arch,\n GKeyFile *metadata,\n const char * const *previous_ids,\n int parent_fd,\n const char *name,\n struct stat *stat_buf,\n char **target,\n GCancellable *cancellable,\n GError **error)\n{\n gboolean ret = FALSE;\n glnx_autofd int desktop_fd = -1;\n g_autofree char *tmpfile_name = g_strdup_printf (\"export-desktop-XXXXXX\");\n g_autoptr(GOutputStream) out_stream = NULL;\n g_autofree gchar *data = NULL;\n gsize data_len;\n g_autofree gchar *new_data = NULL;\n gsize new_data_len;\n g_autoptr(GKeyFile) keyfile = NULL;\n g_autofree gchar *old_exec = NULL;\n gint old_argc;\n g_auto(GStrv) old_argv = NULL;\n g_auto(GStrv) groups = NULL;\n GString *new_exec = NULL;\n g_autofree char *escaped_app = maybe_quote (app);\n g_autofree char *escaped_branch = maybe_quote (branch);\n g_autofree char *escaped_arch = maybe_quote (arch);\n int i;\n\n if (!flatpak_openat_noatime (parent_fd, name, &desktop_fd, cancellable, error))\n goto out;\n\n if (!read_fd (desktop_fd, stat_buf, &data, &data_len, error))\n goto out;\n\n keyfile = g_key_file_new ();\n if (!g_key_file_load_from_data (keyfile, data, data_len, G_KEY_FILE_KEEP_TRANSLATIONS, error))\n goto out;\n\n if (g_str_has_suffix (name, \".service\"))\n {\n g_autofree gchar *dbus_name = NULL;\n g_autofree gchar *expected_dbus_name = g_strndup (name, strlen (name) - strlen (\".service\"));\n\n dbus_name = g_key_file_get_string (keyfile, \"D-BUS Service\", \"Name\", NULL);\n\n if (dbus_name == NULL || strcmp (dbus_name, expected_dbus_name) != 0)\n {\n return flatpak_fail_error (error, FLATPAK_ERROR_EXPORT_FAILED,\n _(\"D-Bus service file '%s' has wrong name\"), name);\n }\n }\n\n if (g_str_has_suffix (name, \".desktop\"))\n {\n gsize length;\n g_auto(GStrv) tags = g_key_file_get_string_list (metadata,\n \"Application\",\n \"tags\", &length,\n NULL);\n\n if (tags != NULL)\n {\n g_key_file_set_string_list (keyfile,\n G_KEY_FILE_DESKTOP_GROUP,\n \"X-Flatpak-Tags\",\n (const char * const *) tags, length);\n }\n\n /* Add a marker so consumers can easily find out that this launches a sandbox */\n g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, \"X-Flatpak\", app);\n\n /* If the app has been renamed, add its old .desktop filename to\n * X-Flatpak-RenamedFrom in the new .desktop file, taking care not to\n * introduce duplicates.\n */\n if (previous_ids != NULL)\n {\n const char *X_FLATPAK_RENAMED_FROM = \"X-Flatpak-RenamedFrom\";\n g_auto(GStrv) renamed_from = g_key_file_get_string_list (keyfile,\n G_KEY_FILE_DESKTOP_GROUP,\n X_FLATPAK_RENAMED_FROM,\n NULL, NULL);\n g_autoptr(GPtrArray) merged = g_ptr_array_new_with_free_func (g_free);\n g_autoptr(GHashTable) seen = g_hash_table_new (g_str_hash, g_str_equal);\n const char *new_suffix;\n\n for (i = 0; renamed_from != NULL && renamed_from[i] != NULL; i++)\n {\n if (!g_hash_table_contains (seen, renamed_from[i]))\n {\n gchar *copy = g_strdup (renamed_from[i]);\n g_hash_table_insert (seen, copy, copy);\n g_ptr_array_add (merged, g_steal_pointer (©));\n }\n }\n\n /* If an app was renamed from com.example.Foo to net.example.Bar, and\n * the new version exports net.example.Bar-suffix.desktop, we assume the\n * old version exported com.example.Foo-suffix.desktop.\n *\n * This assertion is true because\n * flatpak_name_matches_one_wildcard_prefix() is called on all\n * exported files before we get here.\n */\n g_assert (g_str_has_prefix (name, app));\n /* \".desktop\" for the \"main\" desktop file; something like\n * \"-suffix.desktop\" for extra ones.\n */\n new_suffix = name + strlen (app);\n\n for (i = 0; previous_ids[i] != NULL; i++)\n {\n g_autofree gchar *previous_desktop = g_strconcat (previous_ids[i], new_suffix, NULL);\n if (!g_hash_table_contains (seen, previous_desktop))\n {\n g_hash_table_insert (seen, previous_desktop, previous_desktop);\n g_ptr_array_add (merged, g_steal_pointer (&previous_desktop));\n }\n }\n\n if (merged->len > 0)\n {\n g_ptr_array_add (merged, NULL);\n g_key_file_set_string_list (keyfile,\n G_KEY_FILE_DESKTOP_GROUP,\n X_FLATPAK_RENAMED_FROM,\n (const char * const *) merged->pdata,\n merged->len - 1);\n }\n }\n }\n\n groups = g_key_file_get_groups (keyfile, NULL);\n\n for (i = 0; groups[i] != NULL; i++)\n {\n g_auto(GStrv) flatpak_run_opts = g_key_file_get_string_list (keyfile, groups[i], \"X-Flatpak-RunOptions\", NULL, NULL);\n g_autofree char *flatpak_run_args = format_flatpak_run_args_from_run_opts (flatpak_run_opts);\n\n g_key_file_remove_key (keyfile, groups[i], \"X-Flatpak-RunOptions\", NULL);\n g_key_file_remove_key (keyfile, groups[i], \"TryExec\", NULL);\n\n /* Remove this to make sure nothing tries to execute it outside the sandbox*/\n g_key_file_remove_key (keyfile, groups[i], \"X-GNOME-Bugzilla-ExtraInfoScript\", NULL);\n\n new_exec = g_string_new (\"\");\n g_string_append_printf (new_exec,\n FLATPAK_BINDIR \"/flatpak run --branch=%s --arch=%s\",\n escaped_branch,\n escaped_arch);\n\n if (flatpak_run_args != NULL)\n g_string_append_printf (new_exec, \"%s\", flatpak_run_args);\n\n old_exec = g_key_file_get_string (keyfile, groups[i], \"Exec\", NULL);\n if (old_exec && g_shell_parse_argv (old_exec, &old_argc, &old_argv, NULL) && old_argc >= 1)\n {\n int j;\n g_autofree char *command = maybe_quote (old_argv[0]);\n\n g_string_append_printf (new_exec, \" --command=%s\", command);\n\n for (j = 1; j < old_argc; j++)\n {\n if (strcasecmp (old_argv[j], \"%f\") == 0 ||\n strcasecmp (old_argv[j], \"%u\") == 0)\n {\n g_string_append (new_exec, \" --file-forwarding\");\n break;\n }\n }\n\n g_string_append (new_exec, \" \");\n g_string_append (new_exec, escaped_app);\n\n for (j = 1; j < old_argc; j++)\n {\n g_autofree char *arg = maybe_quote (old_argv[j]);\n\n if (strcasecmp (arg, \"%f\") == 0)\n g_string_append_printf (new_exec, \" @@ %s @@\", arg);\n else if (strcasecmp (arg, \"%u\") == 0)\n g_string_append_printf (new_exec, \" @@u %s @@\", arg);\n else if (g_str_has_prefix (arg, \"@@\"))\n g_print (_(\"Skipping invalid Exec argument %s\\n\"), arg);\n else\n g_string_append_printf (new_exec, \" %s\", arg);\n }\n }\n else\n {\n g_string_append (new_exec, \" \");\n g_string_append (new_exec, escaped_app);\n }\n\n g_key_file_set_string (keyfile, groups[i], G_KEY_FILE_DESKTOP_KEY_EXEC, new_exec->str);\n }\n\n new_data = g_key_file_to_data (keyfile, &new_data_len, error);\n if (new_data == NULL)\n goto out;\n\n if (!flatpak_open_in_tmpdir_at (parent_fd, 0755, tmpfile_name, &out_stream, cancellable, error))\n goto out;\n\n if (!g_output_stream_write_all (out_stream, new_data, new_data_len, NULL, cancellable, error))\n goto out;\n\n if (!g_output_stream_close (out_stream, cancellable, error))\n goto out;\n\n if (target)\n *target = g_steal_pointer (&tmpfile_name);\n\n ret = TRUE;\nout:\n\n if (new_exec != NULL)\n g_string_free (new_exec, TRUE);\n\n return ret;\n}", "project": "flatpak", "hash": 158761630201972013011166444905331694845, "size": 225, "commit_id": "a7401e638bf0c03102039e216ab1081922f140ae", "message": "dir: Refuse to export .desktop files with suspicious uses of @@ tokens\n\nThis is either a malicious/compromised app trying to do an attack, or\na mistake that will break handling of %f, %u and so on. Either way,\nif we refuse to export the .desktop file, resulting in installation\nfailing, then it makes the rejection more obvious than quietly\nremoving the magic tokens.\n\nSigned-off-by: Simon McVittie \n(cherry picked from commit 46b3ede5241561c7d588951048c687c5075a3eac)", "target": 1, "dataset": "other", "idx": 197260} {"func": "export_desktop_file (const char *app,\n const char *branch,\n const char *arch,\n GKeyFile *metadata,\n const char * const *previous_ids,\n int parent_fd,\n const char *name,\n struct stat *stat_buf,\n char **target,\n GCancellable *cancellable,\n GError **error)\n{\n gboolean ret = FALSE;\n glnx_autofd int desktop_fd = -1;\n g_autofree char *tmpfile_name = g_strdup_printf (\"export-desktop-XXXXXX\");\n g_autoptr(GOutputStream) out_stream = NULL;\n g_autofree gchar *data = NULL;\n gsize data_len;\n g_autofree gchar *new_data = NULL;\n gsize new_data_len;\n g_autoptr(GKeyFile) keyfile = NULL;\n g_autofree gchar *old_exec = NULL;\n gint old_argc;\n g_auto(GStrv) old_argv = NULL;\n g_auto(GStrv) groups = NULL;\n GString *new_exec = NULL;\n g_autofree char *escaped_app = maybe_quote (app);\n g_autofree char *escaped_branch = maybe_quote (branch);\n g_autofree char *escaped_arch = maybe_quote (arch);\n int i;\n\n if (!flatpak_openat_noatime (parent_fd, name, &desktop_fd, cancellable, error))\n goto out;\n\n if (!read_fd (desktop_fd, stat_buf, &data, &data_len, error))\n goto out;\n\n keyfile = g_key_file_new ();\n if (!g_key_file_load_from_data (keyfile, data, data_len, G_KEY_FILE_KEEP_TRANSLATIONS, error))\n goto out;\n\n if (g_str_has_suffix (name, \".service\"))\n {\n g_autofree gchar *dbus_name = NULL;\n g_autofree gchar *expected_dbus_name = g_strndup (name, strlen (name) - strlen (\".service\"));\n\n dbus_name = g_key_file_get_string (keyfile, \"D-BUS Service\", \"Name\", NULL);\n\n if (dbus_name == NULL || strcmp (dbus_name, expected_dbus_name) != 0)\n {\n return flatpak_fail_error (error, FLATPAK_ERROR_EXPORT_FAILED,\n _(\"D-Bus service file '%s' has wrong name\"), name);\n }\n }\n\n if (g_str_has_suffix (name, \".desktop\"))\n {\n gsize length;\n g_auto(GStrv) tags = g_key_file_get_string_list (metadata,\n \"Application\",\n \"tags\", &length,\n NULL);\n\n if (tags != NULL)\n {\n g_key_file_set_string_list (keyfile,\n G_KEY_FILE_DESKTOP_GROUP,\n \"X-Flatpak-Tags\",\n (const char * const *) tags, length);\n }\n\n /* Add a marker so consumers can easily find out that this launches a sandbox */\n g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, \"X-Flatpak\", app);\n\n /* If the app has been renamed, add its old .desktop filename to\n * X-Flatpak-RenamedFrom in the new .desktop file, taking care not to\n * introduce duplicates.\n */\n if (previous_ids != NULL)\n {\n const char *X_FLATPAK_RENAMED_FROM = \"X-Flatpak-RenamedFrom\";\n g_auto(GStrv) renamed_from = g_key_file_get_string_list (keyfile,\n G_KEY_FILE_DESKTOP_GROUP,\n X_FLATPAK_RENAMED_FROM,\n NULL, NULL);\n g_autoptr(GPtrArray) merged = g_ptr_array_new_with_free_func (g_free);\n g_autoptr(GHashTable) seen = g_hash_table_new (g_str_hash, g_str_equal);\n const char *new_suffix;\n\n for (i = 0; renamed_from != NULL && renamed_from[i] != NULL; i++)\n {\n if (!g_hash_table_contains (seen, renamed_from[i]))\n {\n gchar *copy = g_strdup (renamed_from[i]);\n g_hash_table_insert (seen, copy, copy);\n g_ptr_array_add (merged, g_steal_pointer (©));\n }\n }\n\n /* If an app was renamed from com.example.Foo to net.example.Bar, and\n * the new version exports net.example.Bar-suffix.desktop, we assume the\n * old version exported com.example.Foo-suffix.desktop.\n *\n * This assertion is true because\n * flatpak_name_matches_one_wildcard_prefix() is called on all\n * exported files before we get here.\n */\n g_assert (g_str_has_prefix (name, app));\n /* \".desktop\" for the \"main\" desktop file; something like\n * \"-suffix.desktop\" for extra ones.\n */\n new_suffix = name + strlen (app);\n\n for (i = 0; previous_ids[i] != NULL; i++)\n {\n g_autofree gchar *previous_desktop = g_strconcat (previous_ids[i], new_suffix, NULL);\n if (!g_hash_table_contains (seen, previous_desktop))\n {\n g_hash_table_insert (seen, previous_desktop, previous_desktop);\n g_ptr_array_add (merged, g_steal_pointer (&previous_desktop));\n }\n }\n\n if (merged->len > 0)\n {\n g_ptr_array_add (merged, NULL);\n g_key_file_set_string_list (keyfile,\n G_KEY_FILE_DESKTOP_GROUP,\n X_FLATPAK_RENAMED_FROM,\n (const char * const *) merged->pdata,\n merged->len - 1);\n }\n }\n }\n\n groups = g_key_file_get_groups (keyfile, NULL);\n\n for (i = 0; groups[i] != NULL; i++)\n {\n g_auto(GStrv) flatpak_run_opts = g_key_file_get_string_list (keyfile, groups[i], \"X-Flatpak-RunOptions\", NULL, NULL);\n g_autofree char *flatpak_run_args = format_flatpak_run_args_from_run_opts (flatpak_run_opts);\n\n g_key_file_remove_key (keyfile, groups[i], \"X-Flatpak-RunOptions\", NULL);\n g_key_file_remove_key (keyfile, groups[i], \"TryExec\", NULL);\n\n /* Remove this to make sure nothing tries to execute it outside the sandbox*/\n g_key_file_remove_key (keyfile, groups[i], \"X-GNOME-Bugzilla-ExtraInfoScript\", NULL);\n\n new_exec = g_string_new (\"\");\n g_string_append_printf (new_exec,\n FLATPAK_BINDIR \"/flatpak run --branch=%s --arch=%s\",\n escaped_branch,\n escaped_arch);\n\n if (flatpak_run_args != NULL)\n g_string_append_printf (new_exec, \"%s\", flatpak_run_args);\n\n old_exec = g_key_file_get_string (keyfile, groups[i], \"Exec\", NULL);\n if (old_exec && g_shell_parse_argv (old_exec, &old_argc, &old_argv, NULL) && old_argc >= 1)\n {\n int j;\n g_autofree char *command = maybe_quote (old_argv[0]);\n\n g_string_append_printf (new_exec, \" --command=%s\", command);\n\n for (j = 1; j < old_argc; j++)\n {\n if (strcasecmp (old_argv[j], \"%f\") == 0 ||\n strcasecmp (old_argv[j], \"%u\") == 0)\n {\n g_string_append (new_exec, \" --file-forwarding\");\n break;\n }\n }\n\n g_string_append (new_exec, \" \");\n g_string_append (new_exec, escaped_app);\n\n for (j = 1; j < old_argc; j++)\n {\n g_autofree char *arg = maybe_quote (old_argv[j]);\n\n if (strcasecmp (arg, \"%f\") == 0)\n g_string_append_printf (new_exec, \" @@ %s @@\", arg);\n else if (strcasecmp (arg, \"%u\") == 0)\n g_string_append_printf (new_exec, \" @@u %s @@\", arg);\n else if (g_str_has_prefix (arg, \"@@\"))\n {\n flatpak_fail_error (error, FLATPAK_ERROR_EXPORT_FAILED,\n _(\"Invalid Exec argument %s\"), arg);\n goto out;\n }\n else\n g_string_append_printf (new_exec, \" %s\", arg);\n }\n }\n else\n {\n g_string_append (new_exec, \" \");\n g_string_append (new_exec, escaped_app);\n }\n\n g_key_file_set_string (keyfile, groups[i], G_KEY_FILE_DESKTOP_KEY_EXEC, new_exec->str);\n }\n\n new_data = g_key_file_to_data (keyfile, &new_data_len, error);\n if (new_data == NULL)\n goto out;\n\n if (!flatpak_open_in_tmpdir_at (parent_fd, 0755, tmpfile_name, &out_stream, cancellable, error))\n goto out;\n\n if (!g_output_stream_write_all (out_stream, new_data, new_data_len, NULL, cancellable, error))\n goto out;\n\n if (!g_output_stream_close (out_stream, cancellable, error))\n goto out;\n\n if (target)\n *target = g_steal_pointer (&tmpfile_name);\n\n ret = TRUE;\nout:\n\n if (new_exec != NULL)\n g_string_free (new_exec, TRUE);\n\n return ret;\n}", "project": "flatpak", "hash": 177220367868311421112771074203606020515, "size": 229, "commit_id": "a7401e638bf0c03102039e216ab1081922f140ae", "message": "dir: Refuse to export .desktop files with suspicious uses of @@ tokens\n\nThis is either a malicious/compromised app trying to do an attack, or\na mistake that will break handling of %f, %u and so on. Either way,\nif we refuse to export the .desktop file, resulting in installation\nfailing, then it makes the rejection more obvious than quietly\nremoving the magic tokens.\n\nSigned-off-by: Simon McVittie \n(cherry picked from commit 46b3ede5241561c7d588951048c687c5075a3eac)", "target": 0, "dataset": "other", "idx": 256099} {"func": "Status SparseTensorToCSRSparseMatrixCPUFunctor::operator()(\n const int64 batch_size, const int num_rows,\n TTypes::ConstMatrix indices, TTypes::Vec batch_ptr,\n TTypes::Vec csr_row_ptr, TTypes::Vec csr_col_ind) {\n // Validate inputs.\n if (batch_ptr.size() != batch_size + 1) {\n return errors::InvalidArgument(\n \"Expected batch_ptr.size() == batch_size + 1. Got: \", batch_ptr.size(),\n \" vs. \", batch_size + 1);\n }\n if (csr_row_ptr.size() != batch_size * (num_rows + 1)) {\n return errors::InvalidArgument(\n \"Expected csr_row_ptr.size() == batch_size * (num_rows + 1). Got: \",\n csr_row_ptr.size(), \" vs. \", batch_size * (num_rows + 1));\n }\n\n const int64 total_nnz = indices.dimension(0);\n const int rank = indices.dimension(1);\n if (rank == 2 && batch_size != 1) {\n return errors::InvalidArgument(\n \"Expected batch_size == 1 when rank is 2. Got batch_size: \",\n batch_size);\n }\n if (csr_col_ind.size() != total_nnz) {\n return errors::InvalidArgument(\n \"Expected csr_col_ind.size() == total_nnz. Got: \", csr_col_ind.size(),\n \" vs. \", total_nnz);\n }\n\n int prev_batch = -1;\n if (rank == 2) {\n // For a single batch, the batch_ptrs are {0, total_nnz}.\n batch_ptr(0) = 0;\n ++prev_batch;\n\n for (int64 i = 0; i < total_nnz; ++i) {\n // For now, the rows pointers store the corresponding row counts.\n csr_row_ptr(indices(i, 0) + 1) += 1;\n csr_col_ind(i) = indices(i, 1);\n }\n } else { // rank == 3\n for (int64 i = 0; i < total_nnz; ++i) {\n const int cur_batch = indices(i, 0);\n // For now, the rows pointers store the corresponding row counts.\n csr_row_ptr(cur_batch * (num_rows + 1) + indices(i, 1) + 1) += 1;\n csr_col_ind(i) = indices(i, 2);\n\n // We're at a new batch and might have skipped over empty batches.\n while (prev_batch < cur_batch) {\n // The previous batch ends at position i.\n batch_ptr(prev_batch + 1) = i;\n ++prev_batch;\n }\n }\n }\n // Set the last element of batch_ptr and account for trailing empty batches.\n while (prev_batch < batch_size) {\n batch_ptr(prev_batch + 1) = total_nnz;\n ++prev_batch;\n }\n\n // Compute the cumulative row counts for each batch.\n for (int batch_idx = 0; batch_idx < batch_size; ++batch_idx) {\n auto* row_ptr_batch = csr_row_ptr.data() + batch_idx * (num_rows + 1);\n std::partial_sum(row_ptr_batch, row_ptr_batch + num_rows + 1,\n row_ptr_batch);\n }\n return Status::OK();\n}", "project": "tensorflow", "hash": 11864789206738985824119536060770076338, "size": 69, "commit_id": "1e922ccdf6bf46a3a52641f99fd47d54c1decd13", "message": "Fix crash in `SparseTensorToCSRSparseMatrixCPUFunctor`\n\nPiperOrigin-RevId: 370110290\nChange-Id: I4451e92661a55c2180f80d38b67a9b50bf5edec5", "target": 1, "dataset": "other", "idx": 197301} {"func": "Status SparseTensorToCSRSparseMatrixCPUFunctor::operator()(\n const int64 batch_size, const int num_rows,\n TTypes::ConstMatrix indices, TTypes::Vec batch_ptr,\n TTypes::Vec csr_row_ptr, TTypes::Vec csr_col_ind) {\n // Validate inputs.\n if (batch_ptr.size() != batch_size + 1) {\n return errors::InvalidArgument(\n \"Expected batch_ptr.size() == batch_size + 1. Got: \", batch_ptr.size(),\n \" vs. \", batch_size + 1);\n }\n if (csr_row_ptr.size() != batch_size * (num_rows + 1)) {\n return errors::InvalidArgument(\n \"Expected csr_row_ptr.size() == batch_size * (num_rows + 1). Got: \",\n csr_row_ptr.size(), \" vs. \", batch_size * (num_rows + 1));\n }\n\n const int64 total_nnz = indices.dimension(0);\n const int rank = indices.dimension(1);\n if (rank == 2 && batch_size != 1) {\n return errors::InvalidArgument(\n \"Expected batch_size == 1 when rank is 2. Got batch_size: \",\n batch_size);\n }\n if (csr_col_ind.size() != total_nnz) {\n return errors::InvalidArgument(\n \"Expected csr_col_ind.size() == total_nnz. Got: \", csr_col_ind.size(),\n \" vs. \", total_nnz);\n }\n\n int prev_batch = -1;\n if (rank == 2) {\n // For a single batch, the batch_ptrs are {0, total_nnz}.\n batch_ptr(0) = 0;\n ++prev_batch;\n\n for (int64 i = 0; i < total_nnz; ++i) {\n // For now, the rows pointers store the corresponding row counts.\n int64 ix = indices(i, 0) + 1;\n if (ix >= csr_row_ptr.size()) {\n return errors::InvalidArgument(\"Got an index \", ix,\n \" that is outside of csr_row_ptr\");\n }\n csr_row_ptr(indices(i, 0) + 1) += 1;\n csr_col_ind(i) = indices(i, 1);\n }\n } else { // rank == 3\n for (int64 i = 0; i < total_nnz; ++i) {\n const int cur_batch = indices(i, 0);\n // For now, the rows pointers store the corresponding row counts.\n csr_row_ptr(cur_batch * (num_rows + 1) + indices(i, 1) + 1) += 1;\n csr_col_ind(i) = indices(i, 2);\n\n // We're at a new batch and might have skipped over empty batches.\n while (prev_batch < cur_batch) {\n // The previous batch ends at position i.\n batch_ptr(prev_batch + 1) = i;\n ++prev_batch;\n }\n }\n }\n // Set the last element of batch_ptr and account for trailing empty batches.\n while (prev_batch < batch_size) {\n batch_ptr(prev_batch + 1) = total_nnz;\n ++prev_batch;\n }\n\n // Compute the cumulative row counts for each batch.\n for (int batch_idx = 0; batch_idx < batch_size; ++batch_idx) {\n auto* row_ptr_batch = csr_row_ptr.data() + batch_idx * (num_rows + 1);\n std::partial_sum(row_ptr_batch, row_ptr_batch + num_rows + 1,\n row_ptr_batch);\n }\n return Status::OK();\n}", "project": "tensorflow", "hash": 184237572670370834113480134201938058069, "size": 74, "commit_id": "1e922ccdf6bf46a3a52641f99fd47d54c1decd13", "message": "Fix crash in `SparseTensorToCSRSparseMatrixCPUFunctor`\n\nPiperOrigin-RevId: 370110290\nChange-Id: I4451e92661a55c2180f80d38b67a9b50bf5edec5", "target": 0, "dataset": "other", "idx": 256387} {"func": "TfLiteStatus EvalSimple(TfLiteContext* context, TfLiteNode* node,\n const TfLiteTensor* lookup, const TfLiteTensor* value,\n TfLiteTensor* output) {\n const int row_size = SizeOfDimension(value, 0);\n const int row_bytes = value->bytes / row_size;\n\n char* output_raw = GetTensorData(output);\n const char* value_raw = GetTensorData(value);\n const int32_t* lookup_data = GetTensorData(lookup);\n for (int i = 0; i < SizeOfDimension(lookup, 0); i++) {\n int idx = lookup_data[i];\n if (idx >= row_size || idx < 0) {\n context->ReportError(context,\n \"Embedding Lookup: index out of bounds. \"\n \"Got %d, and bounds are [0, %d]\",\n idx, row_size - 1);\n return kTfLiteError;\n } else {\n std::memcpy(output_raw + i * row_bytes, value_raw + idx * row_bytes,\n row_bytes);\n }\n }\n\n return kTfLiteOk;\n}", "project": "tensorflow", "hash": 95188914225004025743598909042817406240, "size": 25, "commit_id": "f61c57bd425878be108ec787f4d96390579fb83e", "message": "Prevent division by 0\n\nPiperOrigin-RevId: 370966645\nChange-Id: I831bfd96c7eb77b02d7ebb744335f59f6e5728cb", "target": 1, "dataset": "other", "idx": 197303} {"func": "TfLiteStatus EvalSimple(TfLiteContext* context, TfLiteNode* node,\n const TfLiteTensor* lookup, const TfLiteTensor* value,\n TfLiteTensor* output) {\n const int row_size = SizeOfDimension(value, 0);\n if (row_size == 0) {\n // Propagate empty tensor if input is empty\n return kTfLiteOk;\n }\n const int row_bytes = value->bytes / row_size;\n\n char* output_raw = GetTensorData(output);\n const char* value_raw = GetTensorData(value);\n const int32_t* lookup_data = GetTensorData(lookup);\n for (int i = 0; i < SizeOfDimension(lookup, 0); i++) {\n int idx = lookup_data[i];\n if (idx >= row_size || idx < 0) {\n context->ReportError(context,\n \"Embedding Lookup: index out of bounds. \"\n \"Got %d, and bounds are [0, %d]\",\n idx, row_size - 1);\n return kTfLiteError;\n } else {\n std::memcpy(output_raw + i * row_bytes, value_raw + idx * row_bytes,\n row_bytes);\n }\n }\n\n return kTfLiteOk;\n}", "project": "tensorflow", "hash": 246624855501188183765525294917134828445, "size": 29, "commit_id": "f61c57bd425878be108ec787f4d96390579fb83e", "message": "Prevent division by 0\n\nPiperOrigin-RevId: 370966645\nChange-Id: I831bfd96c7eb77b02d7ebb744335f59f6e5728cb", "target": 0, "dataset": "other", "idx": 256405} {"func": "static void assemble_file(const char *fname, StrList **depend_ptr)\n{\n char *line;\n insn output_ins;\n int i;\n uint64_t prev_offset_changed;\n int64_t stall_count = 0; /* Make sure we make forward progress... */\n\n switch (cmd_sb) {\n case 16:\n break;\n case 32:\n if (!iflag_cpu_level_ok(&cmd_cpu, IF_386))\n nasm_fatal(0, \"command line: 32-bit segment size requires a higher cpu\");\n break;\n case 64:\n if (!iflag_cpu_level_ok(&cmd_cpu, IF_X86_64))\n nasm_fatal(0, \"command line: 64-bit segment size requires a higher cpu\");\n break;\n default:\n panic();\n break;\n }\n\n prev_offset_changed = nasm_limit[LIMIT_PASSES];\n for (passn = 1; pass0 <= 2; passn++) {\n pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */\n pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */\n /* pass0 0, 0, 0, ..., 1, 2 */\n\n globalbits = cmd_sb; /* set 'bits' to command line default */\n cpu = cmd_cpu;\n if (pass0 == 2) {\n\t lfmt->init(listname);\n } else if (passn == 1 && listname && !keep_all) {\n /* Remove the list file in case we die before the output pass */\n remove(listname);\n }\n in_absolute = false;\n global_offset_changed = 0; /* set by redefine_label */\n if (passn > 1) {\n saa_rewind(forwrefs);\n forwref = saa_rstruct(forwrefs);\n raa_free(offsets);\n offsets = raa_init();\n }\n location.segment = NO_SEG;\n location.offset = 0;\n if (passn == 1)\n location.known = true;\n ofmt->reset();\n switch_segment(ofmt->section(NULL, pass2, &globalbits));\n preproc->reset(fname, pass1, pass1 == 2 ? depend_ptr : NULL);\n\n\t/* Revert all warnings to the default state */\n\tmemcpy(warning_state, warning_state_init, sizeof warning_state);\n\n globallineno = 0;\n\n while ((line = preproc->getline())) {\n if (++globallineno > nasm_limit[LIMIT_LINES])\n nasm_fatal(0,\n \"overall line count exceeds the maximum %\"PRId64\"\\n\",\n nasm_limit[LIMIT_LINES]);\n\n /*\n * Here we parse our directives; this is not handled by the\n * main parser.\n */\n if (process_directives(line))\n goto end_of_line; /* Just do final cleanup */\n\n /* Not a directive, or even something that starts with [ */\n parse_line(pass1, line, &output_ins);\n\n if (optimizing.level > 0) {\n if (forwref != NULL && globallineno == forwref->lineno) {\n output_ins.forw_ref = true;\n do {\n output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;\n forwref = saa_rstruct(forwrefs);\n } while (forwref != NULL\n && forwref->lineno == globallineno);\n } else\n output_ins.forw_ref = false;\n\n if (output_ins.forw_ref) {\n if (passn == 1) {\n for (i = 0; i < output_ins.operands; i++) {\n if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {\n struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);\n fwinf->lineno = globallineno;\n fwinf->operand = i;\n }\n }\n }\n }\n }\n\n /* forw_ref */\n if (output_ins.opcode == I_EQU) {\n if (!output_ins.label)\n nasm_error(ERR_NONFATAL,\n \"EQU not preceded by label\");\n\n if (output_ins.operands == 1 &&\n (output_ins.oprs[0].type & IMMEDIATE) &&\n output_ins.oprs[0].wrt == NO_SEG) {\n define_label(output_ins.label,\n output_ins.oprs[0].segment,\n output_ins.oprs[0].offset, false);\n } else if (output_ins.operands == 2\n && (output_ins.oprs[0].type & IMMEDIATE)\n && (output_ins.oprs[0].type & COLON)\n && output_ins.oprs[0].segment == NO_SEG\n && output_ins.oprs[0].wrt == NO_SEG\n && (output_ins.oprs[1].type & IMMEDIATE)\n && output_ins.oprs[1].segment == NO_SEG\n && output_ins.oprs[1].wrt == NO_SEG) {\n define_label(output_ins.label,\n output_ins.oprs[0].offset | SEG_ABS,\n output_ins.oprs[1].offset, false);\n } else {\n nasm_error(ERR_NONFATAL, \"bad syntax for EQU\");\n }\n } else { /* instruction isn't an EQU */\n int32_t n;\n\n nasm_assert(output_ins.times >= 0);\n\n for (n = 1; n <= output_ins.times; n++) {\n if (pass1 == 1) {\n int64_t l = insn_size(location.segment,\n location.offset,\n globalbits, &output_ins);\n\n /* if (using_debug_info) && output_ins.opcode != -1) */\n if (using_debug_info)\n { /* fbk 03/25/01 */\n /* this is done here so we can do debug type info */\n int32_t typeinfo =\n TYS_ELEMENTS(output_ins.operands);\n switch (output_ins.opcode) {\n case I_RESB:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;\n break;\n case I_RESW:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;\n break;\n case I_RESD:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;\n break;\n case I_RESQ:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;\n break;\n case I_REST:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;\n break;\n case I_RESO:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;\n break;\n case I_RESY:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;\n break;\n case I_RESZ:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_ZWORD;\n break;\n case I_DB:\n typeinfo |= TY_BYTE;\n break;\n case I_DW:\n typeinfo |= TY_WORD;\n break;\n case I_DD:\n if (output_ins.eops_float)\n typeinfo |= TY_FLOAT;\n else\n typeinfo |= TY_DWORD;\n break;\n case I_DQ:\n typeinfo |= TY_QWORD;\n break;\n case I_DT:\n typeinfo |= TY_TBYTE;\n break;\n case I_DO:\n typeinfo |= TY_OWORD;\n break;\n case I_DY:\n typeinfo |= TY_YWORD;\n break;\n case I_DZ:\n typeinfo |= TY_ZWORD;\n break;\n default:\n typeinfo = TY_LABEL;\n break;\n }\n\n dfmt->debug_typevalue(typeinfo);\n }\n\n /*\n * For INCBIN, let the code in assemble\n * handle TIMES, so we don't have to read the\n * input file over and over.\n */\n if (l != -1) {\n increment_offset(l);\n }\n /*\n * else l == -1 => invalid instruction, which will be\n * flagged as an error on pass 2\n */\n } else {\n if (n == 2)\n lfmt->uplevel(LIST_TIMES);\n increment_offset(assemble(location.segment,\n location.offset,\n globalbits, &output_ins));\n }\n } /* not an EQU */\n }\n if (output_ins.times > 1)\n lfmt->downlevel(LIST_TIMES);\n\n cleanup_insn(&output_ins);\n\n end_of_line:\n nasm_free(line);\n } /* end while (line = preproc->getline... */\n\n if (global_offset_changed && !terminate_after_phase) {\n switch (pass0) {\n case 1:\n nasm_error(ERR_WARNING|ERR_WARN_PHASE,\n \"phase error during stabilization pass, hoping for the best\");\n break;\n\n case 2:\n nasm_error(ERR_NONFATAL,\n \"phase error during code generation pass\");\n break;\n\n default:\n /* This is normal, we'll keep going... */\n break;\n }\n }\n\n if (pass1 == 1)\n preproc->cleanup(1);\n\n /*\n * Always run at least two optimization passes (pass0 == 0);\n * things like subsections will fail miserably without that.\n * Once we commit to a stabilization pass (pass0 == 1), we can't\n * go back, and if something goes bad, we can only hope\n * that we don't end up with a phase error at the end.\n */\n if ((passn > 1 && !global_offset_changed) || pass0 > 0) {\n pass0++;\n } else if (global_offset_changed &&\n global_offset_changed < prev_offset_changed) {\n prev_offset_changed = global_offset_changed;\n stall_count = 0;\n } else {\n stall_count++;\n }\n\n if (terminate_after_phase)\n break;\n\n if ((stall_count > nasm_limit[LIMIT_STALLED]) ||\n (passn >= nasm_limit[LIMIT_PASSES])) {\n /* We get here if the labels don't converge\n * Example: FOO equ FOO + 1\n */\n nasm_error(ERR_NONFATAL,\n \"Can't find valid values for all labels \"\n \"after %\"PRId64\" passes, giving up.\", passn);\n nasm_error(ERR_NONFATAL,\n \"Possible causes: recursive EQUs, macro abuse.\");\n break;\n }\n }\n\n preproc->cleanup(0);\n lfmt->cleanup();\n if (!terminate_after_phase && opt_verbose_info) {\n /* -On and -Ov switches */\n fprintf(stdout, \"info: assembly required 1+%\"PRId64\"+1 passes\\n\",\n passn-3);\n }\n}", "project": "nasm", "hash": 308312917854211633508209765710891290112, "size": 303, "commit_id": "e996d28c70d45008085322b442b44a9224308548", "message": "labels: Don't nil dereference if no label provided\n\nAn equ without label may cause nil dereference\n\n |\tequ 0x100\n\nFixes 98578071b9d71ecaa2344dd9c185237c1765041e\n\nSigned-off-by: Cyrill Gorcunov ", "target": 1, "dataset": "other", "idx": 197360} {"func": "static void assemble_file(const char *fname, StrList **depend_ptr)\n{\n char *line;\n insn output_ins;\n int i;\n uint64_t prev_offset_changed;\n int64_t stall_count = 0; /* Make sure we make forward progress... */\n\n switch (cmd_sb) {\n case 16:\n break;\n case 32:\n if (!iflag_cpu_level_ok(&cmd_cpu, IF_386))\n nasm_fatal(0, \"command line: 32-bit segment size requires a higher cpu\");\n break;\n case 64:\n if (!iflag_cpu_level_ok(&cmd_cpu, IF_X86_64))\n nasm_fatal(0, \"command line: 64-bit segment size requires a higher cpu\");\n break;\n default:\n panic();\n break;\n }\n\n prev_offset_changed = nasm_limit[LIMIT_PASSES];\n for (passn = 1; pass0 <= 2; passn++) {\n pass1 = pass0 == 2 ? 2 : 1; /* 1, 1, 1, ..., 1, 2 */\n pass2 = passn > 1 ? 2 : 1; /* 1, 2, 2, ..., 2, 2 */\n /* pass0 0, 0, 0, ..., 1, 2 */\n\n globalbits = cmd_sb; /* set 'bits' to command line default */\n cpu = cmd_cpu;\n if (pass0 == 2) {\n\t lfmt->init(listname);\n } else if (passn == 1 && listname && !keep_all) {\n /* Remove the list file in case we die before the output pass */\n remove(listname);\n }\n in_absolute = false;\n global_offset_changed = 0; /* set by redefine_label */\n if (passn > 1) {\n saa_rewind(forwrefs);\n forwref = saa_rstruct(forwrefs);\n raa_free(offsets);\n offsets = raa_init();\n }\n location.segment = NO_SEG;\n location.offset = 0;\n if (passn == 1)\n location.known = true;\n ofmt->reset();\n switch_segment(ofmt->section(NULL, pass2, &globalbits));\n preproc->reset(fname, pass1, pass1 == 2 ? depend_ptr : NULL);\n\n\t/* Revert all warnings to the default state */\n\tmemcpy(warning_state, warning_state_init, sizeof warning_state);\n\n globallineno = 0;\n\n while ((line = preproc->getline())) {\n if (++globallineno > nasm_limit[LIMIT_LINES])\n nasm_fatal(0,\n \"overall line count exceeds the maximum %\"PRId64\"\\n\",\n nasm_limit[LIMIT_LINES]);\n\n /*\n * Here we parse our directives; this is not handled by the\n * main parser.\n */\n if (process_directives(line))\n goto end_of_line; /* Just do final cleanup */\n\n /* Not a directive, or even something that starts with [ */\n parse_line(pass1, line, &output_ins);\n\n if (optimizing.level > 0) {\n if (forwref != NULL && globallineno == forwref->lineno) {\n output_ins.forw_ref = true;\n do {\n output_ins.oprs[forwref->operand].opflags |= OPFLAG_FORWARD;\n forwref = saa_rstruct(forwrefs);\n } while (forwref != NULL\n && forwref->lineno == globallineno);\n } else\n output_ins.forw_ref = false;\n\n if (output_ins.forw_ref) {\n if (passn == 1) {\n for (i = 0; i < output_ins.operands; i++) {\n if (output_ins.oprs[i].opflags & OPFLAG_FORWARD) {\n struct forwrefinfo *fwinf = (struct forwrefinfo *)saa_wstruct(forwrefs);\n fwinf->lineno = globallineno;\n fwinf->operand = i;\n }\n }\n }\n }\n }\n\n /* forw_ref */\n if (output_ins.opcode == I_EQU) {\n if (!output_ins.label) {\n nasm_error(ERR_NONFATAL, \"EQU not preceded by label\");\n } else if (output_ins.operands == 1 &&\n (output_ins.oprs[0].type & IMMEDIATE) &&\n output_ins.oprs[0].wrt == NO_SEG) {\n define_label(output_ins.label,\n output_ins.oprs[0].segment,\n output_ins.oprs[0].offset, false);\n } else if (output_ins.operands == 2\n && (output_ins.oprs[0].type & IMMEDIATE)\n && (output_ins.oprs[0].type & COLON)\n && output_ins.oprs[0].segment == NO_SEG\n && output_ins.oprs[0].wrt == NO_SEG\n && (output_ins.oprs[1].type & IMMEDIATE)\n && output_ins.oprs[1].segment == NO_SEG\n && output_ins.oprs[1].wrt == NO_SEG) {\n define_label(output_ins.label,\n output_ins.oprs[0].offset | SEG_ABS,\n output_ins.oprs[1].offset, false);\n } else {\n nasm_error(ERR_NONFATAL, \"bad syntax for EQU\");\n }\n } else { /* instruction isn't an EQU */\n int32_t n;\n\n nasm_assert(output_ins.times >= 0);\n\n for (n = 1; n <= output_ins.times; n++) {\n if (pass1 == 1) {\n int64_t l = insn_size(location.segment,\n location.offset,\n globalbits, &output_ins);\n\n /* if (using_debug_info) && output_ins.opcode != -1) */\n if (using_debug_info)\n { /* fbk 03/25/01 */\n /* this is done here so we can do debug type info */\n int32_t typeinfo =\n TYS_ELEMENTS(output_ins.operands);\n switch (output_ins.opcode) {\n case I_RESB:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_BYTE;\n break;\n case I_RESW:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_WORD;\n break;\n case I_RESD:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_DWORD;\n break;\n case I_RESQ:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_QWORD;\n break;\n case I_REST:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_TBYTE;\n break;\n case I_RESO:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_OWORD;\n break;\n case I_RESY:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_YWORD;\n break;\n case I_RESZ:\n typeinfo =\n TYS_ELEMENTS(output_ins.oprs[0].offset) | TY_ZWORD;\n break;\n case I_DB:\n typeinfo |= TY_BYTE;\n break;\n case I_DW:\n typeinfo |= TY_WORD;\n break;\n case I_DD:\n if (output_ins.eops_float)\n typeinfo |= TY_FLOAT;\n else\n typeinfo |= TY_DWORD;\n break;\n case I_DQ:\n typeinfo |= TY_QWORD;\n break;\n case I_DT:\n typeinfo |= TY_TBYTE;\n break;\n case I_DO:\n typeinfo |= TY_OWORD;\n break;\n case I_DY:\n typeinfo |= TY_YWORD;\n break;\n case I_DZ:\n typeinfo |= TY_ZWORD;\n break;\n default:\n typeinfo = TY_LABEL;\n break;\n }\n\n dfmt->debug_typevalue(typeinfo);\n }\n\n /*\n * For INCBIN, let the code in assemble\n * handle TIMES, so we don't have to read the\n * input file over and over.\n */\n if (l != -1) {\n increment_offset(l);\n }\n /*\n * else l == -1 => invalid instruction, which will be\n * flagged as an error on pass 2\n */\n } else {\n if (n == 2)\n lfmt->uplevel(LIST_TIMES);\n increment_offset(assemble(location.segment,\n location.offset,\n globalbits, &output_ins));\n }\n } /* not an EQU */\n }\n if (output_ins.times > 1)\n lfmt->downlevel(LIST_TIMES);\n\n cleanup_insn(&output_ins);\n\n end_of_line:\n nasm_free(line);\n } /* end while (line = preproc->getline... */\n\n if (global_offset_changed && !terminate_after_phase) {\n switch (pass0) {\n case 1:\n nasm_error(ERR_WARNING|ERR_WARN_PHASE,\n \"phase error during stabilization pass, hoping for the best\");\n break;\n\n case 2:\n nasm_error(ERR_NONFATAL,\n \"phase error during code generation pass\");\n break;\n\n default:\n /* This is normal, we'll keep going... */\n break;\n }\n }\n\n if (pass1 == 1)\n preproc->cleanup(1);\n\n /*\n * Always run at least two optimization passes (pass0 == 0);\n * things like subsections will fail miserably without that.\n * Once we commit to a stabilization pass (pass0 == 1), we can't\n * go back, and if something goes bad, we can only hope\n * that we don't end up with a phase error at the end.\n */\n if ((passn > 1 && !global_offset_changed) || pass0 > 0) {\n pass0++;\n } else if (global_offset_changed &&\n global_offset_changed < prev_offset_changed) {\n prev_offset_changed = global_offset_changed;\n stall_count = 0;\n } else {\n stall_count++;\n }\n\n if (terminate_after_phase)\n break;\n\n if ((stall_count > nasm_limit[LIMIT_STALLED]) ||\n (passn >= nasm_limit[LIMIT_PASSES])) {\n /* We get here if the labels don't converge\n * Example: FOO equ FOO + 1\n */\n nasm_error(ERR_NONFATAL,\n \"Can't find valid values for all labels \"\n \"after %\"PRId64\" passes, giving up.\", passn);\n nasm_error(ERR_NONFATAL,\n \"Possible causes: recursive EQUs, macro abuse.\");\n break;\n }\n }\n\n preproc->cleanup(0);\n lfmt->cleanup();\n if (!terminate_after_phase && opt_verbose_info) {\n /* -On and -Ov switches */\n fprintf(stdout, \"info: assembly required 1+%\"PRId64\"+1 passes\\n\",\n passn-3);\n }\n}", "project": "nasm", "hash": 217297003284158501046538109816031999494, "size": 301, "commit_id": "e996d28c70d45008085322b442b44a9224308548", "message": "labels: Don't nil dereference if no label provided\n\nAn equ without label may cause nil dereference\n\n |\tequ 0x100\n\nFixes 98578071b9d71ecaa2344dd9c185237c1765041e\n\nSigned-off-by: Cyrill Gorcunov ", "target": 0, "dataset": "other", "idx": 257477} {"func": "kdc_code kpasswd_process(struct kdc_server *kdc,\n\t\t\t TALLOC_CTX *mem_ctx,\n\t\t\t DATA_BLOB *request,\n\t\t\t DATA_BLOB *reply,\n\t\t\t struct tsocket_address *remote_addr,\n\t\t\t struct tsocket_address *local_addr,\n\t\t\t int datagram)\n{\n\tuint16_t len;\n\tuint16_t verno;\n\tuint16_t ap_req_len;\n\tuint16_t enc_data_len;\n\tDATA_BLOB ap_req_blob = data_blob_null;\n\tDATA_BLOB ap_rep_blob = data_blob_null;\n\tDATA_BLOB enc_data_blob = data_blob_null;\n\tDATA_BLOB dec_data_blob = data_blob_null;\n\tDATA_BLOB kpasswd_dec_reply = data_blob_null;\n\tconst char *error_string = NULL;\n\tkrb5_error_code error_code = 0;\n\tstruct cli_credentials *server_credentials;\n\tstruct gensec_security *gensec_security;\n#ifndef SAMBA4_USES_HEIMDAL\n\tstruct sockaddr_storage remote_ss;\n#endif\n\tstruct sockaddr_storage local_ss;\n\tssize_t socklen;\n\tTALLOC_CTX *tmp_ctx;\n\tkdc_code rc = KDC_ERROR;\n\tkrb5_error_code code = 0;\n\tNTSTATUS status;\n\tint rv;\n\tbool is_inet;\n\tbool ok;\n\n\tif (kdc->am_rodc) {\n\t\treturn KDC_PROXY_REQUEST;\n\t}\n\n\ttmp_ctx = talloc_new(mem_ctx);\n\tif (tmp_ctx == NULL) {\n\t\treturn KDC_ERROR;\n\t}\n\n\tis_inet = tsocket_address_is_inet(remote_addr, \"ip\");\n\tif (!is_inet) {\n\t\tDBG_WARNING(\"Invalid remote IP address\");\n\t\tgoto done;\n\t}\n\n#ifndef SAMBA4_USES_HEIMDAL\n\t/*\n\t * FIXME: Heimdal fails to to do a krb5_rd_req() in gensec_krb5 if we\n\t * set the remote address.\n\t */\n\n\t/* remote_addr */\n\tsocklen = tsocket_address_bsd_sockaddr(remote_addr,\n\t\t\t\t\t (struct sockaddr *)&remote_ss,\n\t\t\t\t\t sizeof(struct sockaddr_storage));\n\tif (socklen < 0) {\n\t\tDBG_WARNING(\"Invalid remote IP address\");\n\t\tgoto done;\n\t}\n#endif\n\n\t/* local_addr */\n\tsocklen = tsocket_address_bsd_sockaddr(local_addr,\n\t\t\t\t\t (struct sockaddr *)&local_ss,\n\t\t\t\t\t sizeof(struct sockaddr_storage));\n\tif (socklen < 0) {\n\t\tDBG_WARNING(\"Invalid local IP address\");\n\t\tgoto done;\n\t}\n\n\tif (request->length <= HEADER_LEN) {\n\t\tDBG_WARNING(\"Request truncated\\n\");\n\t\tgoto done;\n\t}\n\n\tlen = RSVAL(request->data, 0);\n\tif (request->length != len) {\n\t\tDBG_WARNING(\"Request length does not match\\n\");\n\t\tgoto done;\n\t}\n\n\tverno = RSVAL(request->data, 2);\n\tif (verno != 1 && verno != RFC3244_VERSION) {\n\t\tDBG_WARNING(\"Unsupported version: 0x%04x\\n\", verno);\n\t}\n\n\tap_req_len = RSVAL(request->data, 4);\n\tif ((ap_req_len >= len) || ((ap_req_len + HEADER_LEN) >= len)) {\n\t\tDBG_WARNING(\"AP_REQ truncated\\n\");\n\t\tgoto done;\n\t}\n\n\tap_req_blob = data_blob_const(&request->data[HEADER_LEN], ap_req_len);\n\n\tenc_data_len = len - ap_req_len;\n\tenc_data_blob = data_blob_const(&request->data[HEADER_LEN + ap_req_len],\n\t\t\t\t\tenc_data_len);\n\n\tserver_credentials = cli_credentials_init(tmp_ctx);\n\tif (server_credentials == NULL) {\n\t\tDBG_ERR(\"Failed to initialize server credentials!\\n\");\n\t\tgoto done;\n\t}\n\n\t/*\n\t * We want the credentials subsystem to use the krb5 context we already\n\t * have, rather than a new context.\n\t *\n\t * On this context the KDB plugin has been loaded, so we can access\n\t * dsdb.\n\t */\n\tstatus = cli_credentials_set_krb5_context(server_credentials,\n\t\t\t\t\t\t kdc->smb_krb5_context);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\tok = cli_credentials_set_conf(server_credentials, kdc->task->lp_ctx);\n\tif (!ok) {\n\t\tgoto done;\n\t}\n\n\tok = cli_credentials_set_username(server_credentials,\n\t\t\t\t\t \"kadmin/changepw\",\n\t\t\t\t\t CRED_SPECIFIED);\n\tif (!ok) {\n\t\tgoto done;\n\t}\n\n\trv = cli_credentials_set_keytab_name(server_credentials,\n\t\t\t\t\t kdc->task->lp_ctx,\n\t\t\t\t\t kdc->kpasswd_keytab_name,\n\t\t\t\t\t CRED_SPECIFIED);\n\tif (rv != 0) {\n\t\tDBG_ERR(\"Failed to set credentials keytab name\\n\");\n\t\tgoto done;\n\t}\n\n\tstatus = samba_server_gensec_start(tmp_ctx,\n\t\t\t\t\t kdc->task->event_ctx,\n\t\t\t\t\t kdc->task->msg_ctx,\n\t\t\t\t\t kdc->task->lp_ctx,\n\t\t\t\t\t server_credentials,\n\t\t\t\t\t \"kpasswd\",\n\t\t\t\t\t &gensec_security);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\tstatus = gensec_set_local_address(gensec_security, local_addr);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n#ifndef SAMBA4_USES_HEIMDAL\n\tstatus = gensec_set_remote_address(gensec_security, remote_addr);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n#endif\n\n\t/* We want the GENSEC wrap calls to generate PRIV tokens */\n\tgensec_want_feature(gensec_security, GENSEC_FEATURE_SEAL);\n\n\t/* Use the krb5 gesec mechanism so we can load DB modules */\n\tstatus = gensec_start_mech_by_name(gensec_security, \"krb5\");\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\t/*\n\t * Accept the AP-REQ and generate the AP-REP we need for the reply\n\t *\n\t * We only allow KRB5 and make sure the backend to is RPC/IPC free.\n\t *\n\t * See gensec_krb5_update_internal() as GENSEC_SERVER.\n\t *\n\t * It allows gensec_update() not to block.\n\t *\n\t * If that changes in future we need to use\n\t * gensec_update_send/recv here!\n\t */\n\tstatus = gensec_update(gensec_security, tmp_ctx,\n\t\t\t ap_req_blob, &ap_rep_blob);\n\tif (!NT_STATUS_IS_OK(status) &&\n\t !NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {\n\t\tap_rep_blob = data_blob_null;\n\t\terror_code = KRB5_KPASSWD_HARDERROR;\n\t\terror_string = talloc_asprintf(tmp_ctx,\n\t\t\t\t\t \"gensec_update failed - %s\\n\",\n\t\t\t\t\t nt_errstr(status));\n\t\tDBG_ERR(\"%s\", error_string);\n\t\tgoto reply;\n\t}\n\n\tstatus = gensec_unwrap(gensec_security,\n\t\t\t tmp_ctx,\n\t\t\t &enc_data_blob,\n\t\t\t &dec_data_blob);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tap_rep_blob = data_blob_null;\n\t\terror_code = KRB5_KPASSWD_HARDERROR;\n\t\terror_string = talloc_asprintf(tmp_ctx,\n\t\t\t\t\t \"gensec_unwrap failed - %s\\n\",\n\t\t\t\t\t nt_errstr(status));\n\t\tDBG_ERR(\"%s\", error_string);\n\t\tgoto reply;\n\t}\n\n\tcode = kpasswd_handle_request(kdc,\n\t\t\t\t tmp_ctx,\n\t\t\t\t gensec_security,\n\t\t\t\t verno,\n\t\t\t\t &dec_data_blob,\n\t\t\t\t &kpasswd_dec_reply,\n\t\t\t\t &error_string);\n\tif (code != 0) {\n\t\tap_rep_blob = data_blob_null;\n\t\terror_code = code;\n\t\tgoto reply;\n\t}\n\n\tstatus = gensec_wrap(gensec_security,\n\t\t\t tmp_ctx,\n\t\t\t &kpasswd_dec_reply,\n\t\t\t &enc_data_blob);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tap_rep_blob = data_blob_null;\n\t\terror_code = KRB5_KPASSWD_HARDERROR;\n\t\terror_string = talloc_asprintf(tmp_ctx,\n\t\t\t\t\t \"gensec_wrap failed - %s\\n\",\n\t\t\t\t\t nt_errstr(status));\n\t\tDBG_ERR(\"%s\", error_string);\n\t\tgoto reply;\n\t}\n\nreply:\n\tif (error_code != 0) {\n\t\tkrb5_data k_enc_data;\n\t\tkrb5_data k_dec_data;\n\t\tconst char *principal_string;\n\t\tkrb5_principal server_principal;\n\n\t\tif (error_string == NULL) {\n\t\t\tDBG_ERR(\"Invalid error string! This should not happen\\n\");\n\t\t\tgoto done;\n\t\t}\n\n\t\tok = kpasswd_make_error_reply(tmp_ctx,\n\t\t\t\t\t error_code,\n\t\t\t\t\t error_string,\n\t\t\t\t\t &dec_data_blob);\n\t\tif (!ok) {\n\t\t\tDBG_ERR(\"Failed to create error reply\\n\");\n\t\t\tgoto done;\n\t\t}\n\n\t\tk_dec_data.length = dec_data_blob.length;\n\t\tk_dec_data.data = (char *)dec_data_blob.data;\n\n\t\tprincipal_string = cli_credentials_get_principal(server_credentials,\n\t\t\t\t\t\t\t\t tmp_ctx);\n\t\tif (principal_string == NULL) {\n\t\t\tgoto done;\n\t\t}\n\n\t\tcode = smb_krb5_parse_name(kdc->smb_krb5_context->krb5_context,\n\t\t\t\t\t principal_string,\n\t\t\t\t\t &server_principal);\n\t\tif (code != 0) {\n\t\t\tDBG_ERR(\"Failed to create principal: %s\\n\",\n\t\t\t\terror_message(code));\n\t\t\tgoto done;\n\t\t}\n\n\t\tcode = smb_krb5_mk_error(kdc->smb_krb5_context->krb5_context,\n\t\t\t\t\t KRB5KDC_ERR_NONE + error_code,\n\t\t\t\t\t NULL, /* e_text */\n\t\t\t\t\t &k_dec_data,\n\t\t\t\t\t NULL, /* client */\n\t\t\t\t\t server_principal,\n\t\t\t\t\t &k_enc_data);\n\t\tkrb5_free_principal(kdc->smb_krb5_context->krb5_context,\n\t\t\t\t server_principal);\n\t\tif (code != 0) {\n\t\t\tDBG_ERR(\"Failed to create krb5 error reply: %s\\n\",\n\t\t\t\terror_message(code));\n\t\t\tgoto done;\n\t\t}\n\n\t\tenc_data_blob = data_blob_talloc(tmp_ctx,\n\t\t\t\t\t\t k_enc_data.data,\n\t\t\t\t\t\t k_enc_data.length);\n\t\tif (enc_data_blob.data == NULL) {\n\t\t\tDBG_ERR(\"Failed to allocate memory for error reply\\n\");\n\t\t\tgoto done;\n\t\t}\n\t}\n\n\t*reply = data_blob_talloc(mem_ctx,\n\t\t\t\t NULL,\n\t\t\t\t HEADER_LEN + ap_rep_blob.length + enc_data_blob.length);\n\tif (reply->data == NULL) {\n\t\tgoto done;\n\t}\n\tRSSVAL(reply->data, 0, reply->length);\n\tRSSVAL(reply->data, 2, 1);\n\tRSSVAL(reply->data, 4, ap_rep_blob.length);\n\tmemcpy(reply->data + HEADER_LEN,\n\t ap_rep_blob.data,\n\t ap_rep_blob.length);\n\tmemcpy(reply->data + HEADER_LEN + ap_rep_blob.length,\n\t enc_data_blob.data,\n\t enc_data_blob.length);\n\n\trc = KDC_OK;\ndone:\n\ttalloc_free(tmp_ctx);\n\treturn rc;\n}", "project": "samba", "hash": 291020563554827357122154858202521821517, "size": 324, "commit_id": "52dd9f8f835bc23415ec51dcc344478497e208c3", "message": "CVE-2022-32744 s4:kpasswd: Ensure we pass the kpasswd server principal into krb5_rd_req_ctx()\n\nTo ensure that, when decrypting the kpasswd ticket, we look up the\ncorrect principal and don't trust the sname from the ticket, we should\npass the principal name of the kpasswd service into krb5_rd_req_ctx().\nHowever, gensec_krb5_update_internal() will pass in NULL unless the\nprincipal in our credentials is CRED_SPECIFIED.\n\nAt present, our principal will be considered obtained as CRED_SMB_CONF\n(from the cli_credentials_set_conf() a few lines up), so we explicitly\nset the realm again, but this time as CRED_SPECIFIED. Now the value of\nserver_in_keytab that we provide to smb_krb5_rd_req_decoded() will not\nbe NULL.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=15074\n\nSigned-off-by: Joseph Sutton \nReviewed-by: Andreas Schneider ", "target": 1, "dataset": "other", "idx": 197396} {"func": "kdc_code kpasswd_process(struct kdc_server *kdc,\n\t\t\t TALLOC_CTX *mem_ctx,\n\t\t\t DATA_BLOB *request,\n\t\t\t DATA_BLOB *reply,\n\t\t\t struct tsocket_address *remote_addr,\n\t\t\t struct tsocket_address *local_addr,\n\t\t\t int datagram)\n{\n\tuint16_t len;\n\tuint16_t verno;\n\tuint16_t ap_req_len;\n\tuint16_t enc_data_len;\n\tDATA_BLOB ap_req_blob = data_blob_null;\n\tDATA_BLOB ap_rep_blob = data_blob_null;\n\tDATA_BLOB enc_data_blob = data_blob_null;\n\tDATA_BLOB dec_data_blob = data_blob_null;\n\tDATA_BLOB kpasswd_dec_reply = data_blob_null;\n\tconst char *error_string = NULL;\n\tkrb5_error_code error_code = 0;\n\tstruct cli_credentials *server_credentials;\n\tstruct gensec_security *gensec_security;\n#ifndef SAMBA4_USES_HEIMDAL\n\tstruct sockaddr_storage remote_ss;\n#endif\n\tstruct sockaddr_storage local_ss;\n\tssize_t socklen;\n\tTALLOC_CTX *tmp_ctx;\n\tkdc_code rc = KDC_ERROR;\n\tkrb5_error_code code = 0;\n\tNTSTATUS status;\n\tint rv;\n\tbool is_inet;\n\tbool ok;\n\n\tif (kdc->am_rodc) {\n\t\treturn KDC_PROXY_REQUEST;\n\t}\n\n\ttmp_ctx = talloc_new(mem_ctx);\n\tif (tmp_ctx == NULL) {\n\t\treturn KDC_ERROR;\n\t}\n\n\tis_inet = tsocket_address_is_inet(remote_addr, \"ip\");\n\tif (!is_inet) {\n\t\tDBG_WARNING(\"Invalid remote IP address\");\n\t\tgoto done;\n\t}\n\n#ifndef SAMBA4_USES_HEIMDAL\n\t/*\n\t * FIXME: Heimdal fails to to do a krb5_rd_req() in gensec_krb5 if we\n\t * set the remote address.\n\t */\n\n\t/* remote_addr */\n\tsocklen = tsocket_address_bsd_sockaddr(remote_addr,\n\t\t\t\t\t (struct sockaddr *)&remote_ss,\n\t\t\t\t\t sizeof(struct sockaddr_storage));\n\tif (socklen < 0) {\n\t\tDBG_WARNING(\"Invalid remote IP address\");\n\t\tgoto done;\n\t}\n#endif\n\n\t/* local_addr */\n\tsocklen = tsocket_address_bsd_sockaddr(local_addr,\n\t\t\t\t\t (struct sockaddr *)&local_ss,\n\t\t\t\t\t sizeof(struct sockaddr_storage));\n\tif (socklen < 0) {\n\t\tDBG_WARNING(\"Invalid local IP address\");\n\t\tgoto done;\n\t}\n\n\tif (request->length <= HEADER_LEN) {\n\t\tDBG_WARNING(\"Request truncated\\n\");\n\t\tgoto done;\n\t}\n\n\tlen = RSVAL(request->data, 0);\n\tif (request->length != len) {\n\t\tDBG_WARNING(\"Request length does not match\\n\");\n\t\tgoto done;\n\t}\n\n\tverno = RSVAL(request->data, 2);\n\tif (verno != 1 && verno != RFC3244_VERSION) {\n\t\tDBG_WARNING(\"Unsupported version: 0x%04x\\n\", verno);\n\t}\n\n\tap_req_len = RSVAL(request->data, 4);\n\tif ((ap_req_len >= len) || ((ap_req_len + HEADER_LEN) >= len)) {\n\t\tDBG_WARNING(\"AP_REQ truncated\\n\");\n\t\tgoto done;\n\t}\n\n\tap_req_blob = data_blob_const(&request->data[HEADER_LEN], ap_req_len);\n\n\tenc_data_len = len - ap_req_len;\n\tenc_data_blob = data_blob_const(&request->data[HEADER_LEN + ap_req_len],\n\t\t\t\t\tenc_data_len);\n\n\tserver_credentials = cli_credentials_init(tmp_ctx);\n\tif (server_credentials == NULL) {\n\t\tDBG_ERR(\"Failed to initialize server credentials!\\n\");\n\t\tgoto done;\n\t}\n\n\t/*\n\t * We want the credentials subsystem to use the krb5 context we already\n\t * have, rather than a new context.\n\t *\n\t * On this context the KDB plugin has been loaded, so we can access\n\t * dsdb.\n\t */\n\tstatus = cli_credentials_set_krb5_context(server_credentials,\n\t\t\t\t\t\t kdc->smb_krb5_context);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\tok = cli_credentials_set_conf(server_credentials, kdc->task->lp_ctx);\n\tif (!ok) {\n\t\tgoto done;\n\t}\n\n\t/*\n\t * After calling cli_credentials_set_conf(), explicitly set the realm\n\t * with CRED_SPECIFIED. We need to do this so the result of\n\t * principal_from_credentials() called from the gensec layer is\n\t * CRED_SPECIFIED rather than CRED_SMB_CONF, avoiding a fallback to\n\t * match-by-key (very undesirable in this case).\n\t */\n\tok = cli_credentials_set_realm(server_credentials,\n\t\t\t\t lpcfg_realm(kdc->task->lp_ctx),\n\t\t\t\t CRED_SPECIFIED);\n\tif (!ok) {\n\t\tgoto done;\n\t}\n\n\tok = cli_credentials_set_username(server_credentials,\n\t\t\t\t\t \"kadmin/changepw\",\n\t\t\t\t\t CRED_SPECIFIED);\n\tif (!ok) {\n\t\tgoto done;\n\t}\n\n\t/* Check that the server principal is indeed CRED_SPECIFIED. */\n\t{\n\t\tchar *principal = NULL;\n\t\tenum credentials_obtained obtained;\n\n\t\tprincipal = cli_credentials_get_principal_and_obtained(server_credentials,\n\t\t\t\t\t\t\t\t tmp_ctx,\n\t\t\t\t\t\t\t\t &obtained);\n\t\tif (obtained < CRED_SPECIFIED) {\n\t\t\tgoto done;\n\t\t}\n\n\t\tTALLOC_FREE(principal);\n\t}\n\n\trv = cli_credentials_set_keytab_name(server_credentials,\n\t\t\t\t\t kdc->task->lp_ctx,\n\t\t\t\t\t kdc->kpasswd_keytab_name,\n\t\t\t\t\t CRED_SPECIFIED);\n\tif (rv != 0) {\n\t\tDBG_ERR(\"Failed to set credentials keytab name\\n\");\n\t\tgoto done;\n\t}\n\n\tstatus = samba_server_gensec_start(tmp_ctx,\n\t\t\t\t\t kdc->task->event_ctx,\n\t\t\t\t\t kdc->task->msg_ctx,\n\t\t\t\t\t kdc->task->lp_ctx,\n\t\t\t\t\t server_credentials,\n\t\t\t\t\t \"kpasswd\",\n\t\t\t\t\t &gensec_security);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\tstatus = gensec_set_local_address(gensec_security, local_addr);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n#ifndef SAMBA4_USES_HEIMDAL\n\tstatus = gensec_set_remote_address(gensec_security, remote_addr);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n#endif\n\n\t/* We want the GENSEC wrap calls to generate PRIV tokens */\n\tgensec_want_feature(gensec_security, GENSEC_FEATURE_SEAL);\n\n\t/* Use the krb5 gesec mechanism so we can load DB modules */\n\tstatus = gensec_start_mech_by_name(gensec_security, \"krb5\");\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tgoto done;\n\t}\n\n\t/*\n\t * Accept the AP-REQ and generate the AP-REP we need for the reply\n\t *\n\t * We only allow KRB5 and make sure the backend to is RPC/IPC free.\n\t *\n\t * See gensec_krb5_update_internal() as GENSEC_SERVER.\n\t *\n\t * It allows gensec_update() not to block.\n\t *\n\t * If that changes in future we need to use\n\t * gensec_update_send/recv here!\n\t */\n\tstatus = gensec_update(gensec_security, tmp_ctx,\n\t\t\t ap_req_blob, &ap_rep_blob);\n\tif (!NT_STATUS_IS_OK(status) &&\n\t !NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {\n\t\tap_rep_blob = data_blob_null;\n\t\terror_code = KRB5_KPASSWD_HARDERROR;\n\t\terror_string = talloc_asprintf(tmp_ctx,\n\t\t\t\t\t \"gensec_update failed - %s\\n\",\n\t\t\t\t\t nt_errstr(status));\n\t\tDBG_ERR(\"%s\", error_string);\n\t\tgoto reply;\n\t}\n\n\tstatus = gensec_unwrap(gensec_security,\n\t\t\t tmp_ctx,\n\t\t\t &enc_data_blob,\n\t\t\t &dec_data_blob);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tap_rep_blob = data_blob_null;\n\t\terror_code = KRB5_KPASSWD_HARDERROR;\n\t\terror_string = talloc_asprintf(tmp_ctx,\n\t\t\t\t\t \"gensec_unwrap failed - %s\\n\",\n\t\t\t\t\t nt_errstr(status));\n\t\tDBG_ERR(\"%s\", error_string);\n\t\tgoto reply;\n\t}\n\n\tcode = kpasswd_handle_request(kdc,\n\t\t\t\t tmp_ctx,\n\t\t\t\t gensec_security,\n\t\t\t\t verno,\n\t\t\t\t &dec_data_blob,\n\t\t\t\t &kpasswd_dec_reply,\n\t\t\t\t &error_string);\n\tif (code != 0) {\n\t\tap_rep_blob = data_blob_null;\n\t\terror_code = code;\n\t\tgoto reply;\n\t}\n\n\tstatus = gensec_wrap(gensec_security,\n\t\t\t tmp_ctx,\n\t\t\t &kpasswd_dec_reply,\n\t\t\t &enc_data_blob);\n\tif (!NT_STATUS_IS_OK(status)) {\n\t\tap_rep_blob = data_blob_null;\n\t\terror_code = KRB5_KPASSWD_HARDERROR;\n\t\terror_string = talloc_asprintf(tmp_ctx,\n\t\t\t\t\t \"gensec_wrap failed - %s\\n\",\n\t\t\t\t\t nt_errstr(status));\n\t\tDBG_ERR(\"%s\", error_string);\n\t\tgoto reply;\n\t}\n\nreply:\n\tif (error_code != 0) {\n\t\tkrb5_data k_enc_data;\n\t\tkrb5_data k_dec_data;\n\t\tconst char *principal_string;\n\t\tkrb5_principal server_principal;\n\n\t\tif (error_string == NULL) {\n\t\t\tDBG_ERR(\"Invalid error string! This should not happen\\n\");\n\t\t\tgoto done;\n\t\t}\n\n\t\tok = kpasswd_make_error_reply(tmp_ctx,\n\t\t\t\t\t error_code,\n\t\t\t\t\t error_string,\n\t\t\t\t\t &dec_data_blob);\n\t\tif (!ok) {\n\t\t\tDBG_ERR(\"Failed to create error reply\\n\");\n\t\t\tgoto done;\n\t\t}\n\n\t\tk_dec_data.length = dec_data_blob.length;\n\t\tk_dec_data.data = (char *)dec_data_blob.data;\n\n\t\tprincipal_string = cli_credentials_get_principal(server_credentials,\n\t\t\t\t\t\t\t\t tmp_ctx);\n\t\tif (principal_string == NULL) {\n\t\t\tgoto done;\n\t\t}\n\n\t\tcode = smb_krb5_parse_name(kdc->smb_krb5_context->krb5_context,\n\t\t\t\t\t principal_string,\n\t\t\t\t\t &server_principal);\n\t\tif (code != 0) {\n\t\t\tDBG_ERR(\"Failed to create principal: %s\\n\",\n\t\t\t\terror_message(code));\n\t\t\tgoto done;\n\t\t}\n\n\t\tcode = smb_krb5_mk_error(kdc->smb_krb5_context->krb5_context,\n\t\t\t\t\t KRB5KDC_ERR_NONE + error_code,\n\t\t\t\t\t NULL, /* e_text */\n\t\t\t\t\t &k_dec_data,\n\t\t\t\t\t NULL, /* client */\n\t\t\t\t\t server_principal,\n\t\t\t\t\t &k_enc_data);\n\t\tkrb5_free_principal(kdc->smb_krb5_context->krb5_context,\n\t\t\t\t server_principal);\n\t\tif (code != 0) {\n\t\t\tDBG_ERR(\"Failed to create krb5 error reply: %s\\n\",\n\t\t\t\terror_message(code));\n\t\t\tgoto done;\n\t\t}\n\n\t\tenc_data_blob = data_blob_talloc(tmp_ctx,\n\t\t\t\t\t\t k_enc_data.data,\n\t\t\t\t\t\t k_enc_data.length);\n\t\tif (enc_data_blob.data == NULL) {\n\t\t\tDBG_ERR(\"Failed to allocate memory for error reply\\n\");\n\t\t\tgoto done;\n\t\t}\n\t}\n\n\t*reply = data_blob_talloc(mem_ctx,\n\t\t\t\t NULL,\n\t\t\t\t HEADER_LEN + ap_rep_blob.length + enc_data_blob.length);\n\tif (reply->data == NULL) {\n\t\tgoto done;\n\t}\n\tRSSVAL(reply->data, 0, reply->length);\n\tRSSVAL(reply->data, 2, 1);\n\tRSSVAL(reply->data, 4, ap_rep_blob.length);\n\tmemcpy(reply->data + HEADER_LEN,\n\t ap_rep_blob.data,\n\t ap_rep_blob.length);\n\tmemcpy(reply->data + HEADER_LEN + ap_rep_blob.length,\n\t enc_data_blob.data,\n\t enc_data_blob.length);\n\n\trc = KDC_OK;\ndone:\n\ttalloc_free(tmp_ctx);\n\treturn rc;\n}", "project": "samba", "hash": 151175540041094190578263195911591115877, "size": 353, "commit_id": "52dd9f8f835bc23415ec51dcc344478497e208c3", "message": "CVE-2022-32744 s4:kpasswd: Ensure we pass the kpasswd server principal into krb5_rd_req_ctx()\n\nTo ensure that, when decrypting the kpasswd ticket, we look up the\ncorrect principal and don't trust the sname from the ticket, we should\npass the principal name of the kpasswd service into krb5_rd_req_ctx().\nHowever, gensec_krb5_update_internal() will pass in NULL unless the\nprincipal in our credentials is CRED_SPECIFIED.\n\nAt present, our principal will be considered obtained as CRED_SMB_CONF\n(from the cli_credentials_set_conf() a few lines up), so we explicitly\nset the realm again, but this time as CRED_SPECIFIED. Now the value of\nserver_in_keytab that we provide to smb_krb5_rd_req_decoded() will not\nbe NULL.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=15074\n\nSigned-off-by: Joseph Sutton \nReviewed-by: Andreas Schneider ", "target": 0, "dataset": "other", "idx": 258087} {"func": " explicit ReverseSequenceOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"batch_dim\", &batch_dim_));\n OP_REQUIRES_OK(context, context->GetAttr(\"seq_dim\", &seq_dim_));\n }", "project": "tensorflow", "hash": 309225667495445257046903496583646120315, "size": 5, "commit_id": "ecf768cbe50cedc0a45ce1ee223146a3d3d26d23", "message": "Add missing validations to reverse_sequence_op\n\nPiperOrigin-RevId: 372178683\nChange-Id: Iac97ebab5b342f1262c77a7d9bcb4267b305ce5b", "target": 1, "dataset": "other", "idx": 197404} {"func": " explicit ReverseSequenceOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"batch_dim\", &batch_dim_));\n OP_REQUIRES_OK(context, context->GetAttr(\"seq_dim\", &seq_dim_));\n OP_REQUIRES(context, batch_dim_ >= 0,\n errors::InvalidArgument(\"Invalid batch_dim \", batch_dim_));\n OP_REQUIRES(context, seq_dim_ >= 0,\n errors::InvalidArgument(\"Invalid seq_dim \", seq_dim_));\n }", "project": "tensorflow", "hash": 206808381287582228720200892092547402342, "size": 9, "commit_id": "ecf768cbe50cedc0a45ce1ee223146a3d3d26d23", "message": "Add missing validations to reverse_sequence_op\n\nPiperOrigin-RevId: 372178683\nChange-Id: Iac97ebab5b342f1262c77a7d9bcb4267b305ce5b", "target": 0, "dataset": "other", "idx": 258254} {"func": "static int ssl_verify_cert(struct tunnel *tunnel)\n{\n\tint ret = -1;\n\tint cert_valid = 0;\n\tunsigned char digest[SHA256LEN];\n\tunsigned int len;\n\tstruct x509_digest *elem;\n\tchar digest_str[SHA256STRLEN], *subject, *issuer;\n\tchar *line;\n\tint i;\n\tX509_NAME *subj;\n\n\tSSL_set_verify(tunnel->ssl_handle, SSL_VERIFY_PEER, NULL);\n\n\tX509 *cert = SSL_get_peer_certificate(tunnel->ssl_handle);\n\tif (cert == NULL) {\n\t\tlog_error(\"Unable to get gateway certificate.\\n\");\n\t\treturn 1;\n\t}\n\n\tsubj = X509_get_subject_name(cert);\n\n#ifdef HAVE_X509_CHECK_HOST\n\t// Use OpenSSL native host validation if v >= 1.0.2.\n\t// compare against gateway_host and correctly check return value\n\t// to fix piror Incorrect use of X509_check_host\n\tif (X509_check_host(cert, tunnel->config->gateway_host,\n\t 0, 0, NULL) == 1)\n\t\tcert_valid = 1;\n#else\n\tchar common_name[FIELD_SIZE + 1];\n\t// Use explicit Common Name check if native validation not available.\n\t// Note: this will ignore Subject Alternative Name fields.\n\tif (subj\n\t && X509_NAME_get_text_by_NID(subj, NID_commonName, common_name,\n\t FIELD_SIZE) > 0\n\t && strncasecmp(common_name, tunnel->config->gateway_host,\n\t FIELD_SIZE) == 0)\n\t\tcert_valid = 1;\n#endif\n\n\t// Try to validate certificate using local PKI\n\tif (cert_valid\n\t && SSL_get_verify_result(tunnel->ssl_handle) == X509_V_OK) {\n\t\tlog_debug(\"Gateway certificate validation succeeded.\\n\");\n\t\tret = 0;\n\t\tgoto free_cert;\n\t}\n\tlog_debug(\"Gateway certificate validation failed.\\n\");\n\n\t// If validation failed, check if cert is in the white list\n\tif (X509_digest(cert, EVP_sha256(), digest, &len) <= 0\n\t || len != SHA256LEN) {\n\t\tlog_error(\"Could not compute certificate sha256 digest.\\n\");\n\t\tgoto free_cert;\n\t}\n\t// Encode digest in base16\n\tfor (i = 0; i < SHA256LEN; i++)\n\t\tsprintf(&digest_str[2 * i], \"%02x\", digest[i]);\n\tdigest_str[SHA256STRLEN - 1] = '\\0';\n\t// Is it in whitelist?\n\tfor (elem = tunnel->config->cert_whitelist; elem != NULL;\n\t elem = elem->next)\n\t\tif (memcmp(digest_str, elem->data, SHA256STRLEN - 1) == 0)\n\t\t\tbreak;\n\tif (elem != NULL) { // break before end of loop\n\t\tlog_debug(\"Gateway certificate digest found in white list.\\n\");\n\t\tret = 0;\n\t\tgoto free_cert;\n\t}\n\n\tsubject = X509_NAME_oneline(subj, NULL, 0);\n\tissuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);\n\n\tlog_error(\"Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:\\n\");\n\tlog_error(\" --trusted-cert %s\\n\", digest_str);\n\tlog_error(\"or add this line to your config file:\\n\");\n\tlog_error(\" trusted-cert = %s\\n\", digest_str);\n\tlog_error(\"Gateway certificate:\\n\");\n\tlog_error(\" subject:\\n\");\n\tfor (line = strtok(subject, \"/\"); line != NULL;\n\t line = strtok(NULL, \"/\"))\n\t\tlog_error(\" %s\\n\", line);\n\tlog_error(\" issuer:\\n\");\n\tfor (line = strtok(issuer, \"/\"); line != NULL;\n\t line = strtok(NULL, \"/\"))\n\t\tlog_error(\" %s\\n\", line);\n\tlog_error(\" sha256 digest:\\n\");\n\tlog_error(\" %s\\n\", digest_str);\n\nfree_cert:\n\tX509_free(cert);\n\treturn ret;\n}", "project": "openfortivpn", "hash": 231422686038679305050128276823575782422, "size": 94, "commit_id": "6328a070ddaab16faaf008cb9a8a62439c30f2a8", "message": "fix TLS Certificate CommonName NULL Byte Vulnerability\n\nCVE-2020-7043 TLS Certificate CommonName NULL Byte Vulnerability is fixed\nwith this commit\n\nwith #8 hostname validation for the certificate was introduced\nbut unfortunately strncasecmp() was used to compare the byte array\nagainst the expected hostname. This does not correctly treat a CN\nwhich contains a NULL byte. In order to fix this vulnerability\nthe reference implementation from iSECPartners has been included\ninto the code.", "target": 1, "dataset": "other", "idx": 197415} {"func": "static int ssl_verify_cert(struct tunnel *tunnel)\n{\n\tint ret = -1;\n\tint cert_valid = 0;\n\tunsigned char digest[SHA256LEN];\n\tunsigned int len;\n\tstruct x509_digest *elem;\n\tchar digest_str[SHA256STRLEN], *subject, *issuer;\n\tchar *line;\n\tint i;\n\tX509_NAME *subj;\n\n\tSSL_set_verify(tunnel->ssl_handle, SSL_VERIFY_PEER, NULL);\n\n\tX509 *cert = SSL_get_peer_certificate(tunnel->ssl_handle);\n\tif (cert == NULL) {\n\t\tlog_error(\"Unable to get gateway certificate.\\n\");\n\t\treturn 1;\n\t}\n\n\tsubj = X509_get_subject_name(cert);\n\n#ifdef HAVE_X509_CHECK_HOST\n\t// Use OpenSSL native host validation if v >= 1.0.2.\n\t// compare against gateway_host and correctly check return value\n\t// to fix piror Incorrect use of X509_check_host\n\tif (X509_check_host(cert, tunnel->config->gateway_host,\n\t 0, 0, NULL) == 1)\n\t\tcert_valid = 1;\n#else\n\t// Use validate_hostname form iSECPartners if native validation not available\n\t// in order to avoid TLS Certificate CommonName NULL Byte Vulnerability\n\tif (validate_hostname(tunnel->config->gateway_host, cert) == MatchFound)\n \t\tcert_valid = 1;\n#endif\n\n\t// Try to validate certificate using local PKI\n\tif (cert_valid\n\t && SSL_get_verify_result(tunnel->ssl_handle) == X509_V_OK) {\n\t\tlog_debug(\"Gateway certificate validation succeeded.\\n\");\n\t\tret = 0;\n\t\tgoto free_cert;\n\t}\n\tlog_debug(\"Gateway certificate validation failed.\\n\");\n\n\t// If validation failed, check if cert is in the white list\n\tif (X509_digest(cert, EVP_sha256(), digest, &len) <= 0\n\t || len != SHA256LEN) {\n\t\tlog_error(\"Could not compute certificate sha256 digest.\\n\");\n\t\tgoto free_cert;\n\t}\n\t// Encode digest in base16\n\tfor (i = 0; i < SHA256LEN; i++)\n\t\tsprintf(&digest_str[2 * i], \"%02x\", digest[i]);\n\tdigest_str[SHA256STRLEN - 1] = '\\0';\n\t// Is it in whitelist?\n\tfor (elem = tunnel->config->cert_whitelist; elem != NULL;\n\t elem = elem->next)\n\t\tif (memcmp(digest_str, elem->data, SHA256STRLEN - 1) == 0)\n\t\t\tbreak;\n\tif (elem != NULL) { // break before end of loop\n\t\tlog_debug(\"Gateway certificate digest found in white list.\\n\");\n\t\tret = 0;\n\t\tgoto free_cert;\n\t}\n\n\tsubject = X509_NAME_oneline(subj, NULL, 0);\n\tissuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);\n\n\tlog_error(\"Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:\\n\");\n\tlog_error(\" --trusted-cert %s\\n\", digest_str);\n\tlog_error(\"or add this line to your config file:\\n\");\n\tlog_error(\" trusted-cert = %s\\n\", digest_str);\n\tlog_error(\"Gateway certificate:\\n\");\n\tlog_error(\" subject:\\n\");\n\tfor (line = strtok(subject, \"/\"); line != NULL;\n\t line = strtok(NULL, \"/\"))\n\t\tlog_error(\" %s\\n\", line);\n\tlog_error(\" issuer:\\n\");\n\tfor (line = strtok(issuer, \"/\"); line != NULL;\n\t line = strtok(NULL, \"/\"))\n\t\tlog_error(\" %s\\n\", line);\n\tlog_error(\" sha256 digest:\\n\");\n\tlog_error(\" %s\\n\", digest_str);\n\nfree_cert:\n\tX509_free(cert);\n\treturn ret;\n}", "project": "openfortivpn", "hash": 135184877244989477016611417442939527322, "size": 89, "commit_id": "6328a070ddaab16faaf008cb9a8a62439c30f2a8", "message": "fix TLS Certificate CommonName NULL Byte Vulnerability\n\nCVE-2020-7043 TLS Certificate CommonName NULL Byte Vulnerability is fixed\nwith this commit\n\nwith #8 hostname validation for the certificate was introduced\nbut unfortunately strncasecmp() was used to compare the byte array\nagainst the expected hostname. This does not correctly treat a CN\nwhich contains a NULL byte. In order to fix this vulnerability\nthe reference implementation from iSECPartners has been included\ninto the code.", "target": 0, "dataset": "other", "idx": 258435} {"func": "void CleanWriters(GF_List *writers)\n{\n\twhile (gf_list_count(writers)) {\n\t\tTrackWriter *writer = (TrackWriter*)gf_list_get(writers, 0);\n\t\tgf_isom_box_del(writer->stco);\n\t\tgf_isom_box_del((GF_Box *)writer->stsc);\n\t\tgf_free(writer);\n\t\tgf_list_rem(writers, 0);\n\t}\n}", "project": "gpac", "hash": 165424775529354588660088197830809888026, "size": 10, "commit_id": "5aba27604d957e960d8069d85ccaf868f8a7b07a", "message": "fixed #1661", "target": 1, "dataset": "other", "idx": 197417} {"func": "void CleanWriters(GF_List *writers)\n{\n\twhile (gf_list_count(writers)) {\n\t\tTrackWriter *writer = (TrackWriter*)gf_list_get(writers, 0);\n\t\t//in case we have an error in the middle of file write, remove our created stco and stsc from sample table\n\t\tgf_list_del_item(writer->stbl->child_boxes, writer->stco);\n\t\tgf_list_del_item(writer->stbl->child_boxes, writer->stsc);\n\t\tgf_isom_box_del(writer->stco);\n\t\tgf_isom_box_del((GF_Box *)writer->stsc);\n\t\tgf_free(writer);\n\t\tgf_list_rem(writers, 0);\n\t}\n}", "project": "gpac", "hash": 34423418132464214395988583124871092916, "size": 13, "commit_id": "5aba27604d957e960d8069d85ccaf868f8a7b07a", "message": "fixed #1661", "target": 0, "dataset": "other", "idx": 258460} {"func": "GF_Err stbl_GetSampleInfos(GF_SampleTableBox *stbl, u32 sampleNumber, u64 *offset, u32 *chunkNumber, u32 *descIndex, GF_StscEntry **out_ent)\n{\n\tGF_Err e;\n\tu32 i, k, offsetInChunk, size, chunk_num;\n\tGF_ChunkOffsetBox *stco;\n\tGF_ChunkLargeOffsetBox *co64;\n\tGF_StscEntry *ent;\n\n\t(*offset) = 0;\n\t(*chunkNumber) = (*descIndex) = 0;\n\tif (out_ent) (*out_ent) = NULL;\n\tif (!stbl || !sampleNumber) return GF_BAD_PARAM;\n\tif (!stbl->ChunkOffset || !stbl->SampleToChunk || !stbl->SampleSize) return GF_ISOM_INVALID_FILE;\n\n\tif (stbl->SampleSize && stbl->SampleToChunk->nb_entries == stbl->SampleSize->sampleCount) {\n\t\tent = &stbl->SampleToChunk->entries[sampleNumber-1];\n\t\tif (!ent) return GF_BAD_PARAM;\n\t\t(*descIndex) = ent->sampleDescriptionIndex;\n\t\t(*chunkNumber) = sampleNumber;\n\t\tif (out_ent) *out_ent = ent;\n\t\tif ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\t\tstco = (GF_ChunkOffsetBox *)stbl->ChunkOffset;\n\t\t\tif (!stco->offsets) return GF_ISOM_INVALID_FILE;\n\n\t\t\t(*offset) = (u64) stco->offsets[sampleNumber - 1];\n\t\t} else {\n\t\t\tco64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset;\n\t\t\tif (!co64->offsets) return GF_ISOM_INVALID_FILE;\n\n\t\t\t(*offset) = co64->offsets[sampleNumber - 1];\n\t\t}\n\t\treturn GF_OK;\n\t}\n\n\t//check our cache: if desired sample is at or above current cache entry, start from here\n\tif (stbl->SampleToChunk->firstSampleInCurrentChunk &&\n\t (stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber)) {\n\n\t\ti = stbl->SampleToChunk->currentIndex;\n\t\tent = &stbl->SampleToChunk->entries[stbl->SampleToChunk->currentIndex];\n\t\tGetGhostNum(ent, i, stbl->SampleToChunk->nb_entries, stbl);\n\t\tk = stbl->SampleToChunk->currentChunk;\n\t}\n\t//otherwise start from first entry\n\telse {\n\t\ti = 0;\n\t\tstbl->SampleToChunk->currentIndex = 0;\n\t\tstbl->SampleToChunk->currentChunk = 1;\n\t\tstbl->SampleToChunk->ghostNumber = 1;\n\t\tstbl->SampleToChunk->firstSampleInCurrentChunk = 1;\n\t\tent = &stbl->SampleToChunk->entries[0];\n\t\tGetGhostNum(ent, 0, stbl->SampleToChunk->nb_entries, stbl);\n\t\tk = stbl->SampleToChunk->currentChunk;\n\t}\n\n\t//first get the chunk\n\tfor (; i < stbl->SampleToChunk->nb_entries; i++) {\n\t\tassert(stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber);\n\t\t//corrupted file (less sample2chunk info than sample count\n\t\tif (k > stbl->SampleToChunk->ghostNumber) {\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\n\t\t//check if sample is in current chunk\n\t\tu32 max_chunks_in_entry = stbl->SampleToChunk->ghostNumber - k;\n\t\tu32 nb_chunks_for_sample = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk;\n\t\tif (ent->samplesPerChunk) \n\t\t\tnb_chunks_for_sample /= ent->samplesPerChunk;\n\n\t\tif (\n\t\t\t(nb_chunks_for_sample <= max_chunks_in_entry)\n\t\t\t&& (stbl->SampleToChunk->firstSampleInCurrentChunk + (nb_chunks_for_sample+1) * ent->samplesPerChunk > sampleNumber)\n\t\t) {\n\n\t\t\tstbl->SampleToChunk->firstSampleInCurrentChunk += nb_chunks_for_sample * ent->samplesPerChunk;\n\t\t\tstbl->SampleToChunk->currentChunk += nb_chunks_for_sample;\n\t\t\tgoto sample_found;\n\t\t}\n\t\tmax_chunks_in_entry += 1;\n\t\tstbl->SampleToChunk->firstSampleInCurrentChunk += max_chunks_in_entry * ent->samplesPerChunk;\n\t\tstbl->SampleToChunk->currentChunk += max_chunks_in_entry;\n\n\t\t//not in this entry, get the next entry if not the last one\n\t\tif (i+1 != stbl->SampleToChunk->nb_entries) {\n\t\t\tent = &stbl->SampleToChunk->entries[i+1];\n\t\t\t//update the GhostNumber\n\t\t\tGetGhostNum(ent, i+1, stbl->SampleToChunk->nb_entries, stbl);\n\t\t\t//update the entry in our cache\n\t\t\tstbl->SampleToChunk->currentIndex = i+1;\n\t\t\tstbl->SampleToChunk->currentChunk = 1;\n\t\t\tk = 1;\n\t\t}\n\t}\n\t//if we get here, gasp, the sample was not found\n\treturn GF_ISOM_INVALID_FILE;\n\nsample_found:\n\n\t(*descIndex) = ent->sampleDescriptionIndex;\n\t(*chunkNumber) = chunk_num = ent->firstChunk + stbl->SampleToChunk->currentChunk - 1;\n\tif (out_ent) *out_ent = ent;\n\tif (! *chunkNumber)\n\t\treturn GF_ISOM_INVALID_FILE;\n\t\n\t//ok, get the size of all the previous samples in the chunk\n\toffsetInChunk = 0;\n\t//constant size\n\tif (stbl->SampleSize && stbl->SampleSize->sampleSize) {\n\t\tu32 diff = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk;\n\t\toffsetInChunk += diff * stbl->SampleSize->sampleSize;\n\t} else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num == sampleNumber)) {\n\t\toffsetInChunk = stbl->r_last_offset_in_chunk;\n\t} else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num + 1 == sampleNumber)) {\n\t\te = stbl_GetSampleSize(stbl->SampleSize, stbl->r_last_sample_num, &size);\n\t\tif (e) return e;\n\t\tstbl->r_last_offset_in_chunk += size;\n\t\tstbl->r_last_sample_num = sampleNumber;\n\t\toffsetInChunk = stbl->r_last_offset_in_chunk;\n\t} else {\n\t\t//warning, firstSampleInChunk is at least 1 - not 0\n\t\tfor (i = stbl->SampleToChunk->firstSampleInCurrentChunk; i < sampleNumber; i++) {\n\t\t\te = stbl_GetSampleSize(stbl->SampleSize, i, &size);\n\t\t\tif (e) return e;\n\t\t\toffsetInChunk += size;\n\t\t}\n\t\tstbl->r_last_chunk_num = chunk_num;\n\t\tstbl->r_last_sample_num = sampleNumber;\n\t\tstbl->r_last_offset_in_chunk = offsetInChunk;\n\t}\n\t//OK, that's the size of our offset in the chunk\n\t//now get the chunk\n\tif ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\tstco = (GF_ChunkOffsetBox *)stbl->ChunkOffset;\n\t\tif (stco->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE;\n\t\t(*offset) = (u64) stco->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk;\n\t} else {\n\t\tco64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset;\n\t\tif (co64->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE;\n\t\t(*offset) = co64->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk;\n\t}\n\treturn GF_OK;\n}", "project": "gpac", "hash": 114947250168727677329220353898394132242, "size": 143, "commit_id": "2da2f68bffd51d89b1d272d22aa8cc023c1c066e", "message": "fixed #1705", "target": 1, "dataset": "other", "idx": 197433} {"func": "GF_Err stbl_GetSampleInfos(GF_SampleTableBox *stbl, u32 sampleNumber, u64 *offset, u32 *chunkNumber, u32 *descIndex, GF_StscEntry **out_ent)\n{\n\tGF_Err e;\n\tu32 i, k, offsetInChunk, size, chunk_num;\n\tGF_ChunkOffsetBox *stco;\n\tGF_ChunkLargeOffsetBox *co64;\n\tGF_StscEntry *ent;\n\n\t(*offset) = 0;\n\t(*chunkNumber) = (*descIndex) = 0;\n\tif (out_ent) (*out_ent) = NULL;\n\tif (!stbl || !sampleNumber) return GF_BAD_PARAM;\n\tif (!stbl->ChunkOffset || !stbl->SampleToChunk || !stbl->SampleSize) return GF_ISOM_INVALID_FILE;\n\n\tif (stbl->SampleSize && stbl->SampleToChunk->nb_entries == stbl->SampleSize->sampleCount) {\n\t\tent = &stbl->SampleToChunk->entries[sampleNumber-1];\n\t\tif (!ent) return GF_BAD_PARAM;\n\t\t(*descIndex) = ent->sampleDescriptionIndex;\n\t\t(*chunkNumber) = sampleNumber;\n\t\tif (out_ent) *out_ent = ent;\n\t\tif ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\t\tstco = (GF_ChunkOffsetBox *)stbl->ChunkOffset;\n\t\t\tif (!stco->offsets) return GF_ISOM_INVALID_FILE;\n\t\t\tif (stco->nb_entries < sampleNumber) return GF_ISOM_INVALID_FILE;\n\n\t\t\t(*offset) = (u64) stco->offsets[sampleNumber - 1];\n\t\t} else {\n\t\t\tco64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset;\n\t\t\tif (!co64->offsets) return GF_ISOM_INVALID_FILE;\n\t\t\tif (co64->nb_entries < sampleNumber) return GF_ISOM_INVALID_FILE;\n\n\t\t\t(*offset) = co64->offsets[sampleNumber - 1];\n\t\t}\n\t\treturn GF_OK;\n\t}\n\n\t//check our cache: if desired sample is at or above current cache entry, start from here\n\tif (stbl->SampleToChunk->firstSampleInCurrentChunk &&\n\t (stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber)) {\n\n\t\ti = stbl->SampleToChunk->currentIndex;\n\t\tent = &stbl->SampleToChunk->entries[stbl->SampleToChunk->currentIndex];\n\t\tGetGhostNum(ent, i, stbl->SampleToChunk->nb_entries, stbl);\n\t\tk = stbl->SampleToChunk->currentChunk;\n\t}\n\t//otherwise start from first entry\n\telse {\n\t\ti = 0;\n\t\tstbl->SampleToChunk->currentIndex = 0;\n\t\tstbl->SampleToChunk->currentChunk = 1;\n\t\tstbl->SampleToChunk->ghostNumber = 1;\n\t\tstbl->SampleToChunk->firstSampleInCurrentChunk = 1;\n\t\tent = &stbl->SampleToChunk->entries[0];\n\t\tGetGhostNum(ent, 0, stbl->SampleToChunk->nb_entries, stbl);\n\t\tk = stbl->SampleToChunk->currentChunk;\n\t}\n\n\t//first get the chunk\n\tfor (; i < stbl->SampleToChunk->nb_entries; i++) {\n\t\tassert(stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber);\n\t\t//corrupted file (less sample2chunk info than sample count\n\t\tif (k > stbl->SampleToChunk->ghostNumber) {\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\n\t\t//check if sample is in current chunk\n\t\tu32 max_chunks_in_entry = stbl->SampleToChunk->ghostNumber - k;\n\t\tu32 nb_chunks_for_sample = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk;\n\t\tif (ent->samplesPerChunk) \n\t\t\tnb_chunks_for_sample /= ent->samplesPerChunk;\n\n\t\tif (\n\t\t\t(nb_chunks_for_sample <= max_chunks_in_entry)\n\t\t\t&& (stbl->SampleToChunk->firstSampleInCurrentChunk + (nb_chunks_for_sample+1) * ent->samplesPerChunk > sampleNumber)\n\t\t) {\n\n\t\t\tstbl->SampleToChunk->firstSampleInCurrentChunk += nb_chunks_for_sample * ent->samplesPerChunk;\n\t\t\tstbl->SampleToChunk->currentChunk += nb_chunks_for_sample;\n\t\t\tgoto sample_found;\n\t\t}\n\t\tmax_chunks_in_entry += 1;\n\t\tstbl->SampleToChunk->firstSampleInCurrentChunk += max_chunks_in_entry * ent->samplesPerChunk;\n\t\tstbl->SampleToChunk->currentChunk += max_chunks_in_entry;\n\n\t\t//not in this entry, get the next entry if not the last one\n\t\tif (i+1 != stbl->SampleToChunk->nb_entries) {\n\t\t\tent = &stbl->SampleToChunk->entries[i+1];\n\t\t\t//update the GhostNumber\n\t\t\tGetGhostNum(ent, i+1, stbl->SampleToChunk->nb_entries, stbl);\n\t\t\t//update the entry in our cache\n\t\t\tstbl->SampleToChunk->currentIndex = i+1;\n\t\t\tstbl->SampleToChunk->currentChunk = 1;\n\t\t\tk = 1;\n\t\t}\n\t}\n\t//if we get here, gasp, the sample was not found\n\treturn GF_ISOM_INVALID_FILE;\n\nsample_found:\n\n\t(*descIndex) = ent->sampleDescriptionIndex;\n\t(*chunkNumber) = chunk_num = ent->firstChunk + stbl->SampleToChunk->currentChunk - 1;\n\tif (out_ent) *out_ent = ent;\n\tif (! *chunkNumber)\n\t\treturn GF_ISOM_INVALID_FILE;\n\t\n\t//ok, get the size of all the previous samples in the chunk\n\toffsetInChunk = 0;\n\t//constant size\n\tif (stbl->SampleSize && stbl->SampleSize->sampleSize) {\n\t\tu32 diff = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk;\n\t\toffsetInChunk += diff * stbl->SampleSize->sampleSize;\n\t} else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num == sampleNumber)) {\n\t\toffsetInChunk = stbl->r_last_offset_in_chunk;\n\t} else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num + 1 == sampleNumber)) {\n\t\te = stbl_GetSampleSize(stbl->SampleSize, stbl->r_last_sample_num, &size);\n\t\tif (e) return e;\n\t\tstbl->r_last_offset_in_chunk += size;\n\t\tstbl->r_last_sample_num = sampleNumber;\n\t\toffsetInChunk = stbl->r_last_offset_in_chunk;\n\t} else {\n\t\t//warning, firstSampleInChunk is at least 1 - not 0\n\t\tfor (i = stbl->SampleToChunk->firstSampleInCurrentChunk; i < sampleNumber; i++) {\n\t\t\te = stbl_GetSampleSize(stbl->SampleSize, i, &size);\n\t\t\tif (e) return e;\n\t\t\toffsetInChunk += size;\n\t\t}\n\t\tstbl->r_last_chunk_num = chunk_num;\n\t\tstbl->r_last_sample_num = sampleNumber;\n\t\tstbl->r_last_offset_in_chunk = offsetInChunk;\n\t}\n\t//OK, that's the size of our offset in the chunk\n\t//now get the chunk\n\tif ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) {\n\t\tstco = (GF_ChunkOffsetBox *)stbl->ChunkOffset;\n\t\tif (stco->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE;\n\t\t(*offset) = (u64) stco->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk;\n\t} else {\n\t\tco64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset;\n\t\tif (co64->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE;\n\t\t(*offset) = co64->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk;\n\t}\n\treturn GF_OK;\n}", "project": "gpac", "hash": 241891346465159261036739589837185271650, "size": 145, "commit_id": "2da2f68bffd51d89b1d272d22aa8cc023c1c066e", "message": "fixed #1705", "target": 0, "dataset": "other", "idx": 258553} {"func": "static mf_t *open_mf_pattern(void *talloc_ctx, struct demuxer *d, char *filename)\n{\n struct mp_log *log = d->log;\n int error_count = 0;\n int count = 0;\n\n mf_t *mf = talloc_zero(talloc_ctx, mf_t);\n mf->log = log;\n\n if (filename[0] == '@') {\n struct stream *s = stream_create(filename + 1,\n d->stream_origin | STREAM_READ, d->cancel, d->global);\n if (s) {\n while (1) {\n char buf[512];\n int len = stream_read_peek(s, buf, sizeof(buf));\n if (!len)\n break;\n bstr data = (bstr){buf, len};\n int pos = bstrchr(data, '\\n');\n data = bstr_splice(data, 0, pos < 0 ? data.len : pos + 1);\n bstr fname = bstr_strip(data);\n if (fname.len) {\n if (bstrchr(fname, '\\0') >= 0) {\n mp_err(log, \"invalid filename\\n\");\n break;\n }\n char *entry = bstrto0(mf, fname);\n if (!mp_path_exists(entry)) {\n mp_verbose(log, \"file not found: '%s'\\n\", entry);\n } else {\n MP_TARRAY_APPEND(mf, mf->names, mf->nr_of_files, entry);\n }\n }\n stream_seek_skip(s, stream_tell(s) + data.len);\n }\n free_stream(s);\n\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n goto exit_mf;\n }\n mp_info(log, \"%s is not indirect filelist\\n\", filename + 1);\n }\n\n if (strchr(filename, ',')) {\n mp_info(log, \"filelist: %s\\n\", filename);\n bstr bfilename = bstr0(filename);\n\n while (bfilename.len) {\n bstr bfname;\n bstr_split_tok(bfilename, \",\", &bfname, &bfilename);\n char *fname2 = bstrdup0(mf, bfname);\n\n if (!mp_path_exists(fname2))\n mp_verbose(log, \"file not found: '%s'\\n\", fname2);\n else {\n mf_add(mf, fname2);\n }\n talloc_free(fname2);\n }\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n\n goto exit_mf;\n }\n\n char *fname = talloc_size(mf, strlen(filename) + 32);\n\n#if HAVE_GLOB\n if (!strchr(filename, '%')) {\n strcpy(fname, filename);\n if (!strchr(filename, '*'))\n strcat(fname, \"*\");\n\n mp_info(log, \"search expr: %s\\n\", fname);\n\n glob_t gg;\n if (glob(fname, 0, NULL, &gg)) {\n talloc_free(mf);\n return NULL;\n }\n\n for (int i = 0; i < gg.gl_pathc; i++) {\n if (mp_path_isdir(gg.gl_pathv[i]))\n continue;\n mf_add(mf, gg.gl_pathv[i]);\n }\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n globfree(&gg);\n goto exit_mf;\n }\n#endif\n\n mp_info(log, \"search expr: %s\\n\", filename);\n\n while (error_count < 5) {\n sprintf(fname, filename, count++);\n if (!mp_path_exists(fname)) {\n error_count++;\n mp_verbose(log, \"file not found: '%s'\\n\", fname);\n } else {\n mf_add(mf, fname);\n }\n }\n\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n\nexit_mf:\n return mf;\n}", "project": "mpv", "hash": 274378014879641404725355042981539405209, "size": 109, "commit_id": "d0c530919d8cd4d7a774e38ab064e0fabdae34e6", "message": "demux_mf: improve format string processing\n\nBefore this commit, the user could specify a printf format string\nwhich wasn't verified, and could result in:\n- Undefined behavior due to missing or non-matching arguments.\n- Buffer overflow due to untested result length.\n\nThe offending code was added at commit 103a9609 (2002, mplayer svn):\ngit-svn-id: svn://svn.mplayerhq.hu/mplayer/trunk@4566 b3059339-0415-0410-9bf9-f77b7e298cf2\n\nIt moved around but was not modified meaningfully until now.\n\nNow we reject all conversion specifiers at the format except %%\nand a simple subset of the valid specifiers. Also, we now use\nsnprintf to avoid buffer overflow.\n\nThe format string is provided by the user as part of mf:// URI.\n\nReport and initial patch by Stefan Schiller.\nPatch reviewed by @jeeb, @sfan5, Stefan Schiller.", "target": 1, "dataset": "other", "idx": 197465} {"func": "static mf_t *open_mf_pattern(void *talloc_ctx, struct demuxer *d, char *filename)\n{\n struct mp_log *log = d->log;\n int error_count = 0;\n int count = 0;\n\n mf_t *mf = talloc_zero(talloc_ctx, mf_t);\n mf->log = log;\n\n if (filename[0] == '@') {\n struct stream *s = stream_create(filename + 1,\n d->stream_origin | STREAM_READ, d->cancel, d->global);\n if (s) {\n while (1) {\n char buf[512];\n int len = stream_read_peek(s, buf, sizeof(buf));\n if (!len)\n break;\n bstr data = (bstr){buf, len};\n int pos = bstrchr(data, '\\n');\n data = bstr_splice(data, 0, pos < 0 ? data.len : pos + 1);\n bstr fname = bstr_strip(data);\n if (fname.len) {\n if (bstrchr(fname, '\\0') >= 0) {\n mp_err(log, \"invalid filename\\n\");\n break;\n }\n char *entry = bstrto0(mf, fname);\n if (!mp_path_exists(entry)) {\n mp_verbose(log, \"file not found: '%s'\\n\", entry);\n } else {\n MP_TARRAY_APPEND(mf, mf->names, mf->nr_of_files, entry);\n }\n }\n stream_seek_skip(s, stream_tell(s) + data.len);\n }\n free_stream(s);\n\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n goto exit_mf;\n }\n mp_info(log, \"%s is not indirect filelist\\n\", filename + 1);\n }\n\n if (strchr(filename, ',')) {\n mp_info(log, \"filelist: %s\\n\", filename);\n bstr bfilename = bstr0(filename);\n\n while (bfilename.len) {\n bstr bfname;\n bstr_split_tok(bfilename, \",\", &bfname, &bfilename);\n char *fname2 = bstrdup0(mf, bfname);\n\n if (!mp_path_exists(fname2))\n mp_verbose(log, \"file not found: '%s'\\n\", fname2);\n else {\n mf_add(mf, fname2);\n }\n talloc_free(fname2);\n }\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n\n goto exit_mf;\n }\n\n size_t fname_avail = strlen(filename) + 32;\n char *fname = talloc_size(mf, fname_avail);\n\n#if HAVE_GLOB\n if (!strchr(filename, '%')) {\n strcpy(fname, filename);\n if (!strchr(filename, '*'))\n strcat(fname, \"*\");\n\n mp_info(log, \"search expr: %s\\n\", fname);\n\n glob_t gg;\n if (glob(fname, 0, NULL, &gg)) {\n talloc_free(mf);\n return NULL;\n }\n\n for (int i = 0; i < gg.gl_pathc; i++) {\n if (mp_path_isdir(gg.gl_pathv[i]))\n continue;\n mf_add(mf, gg.gl_pathv[i]);\n }\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n globfree(&gg);\n goto exit_mf;\n }\n#endif\n\n // We're using arbitrary user input as printf format with 1 int argument.\n // Any format which uses exactly 1 int argument would be valid, but for\n // simplicity we reject all conversion specifiers except %% and simple\n // integer specifier: %[.][NUM]d where NUM is 1-3 digits (%.d is valid)\n const char *f = filename;\n int MAXDIGS = 3, nspec = 0, bad_spec = 0, c;\n\n while (nspec < 2 && (c = *f++)) {\n if (c != '%')\n continue;\n if (*f != '%') {\n nspec++; // conversion specifier which isn't %%\n if (*f == '.')\n f++;\n for (int ndig = 0; mp_isdigit(*f) && ndig < MAXDIGS; ndig++, f++)\n /* no-op */;\n if (*f != 'd') {\n bad_spec++; // not int, or beyond our validation capacity\n break;\n }\n }\n // *f is '%' or 'd'\n f++;\n }\n\n // nspec==0 (zero specifiers) is rejected because fname wouldn't advance.\n if (bad_spec || nspec != 1) {\n mp_err(log, \"unsupported expr format: '%s'\\n\", filename);\n goto exit_mf;\n }\n\n mp_info(log, \"search expr: %s\\n\", filename);\n\n while (error_count < 5) {\n if (snprintf(fname, fname_avail, filename, count++) >= fname_avail) {\n mp_err(log, \"format result too long: '%s'\\n\", filename);\n goto exit_mf;\n }\n if (!mp_path_exists(fname)) {\n error_count++;\n mp_verbose(log, \"file not found: '%s'\\n\", fname);\n } else {\n mf_add(mf, fname);\n }\n }\n\n mp_info(log, \"number of files: %d\\n\", mf->nr_of_files);\n\nexit_mf:\n return mf;\n}", "project": "mpv", "hash": 167587795732249525600053650581205374378, "size": 144, "commit_id": "d0c530919d8cd4d7a774e38ab064e0fabdae34e6", "message": "demux_mf: improve format string processing\n\nBefore this commit, the user could specify a printf format string\nwhich wasn't verified, and could result in:\n- Undefined behavior due to missing or non-matching arguments.\n- Buffer overflow due to untested result length.\n\nThe offending code was added at commit 103a9609 (2002, mplayer svn):\ngit-svn-id: svn://svn.mplayerhq.hu/mplayer/trunk@4566 b3059339-0415-0410-9bf9-f77b7e298cf2\n\nIt moved around but was not modified meaningfully until now.\n\nNow we reject all conversion specifiers at the format except %%\nand a simple subset of the valid specifiers. Also, we now use\nsnprintf to avoid buffer overflow.\n\nThe format string is provided by the user as part of mf:// URI.\n\nReport and initial patch by Stefan Schiller.\nPatch reviewed by @jeeb, @sfan5, Stefan Schiller.", "target": 0, "dataset": "other", "idx": 259078} {"func": "CallResult JSObject::putComputedWithReceiver_RJS(\n Handle selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> valueHandle,\n Handle<> receiver,\n PropOpFlags opFlags) {\n assert(\n !opFlags.getMustExist() &&\n \"mustExist flag cannot be used with computed properties\");\n\n // Try the fast-path first: has \"index-like\" properties, the \"name\"\n // already is a valid integer index, selfHandle and receiver are the\n // same, and it is present in storage.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n if (selfHandle.getHermesValue().getRaw() == receiver->getRaw()) {\n if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) {\n auto result =\n setOwnIndexed(selfHandle, runtime, *arrayIndex, valueHandle);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_LIKELY(*result))\n return true;\n if (opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\n \"Cannot assign to read-only property\");\n }\n return false;\n }\n }\n }\n }\n\n // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;\n\n ComputedPropertyDescriptor desc;\n\n // Look for the property in this object or along the prototype chain.\n MutableHandle propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n\n // If the property exists (or, we hit a proxy/hostobject on the way\n // up the chain)\n if (propObj) {\n // Get the simple case out of the way: If the property already\n // exists on selfHandle, is not an accessor, selfHandle and\n // receiver are the same, selfHandle is not a host\n // object/proxy/internal setter, and the property is writable,\n // just write into the same slot.\n\n if (LLVM_LIKELY(\n selfHandle == propObj &&\n selfHandle.getHermesValue().getRaw() == receiver->getRaw() &&\n !desc.flags.accessor && !desc.flags.internalSetter &&\n !desc.flags.hostObject && !desc.flags.proxyObject &&\n desc.flags.writable)) {\n if (LLVM_UNLIKELY(\n setComputedSlotValue(selfHandle, runtime, desc, valueHandle) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n\n // Is it an accessor?\n if (LLVM_UNLIKELY(desc.flags.accessor)) {\n auto *accessor = vmcast(\n getComputedSlotValue(propObj.get(), runtime, desc));\n\n // If it is a read-only accessor, fail.\n if (!accessor->setter) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeErrorForValue(\n \"Cannot assign to property \",\n nameValPrimitiveHandle,\n \" which has only a getter\");\n }\n return false;\n }\n\n // Execute the accessor on this object.\n if (accessor->setter.get(runtime)->executeCall1(\n runtime->makeHandle(accessor->setter),\n runtime,\n receiver,\n valueHandle.get()) == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n\n if (LLVM_UNLIKELY(desc.flags.proxyObject)) {\n assert(\n !opFlags.getMustExist() &&\n \"MustExist cannot be used with Proxy objects\");\n CallResult> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n CallResult setRes =\n JSProxy::setComputed(propObj, runtime, *key, valueHandle, receiver);\n if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!*setRes && opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\n TwineChar16(\"Proxy trap returned false for property\"));\n }\n return setRes;\n }\n\n if (LLVM_UNLIKELY(!desc.flags.writable)) {\n if (desc.flags.staticBuiltin) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n return raiseErrorForOverridingStaticBuiltin(\n selfHandle, runtime, runtime->makeHandle(id));\n }\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeErrorForValue(\n \"Cannot assign to read-only property \", nameValPrimitiveHandle, \"\");\n }\n return false;\n }\n\n if (selfHandle == propObj && desc.flags.internalSetter) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n return internalSetter(\n selfHandle,\n runtime,\n id,\n desc.castToNamedPropertyDescriptorRef(),\n valueHandle,\n opFlags);\n }\n }\n\n // The property does not exist as an conventional own property on\n // this object.\n\n MutableHandle receiverHandle{runtime, *selfHandle};\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() ||\n receiverHandle->isHostObject() || receiverHandle->isProxyObject()) {\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) {\n receiverHandle = dyn_vmcast(*receiver);\n }\n if (!receiverHandle) {\n return false;\n }\n CallResult descDefinedRes = getOwnComputedPrimitiveDescriptor(\n receiverHandle, runtime, nameValPrimitiveHandle, IgnoreProxy::No, desc);\n if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n DefinePropertyFlags dpf;\n if (*descDefinedRes) {\n if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) {\n return false;\n }\n\n if (LLVM_LIKELY(\n !desc.flags.internalSetter && !receiverHandle->isHostObject() &&\n !receiverHandle->isProxyObject())) {\n if (LLVM_UNLIKELY(\n setComputedSlotValue(\n receiverHandle, runtime, desc, valueHandle) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n }\n\n if (LLVM_UNLIKELY(\n desc.flags.internalSetter || receiverHandle->isHostObject() ||\n receiverHandle->isProxyObject())) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n if (desc.flags.internalSetter) {\n return internalSetter(\n receiverHandle,\n runtime,\n id,\n desc.castToNamedPropertyDescriptorRef(),\n valueHandle,\n opFlags);\n } else if (receiverHandle->isHostObject()) {\n return vmcast(receiverHandle.get())->set(id, *valueHandle);\n }\n assert(\n receiverHandle->isProxyObject() && \"descriptor flags are impossible\");\n if (*descDefinedRes) {\n dpf.setValue = 1;\n } else {\n dpf = DefinePropertyFlags::getDefaultNewPropertyFlags();\n }\n return JSProxy::defineOwnProperty(\n receiverHandle,\n runtime,\n nameValPrimitiveHandle,\n dpf,\n valueHandle,\n opFlags);\n }\n }\n\n /// Can we add more properties?\n if (LLVM_UNLIKELY(!receiverHandle->isExtensible())) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"cannot add a new property\"); // TODO: better message.\n }\n return false;\n }\n\n // If we have indexed storage we must check whether the property is an index,\n // and if it is, store it in indexed storage.\n if (receiverHandle->flags_.indexedStorage) {\n OptValue arrayIndex;\n MutableHandle strPrim{runtime};\n TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex);\n if (arrayIndex) {\n // Check whether we need to update array's \".length\" property.\n if (auto *array = dyn_vmcast(receiverHandle.get())) {\n if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(array))) {\n auto cr = putNamed_RJS(\n receiverHandle,\n runtime,\n Predefined::getSymbolID(Predefined::length),\n runtime->makeHandle(\n HermesValue::encodeNumberValue(*arrayIndex + 1)),\n opFlags);\n if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_UNLIKELY(!*cr))\n return false;\n }\n }\n\n auto result =\n setOwnIndexed(receiverHandle, runtime, *arrayIndex, valueHandle);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_LIKELY(*result))\n return true;\n\n if (opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\"Cannot assign to read-only property\");\n }\n return false;\n }\n }\n\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n\n // Add a new named property.\n return addOwnProperty(\n receiverHandle,\n runtime,\n id,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n valueHandle,\n opFlags);\n}", "project": "hermes", "hash": 22276050551116012672246483362569889414, "size": 281, "commit_id": "8cb935cd3b2321c46aa6b7ed8454d95c75a7fca0", "message": "Handle set where internalSetter and Proxy are both true\n\nSummary:\nIf putComputed is called on a proxy whose target's prototype\nis an array with a propname of 'length', then internalSetter will be\ntrue, and the receiver will be a proxy. In that case, proxy needs to\nwin; the behavior may assert or be UB otherwise.\n\nReviewed By: tmikov\n\nDifferential Revision: D23916279\n\nfbshipit-source-id: c760356d48a02ece565fb4bc1acdafd7ccad7c68", "target": 1, "dataset": "other", "idx": 197476} {"func": "CallResult JSObject::putComputedWithReceiver_RJS(\n Handle selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> valueHandle,\n Handle<> receiver,\n PropOpFlags opFlags) {\n assert(\n !opFlags.getMustExist() &&\n \"mustExist flag cannot be used with computed properties\");\n\n // Try the fast-path first: has \"index-like\" properties, the \"name\"\n // already is a valid integer index, selfHandle and receiver are the\n // same, and it is present in storage.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n if (selfHandle.getHermesValue().getRaw() == receiver->getRaw()) {\n if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) {\n auto result =\n setOwnIndexed(selfHandle, runtime, *arrayIndex, valueHandle);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_LIKELY(*result))\n return true;\n if (opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\n \"Cannot assign to read-only property\");\n }\n return false;\n }\n }\n }\n }\n\n // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;\n\n ComputedPropertyDescriptor desc;\n\n // Look for the property in this object or along the prototype chain.\n MutableHandle propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n\n // If the property exists (or, we hit a proxy/hostobject on the way\n // up the chain)\n if (propObj) {\n // Get the simple case out of the way: If the property already\n // exists on selfHandle, is not an accessor, selfHandle and\n // receiver are the same, selfHandle is not a host\n // object/proxy/internal setter, and the property is writable,\n // just write into the same slot.\n\n if (LLVM_LIKELY(\n selfHandle == propObj &&\n selfHandle.getHermesValue().getRaw() == receiver->getRaw() &&\n !desc.flags.accessor && !desc.flags.internalSetter &&\n !desc.flags.hostObject && !desc.flags.proxyObject &&\n desc.flags.writable)) {\n if (LLVM_UNLIKELY(\n setComputedSlotValue(selfHandle, runtime, desc, valueHandle) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n\n // Is it an accessor?\n if (LLVM_UNLIKELY(desc.flags.accessor)) {\n auto *accessor = vmcast(\n getComputedSlotValue(propObj.get(), runtime, desc));\n\n // If it is a read-only accessor, fail.\n if (!accessor->setter) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeErrorForValue(\n \"Cannot assign to property \",\n nameValPrimitiveHandle,\n \" which has only a getter\");\n }\n return false;\n }\n\n // Execute the accessor on this object.\n if (accessor->setter.get(runtime)->executeCall1(\n runtime->makeHandle(accessor->setter),\n runtime,\n receiver,\n valueHandle.get()) == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n\n if (LLVM_UNLIKELY(desc.flags.proxyObject)) {\n assert(\n !opFlags.getMustExist() &&\n \"MustExist cannot be used with Proxy objects\");\n CallResult> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n CallResult setRes =\n JSProxy::setComputed(propObj, runtime, *key, valueHandle, receiver);\n if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!*setRes && opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\n TwineChar16(\"Proxy trap returned false for property\"));\n }\n return setRes;\n }\n\n if (LLVM_UNLIKELY(!desc.flags.writable)) {\n if (desc.flags.staticBuiltin) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n return raiseErrorForOverridingStaticBuiltin(\n selfHandle, runtime, runtime->makeHandle(id));\n }\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeErrorForValue(\n \"Cannot assign to read-only property \", nameValPrimitiveHandle, \"\");\n }\n return false;\n }\n\n if (selfHandle == propObj && desc.flags.internalSetter) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n return internalSetter(\n selfHandle,\n runtime,\n id,\n desc.castToNamedPropertyDescriptorRef(),\n valueHandle,\n opFlags);\n }\n }\n\n // The property does not exist as an conventional own property on\n // this object.\n\n MutableHandle receiverHandle{runtime, *selfHandle};\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() ||\n receiverHandle->isHostObject() || receiverHandle->isProxyObject()) {\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) {\n receiverHandle = dyn_vmcast(*receiver);\n }\n if (!receiverHandle) {\n return false;\n }\n CallResult descDefinedRes = getOwnComputedPrimitiveDescriptor(\n receiverHandle, runtime, nameValPrimitiveHandle, IgnoreProxy::No, desc);\n if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n DefinePropertyFlags dpf;\n if (*descDefinedRes) {\n if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) {\n return false;\n }\n\n if (LLVM_LIKELY(\n !desc.flags.internalSetter && !receiverHandle->isHostObject() &&\n !receiverHandle->isProxyObject())) {\n if (LLVM_UNLIKELY(\n setComputedSlotValue(\n receiverHandle, runtime, desc, valueHandle) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n }\n\n if (LLVM_UNLIKELY(\n desc.flags.internalSetter || receiverHandle->isHostObject() ||\n receiverHandle->isProxyObject())) {\n // If putComputed is called on a proxy whose target's prototype\n // is an array with a propname of 'length', then internalSetter\n // will be true, and the receiver will be a proxy. In that case,\n // proxy wins.\n if (receiverHandle->isProxyObject()) {\n if (*descDefinedRes) {\n dpf.setValue = 1;\n } else {\n dpf = DefinePropertyFlags::getDefaultNewPropertyFlags();\n }\n return JSProxy::defineOwnProperty(\n receiverHandle,\n runtime,\n nameValPrimitiveHandle,\n dpf,\n valueHandle,\n opFlags);\n }\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n if (desc.flags.internalSetter) {\n return internalSetter(\n receiverHandle,\n runtime,\n id,\n desc.castToNamedPropertyDescriptorRef(),\n valueHandle,\n opFlags);\n }\n assert(\n receiverHandle->isHostObject() && \"descriptor flags are impossible\");\n return vmcast(receiverHandle.get())->set(id, *valueHandle);\n }\n }\n\n /// Can we add more properties?\n if (LLVM_UNLIKELY(!receiverHandle->isExtensible())) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"cannot add a new property\"); // TODO: better message.\n }\n return false;\n }\n\n // If we have indexed storage we must check whether the property is an index,\n // and if it is, store it in indexed storage.\n if (receiverHandle->flags_.indexedStorage) {\n OptValue arrayIndex;\n MutableHandle strPrim{runtime};\n TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex);\n if (arrayIndex) {\n // Check whether we need to update array's \".length\" property.\n if (auto *array = dyn_vmcast(receiverHandle.get())) {\n if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(array))) {\n auto cr = putNamed_RJS(\n receiverHandle,\n runtime,\n Predefined::getSymbolID(Predefined::length),\n runtime->makeHandle(\n HermesValue::encodeNumberValue(*arrayIndex + 1)),\n opFlags);\n if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_UNLIKELY(!*cr))\n return false;\n }\n }\n\n auto result =\n setOwnIndexed(receiverHandle, runtime, *arrayIndex, valueHandle);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_LIKELY(*result))\n return true;\n\n if (opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\"Cannot assign to read-only property\");\n }\n return false;\n }\n }\n\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n\n // Add a new named property.\n return addOwnProperty(\n receiverHandle,\n runtime,\n id,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n valueHandle,\n opFlags);\n}", "project": "hermes", "hash": 22945775706399007322739222011717058068, "size": 286, "commit_id": "8cb935cd3b2321c46aa6b7ed8454d95c75a7fca0", "message": "Handle set where internalSetter and Proxy are both true\n\nSummary:\nIf putComputed is called on a proxy whose target's prototype\nis an array with a propname of 'length', then internalSetter will be\ntrue, and the receiver will be a proxy. In that case, proxy needs to\nwin; the behavior may assert or be UB otherwise.\n\nReviewed By: tmikov\n\nDifferential Revision: D23916279\n\nfbshipit-source-id: c760356d48a02ece565fb4bc1acdafd7ccad7c68", "target": 0, "dataset": "other", "idx": 259369} {"func": " void Compute(OpKernelContext* context) override {\n // Checks what we're remapping and inverts the relevant remapping Tensors to\n // be maps with key = old ID, value = new ID.\n std::unordered_map old_row_to_new_row_map;\n std::vector row_id_present;\n const Tensor* row_remapping_t;\n OP_REQUIRES_OK(context, context->input(\"row_remapping\", &row_remapping_t));\n const auto row_remapping = row_remapping_t->vec();\n OP_REQUIRES(context, row_remapping.size() == num_rows_,\n errors::InvalidArgument(strings::StrCat(\n \"Size of row_remapping is \", row_remapping.size(),\n \" instead of being equal to num_rows=\", num_rows_)));\n OP_REQUIRES_OK(context, RemapVectorToMap(row_remapping, &row_id_present,\n &old_row_to_new_row_map));\n\n // Calculates the min/max old row ID that we need to read, to save us from\n // reading some unnecessary slices of the old tensor.\n int64 min_old_row = -1;\n int64 max_old_row = -1;\n for (int i = 0; i < row_remapping.size(); ++i) {\n if (min_old_row < 0 ||\n (row_remapping(i) >= 0 && row_remapping(i) < min_old_row)) {\n min_old_row = row_remapping(i);\n }\n if (max_old_row < 0 ||\n (row_remapping(i) >= 0 && row_remapping(i) > max_old_row)) {\n max_old_row = row_remapping(i);\n }\n }\n\n // Processes the remapping for columns.\n std::unordered_map old_col_to_new_col_map;\n std::vector col_id_present;\n const Tensor* col_remapping_t;\n OP_REQUIRES_OK(context, context->input(\"col_remapping\", &col_remapping_t));\n const auto col_remapping = col_remapping_t->vec();\n // Note that we always \"remap rows\", even when the row vocabulary does\n // not change, because partitioning requires a mapping from partitioned\n // Variables to the full checkpoints we load.\n const bool remap_cols = col_remapping.size() > 0;\n if (remap_cols) {\n OP_REQUIRES(\n context, col_remapping.size() == num_cols_,\n errors::InvalidArgument(strings::StrCat(\n \"Provided col_remapping, but its size is \", col_remapping.size(),\n \" instead of being equal to num_cols=\", num_cols_)));\n OP_REQUIRES_OK(context, RemapVectorToMap(col_remapping, &col_id_present,\n &old_col_to_new_col_map));\n } else {\n col_id_present.clear();\n col_id_present.resize(num_cols_, true);\n }\n\n // Processes the checkpoint source and the provided Tensor name.\n const Tensor* ckpt_path_t;\n OP_REQUIRES_OK(context, context->input(\"ckpt_path\", &ckpt_path_t));\n const string& ckpt_path = ckpt_path_t->scalar()();\n const Tensor* old_tensor_name_t;\n OP_REQUIRES_OK(context,\n context->input(\"old_tensor_name\", &old_tensor_name_t));\n const string& old_tensor_name = old_tensor_name_t->scalar()();\n\n LOG(INFO) << \"Processing checkpoint : \" << ckpt_path;\n BundleReader reader(context->env(), ckpt_path);\n OP_REQUIRES_OK(context, reader.status());\n\n DataType tensor_type;\n TensorShape tensor_shape;\n OP_REQUIRES_OK(context, reader.LookupDtypeAndShape(\n old_tensor_name, &tensor_type, &tensor_shape));\n OP_REQUIRES(context, tensor_type == DT_FLOAT,\n errors::InvalidArgument(strings::StrCat(\n \"Tensor \", old_tensor_name, \" has invalid type \",\n DataTypeString(tensor_type), \" instead of expected type \",\n DataTypeString(DT_FLOAT))));\n // This op is limited to loading Tensors of rank 2 (matrices).\n OP_REQUIRES(\n context, tensor_shape.dims() == 2,\n errors::InvalidArgument(strings::StrCat(\n \"Tensor \", old_tensor_name, \" has shape \",\n tensor_shape.DebugString(), \" of invalid rank \",\n tensor_shape.dims(), \" instead of expected shape of rank 2.\")));\n\n if (!remap_cols) {\n // TODO(weiho): Consider relaxing this restriction to allow partial column\n // loading (even when no column remapping is specified) if there turns out\n // to be a use case for it.\n OP_REQUIRES(context, num_cols_ == tensor_shape.dim_size(1),\n errors::InvalidArgument(strings::StrCat(\n \"Tensor \", old_tensor_name, \" has shape \",\n tensor_shape.DebugString(),\n \", where the size of its 2nd dimension is \",\n tensor_shape.dim_size(1),\n \" instead of being equal to num_cols=\", num_cols_)));\n }\n\n // Uses TensorSlice to potentially load the old tensor in chunks in case\n // memory usage is a concern.\n std::vector tensor_slices;\n TensorSlice slice(tensor_shape.dims());\n if (min_old_row >= 0 && max_old_row >= 0) {\n int64 row_start = min_old_row;\n // TODO(weiho): Given the list of old row IDs of interest (the keys of\n // old_row_to_new_row_map), we could also try something smarter to\n // find some minimal set of covering ranges for the list of old row IDs\n // such that the size of each range is less than max_rows_in_memory_.\n while (row_start <= max_old_row) {\n const int64 slice_length =\n max_rows_in_memory_ <= 0\n // If max_rows_in_memory_ <= 0, we just load the entire chunk.\n ? max_old_row - row_start + 1\n : std::min(max_rows_in_memory_, max_old_row - row_start + 1);\n slice.set_start(0, row_start);\n slice.set_length(0, slice_length);\n tensor_slices.push_back(slice);\n row_start += slice_length;\n }\n }\n\n // Allocates the output matrix.\n Tensor* output_matrix_t = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\"output_matrix\",\n TensorShape({num_rows_, num_cols_}),\n &output_matrix_t));\n auto output_matrix = output_matrix_t->matrix();\n\n // Iterates through tensor slices and copies over values from the old tensor\n // to the output matrix.\n int64 row_index = min_old_row;\n int64 rows_copied = 0;\n Tensor loaded_tensor_t;\n for (const TensorSlice& tensor_slice : tensor_slices) {\n LOG(INFO) << \"Loading slice \" << tensor_slice.DebugString();\n TensorShape slice_shape;\n OP_REQUIRES_OK(context,\n tensor_slice.SliceTensorShape(tensor_shape, &slice_shape));\n // Potentially re-allocates the tensor buffer since the last slice may\n // have fewer rows than the other slices.\n if (loaded_tensor_t.shape() != slice_shape) {\n loaded_tensor_t = Tensor(DT_FLOAT, slice_shape);\n }\n OP_REQUIRES_OK(context, reader.LookupSlice(old_tensor_name, tensor_slice,\n &loaded_tensor_t));\n\n // Iterates through the old loaded tensor slice row-by-row.\n for (int row = 0; row < loaded_tensor_t.dim_size(0); ++row, ++row_index) {\n if (row_index % 500000 == min_old_row) {\n LOG(INFO) << \"Processing old row \" << row_index;\n }\n\n // If the old row ID is not found in old_row_to_new_row_map, continue\n // to the next row; otherwise, copy it to the output matrix.\n const int64* new_row_ptr =\n gtl::FindOrNull(old_row_to_new_row_map, row_index);\n if (new_row_ptr == nullptr) {\n continue;\n }\n ++rows_copied;\n const int64 new_row = *new_row_ptr;\n\n // Copies over the row element-by-element, in case remapping is needed\n // along the column axis.\n const auto& loaded_tensor = loaded_tensor_t.matrix();\n for (int old_col = 0; old_col < loaded_tensor_t.dim_size(1);\n ++old_col) {\n int64 new_col = old_col;\n if (remap_cols) {\n const int64* new_col_ptr =\n gtl::FindOrNull(old_col_to_new_col_map, old_col);\n if (new_col_ptr == nullptr) {\n // Column remapping is specified, but this column is not found in\n // old_col_to_new_col_map, so we leave it uninitialized, to be\n // filled in with initializing_values later.\n continue;\n }\n new_col = *new_col_ptr;\n }\n\n OP_REQUIRES(context,\n new_row < num_rows_ && new_col < num_cols_ &&\n new_row >= 0 && new_col >= 0,\n errors::Internal(strings::StrCat(\n \"new_row=\", new_row, \" and new_col=\", new_col,\n \" should have been less than num_rows_=\", num_rows_,\n \" and num_cols_=\", num_cols_,\n \" and non-negative. This should never have happened \"\n \"if the code were correct. Please file a bug.\")));\n output_matrix(new_row, new_col) = loaded_tensor(row, old_col);\n }\n }\n }\n LOG(INFO) << \"Copied \" << rows_copied << \" rows from old matrix (with \"\n << tensor_shape.dim_size(0) << \" rows) to new matrix (with \"\n << num_rows_ << \" rows).\";\n\n // At this point, there are potentially whole rows/columns uninitialized\n // (corresponding to the indices where row_id_present/col_id_present are\n // false). We fill this in cell-by-cell using row_id_present and\n // col_id_present while dequeuing from the initializing_values vector.\n const Tensor* initializing_values_t;\n OP_REQUIRES_OK(\n context, context->input(\"initializing_values\", &initializing_values_t));\n const auto initializing_values = initializing_values_t->flat();\n int64 initializing_values_index = 0;\n for (int i = 0; i < num_rows_; ++i) {\n for (int j = 0; j < num_cols_; ++j) {\n if (row_id_present[i] && col_id_present[j]) continue;\n OP_REQUIRES(\n context, initializing_values_index < initializing_values.size(),\n errors::InvalidArgument(\n \"initializing_values contained \", initializing_values.size(),\n \" elements, but more missing values remain.\"));\n output_matrix(i, j) = initializing_values(initializing_values_index);\n ++initializing_values_index;\n }\n }\n\n // Checks that we used all the given initializing values.\n OP_REQUIRES(\n context, initializing_values_index == initializing_values.size(),\n errors::InvalidArgument(\n \"initializing_values contained \", initializing_values.size(),\n \" elements, but only \", initializing_values_index,\n \" elements were used to fill in missing values.\"));\n }", "project": "tensorflow", "hash": 52693165629132470358185846768404409366, "size": 226, "commit_id": "77dd114513d7796e1e2b8aece214a380af26fbf4", "message": "Fix a check fail\n\nPiperOrigin-RevId: 372011072\nChange-Id: I1062cfaed0aa16884e9a16312483794d188db76f", "target": 1, "dataset": "other", "idx": 197512} {"func": " void Compute(OpKernelContext* context) override {\n // Checks what we're remapping and inverts the relevant remapping Tensors to\n // be maps with key = old ID, value = new ID.\n std::unordered_map old_row_to_new_row_map;\n std::vector row_id_present;\n const Tensor* row_remapping_t;\n OP_REQUIRES_OK(context, context->input(\"row_remapping\", &row_remapping_t));\n const auto row_remapping = row_remapping_t->vec();\n OP_REQUIRES(context, row_remapping.size() == num_rows_,\n errors::InvalidArgument(strings::StrCat(\n \"Size of row_remapping is \", row_remapping.size(),\n \" instead of being equal to num_rows=\", num_rows_)));\n OP_REQUIRES_OK(context, RemapVectorToMap(row_remapping, &row_id_present,\n &old_row_to_new_row_map));\n\n // Calculates the min/max old row ID that we need to read, to save us from\n // reading some unnecessary slices of the old tensor.\n int64 min_old_row = -1;\n int64 max_old_row = -1;\n for (int i = 0; i < row_remapping.size(); ++i) {\n if (min_old_row < 0 ||\n (row_remapping(i) >= 0 && row_remapping(i) < min_old_row)) {\n min_old_row = row_remapping(i);\n }\n if (max_old_row < 0 ||\n (row_remapping(i) >= 0 && row_remapping(i) > max_old_row)) {\n max_old_row = row_remapping(i);\n }\n }\n\n // Processes the remapping for columns.\n std::unordered_map old_col_to_new_col_map;\n std::vector col_id_present;\n const Tensor* col_remapping_t;\n OP_REQUIRES_OK(context, context->input(\"col_remapping\", &col_remapping_t));\n const auto col_remapping = col_remapping_t->vec();\n // Note that we always \"remap rows\", even when the row vocabulary does\n // not change, because partitioning requires a mapping from partitioned\n // Variables to the full checkpoints we load.\n const bool remap_cols = col_remapping.size() > 0;\n if (remap_cols) {\n OP_REQUIRES(\n context, col_remapping.size() == num_cols_,\n errors::InvalidArgument(strings::StrCat(\n \"Provided col_remapping, but its size is \", col_remapping.size(),\n \" instead of being equal to num_cols=\", num_cols_)));\n OP_REQUIRES_OK(context, RemapVectorToMap(col_remapping, &col_id_present,\n &old_col_to_new_col_map));\n } else {\n col_id_present.clear();\n col_id_present.resize(num_cols_, true);\n }\n\n // Processes the checkpoint source and the provided Tensor name.\n const Tensor* ckpt_path_t;\n OP_REQUIRES_OK(context, context->input(\"ckpt_path\", &ckpt_path_t));\n OP_REQUIRES(\n context, ckpt_path_t->NumElements() == 1,\n errors::InvalidArgument(\"The `ckpt_path` tensor must have exactly one \"\n \"element, got tensor of shape \",\n ckpt_path_t->shape().DebugString()));\n const string& ckpt_path = ckpt_path_t->scalar()();\n const Tensor* old_tensor_name_t;\n OP_REQUIRES_OK(context,\n context->input(\"old_tensor_name\", &old_tensor_name_t));\n const string& old_tensor_name = old_tensor_name_t->scalar()();\n\n LOG(INFO) << \"Processing checkpoint : \" << ckpt_path;\n BundleReader reader(context->env(), ckpt_path);\n OP_REQUIRES_OK(context, reader.status());\n\n DataType tensor_type;\n TensorShape tensor_shape;\n OP_REQUIRES_OK(context, reader.LookupDtypeAndShape(\n old_tensor_name, &tensor_type, &tensor_shape));\n OP_REQUIRES(context, tensor_type == DT_FLOAT,\n errors::InvalidArgument(strings::StrCat(\n \"Tensor \", old_tensor_name, \" has invalid type \",\n DataTypeString(tensor_type), \" instead of expected type \",\n DataTypeString(DT_FLOAT))));\n // This op is limited to loading Tensors of rank 2 (matrices).\n OP_REQUIRES(\n context, tensor_shape.dims() == 2,\n errors::InvalidArgument(strings::StrCat(\n \"Tensor \", old_tensor_name, \" has shape \",\n tensor_shape.DebugString(), \" of invalid rank \",\n tensor_shape.dims(), \" instead of expected shape of rank 2.\")));\n\n if (!remap_cols) {\n // TODO(weiho): Consider relaxing this restriction to allow partial column\n // loading (even when no column remapping is specified) if there turns out\n // to be a use case for it.\n OP_REQUIRES(context, num_cols_ == tensor_shape.dim_size(1),\n errors::InvalidArgument(strings::StrCat(\n \"Tensor \", old_tensor_name, \" has shape \",\n tensor_shape.DebugString(),\n \", where the size of its 2nd dimension is \",\n tensor_shape.dim_size(1),\n \" instead of being equal to num_cols=\", num_cols_)));\n }\n\n // Uses TensorSlice to potentially load the old tensor in chunks in case\n // memory usage is a concern.\n std::vector tensor_slices;\n TensorSlice slice(tensor_shape.dims());\n if (min_old_row >= 0 && max_old_row >= 0) {\n int64 row_start = min_old_row;\n // TODO(weiho): Given the list of old row IDs of interest (the keys of\n // old_row_to_new_row_map), we could also try something smarter to\n // find some minimal set of covering ranges for the list of old row IDs\n // such that the size of each range is less than max_rows_in_memory_.\n while (row_start <= max_old_row) {\n const int64 slice_length =\n max_rows_in_memory_ <= 0\n // If max_rows_in_memory_ <= 0, we just load the entire chunk.\n ? max_old_row - row_start + 1\n : std::min(max_rows_in_memory_, max_old_row - row_start + 1);\n slice.set_start(0, row_start);\n slice.set_length(0, slice_length);\n tensor_slices.push_back(slice);\n row_start += slice_length;\n }\n }\n\n // Allocates the output matrix.\n Tensor* output_matrix_t = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(\"output_matrix\",\n TensorShape({num_rows_, num_cols_}),\n &output_matrix_t));\n auto output_matrix = output_matrix_t->matrix();\n\n // Iterates through tensor slices and copies over values from the old tensor\n // to the output matrix.\n int64 row_index = min_old_row;\n int64 rows_copied = 0;\n Tensor loaded_tensor_t;\n for (const TensorSlice& tensor_slice : tensor_slices) {\n LOG(INFO) << \"Loading slice \" << tensor_slice.DebugString();\n TensorShape slice_shape;\n OP_REQUIRES_OK(context,\n tensor_slice.SliceTensorShape(tensor_shape, &slice_shape));\n // Potentially re-allocates the tensor buffer since the last slice may\n // have fewer rows than the other slices.\n if (loaded_tensor_t.shape() != slice_shape) {\n loaded_tensor_t = Tensor(DT_FLOAT, slice_shape);\n }\n OP_REQUIRES_OK(context, reader.LookupSlice(old_tensor_name, tensor_slice,\n &loaded_tensor_t));\n\n // Iterates through the old loaded tensor slice row-by-row.\n for (int row = 0; row < loaded_tensor_t.dim_size(0); ++row, ++row_index) {\n if (row_index % 500000 == min_old_row) {\n LOG(INFO) << \"Processing old row \" << row_index;\n }\n\n // If the old row ID is not found in old_row_to_new_row_map, continue\n // to the next row; otherwise, copy it to the output matrix.\n const int64* new_row_ptr =\n gtl::FindOrNull(old_row_to_new_row_map, row_index);\n if (new_row_ptr == nullptr) {\n continue;\n }\n ++rows_copied;\n const int64 new_row = *new_row_ptr;\n\n // Copies over the row element-by-element, in case remapping is needed\n // along the column axis.\n const auto& loaded_tensor = loaded_tensor_t.matrix();\n for (int old_col = 0; old_col < loaded_tensor_t.dim_size(1);\n ++old_col) {\n int64 new_col = old_col;\n if (remap_cols) {\n const int64* new_col_ptr =\n gtl::FindOrNull(old_col_to_new_col_map, old_col);\n if (new_col_ptr == nullptr) {\n // Column remapping is specified, but this column is not found in\n // old_col_to_new_col_map, so we leave it uninitialized, to be\n // filled in with initializing_values later.\n continue;\n }\n new_col = *new_col_ptr;\n }\n\n OP_REQUIRES(context,\n new_row < num_rows_ && new_col < num_cols_ &&\n new_row >= 0 && new_col >= 0,\n errors::Internal(strings::StrCat(\n \"new_row=\", new_row, \" and new_col=\", new_col,\n \" should have been less than num_rows_=\", num_rows_,\n \" and num_cols_=\", num_cols_,\n \" and non-negative. This should never have happened \"\n \"if the code were correct. Please file a bug.\")));\n output_matrix(new_row, new_col) = loaded_tensor(row, old_col);\n }\n }\n }\n LOG(INFO) << \"Copied \" << rows_copied << \" rows from old matrix (with \"\n << tensor_shape.dim_size(0) << \" rows) to new matrix (with \"\n << num_rows_ << \" rows).\";\n\n // At this point, there are potentially whole rows/columns uninitialized\n // (corresponding to the indices where row_id_present/col_id_present are\n // false). We fill this in cell-by-cell using row_id_present and\n // col_id_present while dequeuing from the initializing_values vector.\n const Tensor* initializing_values_t;\n OP_REQUIRES_OK(\n context, context->input(\"initializing_values\", &initializing_values_t));\n const auto initializing_values = initializing_values_t->flat();\n int64 initializing_values_index = 0;\n for (int i = 0; i < num_rows_; ++i) {\n for (int j = 0; j < num_cols_; ++j) {\n if (row_id_present[i] && col_id_present[j]) continue;\n OP_REQUIRES(\n context, initializing_values_index < initializing_values.size(),\n errors::InvalidArgument(\n \"initializing_values contained \", initializing_values.size(),\n \" elements, but more missing values remain.\"));\n output_matrix(i, j) = initializing_values(initializing_values_index);\n ++initializing_values_index;\n }\n }\n\n // Checks that we used all the given initializing values.\n OP_REQUIRES(\n context, initializing_values_index == initializing_values.size(),\n errors::InvalidArgument(\n \"initializing_values contained \", initializing_values.size(),\n \" elements, but only \", initializing_values_index,\n \" elements were used to fill in missing values.\"));\n }", "project": "tensorflow", "hash": 262389193985354269110422891412562548793, "size": 231, "commit_id": "77dd114513d7796e1e2b8aece214a380af26fbf4", "message": "Fix a check fail\n\nPiperOrigin-RevId: 372011072\nChange-Id: I1062cfaed0aa16884e9a16312483794d188db76f", "target": 0, "dataset": "other", "idx": 259623} {"func": "static int selectExpander(Walker *pWalker, Select *p){\n Parse *pParse = pWalker->pParse;\n int i, j, k;\n SrcList *pTabList;\n ExprList *pEList;\n struct SrcList_item *pFrom;\n sqlite3 *db = pParse->db;\n Expr *pE, *pRight, *pExpr;\n u16 selFlags = p->selFlags;\n u32 elistFlags = 0;\n\n p->selFlags |= SF_Expanded;\n if( db->mallocFailed ){\n return WRC_Abort;\n }\n assert( p->pSrc!=0 );\n if( (selFlags & SF_Expanded)!=0 ){\n return WRC_Prune;\n }\n if( pWalker->eCode ){\n /* Renumber selId because it has been copied from a view */\n p->selId = ++pParse->nSelect;\n }\n pTabList = p->pSrc;\n pEList = p->pEList;\n sqlite3WithPush(pParse, p->pWith, 0);\n\n /* Make sure cursor numbers have been assigned to all entries in\n ** the FROM clause of the SELECT statement.\n */\n sqlite3SrcListAssignCursors(pParse, pTabList);\n\n /* Look up every table named in the FROM clause of the select. If\n ** an entry of the FROM clause is a subquery instead of a table or view,\n ** then create a transient table structure to describe the subquery.\n */\n for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){\n Table *pTab;\n assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );\n if( pFrom->fg.isRecursive ) continue;\n assert( pFrom->pTab==0 );\n#ifndef SQLITE_OMIT_CTE\n if( withExpand(pWalker, pFrom) ) return WRC_Abort;\n if( pFrom->pTab ) {} else\n#endif\n if( pFrom->zName==0 ){\n#ifndef SQLITE_OMIT_SUBQUERY\n Select *pSel = pFrom->pSelect;\n /* A sub-query in the FROM clause of a SELECT */\n assert( pSel!=0 );\n assert( pFrom->pTab==0 );\n if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;\n if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;\n#endif\n }else{\n /* An ordinary table or view name in the FROM clause */\n assert( pFrom->pTab==0 );\n pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);\n if( pTab==0 ) return WRC_Abort;\n if( pTab->nTabRef>=0xffff ){\n sqlite3ErrorMsg(pParse, \"too many references to \\\"%s\\\": max 65535\",\n pTab->zName);\n pFrom->pTab = 0;\n return WRC_Abort;\n }\n pTab->nTabRef++;\n if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){\n return WRC_Abort;\n }\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)\n if( IsVirtual(pTab) || pTab->pSelect ){\n i16 nCol;\n u8 eCodeOrig = pWalker->eCode;\n if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;\n assert( pFrom->pSelect==0 );\n if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){\n sqlite3ErrorMsg(pParse, \"access to view \\\"%s\\\" prohibited\",\n pTab->zName);\n }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n if( IsVirtual(pTab)\n && pFrom->fg.fromDDL\n && ALWAYS(pTab->pVTable!=0)\n && pTab->pVTable->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)\n ){\n sqlite3ErrorMsg(pParse, \"unsafe use of virtual table \\\"%s\\\"\",\n pTab->zName);\n }\n#endif\n pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);\n nCol = pTab->nCol;\n pTab->nCol = -1;\n pWalker->eCode = 1; /* Turn on Select.selId renumbering */\n sqlite3WalkSelect(pWalker, pFrom->pSelect);\n pWalker->eCode = eCodeOrig;\n pTab->nCol = nCol;\n }\n#endif\n }\n\n /* Locate the index named by the INDEXED BY clause, if any. */\n if( sqlite3IndexedByLookup(pParse, pFrom) ){\n return WRC_Abort;\n }\n }\n\n /* Process NATURAL keywords, and ON and USING clauses of joins.\n */\n if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){\n return WRC_Abort;\n }\n\n /* For every \"*\" that occurs in the column list, insert the names of\n ** all columns in all tables. And for every TABLE.* insert the names\n ** of all columns in TABLE. The parser inserted a special expression\n ** with the TK_ASTERISK operator for each \"*\" that it found in the column\n ** list. The following code just has to locate the TK_ASTERISK\n ** expressions and expand each one to the list of all columns in\n ** all tables.\n **\n ** The first loop just checks to see if there are any \"*\" operators\n ** that need expanding.\n */\n for(k=0; knExpr; k++){\n pE = pEList->a[k].pExpr;\n if( pE->op==TK_ASTERISK ) break;\n assert( pE->op!=TK_DOT || pE->pRight!=0 );\n assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );\n if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;\n elistFlags |= pE->flags;\n }\n if( knExpr ){\n /*\n ** If we get here it means the result set contains one or more \"*\"\n ** operators that need to be expanded. Loop through each expression\n ** in the result set and expand them one by one.\n */\n struct ExprList_item *a = pEList->a;\n ExprList *pNew = 0;\n int flags = pParse->db->flags;\n int longNames = (flags & SQLITE_FullColNames)!=0\n && (flags & SQLITE_ShortColNames)==0;\n\n for(k=0; knExpr; k++){\n pE = a[k].pExpr;\n elistFlags |= pE->flags;\n pRight = pE->pRight;\n assert( pE->op!=TK_DOT || pRight!=0 );\n if( pE->op!=TK_ASTERISK\n && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)\n ){\n /* This particular expression does not need to be expanded.\n */\n pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);\n if( pNew ){\n pNew->a[pNew->nExpr-1].zEName = a[k].zEName;\n pNew->a[pNew->nExpr-1].eEName = a[k].eEName;\n a[k].zEName = 0;\n }\n a[k].pExpr = 0;\n }else{\n /* This expression is a \"*\" or a \"TABLE.*\" and needs to be\n ** expanded. */\n int tableSeen = 0; /* Set to 1 when TABLE matches */\n char *zTName = 0; /* text of name of TABLE */\n if( pE->op==TK_DOT ){\n assert( pE->pLeft!=0 );\n assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );\n zTName = pE->pLeft->u.zToken;\n }\n for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){\n Table *pTab = pFrom->pTab;\n Select *pSub = pFrom->pSelect;\n char *zTabName = pFrom->zAlias;\n const char *zSchemaName = 0;\n int iDb;\n if( zTabName==0 ){\n zTabName = pTab->zName;\n }\n if( db->mallocFailed ) break;\n if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){\n pSub = 0;\n if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){\n continue;\n }\n iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : \"*\";\n }\n for(j=0; jnCol; j++){\n char *zName = pTab->aCol[j].zName;\n char *zColname; /* The computed column name */\n char *zToFree; /* Malloced string that needs to be freed */\n Token sColname; /* Computed column name as a token */\n\n assert( zName );\n if( zTName && pSub\n && sqlite3MatchEName(&pSub->pEList->a[j], 0, zTName, 0)==0\n ){\n continue;\n }\n\n /* If a column is marked as 'hidden', omit it from the expanded\n ** result-set list unless the SELECT has the SF_IncludeHidden\n ** bit set.\n */\n if( (p->selFlags & SF_IncludeHidden)==0\n && IsHiddenColumn(&pTab->aCol[j]) \n ){\n continue;\n }\n tableSeen = 1;\n\n if( i>0 && zTName==0 ){\n if( (pFrom->fg.jointype & JT_NATURAL)!=0\n && tableAndColumnIndex(pTabList, i, zName, 0, 0, 1)\n ){\n /* In a NATURAL join, omit the join columns from the \n ** table to the right of the join */\n continue;\n }\n if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){\n /* In a join with a USING clause, omit columns in the\n ** using clause from the table on the right. */\n continue;\n }\n }\n pRight = sqlite3Expr(db, TK_ID, zName);\n zColname = zName;\n zToFree = 0;\n if( longNames || pTabList->nSrc>1 ){\n Expr *pLeft;\n pLeft = sqlite3Expr(db, TK_ID, zTabName);\n pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);\n if( zSchemaName ){\n pLeft = sqlite3Expr(db, TK_ID, zSchemaName);\n pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);\n }\n if( longNames ){\n zColname = sqlite3MPrintf(db, \"%s.%s\", zTabName, zName);\n zToFree = zColname;\n }\n }else{\n pExpr = pRight;\n }\n pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);\n sqlite3TokenInit(&sColname, zColname);\n sqlite3ExprListSetName(pParse, pNew, &sColname, 0);\n if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){\n struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];\n sqlite3DbFree(db, pX->zEName);\n if( pSub ){\n pX->zEName = sqlite3DbStrDup(db, pSub->pEList->a[j].zEName);\n testcase( pX->zEName==0 );\n }else{\n pX->zEName = sqlite3MPrintf(db, \"%s.%s.%s\",\n zSchemaName, zTabName, zColname);\n testcase( pX->zEName==0 );\n }\n pX->eEName = ENAME_TAB;\n }\n sqlite3DbFree(db, zToFree);\n }\n }\n if( !tableSeen ){\n if( zTName ){\n sqlite3ErrorMsg(pParse, \"no such table: %s\", zTName);\n }else{\n sqlite3ErrorMsg(pParse, \"no tables specified\");\n }\n }\n }\n }\n sqlite3ExprListDelete(db, pEList);\n p->pEList = pNew;\n }\n if( p->pEList ){\n if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n sqlite3ErrorMsg(pParse, \"too many columns in result set\");\n return WRC_Abort;\n }\n if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){\n p->selFlags |= SF_ComplexResult;\n }\n }\n return WRC_Continue;\n}", "project": "sqlite", "hash": 173018535421974116346089355628231803850, "size": 286, "commit_id": "0990c415f65d2556a5e4122cbe5727d500411aeb", "message": "Fix a problem with ALTER TABLE for views that have a nested FROM clause.\nTicket [f50af3e8a565776b].\n\nFossilOrigin-Name: c431b3fd8fd0f6a6974bba3e9366b0430ec003d570e7ce70ceefbcff5fe4b6fa", "target": 1, "dataset": "other", "idx": 197522} {"func": "static int selectExpander(Walker *pWalker, Select *p){\n Parse *pParse = pWalker->pParse;\n int i, j, k;\n SrcList *pTabList;\n ExprList *pEList;\n struct SrcList_item *pFrom;\n sqlite3 *db = pParse->db;\n Expr *pE, *pRight, *pExpr;\n u16 selFlags = p->selFlags;\n u32 elistFlags = 0;\n\n p->selFlags |= SF_Expanded;\n if( db->mallocFailed ){\n return WRC_Abort;\n }\n assert( p->pSrc!=0 );\n if( (selFlags & SF_Expanded)!=0 ){\n return WRC_Prune;\n }\n if( pWalker->eCode ){\n /* Renumber selId because it has been copied from a view */\n p->selId = ++pParse->nSelect;\n }\n pTabList = p->pSrc;\n pEList = p->pEList;\n sqlite3WithPush(pParse, p->pWith, 0);\n\n /* Make sure cursor numbers have been assigned to all entries in\n ** the FROM clause of the SELECT statement.\n */\n sqlite3SrcListAssignCursors(pParse, pTabList);\n\n /* Look up every table named in the FROM clause of the select. If\n ** an entry of the FROM clause is a subquery instead of a table or view,\n ** then create a transient table structure to describe the subquery.\n */\n for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){\n Table *pTab;\n assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );\n if( pFrom->fg.isRecursive ) continue;\n assert( pFrom->pTab==0 );\n#ifndef SQLITE_OMIT_CTE\n if( withExpand(pWalker, pFrom) ) return WRC_Abort;\n if( pFrom->pTab ) {} else\n#endif\n if( pFrom->zName==0 ){\n#ifndef SQLITE_OMIT_SUBQUERY\n Select *pSel = pFrom->pSelect;\n /* A sub-query in the FROM clause of a SELECT */\n assert( pSel!=0 );\n assert( pFrom->pTab==0 );\n if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;\n if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;\n#endif\n }else{\n /* An ordinary table or view name in the FROM clause */\n assert( pFrom->pTab==0 );\n pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);\n if( pTab==0 ) return WRC_Abort;\n if( pTab->nTabRef>=0xffff ){\n sqlite3ErrorMsg(pParse, \"too many references to \\\"%s\\\": max 65535\",\n pTab->zName);\n pFrom->pTab = 0;\n return WRC_Abort;\n }\n pTab->nTabRef++;\n if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){\n return WRC_Abort;\n }\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)\n if( IsVirtual(pTab) || pTab->pSelect ){\n i16 nCol;\n u8 eCodeOrig = pWalker->eCode;\n if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;\n assert( pFrom->pSelect==0 );\n if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){\n sqlite3ErrorMsg(pParse, \"access to view \\\"%s\\\" prohibited\",\n pTab->zName);\n }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n if( IsVirtual(pTab)\n && pFrom->fg.fromDDL\n && ALWAYS(pTab->pVTable!=0)\n && pTab->pVTable->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)\n ){\n sqlite3ErrorMsg(pParse, \"unsafe use of virtual table \\\"%s\\\"\",\n pTab->zName);\n }\n#endif\n pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);\n nCol = pTab->nCol;\n pTab->nCol = -1;\n pWalker->eCode = 1; /* Turn on Select.selId renumbering */\n sqlite3WalkSelect(pWalker, pFrom->pSelect);\n pWalker->eCode = eCodeOrig;\n pTab->nCol = nCol;\n }\n#endif\n }\n\n /* Locate the index named by the INDEXED BY clause, if any. */\n if( sqlite3IndexedByLookup(pParse, pFrom) ){\n return WRC_Abort;\n }\n }\n\n /* Process NATURAL keywords, and ON and USING clauses of joins.\n */\n if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){\n return WRC_Abort;\n }\n\n /* For every \"*\" that occurs in the column list, insert the names of\n ** all columns in all tables. And for every TABLE.* insert the names\n ** of all columns in TABLE. The parser inserted a special expression\n ** with the TK_ASTERISK operator for each \"*\" that it found in the column\n ** list. The following code just has to locate the TK_ASTERISK\n ** expressions and expand each one to the list of all columns in\n ** all tables.\n **\n ** The first loop just checks to see if there are any \"*\" operators\n ** that need expanding.\n */\n for(k=0; knExpr; k++){\n pE = pEList->a[k].pExpr;\n if( pE->op==TK_ASTERISK ) break;\n assert( pE->op!=TK_DOT || pE->pRight!=0 );\n assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );\n if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;\n elistFlags |= pE->flags;\n }\n if( knExpr ){\n /*\n ** If we get here it means the result set contains one or more \"*\"\n ** operators that need to be expanded. Loop through each expression\n ** in the result set and expand them one by one.\n */\n struct ExprList_item *a = pEList->a;\n ExprList *pNew = 0;\n int flags = pParse->db->flags;\n int longNames = (flags & SQLITE_FullColNames)!=0\n && (flags & SQLITE_ShortColNames)==0;\n\n for(k=0; knExpr; k++){\n pE = a[k].pExpr;\n elistFlags |= pE->flags;\n pRight = pE->pRight;\n assert( pE->op!=TK_DOT || pRight!=0 );\n if( pE->op!=TK_ASTERISK\n && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)\n ){\n /* This particular expression does not need to be expanded.\n */\n pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);\n if( pNew ){\n pNew->a[pNew->nExpr-1].zEName = a[k].zEName;\n pNew->a[pNew->nExpr-1].eEName = a[k].eEName;\n a[k].zEName = 0;\n }\n a[k].pExpr = 0;\n }else{\n /* This expression is a \"*\" or a \"TABLE.*\" and needs to be\n ** expanded. */\n int tableSeen = 0; /* Set to 1 when TABLE matches */\n char *zTName = 0; /* text of name of TABLE */\n if( pE->op==TK_DOT ){\n assert( pE->pLeft!=0 );\n assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );\n zTName = pE->pLeft->u.zToken;\n }\n for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){\n Table *pTab = pFrom->pTab;\n Select *pSub = pFrom->pSelect;\n char *zTabName = pFrom->zAlias;\n const char *zSchemaName = 0;\n int iDb;\n if( zTabName==0 ){\n zTabName = pTab->zName;\n }\n if( db->mallocFailed ) break;\n if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){\n pSub = 0;\n if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){\n continue;\n }\n iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : \"*\";\n }\n for(j=0; jnCol; j++){\n char *zName = pTab->aCol[j].zName;\n char *zColname; /* The computed column name */\n char *zToFree; /* Malloced string that needs to be freed */\n Token sColname; /* Computed column name as a token */\n\n assert( zName );\n if( zTName && pSub\n && sqlite3MatchEName(&pSub->pEList->a[j], 0, zTName, 0)==0\n ){\n continue;\n }\n\n /* If a column is marked as 'hidden', omit it from the expanded\n ** result-set list unless the SELECT has the SF_IncludeHidden\n ** bit set.\n */\n if( (p->selFlags & SF_IncludeHidden)==0\n && IsHiddenColumn(&pTab->aCol[j]) \n ){\n continue;\n }\n tableSeen = 1;\n\n if( i>0 && zTName==0 ){\n if( (pFrom->fg.jointype & JT_NATURAL)!=0\n && tableAndColumnIndex(pTabList, i, zName, 0, 0, 1)\n ){\n /* In a NATURAL join, omit the join columns from the \n ** table to the right of the join */\n continue;\n }\n if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){\n /* In a join with a USING clause, omit columns in the\n ** using clause from the table on the right. */\n continue;\n }\n }\n pRight = sqlite3Expr(db, TK_ID, zName);\n zColname = zName;\n zToFree = 0;\n if( longNames || pTabList->nSrc>1 ){\n Expr *pLeft;\n pLeft = sqlite3Expr(db, TK_ID, zTabName);\n pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);\n if( zSchemaName ){\n pLeft = sqlite3Expr(db, TK_ID, zSchemaName);\n pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);\n }\n if( longNames ){\n zColname = sqlite3MPrintf(db, \"%s.%s\", zTabName, zName);\n zToFree = zColname;\n }\n }else{\n pExpr = pRight;\n }\n pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);\n sqlite3TokenInit(&sColname, zColname);\n sqlite3ExprListSetName(pParse, pNew, &sColname, 0);\n if( pNew && (p->selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){\n struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];\n sqlite3DbFree(db, pX->zEName);\n if( pSub ){\n pX->zEName = sqlite3DbStrDup(db, pSub->pEList->a[j].zEName);\n testcase( pX->zEName==0 );\n }else{\n pX->zEName = sqlite3MPrintf(db, \"%s.%s.%s\",\n zSchemaName, zTabName, zColname);\n testcase( pX->zEName==0 );\n }\n pX->eEName = ENAME_TAB;\n }\n sqlite3DbFree(db, zToFree);\n }\n }\n if( !tableSeen ){\n if( zTName ){\n sqlite3ErrorMsg(pParse, \"no such table: %s\", zTName);\n }else{\n sqlite3ErrorMsg(pParse, \"no tables specified\");\n }\n }\n }\n }\n sqlite3ExprListDelete(db, pEList);\n p->pEList = pNew;\n }\n if( p->pEList ){\n if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n sqlite3ErrorMsg(pParse, \"too many columns in result set\");\n return WRC_Abort;\n }\n if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){\n p->selFlags |= SF_ComplexResult;\n }\n }\n return WRC_Continue;\n}", "project": "sqlite", "hash": 122260449153361052319909319985506822289, "size": 286, "commit_id": "0990c415f65d2556a5e4122cbe5727d500411aeb", "message": "Fix a problem with ALTER TABLE for views that have a nested FROM clause.\nTicket [f50af3e8a565776b].\n\nFossilOrigin-Name: c431b3fd8fd0f6a6974bba3e9366b0430ec003d570e7ce70ceefbcff5fe4b6fa", "target": 0, "dataset": "other", "idx": 259833} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n const float input_min_float = ctx->input(1).flat()(0);\n const float input_max_float = ctx->input(2).flat()(0);\n Tensor* output_min = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &output_min));\n Tensor* output_max = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_max));\n\n qint32 used_min_quantized;\n qint32 used_max_quantized;\n CalculateUsedRange(input, &used_min_quantized, &used_max_quantized);\n\n // We want to make sure that the minimum is no larger than zero, so that the\n // convolution operation can run efficiently.\n const float used_min_float = std::min(\n 0.0f,\n QuantizedToFloat(used_min_quantized, input_min_float, input_max_float));\n const float used_max_float =\n QuantizedToFloat(used_max_quantized, input_min_float, input_max_float);\n\n output_min->flat().setConstant(used_min_float);\n output_max->flat().setConstant(used_max_float);\n }", "project": "tensorflow", "hash": 11062965309142515619891321633938443899, "size": 24, "commit_id": "ef0c008ee84bad91ec6725ddc42091e19a30cf0e", "message": "Fix out of bound read in requantization_range_op.cc\n\nPiperOrigin-RevId: 372129031\nChange-Id: Ie684ab98a3840c5186ead3eafffc0e0ed0e8030d", "target": 1, "dataset": "other", "idx": 197575} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n OP_REQUIRES(ctx, ctx->input(1).NumElements() > 0,\n errors::InvalidArgument(\"Input min must not be empty.\"));\n OP_REQUIRES(ctx, ctx->input(2).NumElements() > 0,\n errors::InvalidArgument(\"Input max must not be empty.\"));\n const float input_min_float = ctx->input(1).flat()(0);\n const float input_max_float = ctx->input(2).flat()(0);\n Tensor* output_min = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &output_min));\n Tensor* output_max = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_max));\n\n qint32 used_min_quantized;\n qint32 used_max_quantized;\n CalculateUsedRange(input, &used_min_quantized, &used_max_quantized);\n\n // We want to make sure that the minimum is no larger than zero, so that the\n // convolution operation can run efficiently.\n const float used_min_float = std::min(\n 0.0f,\n QuantizedToFloat(used_min_quantized, input_min_float, input_max_float));\n const float used_max_float =\n QuantizedToFloat(used_max_quantized, input_min_float, input_max_float);\n\n output_min->flat().setConstant(used_min_float);\n output_max->flat().setConstant(used_max_float);\n }", "project": "tensorflow", "hash": 249104404907249387447027842196733553165, "size": 28, "commit_id": "ef0c008ee84bad91ec6725ddc42091e19a30cf0e", "message": "Fix out of bound read in requantization_range_op.cc\n\nPiperOrigin-RevId: 372129031\nChange-Id: Ie684ab98a3840c5186ead3eafffc0e0ed0e8030d", "target": 0, "dataset": "other", "idx": 261456} {"func": "int RemoveUnknownSections(void)\r\n{\r\n int a;\r\n int Modified = FALSE;\r\n for (a=0;agr_gid;\n }\n gid_t gid = tty_gid == -1 ? __getgid () : tty_gid;\n\n /* Make sure the group of the device is that special group. */\n if (st.st_gid != gid)\n {\n if (__chown (buf, uid, gid) < 0)\n\tgoto helper;\n }\n\n /* Make sure the permission mode is set to readable and writable by\n the owner, and writable by the group. */\n if ((st.st_mode & ACCESSPERMS) != (S_IRUSR|S_IWUSR|S_IWGRP))\n {\n if (__chmod (buf, S_IRUSR|S_IWUSR|S_IWGRP) < 0)\n\tgoto helper;\n }\n\n retval = 0;\n goto cleanup;\n\n /* We have to use the helper program. */\n helper:;\n\n pid_t pid = __fork ();\n if (pid == -1)\n goto cleanup;\n else if (pid == 0)\n {\n /* Disable core dumps. */\n struct rlimit rl = { 0, 0 };\n __setrlimit (RLIMIT_CORE, &rl);\n\n /* We pass the master pseudo terminal as file descriptor PTY_FILENO. */\n if (fd != PTY_FILENO)\n\tif (__dup2 (fd, PTY_FILENO) < 0)\n\t _exit (FAIL_EBADF);\n\n#ifdef CLOSE_ALL_FDS\n CLOSE_ALL_FDS ();\n#endif\n\n execle (_PATH_PT_CHOWN, basename (_PATH_PT_CHOWN), NULL, NULL);\n _exit (FAIL_EXEC);\n }\n else\n {\n int w;\n\n if (__waitpid (pid, &w, 0) == -1)\n\tgoto cleanup;\n if (!WIFEXITED (w))\n\t__set_errno (ENOEXEC);\n else\n\tswitch (WEXITSTATUS (w))\n\t {\n\t case 0:\n\t retval = 0;\n\t break;\n\t case FAIL_EBADF:\n\t __set_errno (EBADF);\n\t break;\n\t case FAIL_EINVAL:\n\t __set_errno (EINVAL);\n\t break;\n\t case FAIL_EACCES:\n\t __set_errno (EACCES);\n\t break;\n\t case FAIL_EXEC:\n\t __set_errno (ENOEXEC);\n\t break;\n\t case FAIL_ENOMEM:\n\t __set_errno (ENOMEM);\n\t break;\n\n\t default:\n\t assert(! \"getpt: internal error: invalid exit code from pt_chown\");\n\t }\n }\n\n cleanup:\n if (buf != _buf)\n free (buf);\n\n return retval;\n}", "project": "glibc", "hash": 55488823009452919756852590226678328329, "size": 141, "commit_id": "e4608715e6e1dd2adc91982fd151d5ba4f761d69", "message": "CVE-2013-2207, BZ #15755: Disable pt_chown.\n\nThe helper binary pt_chown tricked into granting access to another\nuser's pseudo-terminal.\n\nPre-conditions for the attack:\n\n * Attacker with local user account\n * Kernel with FUSE support\n * \"user_allow_other\" in /etc/fuse.conf\n * Victim with allocated slave in /dev/pts\n\nUsing the setuid installed pt_chown and a weak check on whether a file\ndescriptor is a tty, an attacker could fake a pty check using FUSE and\ntrick pt_chown to grant ownership of a pty descriptor that the current\nuser does not own. It cannot access /dev/pts/ptmx however.\n\nIn most modern distributions pt_chown is not needed because devpts\nis enabled by default. The fix for this CVE is to disable building\nand using pt_chown by default. We still provide a configure option\nto enable hte use of pt_chown but distributions do so at their own\nrisk.", "target": 1, "dataset": "other", "idx": 197630} {"func": "grantpt (int fd)\n{\n int retval = -1;\n#ifdef PATH_MAX\n char _buf[PATH_MAX];\n#else\n char _buf[512];\n#endif\n char *buf = _buf;\n struct stat64 st;\n\n if (__builtin_expect (pts_name (fd, &buf, sizeof (_buf), &st), 0))\n {\n int save_errno = errno;\n\n /* Check, if the file descriptor is valid. pts_name returns the\n\t wrong errno number, so we cannot use that. */\n if (__libc_fcntl (fd, F_GETFD) == -1 && errno == EBADF)\n\treturn -1;\n\n /* If the filedescriptor is no TTY, grantpt has to set errno\n\t to EINVAL. */\n if (save_errno == ENOTTY)\n\t __set_errno (EINVAL);\n else\n\t __set_errno (save_errno);\n\n return -1;\n }\n\n /* Make sure that we own the device. */\n uid_t uid = __getuid ();\n if (st.st_uid != uid)\n {\n if (__chown (buf, uid, st.st_gid) < 0)\n\tgoto helper;\n }\n\n static int tty_gid = -1;\n if (__builtin_expect (tty_gid == -1, 0))\n {\n char *grtmpbuf;\n struct group grbuf;\n size_t grbuflen = __sysconf (_SC_GETGR_R_SIZE_MAX);\n struct group *p;\n\n /* Get the group ID of the special `tty' group. */\n if (grbuflen == (size_t) -1L)\n\t/* `sysconf' does not support _SC_GETGR_R_SIZE_MAX.\n\t Try a moderate value. */\n\tgrbuflen = 1024;\n grtmpbuf = (char *) __alloca (grbuflen);\n __getgrnam_r (TTY_GROUP, &grbuf, grtmpbuf, grbuflen, &p);\n if (p != NULL)\n\ttty_gid = p->gr_gid;\n }\n gid_t gid = tty_gid == -1 ? __getgid () : tty_gid;\n\n /* Make sure the group of the device is that special group. */\n if (st.st_gid != gid)\n {\n if (__chown (buf, uid, gid) < 0)\n\tgoto helper;\n }\n\n /* Make sure the permission mode is set to readable and writable by\n the owner, and writable by the group. */\n if ((st.st_mode & ACCESSPERMS) != (S_IRUSR|S_IWUSR|S_IWGRP))\n {\n if (__chmod (buf, S_IRUSR|S_IWUSR|S_IWGRP) < 0)\n\tgoto helper;\n }\n\n retval = 0;\n goto cleanup;\n\n /* We have to use the helper program if it is available. */\n helper:;\n\n#ifdef HAVE_PT_CHOWN\n pid_t pid = __fork ();\n if (pid == -1)\n goto cleanup;\n else if (pid == 0)\n {\n /* Disable core dumps. */\n struct rlimit rl = { 0, 0 };\n __setrlimit (RLIMIT_CORE, &rl);\n\n /* We pass the master pseudo terminal as file descriptor PTY_FILENO. */\n if (fd != PTY_FILENO)\n\tif (__dup2 (fd, PTY_FILENO) < 0)\n\t _exit (FAIL_EBADF);\n\n# ifdef CLOSE_ALL_FDS\n CLOSE_ALL_FDS ();\n# endif\n\n execle (_PATH_PT_CHOWN, basename (_PATH_PT_CHOWN), NULL, NULL);\n _exit (FAIL_EXEC);\n }\n else\n {\n int w;\n\n if (__waitpid (pid, &w, 0) == -1)\n\tgoto cleanup;\n if (!WIFEXITED (w))\n\t__set_errno (ENOEXEC);\n else\n\tswitch (WEXITSTATUS (w))\n\t {\n\t case 0:\n\t retval = 0;\n\t break;\n\t case FAIL_EBADF:\n\t __set_errno (EBADF);\n\t break;\n\t case FAIL_EINVAL:\n\t __set_errno (EINVAL);\n\t break;\n\t case FAIL_EACCES:\n\t __set_errno (EACCES);\n\t break;\n\t case FAIL_EXEC:\n\t __set_errno (ENOEXEC);\n\t break;\n\t case FAIL_ENOMEM:\n\t __set_errno (ENOMEM);\n\t break;\n\n\t default:\n\t assert(! \"getpt: internal error: invalid exit code from pt_chown\");\n\t }\n }\n#endif\n\n cleanup:\n if (buf != _buf)\n free (buf);\n\n return retval;\n}", "project": "glibc", "hash": 24069894465064036243353813490499424946, "size": 143, "commit_id": "e4608715e6e1dd2adc91982fd151d5ba4f761d69", "message": "CVE-2013-2207, BZ #15755: Disable pt_chown.\n\nThe helper binary pt_chown tricked into granting access to another\nuser's pseudo-terminal.\n\nPre-conditions for the attack:\n\n * Attacker with local user account\n * Kernel with FUSE support\n * \"user_allow_other\" in /etc/fuse.conf\n * Victim with allocated slave in /dev/pts\n\nUsing the setuid installed pt_chown and a weak check on whether a file\ndescriptor is a tty, an attacker could fake a pty check using FUSE and\ntrick pt_chown to grant ownership of a pty descriptor that the current\nuser does not own. It cannot access /dev/pts/ptmx however.\n\nIn most modern distributions pt_chown is not needed because devpts\nis enabled by default. The fix for this CVE is to disable building\nand using pt_chown by default. We still provide a configure option\nto enable hte use of pt_chown but distributions do so at their own\nrisk.", "target": 0, "dataset": "other", "idx": 262137} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& shape_t = ctx->input(0);\n const Tensor& alpha_t = ctx->input(1);\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(shape_t.shape()) &&\n (shape_t.dtype() == DataType::DT_INT32 ||\n shape_t.dtype() == DataType::DT_INT64),\n errors::InvalidArgument(\n \"shape must be a vector of {int32,int64}, got shape: \",\n shape_t.DebugString()));\n TensorShape samples_shape;\n if (shape_t.dtype() == DataType::DT_INT32) {\n auto vec = shape_t.flat();\n OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(vec.data(), vec.size(),\n &samples_shape));\n } else if (shape_t.dtype() == DataType::DT_INT64) {\n auto vec = shape_t.flat();\n OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(vec.data(), vec.size(),\n &samples_shape));\n }\n const int64 samples_per_alpha = samples_shape.num_elements();\n\n samples_shape.AppendShape(alpha_t.shape());\n // Allocate output samples.\n Tensor* samples_t = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, samples_shape, &samples_t));\n\n if (samples_shape.num_elements() == 0) return;\n\n using random::PhiloxRandom;\n\n typedef random::NormalDistribution Normal;\n typedef random::UniformDistribution Uniform;\n#define UNIFORM(X) \\\n if (uniform_remaining == 0) { \\\n uniform_remaining = Uniform::kResultElementCount; \\\n uniform_result = uniform(&gen); \\\n } \\\n uniform_remaining--; \\\n double X = uniform_result[uniform_remaining]\n\n // Each attempt is 95+% successful, and requires 1-2 normal + 1 uniform\n static constexpr int kReservedSamplesPerOutput = 256;\n\n const auto alpha_flat = alpha_t.flat().data();\n const int64 num_alphas = alpha_t.NumElements();\n OP_REQUIRES(ctx, num_alphas > 0,\n errors::InvalidArgument(\n \"Input alpha should have non-zero element count, got: \",\n num_alphas));\n auto samples_flat = samples_t->flat().data();\n PhiloxRandom rng = generator_.ReserveRandomOutputs(\n samples_per_alpha * num_alphas, kReservedSamplesPerOutput);\n\n // We partition work first across alphas then across samples-per-alpha to\n // avoid a couple flops which can be done on a per-alpha basis.\n\n auto DoWork = [samples_per_alpha, num_alphas, &rng, samples_flat,\n alpha_flat](int start_output, int limit_output) {\n using Eigen::numext::exp;\n using Eigen::numext::log;\n using Eigen::numext::log1p;\n using Eigen::numext::pow;\n\n // Capturing \"rng\" by-value would only make a copy for the _shared_\n // lambda. Since we want to let each worker have its own copy, we pass\n // \"rng\" by reference and explicitly do a copy assignment.\n\n Normal normal;\n Uniform uniform;\n typename Normal::ResultType norm_result;\n typename Uniform::ResultType uniform_result;\n for (int64 output_idx = start_output; output_idx < limit_output;\n /* output_idx incremented within inner loop below */) {\n int64 alpha_idx = output_idx / samples_per_alpha;\n\n // Instead of +alpha_idx for each sample, we offset the pointer once.\n T* const samples_alpha_offset = samples_flat + alpha_idx;\n\n // Several calculations can be done on a per-alpha basis.\n const double alpha = static_cast(alpha_flat[alpha_idx]);\n\n DISABLE_FLOAT_EQUALITY_WARNING\n if (alpha == static_cast(1.0)) {\n ENABLE_FLOAT_EQUALITY_WARNING\n // Sample from an exponential distribution.\n for (int64 sample_idx = output_idx % samples_per_alpha;\n sample_idx < samples_per_alpha && output_idx < limit_output;\n sample_idx++, output_idx++) {\n // As we want data stable regardless of sharding\n // (including eventually on GPU), we skip on a per-sample basis.\n PhiloxRandom gen = rng;\n gen.Skip(kReservedSamplesPerOutput * output_idx);\n int16 uniform_remaining = 0;\n UNIFORM(u);\n const double res = -log1p(-u);\n samples_alpha_offset[sample_idx * num_alphas] = static_cast(res);\n } // for (sample_idx)\n } else { // if alpha != 1.0\n // Transformation-rejection from pairs of uniform and normal random\n // variables. http://dl.acm.org/citation.cfm?id=358414\n //\n // The algorithm has an acceptance rate of ~95% for small alpha (~1),\n // and higher accept rates for higher alpha, so runtime is\n // O(NumAlphas * NumSamples * k) with k ~ 1 / 0.95.\n //\n // For alpha<1, we add one to d=alpha-1/3, and multiply the final\n // result by uniform()^(1/alpha)\n const bool alpha_less_than_one = alpha < 1;\n const double d = alpha + (alpha_less_than_one ? 2.0 / 3 : -1.0 / 3);\n const double c = 1.0 / 3 / sqrt(d);\n\n // Compute the rest of the samples for the current alpha value.\n for (int64 sample_idx = output_idx % samples_per_alpha;\n sample_idx < samples_per_alpha && output_idx < limit_output;\n sample_idx++, output_idx++) {\n // Since each sample may use a variable number of normal/uniform\n // samples, and we want data stable regardless of sharding\n // (including eventually on GPU), we skip on a per-sample basis.\n PhiloxRandom gen = rng;\n gen.Skip(kReservedSamplesPerOutput * output_idx);\n int16 norm_remaining = 0;\n int16 uniform_remaining = 0;\n\n // Keep trying until we don't reject a sample. In practice, we will\n // only reject ~5% at worst, for low alpha near 1.\n while (true) {\n if (norm_remaining == 0) {\n norm_remaining = Normal::kResultElementCount;\n norm_result = normal(&gen);\n }\n norm_remaining--;\n const double x = norm_result[norm_remaining];\n double v = 1 + c * x;\n if (v <= 0) {\n continue;\n }\n v = v * v * v;\n UNIFORM(u);\n // The first option in the if is a \"squeeze\" short-circuit to\n // dodge the two logs. Magic constant sourced from the paper\n // linked above. Upward of .91 of the area covered by the log\n // inequality is covered by the squeeze as well (larger coverage\n // for smaller values of alpha).\n if ((u < 1 - 0.0331 * (x * x) * (x * x)) ||\n (log(u) < 0.5 * x * x + d * (1 - v + log(v)))) {\n double res = d * v;\n if (alpha_less_than_one) {\n UNIFORM(b);\n res *= pow(b, 1 / alpha);\n }\n samples_alpha_offset[sample_idx * num_alphas] =\n static_cast(res);\n break;\n }\n } // while: true\n } // for: sample_idx\n } // if (alpha == 1.0)\n } // for: output_idx\n }; // DoWork\n#undef UNIFORM\n // Two calls to log only occur for ~10% of samples reaching the log line.\n // 2 x 100 (64-bit cycles per log) x 0.10 = ~20.\n // Other ops: sqrt, +, *, /, %... something like 15 of these, at 3-6 cycles\n // each = ~60.\n // All of this /0.95 due to the rejection possibility = ~85.\n static const int kElementCost = 85 + 2 * Normal::kElementCost +\n Uniform::kElementCost +\n 3 * PhiloxRandom::kElementCost;\n auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads());\n Shard(worker_threads.num_threads, worker_threads.workers,\n num_alphas * samples_per_alpha, kElementCost, DoWork);\n }", "project": "tensorflow", "hash": 73312061318900783614516195772402837346, "size": 174, "commit_id": "27b417360cbd671ef55915e4bb6bb06af8b8a832", "message": "Prevent `int64` to `int` truncation in `Shard` API usage.\n\nThe function argument in `Shard` must be a function of two `int64` arguments. However, we are passing in a function with two `int` arguments. Thus, for large workloads, these arguments get truncated from positive `int64` values to negative `int` ones, resulting in a buffer out of bounds write.\n\nPiperOrigin-RevId: 332557334\nChange-Id: I236c9a2e7f53580e520571da8ba941a3aa9fa0b5", "target": 1, "dataset": "other", "idx": 197649} {"func": " void Compute(OpKernelContext* ctx) override {\n const Tensor& shape_t = ctx->input(0);\n const Tensor& alpha_t = ctx->input(1);\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(shape_t.shape()) &&\n (shape_t.dtype() == DataType::DT_INT32 ||\n shape_t.dtype() == DataType::DT_INT64),\n errors::InvalidArgument(\n \"shape must be a vector of {int32,int64}, got shape: \",\n shape_t.DebugString()));\n TensorShape samples_shape;\n if (shape_t.dtype() == DataType::DT_INT32) {\n auto vec = shape_t.flat();\n OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(vec.data(), vec.size(),\n &samples_shape));\n } else if (shape_t.dtype() == DataType::DT_INT64) {\n auto vec = shape_t.flat();\n OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(vec.data(), vec.size(),\n &samples_shape));\n }\n const int64 samples_per_alpha = samples_shape.num_elements();\n\n samples_shape.AppendShape(alpha_t.shape());\n // Allocate output samples.\n Tensor* samples_t = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, samples_shape, &samples_t));\n\n if (samples_shape.num_elements() == 0) return;\n\n using random::PhiloxRandom;\n\n typedef random::NormalDistribution Normal;\n typedef random::UniformDistribution Uniform;\n#define UNIFORM(X) \\\n if (uniform_remaining == 0) { \\\n uniform_remaining = Uniform::kResultElementCount; \\\n uniform_result = uniform(&gen); \\\n } \\\n uniform_remaining--; \\\n double X = uniform_result[uniform_remaining]\n\n // Each attempt is 95+% successful, and requires 1-2 normal + 1 uniform\n static constexpr int kReservedSamplesPerOutput = 256;\n\n const auto alpha_flat = alpha_t.flat().data();\n const int64 num_alphas = alpha_t.NumElements();\n OP_REQUIRES(ctx, num_alphas > 0,\n errors::InvalidArgument(\n \"Input alpha should have non-zero element count, got: \",\n num_alphas));\n auto samples_flat = samples_t->flat().data();\n PhiloxRandom rng = generator_.ReserveRandomOutputs(\n samples_per_alpha * num_alphas, kReservedSamplesPerOutput);\n\n // We partition work first across alphas then across samples-per-alpha to\n // avoid a couple flops which can be done on a per-alpha basis.\n\n auto DoWork = [samples_per_alpha, num_alphas, &rng, samples_flat,\n alpha_flat](int64 start_output, int64 limit_output) {\n using Eigen::numext::exp;\n using Eigen::numext::log;\n using Eigen::numext::log1p;\n using Eigen::numext::pow;\n\n // Capturing \"rng\" by-value would only make a copy for the _shared_\n // lambda. Since we want to let each worker have its own copy, we pass\n // \"rng\" by reference and explicitly do a copy assignment.\n\n Normal normal;\n Uniform uniform;\n typename Normal::ResultType norm_result;\n typename Uniform::ResultType uniform_result;\n for (int64 output_idx = start_output; output_idx < limit_output;\n /* output_idx incremented within inner loop below */) {\n int64 alpha_idx = output_idx / samples_per_alpha;\n\n // Instead of +alpha_idx for each sample, we offset the pointer once.\n T* const samples_alpha_offset = samples_flat + alpha_idx;\n\n // Several calculations can be done on a per-alpha basis.\n const double alpha = static_cast(alpha_flat[alpha_idx]);\n\n DISABLE_FLOAT_EQUALITY_WARNING\n if (alpha == static_cast(1.0)) {\n ENABLE_FLOAT_EQUALITY_WARNING\n // Sample from an exponential distribution.\n for (int64 sample_idx = output_idx % samples_per_alpha;\n sample_idx < samples_per_alpha && output_idx < limit_output;\n sample_idx++, output_idx++) {\n // As we want data stable regardless of sharding\n // (including eventually on GPU), we skip on a per-sample basis.\n PhiloxRandom gen = rng;\n gen.Skip(kReservedSamplesPerOutput * output_idx);\n int16 uniform_remaining = 0;\n UNIFORM(u);\n const double res = -log1p(-u);\n samples_alpha_offset[sample_idx * num_alphas] = static_cast(res);\n } // for (sample_idx)\n } else { // if alpha != 1.0\n // Transformation-rejection from pairs of uniform and normal random\n // variables. http://dl.acm.org/citation.cfm?id=358414\n //\n // The algorithm has an acceptance rate of ~95% for small alpha (~1),\n // and higher accept rates for higher alpha, so runtime is\n // O(NumAlphas * NumSamples * k) with k ~ 1 / 0.95.\n //\n // For alpha<1, we add one to d=alpha-1/3, and multiply the final\n // result by uniform()^(1/alpha)\n const bool alpha_less_than_one = alpha < 1;\n const double d = alpha + (alpha_less_than_one ? 2.0 / 3 : -1.0 / 3);\n const double c = 1.0 / 3 / sqrt(d);\n\n // Compute the rest of the samples for the current alpha value.\n for (int64 sample_idx = output_idx % samples_per_alpha;\n sample_idx < samples_per_alpha && output_idx < limit_output;\n sample_idx++, output_idx++) {\n // Since each sample may use a variable number of normal/uniform\n // samples, and we want data stable regardless of sharding\n // (including eventually on GPU), we skip on a per-sample basis.\n PhiloxRandom gen = rng;\n gen.Skip(kReservedSamplesPerOutput * output_idx);\n int16 norm_remaining = 0;\n int16 uniform_remaining = 0;\n\n // Keep trying until we don't reject a sample. In practice, we will\n // only reject ~5% at worst, for low alpha near 1.\n while (true) {\n if (norm_remaining == 0) {\n norm_remaining = Normal::kResultElementCount;\n norm_result = normal(&gen);\n }\n norm_remaining--;\n const double x = norm_result[norm_remaining];\n double v = 1 + c * x;\n if (v <= 0) {\n continue;\n }\n v = v * v * v;\n UNIFORM(u);\n // The first option in the if is a \"squeeze\" short-circuit to\n // dodge the two logs. Magic constant sourced from the paper\n // linked above. Upward of .91 of the area covered by the log\n // inequality is covered by the squeeze as well (larger coverage\n // for smaller values of alpha).\n if ((u < 1 - 0.0331 * (x * x) * (x * x)) ||\n (log(u) < 0.5 * x * x + d * (1 - v + log(v)))) {\n double res = d * v;\n if (alpha_less_than_one) {\n UNIFORM(b);\n res *= pow(b, 1 / alpha);\n }\n samples_alpha_offset[sample_idx * num_alphas] =\n static_cast(res);\n break;\n }\n } // while: true\n } // for: sample_idx\n } // if (alpha == 1.0)\n } // for: output_idx\n }; // DoWork\n#undef UNIFORM\n // Two calls to log only occur for ~10% of samples reaching the log line.\n // 2 x 100 (64-bit cycles per log) x 0.10 = ~20.\n // Other ops: sqrt, +, *, /, %... something like 15 of these, at 3-6 cycles\n // each = ~60.\n // All of this /0.95 due to the rejection possibility = ~85.\n static const int kElementCost = 85 + 2 * Normal::kElementCost +\n Uniform::kElementCost +\n 3 * PhiloxRandom::kElementCost;\n auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads());\n Shard(worker_threads.num_threads, worker_threads.workers,\n num_alphas * samples_per_alpha, kElementCost, DoWork);\n }", "project": "tensorflow", "hash": 46255362625410649769966248535800319854, "size": 174, "commit_id": "27b417360cbd671ef55915e4bb6bb06af8b8a832", "message": "Prevent `int64` to `int` truncation in `Shard` API usage.\n\nThe function argument in `Shard` must be a function of two `int64` arguments. However, we are passing in a function with two `int` arguments. Thus, for large workloads, these arguments get truncated from positive `int64` values to negative `int` ones, resulting in a buffer out of bounds write.\n\nPiperOrigin-RevId: 332557334\nChange-Id: I236c9a2e7f53580e520571da8ba941a3aa9fa0b5", "target": 0, "dataset": "other", "idx": 262651} {"func": "static int dwa_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,\n int uncompressed_size, EXRThreadData *td)\n{\n int64_t version, lo_usize, lo_size;\n int64_t ac_size, dc_size, rle_usize, rle_csize, rle_raw_size;\n int64_t ac_count, dc_count, ac_compression;\n const int dc_w = td->xsize >> 3;\n const int dc_h = td->ysize >> 3;\n GetByteContext gb, agb;\n int skip, ret;\n\n if (compressed_size <= 88)\n return AVERROR_INVALIDDATA;\n\n version = AV_RL64(src + 0);\n if (version != 2)\n return AVERROR_INVALIDDATA;\n\n lo_usize = AV_RL64(src + 8);\n lo_size = AV_RL64(src + 16);\n ac_size = AV_RL64(src + 24);\n dc_size = AV_RL64(src + 32);\n rle_csize = AV_RL64(src + 40);\n rle_usize = AV_RL64(src + 48);\n rle_raw_size = AV_RL64(src + 56);\n ac_count = AV_RL64(src + 64);\n dc_count = AV_RL64(src + 72);\n ac_compression = AV_RL64(src + 80);\n\n if (compressed_size < 88LL + lo_size + ac_size + dc_size + rle_csize)\n return AVERROR_INVALIDDATA;\n\n bytestream2_init(&gb, src + 88, compressed_size - 88);\n skip = bytestream2_get_le16(&gb);\n if (skip < 2)\n return AVERROR_INVALIDDATA;\n\n bytestream2_skip(&gb, skip - 2);\n\n if (lo_size > 0) {\n if (lo_usize > uncompressed_size)\n return AVERROR_INVALIDDATA;\n bytestream2_skip(&gb, lo_size);\n }\n\n if (ac_size > 0) {\n unsigned long dest_len = ac_count * 2LL;\n GetByteContext agb = gb;\n\n if (ac_count > 3LL * td->xsize * s->scan_lines_per_block)\n return AVERROR_INVALIDDATA;\n\n av_fast_padded_malloc(&td->ac_data, &td->ac_size, dest_len);\n if (!td->ac_data)\n return AVERROR(ENOMEM);\n\n switch (ac_compression) {\n case 0:\n ret = huf_uncompress(s, td, &agb, (int16_t *)td->ac_data, ac_count);\n if (ret < 0)\n return ret;\n break;\n case 1:\n if (uncompress(td->ac_data, &dest_len, agb.buffer, ac_size) != Z_OK ||\n dest_len != ac_count * 2LL)\n return AVERROR_INVALIDDATA;\n break;\n default:\n return AVERROR_INVALIDDATA;\n }\n\n bytestream2_skip(&gb, ac_size);\n }\n\n if (dc_size > 0) {\n unsigned long dest_len = dc_count * 2LL;\n GetByteContext agb = gb;\n\n if (dc_count > (6LL * td->xsize * td->ysize + 63) / 64)\n return AVERROR_INVALIDDATA;\n\n av_fast_padded_malloc(&td->dc_data, &td->dc_size, FFALIGN(dest_len, 64) * 2);\n if (!td->dc_data)\n return AVERROR(ENOMEM);\n\n if (uncompress(td->dc_data + FFALIGN(dest_len, 64), &dest_len, agb.buffer, dc_size) != Z_OK ||\n (dest_len != dc_count * 2LL))\n return AVERROR_INVALIDDATA;\n\n s->dsp.predictor(td->dc_data + FFALIGN(dest_len, 64), dest_len);\n s->dsp.reorder_pixels(td->dc_data, td->dc_data + FFALIGN(dest_len, 64), dest_len);\n\n bytestream2_skip(&gb, dc_size);\n }\n\n if (rle_raw_size > 0 && rle_csize > 0 && rle_usize > 0) {\n unsigned long dest_len = rle_usize;\n\n av_fast_padded_malloc(&td->rle_data, &td->rle_size, rle_usize);\n if (!td->rle_data)\n return AVERROR(ENOMEM);\n\n av_fast_padded_malloc(&td->rle_raw_data, &td->rle_raw_size, rle_raw_size);\n if (!td->rle_raw_data)\n return AVERROR(ENOMEM);\n\n if (uncompress(td->rle_data, &dest_len, gb.buffer, rle_csize) != Z_OK ||\n (dest_len != rle_usize))\n return AVERROR_INVALIDDATA;\n\n ret = rle(td->rle_raw_data, td->rle_data, rle_usize, rle_raw_size);\n if (ret < 0)\n return ret;\n bytestream2_skip(&gb, rle_csize);\n }\n\n bytestream2_init(&agb, td->ac_data, ac_count * 2);\n\n for (int y = 0; y < td->ysize; y += 8) {\n for (int x = 0; x < td->xsize; x += 8) {\n memset(td->block, 0, sizeof(td->block));\n\n for (int j = 0; j < 3; j++) {\n float *block = td->block[j];\n const int idx = (x >> 3) + (y >> 3) * dc_w + dc_w * dc_h * j;\n uint16_t *dc = (uint16_t *)td->dc_data;\n union av_intfloat32 dc_val;\n\n dc_val.i = half2float(dc[idx], s->mantissatable,\n s->exponenttable, s->offsettable);\n\n block[0] = dc_val.f;\n ac_uncompress(s, &agb, block);\n dct_inverse(block);\n }\n\n {\n const float scale = s->pixel_type == EXR_FLOAT ? 2.f : 1.f;\n const int o = s->nb_channels == 4;\n float *bo = ((float *)td->uncompressed_data) +\n y * td->xsize * s->nb_channels + td->xsize * (o + 0) + x;\n float *go = ((float *)td->uncompressed_data) +\n y * td->xsize * s->nb_channels + td->xsize * (o + 1) + x;\n float *ro = ((float *)td->uncompressed_data) +\n y * td->xsize * s->nb_channels + td->xsize * (o + 2) + x;\n float *yb = td->block[0];\n float *ub = td->block[1];\n float *vb = td->block[2];\n\n for (int yy = 0; yy < 8; yy++) {\n for (int xx = 0; xx < 8; xx++) {\n const int idx = xx + yy * 8;\n\n convert(yb[idx], ub[idx], vb[idx], &bo[xx], &go[xx], &ro[xx]);\n\n bo[xx] = to_linear(bo[xx], scale);\n go[xx] = to_linear(go[xx], scale);\n ro[xx] = to_linear(ro[xx], scale);\n }\n\n bo += td->xsize * s->nb_channels;\n go += td->xsize * s->nb_channels;\n ro += td->xsize * s->nb_channels;\n }\n }\n }\n }\n\n if (s->nb_channels < 4)\n return 0;\n\n for (int y = 0; y < td->ysize && td->rle_raw_data; y++) {\n uint32_t *ao = ((uint32_t *)td->uncompressed_data) + y * td->xsize * s->nb_channels;\n uint8_t *ai0 = td->rle_raw_data + y * td->xsize;\n uint8_t *ai1 = td->rle_raw_data + y * td->xsize + rle_raw_size / 2;\n\n for (int x = 0; x < td->xsize; x++) {\n uint16_t ha = ai0[x] | (ai1[x] << 8);\n\n ao[x] = half2float(ha, s->mantissatable, s->exponenttable, s->offsettable);\n }\n }\n\n return 0;\n}", "project": "FFmpeg", "hash": 164964024217881679158454133523303710683, "size": 185, "commit_id": "26d3c81bc5ef2f8c3f09d45eaeacfb4b1139a777", "message": "avcodec/exr: More strictly check dc_count\n\nFixes: out of array access\nFixes: exr/deneme\n\nFound-by: Burak \u00c7ar\u0131k\u00e7\u0131 \nSigned-off-by: Michael Niedermayer ", "target": 1, "dataset": "other", "idx": 197652} {"func": "static int dwa_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,\n int uncompressed_size, EXRThreadData *td)\n{\n int64_t version, lo_usize, lo_size;\n int64_t ac_size, dc_size, rle_usize, rle_csize, rle_raw_size;\n int64_t ac_count, dc_count, ac_compression;\n const int dc_w = td->xsize >> 3;\n const int dc_h = td->ysize >> 3;\n GetByteContext gb, agb;\n int skip, ret;\n\n if (compressed_size <= 88)\n return AVERROR_INVALIDDATA;\n\n version = AV_RL64(src + 0);\n if (version != 2)\n return AVERROR_INVALIDDATA;\n\n lo_usize = AV_RL64(src + 8);\n lo_size = AV_RL64(src + 16);\n ac_size = AV_RL64(src + 24);\n dc_size = AV_RL64(src + 32);\n rle_csize = AV_RL64(src + 40);\n rle_usize = AV_RL64(src + 48);\n rle_raw_size = AV_RL64(src + 56);\n ac_count = AV_RL64(src + 64);\n dc_count = AV_RL64(src + 72);\n ac_compression = AV_RL64(src + 80);\n\n if (compressed_size < 88LL + lo_size + ac_size + dc_size + rle_csize)\n return AVERROR_INVALIDDATA;\n\n bytestream2_init(&gb, src + 88, compressed_size - 88);\n skip = bytestream2_get_le16(&gb);\n if (skip < 2)\n return AVERROR_INVALIDDATA;\n\n bytestream2_skip(&gb, skip - 2);\n\n if (lo_size > 0) {\n if (lo_usize > uncompressed_size)\n return AVERROR_INVALIDDATA;\n bytestream2_skip(&gb, lo_size);\n }\n\n if (ac_size > 0) {\n unsigned long dest_len = ac_count * 2LL;\n GetByteContext agb = gb;\n\n if (ac_count > 3LL * td->xsize * s->scan_lines_per_block)\n return AVERROR_INVALIDDATA;\n\n av_fast_padded_malloc(&td->ac_data, &td->ac_size, dest_len);\n if (!td->ac_data)\n return AVERROR(ENOMEM);\n\n switch (ac_compression) {\n case 0:\n ret = huf_uncompress(s, td, &agb, (int16_t *)td->ac_data, ac_count);\n if (ret < 0)\n return ret;\n break;\n case 1:\n if (uncompress(td->ac_data, &dest_len, agb.buffer, ac_size) != Z_OK ||\n dest_len != ac_count * 2LL)\n return AVERROR_INVALIDDATA;\n break;\n default:\n return AVERROR_INVALIDDATA;\n }\n\n bytestream2_skip(&gb, ac_size);\n }\n\n {\n unsigned long dest_len = dc_count * 2LL;\n GetByteContext agb = gb;\n\n if (dc_count != dc_w * dc_h * 3)\n return AVERROR_INVALIDDATA;\n\n av_fast_padded_malloc(&td->dc_data, &td->dc_size, FFALIGN(dest_len, 64) * 2);\n if (!td->dc_data)\n return AVERROR(ENOMEM);\n\n if (uncompress(td->dc_data + FFALIGN(dest_len, 64), &dest_len, agb.buffer, dc_size) != Z_OK ||\n (dest_len != dc_count * 2LL))\n return AVERROR_INVALIDDATA;\n\n s->dsp.predictor(td->dc_data + FFALIGN(dest_len, 64), dest_len);\n s->dsp.reorder_pixels(td->dc_data, td->dc_data + FFALIGN(dest_len, 64), dest_len);\n\n bytestream2_skip(&gb, dc_size);\n }\n\n if (rle_raw_size > 0 && rle_csize > 0 && rle_usize > 0) {\n unsigned long dest_len = rle_usize;\n\n av_fast_padded_malloc(&td->rle_data, &td->rle_size, rle_usize);\n if (!td->rle_data)\n return AVERROR(ENOMEM);\n\n av_fast_padded_malloc(&td->rle_raw_data, &td->rle_raw_size, rle_raw_size);\n if (!td->rle_raw_data)\n return AVERROR(ENOMEM);\n\n if (uncompress(td->rle_data, &dest_len, gb.buffer, rle_csize) != Z_OK ||\n (dest_len != rle_usize))\n return AVERROR_INVALIDDATA;\n\n ret = rle(td->rle_raw_data, td->rle_data, rle_usize, rle_raw_size);\n if (ret < 0)\n return ret;\n bytestream2_skip(&gb, rle_csize);\n }\n\n bytestream2_init(&agb, td->ac_data, ac_count * 2);\n\n for (int y = 0; y < td->ysize; y += 8) {\n for (int x = 0; x < td->xsize; x += 8) {\n memset(td->block, 0, sizeof(td->block));\n\n for (int j = 0; j < 3; j++) {\n float *block = td->block[j];\n const int idx = (x >> 3) + (y >> 3) * dc_w + dc_w * dc_h * j;\n uint16_t *dc = (uint16_t *)td->dc_data;\n union av_intfloat32 dc_val;\n\n dc_val.i = half2float(dc[idx], s->mantissatable,\n s->exponenttable, s->offsettable);\n\n block[0] = dc_val.f;\n ac_uncompress(s, &agb, block);\n dct_inverse(block);\n }\n\n {\n const float scale = s->pixel_type == EXR_FLOAT ? 2.f : 1.f;\n const int o = s->nb_channels == 4;\n float *bo = ((float *)td->uncompressed_data) +\n y * td->xsize * s->nb_channels + td->xsize * (o + 0) + x;\n float *go = ((float *)td->uncompressed_data) +\n y * td->xsize * s->nb_channels + td->xsize * (o + 1) + x;\n float *ro = ((float *)td->uncompressed_data) +\n y * td->xsize * s->nb_channels + td->xsize * (o + 2) + x;\n float *yb = td->block[0];\n float *ub = td->block[1];\n float *vb = td->block[2];\n\n for (int yy = 0; yy < 8; yy++) {\n for (int xx = 0; xx < 8; xx++) {\n const int idx = xx + yy * 8;\n\n convert(yb[idx], ub[idx], vb[idx], &bo[xx], &go[xx], &ro[xx]);\n\n bo[xx] = to_linear(bo[xx], scale);\n go[xx] = to_linear(go[xx], scale);\n ro[xx] = to_linear(ro[xx], scale);\n }\n\n bo += td->xsize * s->nb_channels;\n go += td->xsize * s->nb_channels;\n ro += td->xsize * s->nb_channels;\n }\n }\n }\n }\n\n if (s->nb_channels < 4)\n return 0;\n\n for (int y = 0; y < td->ysize && td->rle_raw_data; y++) {\n uint32_t *ao = ((uint32_t *)td->uncompressed_data) + y * td->xsize * s->nb_channels;\n uint8_t *ai0 = td->rle_raw_data + y * td->xsize;\n uint8_t *ai1 = td->rle_raw_data + y * td->xsize + rle_raw_size / 2;\n\n for (int x = 0; x < td->xsize; x++) {\n uint16_t ha = ai0[x] | (ai1[x] << 8);\n\n ao[x] = half2float(ha, s->mantissatable, s->exponenttable, s->offsettable);\n }\n }\n\n return 0;\n}", "project": "FFmpeg", "hash": 64835961090131636283596112080756004472, "size": 185, "commit_id": "26d3c81bc5ef2f8c3f09d45eaeacfb4b1139a777", "message": "avcodec/exr: More strictly check dc_count\n\nFixes: out of array access\nFixes: exr/deneme\n\nFound-by: Burak \u00c7ar\u0131k\u00e7\u0131 \nSigned-off-by: Michael Niedermayer ", "target": 0, "dataset": "other", "idx": 262684} {"func": " Status ValidateInputsGenerateOutputs(\n OpKernelContext* ctx, const Tensor** inputs, const Tensor** seq_len,\n Tensor** log_prob, OpOutputList* decoded_indices,\n OpOutputList* decoded_values, OpOutputList* decoded_shape) const {\n Status status = ctx->input(\"inputs\", inputs);\n if (!status.ok()) return status;\n status = ctx->input(\"sequence_length\", seq_len);\n if (!status.ok()) return status;\n\n const TensorShape& inputs_shape = (*inputs)->shape();\n\n if (inputs_shape.dims() != 3) {\n return errors::InvalidArgument(\"inputs is not a 3-Tensor\");\n }\n\n const int64 max_time = inputs_shape.dim_size(0);\n const int64 batch_size = inputs_shape.dim_size(1);\n\n if (max_time == 0) {\n return errors::InvalidArgument(\"max_time is 0\");\n }\n if (!TensorShapeUtils::IsVector((*seq_len)->shape())) {\n return errors::InvalidArgument(\"sequence_length is not a vector\");\n }\n\n if (!(batch_size == (*seq_len)->dim_size(0))) {\n return errors::FailedPrecondition(\n \"len(sequence_length) != batch_size. \",\n \"len(sequence_length): \", (*seq_len)->dim_size(0),\n \" batch_size: \", batch_size);\n }\n\n auto seq_len_t = (*seq_len)->vec();\n\n for (int b = 0; b < batch_size; ++b) {\n if (!(seq_len_t(b) <= max_time)) {\n return errors::FailedPrecondition(\"sequence_length(\", b,\n \") <= \", max_time);\n }\n }\n\n Status s = ctx->allocate_output(\n \"log_probability\", TensorShape({batch_size, top_paths_}), log_prob);\n if (!s.ok()) return s;\n\n s = ctx->output_list(\"decoded_indices\", decoded_indices);\n if (!s.ok()) return s;\n s = ctx->output_list(\"decoded_values\", decoded_values);\n if (!s.ok()) return s;\n s = ctx->output_list(\"decoded_shape\", decoded_shape);\n if (!s.ok()) return s;\n\n return Status::OK();\n }", "project": "tensorflow", "hash": 179923620289596823307074921015885142930, "size": 54, "commit_id": "b1b323042264740c398140da32e93fb9c2c9f33e", "message": "Fix SEGV in CTC ops\n\nPiperOrigin-RevId: 372430279\nChange-Id: I7ec2ad9d6f4d0980c33de45d27c6b17df5c6e26f", "target": 1, "dataset": "other", "idx": 197664} {"func": " Status ValidateInputsGenerateOutputs(\n OpKernelContext* ctx, const Tensor** inputs, const Tensor** seq_len,\n Tensor** log_prob, OpOutputList* decoded_indices,\n OpOutputList* decoded_values, OpOutputList* decoded_shape) const {\n Status status = ctx->input(\"inputs\", inputs);\n if (!status.ok()) return status;\n status = ctx->input(\"sequence_length\", seq_len);\n if (!status.ok()) return status;\n\n const TensorShape& inputs_shape = (*inputs)->shape();\n\n if (inputs_shape.dims() != 3) {\n return errors::InvalidArgument(\"inputs is not a 3-Tensor\");\n }\n if (inputs_shape.num_elements() == 0) {\n return errors::InvalidArgument(\"inputs must not be empty\");\n }\n\n const int64 max_time = inputs_shape.dim_size(0);\n const int64 batch_size = inputs_shape.dim_size(1);\n\n if (max_time == 0) {\n return errors::InvalidArgument(\"max_time is 0\");\n }\n if (!TensorShapeUtils::IsVector((*seq_len)->shape())) {\n return errors::InvalidArgument(\"sequence_length is not a vector\");\n }\n\n if (!(batch_size == (*seq_len)->dim_size(0))) {\n return errors::FailedPrecondition(\n \"len(sequence_length) != batch_size. \",\n \"len(sequence_length): \", (*seq_len)->dim_size(0),\n \" batch_size: \", batch_size);\n }\n\n auto seq_len_t = (*seq_len)->vec();\n\n for (int b = 0; b < batch_size; ++b) {\n if (!(seq_len_t(b) <= max_time)) {\n return errors::FailedPrecondition(\"sequence_length(\", b,\n \") <= \", max_time);\n }\n }\n\n Status s = ctx->allocate_output(\n \"log_probability\", TensorShape({batch_size, top_paths_}), log_prob);\n if (!s.ok()) return s;\n\n s = ctx->output_list(\"decoded_indices\", decoded_indices);\n if (!s.ok()) return s;\n s = ctx->output_list(\"decoded_values\", decoded_values);\n if (!s.ok()) return s;\n s = ctx->output_list(\"decoded_shape\", decoded_shape);\n if (!s.ok()) return s;\n\n return Status::OK();\n }", "project": "tensorflow", "hash": 208622133539229492215272569704905304618, "size": 57, "commit_id": "b1b323042264740c398140da32e93fb9c2c9f33e", "message": "Fix SEGV in CTC ops\n\nPiperOrigin-RevId: 372430279\nChange-Id: I7ec2ad9d6f4d0980c33de45d27c6b17df5c6e26f", "target": 0, "dataset": "other", "idx": 262711} {"func": " void ValidateInputs(OpKernelContext* ctx,\n const CSRSparseMatrix& sparse_matrix,\n const Tensor& permutation_indices, int* batch_size,\n int64* num_rows) {\n OP_REQUIRES(ctx, sparse_matrix.dtype() == DataTypeToEnum::value,\n errors::InvalidArgument(\n \"Asked for a CSRSparseMatrix of type \",\n DataTypeString(DataTypeToEnum::value),\n \" but saw dtype: \", DataTypeString(sparse_matrix.dtype())));\n\n const Tensor& dense_shape = sparse_matrix.dense_shape();\n const int rank = dense_shape.dim_size(0);\n OP_REQUIRES(ctx, rank == 2 || rank == 3,\n errors::InvalidArgument(\"sparse matrix must have rank 2 or 3; \",\n \"but dense_shape has size \", rank));\n const int row_dim = (rank == 2) ? 0 : 1;\n auto dense_shape_vec = dense_shape.vec();\n *num_rows = dense_shape_vec(row_dim);\n const int64 num_cols = dense_shape_vec(row_dim + 1);\n OP_REQUIRES(ctx, *num_rows == num_cols,\n errors::InvalidArgument(\"sparse matrix must be square; got: \",\n *num_rows, \" != \", num_cols));\n const TensorShape& perm_shape = permutation_indices.shape();\n OP_REQUIRES(\n ctx, perm_shape.dims() + 1 == rank,\n errors::InvalidArgument(\n \"sparse matrix must have the same rank as permutation; got: \", rank,\n \" != \", perm_shape.dims(), \" + 1.\"));\n OP_REQUIRES(\n ctx, perm_shape.dim_size(rank - 2) == *num_rows,\n errors::InvalidArgument(\n \"permutation must have the same number of elements in each batch \"\n \"as the number of rows in sparse matrix; got: \",\n perm_shape.dim_size(rank - 2), \" != \", *num_rows));\n\n *batch_size = sparse_matrix.batch_size();\n if (*batch_size > 1) {\n OP_REQUIRES(\n ctx, perm_shape.dim_size(0) == *batch_size,\n errors::InvalidArgument(\"permutation must have the same batch size \"\n \"as sparse matrix; got: \",\n perm_shape.dim_size(0), \" != \", *batch_size));\n }\n }", "project": "tensorflow", "hash": 336558180459502144170088935707234439720, "size": 44, "commit_id": "e6a7c7cc18c3aaad1ae0872cb0a959f5c923d2bd", "message": "Remove `OP_REQUIRES` call from helper function.\n\nSince `OP_REQUIRES` macro expands to a `return;` (among other), calling it in a helper function only ends the helper function's execution earlier, but the kernel will still run from start to end. Thus, all the expected validations are actually broken/useless as the code ploughs through the next crash anyway.\n\nPiperOrigin-RevId: 369524386\nChange-Id: I54f6cf9328445675ccc392e661b04336b229c9da", "target": 1, "dataset": "other", "idx": 197715} {"func": " Status ValidateInputs(const CSRSparseMatrix& sparse_matrix,\n const Tensor& permutation_indices, int* batch_size,\n int64* num_rows) {\n if (sparse_matrix.dtype() != DataTypeToEnum::value)\n return errors::InvalidArgument(\n \"Asked for a CSRSparseMatrix of type \",\n DataTypeString(DataTypeToEnum::value),\n \" but saw dtype: \", DataTypeString(sparse_matrix.dtype()));\n\n const Tensor& dense_shape = sparse_matrix.dense_shape();\n const int rank = dense_shape.dim_size(0);\n if (rank < 2 || rank > 3)\n return errors::InvalidArgument(\"sparse matrix must have rank 2 or 3; \",\n \"but dense_shape has size \", rank);\n const int row_dim = (rank == 2) ? 0 : 1;\n auto dense_shape_vec = dense_shape.vec();\n *num_rows = dense_shape_vec(row_dim);\n const int64 num_cols = dense_shape_vec(row_dim + 1);\n if (*num_rows != num_cols)\n return errors::InvalidArgument(\n \"sparse matrix must be square; got: \", *num_rows, \" != \", num_cols);\n const TensorShape& perm_shape = permutation_indices.shape();\n if (perm_shape.dims() + 1 != rank)\n return errors::InvalidArgument(\n \"sparse matrix must have the same rank as permutation; got: \", rank,\n \" != \", perm_shape.dims(), \" + 1.\");\n if (perm_shape.dim_size(rank - 2) != *num_rows)\n return errors::InvalidArgument(\n \"permutation must have the same number of elements in each batch \"\n \"as the number of rows in sparse matrix; got: \",\n perm_shape.dim_size(rank - 2), \" != \", *num_rows);\n\n *batch_size = sparse_matrix.batch_size();\n if (*batch_size > 1) {\n if (perm_shape.dim_size(0) != *batch_size)\n return errors::InvalidArgument(\n \"permutation must have the same batch size \"\n \"as sparse matrix; got: \",\n perm_shape.dim_size(0), \" != \", *batch_size);\n }\n\n return Status::OK();\n }", "project": "tensorflow", "hash": 71539368152818315797596681434801050349, "size": 43, "commit_id": "e6a7c7cc18c3aaad1ae0872cb0a959f5c923d2bd", "message": "Remove `OP_REQUIRES` call from helper function.\n\nSince `OP_REQUIRES` macro expands to a `return;` (among other), calling it in a helper function only ends the helper function's execution earlier, but the kernel will still run from start to end. Thus, all the expected validations are actually broken/useless as the code ploughs through the next crash anyway.\n\nPiperOrigin-RevId: 369524386\nChange-Id: I54f6cf9328445675ccc392e661b04336b229c9da", "target": 0, "dataset": "other", "idx": 262772} {"func": "void dmar_free_irte(const struct intr_source *intr_src, uint16_t index)\n{\n\tstruct dmar_drhd_rt *dmar_unit;\n\tunion dmar_ir_entry *ir_table, *ir_entry;\n\tunion pci_bdf sid;\n\n\tif (intr_src->is_msi) {\n\t\tdmar_unit = device_to_dmaru((uint8_t)intr_src->src.msi.bits.b, intr_src->src.msi.fields.devfun);\n\t} else {\n\t\tdmar_unit = ioapic_to_dmaru(intr_src->src.ioapic_id, &sid);\n\t}\n\n\tif (is_dmar_unit_valid(dmar_unit, sid)) {\n\t\tir_table = (union dmar_ir_entry *)hpa2hva(dmar_unit->ir_table_addr);\n\t\tir_entry = ir_table + index;\n\t\tir_entry->bits.remap.present = 0x0UL;\n\n\t\tiommu_flush_cache(ir_entry, sizeof(union dmar_ir_entry));\n\t\tdmar_invalid_iec(dmar_unit, index, 0U, false);\n\n\t\tif (!is_irte_reserved(dmar_unit, index)) {\n\t\t\tspinlock_obtain(&dmar_unit->lock);\n\t\t\tbitmap_clear_nolock(index & 0x3FU, &dmar_unit->irte_alloc_bitmap[index >> 6U]);\n\t\t\tspinlock_release(&dmar_unit->lock);\n\t\t}\n\t}\n\n}", "project": "acrn-hypervisor", "hash": 138533968807108358104095755982502807971, "size": 28, "commit_id": "25c0e3817eb332660dd63d1d4522e63dcc94e79a", "message": "hv: validate input for dmar_free_irte function\n\n Malicious input 'index' may trigger buffer\n overflow on array 'irte_alloc_bitmap[]'.\n\n This patch validate that 'index' shall be\n less than 'CONFIG_MAX_IR_ENTRIES' and also\n remove unnecessary check on 'index' in\n 'ptirq_free_irte()' function with this fix.\n\nTracked-On: #6132\nSigned-off-by: Yonghua Huang ", "target": 1, "dataset": "other", "idx": 197721} {"func": "void dmar_free_irte(const struct intr_source *intr_src, uint16_t index)\n{\n\tstruct dmar_drhd_rt *dmar_unit;\n\tunion dmar_ir_entry *ir_table, *ir_entry;\n\tunion pci_bdf sid;\n\n\tif (intr_src->is_msi) {\n\t\tdmar_unit = device_to_dmaru((uint8_t)intr_src->src.msi.bits.b, intr_src->src.msi.fields.devfun);\n\t} else {\n\t\tdmar_unit = ioapic_to_dmaru(intr_src->src.ioapic_id, &sid);\n\t}\n\n\tif (is_dmar_unit_valid(dmar_unit, sid) && (index < CONFIG_MAX_IR_ENTRIES)) {\n\t\tir_table = (union dmar_ir_entry *)hpa2hva(dmar_unit->ir_table_addr);\n\t\tir_entry = ir_table + index;\n\t\tir_entry->bits.remap.present = 0x0UL;\n\n\t\tiommu_flush_cache(ir_entry, sizeof(union dmar_ir_entry));\n\t\tdmar_invalid_iec(dmar_unit, index, 0U, false);\n\n\t\tif (!is_irte_reserved(dmar_unit, index)) {\n\t\t\tspinlock_obtain(&dmar_unit->lock);\n\t\t\tbitmap_clear_nolock(index & 0x3FU, &dmar_unit->irte_alloc_bitmap[index >> 6U]);\n\t\t\tspinlock_release(&dmar_unit->lock);\n\t\t}\n\t}\n\n}", "project": "acrn-hypervisor", "hash": 50934453175337732283896052884663765142, "size": 28, "commit_id": "25c0e3817eb332660dd63d1d4522e63dcc94e79a", "message": "hv: validate input for dmar_free_irte function\n\n Malicious input 'index' may trigger buffer\n overflow on array 'irte_alloc_bitmap[]'.\n\n This patch validate that 'index' shall be\n less than 'CONFIG_MAX_IR_ENTRIES' and also\n remove unnecessary check on 'index' in\n 'ptirq_free_irte()' function with this fix.\n\nTracked-On: #6132\nSigned-off-by: Yonghua Huang ", "target": 0, "dataset": "other", "idx": 262864} {"func": "static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) {\n packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL,\n packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0,\n packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL,\n packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0,\n packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL,\n packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0,\n packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL,\n packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL,\n packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL,\n packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0,\n packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0;\n}", "project": "nDPI", "hash": 86484384815441304643195803453281909060, "size": 13, "commit_id": "6a9f5e4f7c3fd5ddab3e6727b071904d76773952", "message": "Fixed use after free caused by dangling pointer\n\n * This fix also improved RCE Injection detection\n\nSigned-off-by: Toni Uhlig ", "target": 1, "dataset": "other", "idx": 197747} {"func": "static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) {\n packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL,\n packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0,\n packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL,\n packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0,\n packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL,\n packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0,\n packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->content_disposition_line.ptr = NULL,\n packet->content_disposition_line.len = 0, packet->http_cookie.ptr = NULL,\n packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL,\n packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL,\n packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0,\n packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0;\n}", "project": "nDPI", "hash": 165714072252586915476330424541219526931, "size": 14, "commit_id": "6a9f5e4f7c3fd5ddab3e6727b071904d76773952", "message": "Fixed use after free caused by dangling pointer\n\n * This fix also improved RCE Injection detection\n\nSigned-off-by: Toni Uhlig ", "target": 0, "dataset": "other", "idx": 263377} {"func": "bool FromkLinuxSockAddr(const struct klinux_sockaddr *input,\n socklen_t input_len, struct sockaddr *output,\n socklen_t *output_len,\n void (*abort_handler)(const char *)) {\n if (!input || !output || !output_len || input_len == 0) {\n output = nullptr;\n return false;\n }\n\n int16_t klinux_family = input->klinux_sa_family;\n if (klinux_family == kLinux_AF_UNIX) {\n struct klinux_sockaddr_un *klinux_sockaddr_un_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_un sockaddr_un_out;\n sockaddr_un_out.sun_family = AF_UNIX;\n InitializeToZeroArray(sockaddr_un_out.sun_path);\n ReinterpretCopyArray(\n sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path,\n std::min(sizeof(sockaddr_un_out.sun_path),\n sizeof(klinux_sockaddr_un_in->klinux_sun_path)));\n CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len);\n } else if (klinux_family == kLinux_AF_INET) {\n struct klinux_sockaddr_in *klinux_sockaddr_in_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_in sockaddr_in_out;\n sockaddr_in_out.sin_family = AF_INET;\n sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port;\n InitializeToZeroSingle(&sockaddr_in_out.sin_addr);\n ReinterpretCopySingle(&sockaddr_in_out.sin_addr,\n &klinux_sockaddr_in_in->klinux_sin_addr);\n InitializeToZeroArray(sockaddr_in_out.sin_zero);\n ReinterpretCopyArray(sockaddr_in_out.sin_zero,\n klinux_sockaddr_in_in->klinux_sin_zero);\n CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len);\n } else if (klinux_family == kLinux_AF_INET6) {\n struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_in6 sockaddr_in6_out;\n sockaddr_in6_out.sin6_family = AF_INET6;\n sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port;\n sockaddr_in6_out.sin6_flowinfo =\n klinux_sockaddr_in6_in->klinux_sin6_flowinfo;\n sockaddr_in6_out.sin6_scope_id =\n klinux_sockaddr_in6_in->klinux_sin6_scope_id;\n InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr);\n ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr,\n &klinux_sockaddr_in6_in->klinux_sin6_addr);\n CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output,\n output_len);\n } else if (klinux_family == kLinux_AF_UNSPEC) {\n output = nullptr;\n *output_len = 0;\n } else {\n if (abort_handler != nullptr) {\n std::string message = absl::StrCat(\n \"Type conversion error - Unsupported AF family: \", klinux_family);\n abort_handler(message.c_str());\n } else {\n abort();\n }\n }\n return true;\n}", "project": "asylo", "hash": 25761054693871753712999801888112976207, "size": 69, "commit_id": "bda9772e7872b0d2b9bee32930cf7a4983837b39", "message": "Check input length in FromLinuxSockAddr\n\nPiperOrigin-RevId: 333785506\nChange-Id: I1d68fb8954665eebc1018d80ff995cbe9e7ed6a9", "target": 1, "dataset": "other", "idx": 197757} {"func": "bool FromkLinuxSockAddr(const struct klinux_sockaddr *input,\n socklen_t input_len, struct sockaddr *output,\n socklen_t *output_len,\n void (*abort_handler)(const char *)) {\n if (!input || !output || !output_len || input_len == 0) {\n output = nullptr;\n return false;\n }\n\n int16_t klinux_family = input->klinux_sa_family;\n if (klinux_family == kLinux_AF_UNIX) {\n if (input_len < sizeof(struct klinux_sockaddr_un)) {\n return false;\n }\n\n struct klinux_sockaddr_un *klinux_sockaddr_un_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_un sockaddr_un_out;\n sockaddr_un_out.sun_family = AF_UNIX;\n InitializeToZeroArray(sockaddr_un_out.sun_path);\n ReinterpretCopyArray(\n sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path,\n std::min(sizeof(sockaddr_un_out.sun_path),\n sizeof(klinux_sockaddr_un_in->klinux_sun_path)));\n CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len);\n } else if (klinux_family == kLinux_AF_INET) {\n if (input_len < sizeof(struct klinux_sockaddr_in)) {\n return false;\n }\n struct klinux_sockaddr_in *klinux_sockaddr_in_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_in sockaddr_in_out;\n sockaddr_in_out.sin_family = AF_INET;\n sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port;\n InitializeToZeroSingle(&sockaddr_in_out.sin_addr);\n ReinterpretCopySingle(&sockaddr_in_out.sin_addr,\n &klinux_sockaddr_in_in->klinux_sin_addr);\n InitializeToZeroArray(sockaddr_in_out.sin_zero);\n ReinterpretCopyArray(sockaddr_in_out.sin_zero,\n klinux_sockaddr_in_in->klinux_sin_zero);\n CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len);\n } else if (klinux_family == kLinux_AF_INET6) {\n if (input_len < sizeof(struct klinux_sockaddr_in6)) {\n return false;\n }\n\n struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_in6 sockaddr_in6_out;\n sockaddr_in6_out.sin6_family = AF_INET6;\n sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port;\n sockaddr_in6_out.sin6_flowinfo =\n klinux_sockaddr_in6_in->klinux_sin6_flowinfo;\n sockaddr_in6_out.sin6_scope_id =\n klinux_sockaddr_in6_in->klinux_sin6_scope_id;\n InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr);\n ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr,\n &klinux_sockaddr_in6_in->klinux_sin6_addr);\n CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output,\n output_len);\n } else if (klinux_family == kLinux_AF_UNSPEC) {\n output = nullptr;\n *output_len = 0;\n } else {\n if (abort_handler != nullptr) {\n std::string message = absl::StrCat(\n \"Type conversion error - Unsupported AF family: \", klinux_family);\n abort_handler(message.c_str());\n } else {\n abort();\n }\n }\n return true;\n}", "project": "asylo", "hash": 244700671016873006082210219872496648727, "size": 80, "commit_id": "bda9772e7872b0d2b9bee32930cf7a4983837b39", "message": "Check input length in FromLinuxSockAddr\n\nPiperOrigin-RevId: 333785506\nChange-Id: I1d68fb8954665eebc1018d80ff995cbe9e7ed6a9", "target": 0, "dataset": "other", "idx": 263436} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& input = context->input(0);\n const float input_min = context->input(1).flat()(0);\n const float input_max = context->input(2).flat()(0);\n const Tensor& mean = context->input(3);\n const float mean_min = context->input(4).flat()(0);\n const float mean_max = context->input(5).flat()(0);\n const Tensor& var = context->input(6);\n const float var_min = context->input(7).flat()(0);\n const float var_max = context->input(8).flat()(0);\n const Tensor& beta = context->input(9);\n const float beta_min = context->input(10).flat()(0);\n const float beta_max = context->input(11).flat()(0);\n const Tensor& gamma = context->input(12);\n const float gamma_min = context->input(13).flat()(0);\n const float gamma_max = context->input(14).flat()(0);\n\n OP_REQUIRES(context, input.dims() == 4,\n errors::InvalidArgument(\"input must be 4-dimensional\",\n input.shape().DebugString()));\n OP_REQUIRES(context, mean.dims() == 1,\n errors::InvalidArgument(\"mean must be 1-dimensional\",\n mean.shape().DebugString()));\n OP_REQUIRES(context, var.dims() == 1,\n errors::InvalidArgument(\"var must be 1-dimensional\",\n var.shape().DebugString()));\n OP_REQUIRES(context, beta.dims() == 1,\n errors::InvalidArgument(\"beta must be 1-dimensional\",\n beta.shape().DebugString()));\n OP_REQUIRES(context, gamma.dims() == 1,\n errors::InvalidArgument(\"gamma must be 1-dimensional\",\n gamma.shape().DebugString()));\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, input.shape(), &output));\n float output_min;\n float output_max;\n FixedPointBatchNorm(input, input_min, input_max, mean, mean_min,\n mean_max, var, var_min, var_max, beta, beta_min,\n beta_max, gamma, gamma_min, gamma_max,\n variance_epsilon_, scale_after_normalization_,\n output, &output_min, &output_max);\n\n Tensor* output_min_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(1, {}, &output_min_tensor));\n output_min_tensor->flat()(0) = output_min;\n\n Tensor* output_max_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(2, {}, &output_max_tensor));\n output_max_tensor->flat()(0) = output_max;\n }", "project": "tensorflow", "hash": 39891708146580454794486373109005381550, "size": 54, "commit_id": "d6ed5bcfe1dcab9e85a4d39931bd18d99018e75b", "message": "Add missing validation in `QuantizedBatchNormWithGlobalNormalization`\n\nPiperOrigin-RevId: 370123451\nChange-Id: Id234d6dab1ec21230bb8e503dba30f899af87f33", "target": 1, "dataset": "other", "idx": 197761} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& input = context->input(0);\n const auto& input_min_tensor = context->input(1);\n OP_REQUIRES(context, input_min_tensor.NumElements() == 1,\n errors::InvalidArgument(\"input_min must have 1 element\"));\n const float input_min = input_min_tensor.flat()(0);\n const auto& input_max_tensor = context->input(2);\n OP_REQUIRES(context, input_max_tensor.NumElements() == 1,\n errors::InvalidArgument(\"input_max must have 1 element\"));\n const float input_max = input_max_tensor.flat()(0);\n const Tensor& mean = context->input(3);\n const auto& mean_min_tensor = context->input(4);\n OP_REQUIRES(context, mean_min_tensor.NumElements() == 1,\n errors::InvalidArgument(\"mean_min must have 1 element\"));\n const float mean_min = mean_min_tensor.flat()(0);\n const auto& mean_max_tensor = context->input(5);\n OP_REQUIRES(context, mean_max_tensor.NumElements() == 1,\n errors::InvalidArgument(\"mean_max must have 1 element\"));\n const float mean_max = mean_max_tensor.flat()(0);\n const Tensor& var = context->input(6);\n const auto& var_min_tensor = context->input(7);\n OP_REQUIRES(context, var_min_tensor.NumElements() == 1,\n errors::InvalidArgument(\"var_min must have 1 element\"));\n const float var_min = var_min_tensor.flat()(0);\n const auto& var_max_tensor = context->input(8);\n OP_REQUIRES(context, var_max_tensor.NumElements() == 1,\n errors::InvalidArgument(\"var_max must have 1 element\"));\n const float var_max = var_max_tensor.flat()(0);\n const Tensor& beta = context->input(9);\n const auto& beta_min_tensor = context->input(10);\n OP_REQUIRES(context, beta_min_tensor.NumElements() == 1,\n errors::InvalidArgument(\"beta_min must have 1 element\"));\n const float beta_min = beta_min_tensor.flat()(0);\n const auto& beta_max_tensor = context->input(11);\n OP_REQUIRES(context, beta_max_tensor.NumElements() == 1,\n errors::InvalidArgument(\"beta_max must have 1 element\"));\n const float beta_max = beta_max_tensor.flat()(0);\n const Tensor& gamma = context->input(12);\n const auto& gamma_min_tensor = context->input(13);\n OP_REQUIRES(context, gamma_min_tensor.NumElements() == 1,\n errors::InvalidArgument(\"gamma_min must have 1 element\"));\n const float gamma_min = gamma_min_tensor.flat()(0);\n const auto& gamma_max_tensor = context->input(14);\n OP_REQUIRES(context, gamma_max_tensor.NumElements() == 1,\n errors::InvalidArgument(\"gamma_max must have 1 element\"));\n const float gamma_max = gamma_max_tensor.flat()(0);\n\n OP_REQUIRES(context, input.dims() == 4,\n errors::InvalidArgument(\"input must be 4-dimensional\",\n input.shape().DebugString()));\n OP_REQUIRES(context, mean.dims() == 1,\n errors::InvalidArgument(\"mean must be 1-dimensional\",\n mean.shape().DebugString()));\n OP_REQUIRES(context, var.dims() == 1,\n errors::InvalidArgument(\"var must be 1-dimensional\",\n var.shape().DebugString()));\n OP_REQUIRES(context, beta.dims() == 1,\n errors::InvalidArgument(\"beta must be 1-dimensional\",\n beta.shape().DebugString()));\n OP_REQUIRES(context, gamma.dims() == 1,\n errors::InvalidArgument(\"gamma must be 1-dimensional\",\n gamma.shape().DebugString()));\n OP_REQUIRES(context, mean.NumElements() > 1,\n errors::InvalidArgument(\"Must have at least a mean value\",\n gamma.shape().DebugString()));\n OP_REQUIRES(context, mean.NumElements() > 1,\n errors::InvalidArgument(\"Must have at least a mean value\"));\n const auto last_dim = input.shape().dims() - 1;\n OP_REQUIRES(context,\n mean.shape().dim_size(0) == input.shape().dim_size(last_dim),\n errors::InvalidArgument(\"Must provide as many means as the \"\n \"last dimension of the input tensor: \",\n mean.shape().DebugString(), \" vs. \",\n input.shape().DebugString()));\n OP_REQUIRES(\n context, mean.shape().dim_size(0) == var.shape().dim_size(0),\n errors::InvalidArgument(\n \"Mean and variance tensors must have the same shape: \",\n mean.shape().DebugString(), \" vs. \", var.shape().DebugString()));\n OP_REQUIRES(\n context, mean.shape().dim_size(0) == beta.shape().dim_size(0),\n errors::InvalidArgument(\n \"Mean and beta tensors must have the same shape: \",\n mean.shape().DebugString(), \" vs. \", beta.shape().DebugString()));\n OP_REQUIRES(\n context, mean.shape().dim_size(0) == gamma.shape().dim_size(0),\n errors::InvalidArgument(\n \"Mean and gamma tensors must have the same shape: \",\n mean.shape().DebugString(), \" vs. \", gamma.shape().DebugString()));\n\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, input.shape(), &output));\n float output_min;\n float output_max;\n FixedPointBatchNorm(input, input_min, input_max, mean, mean_min,\n mean_max, var, var_min, var_max, beta, beta_min,\n beta_max, gamma, gamma_min, gamma_max,\n variance_epsilon_, scale_after_normalization_,\n output, &output_min, &output_max);\n\n Tensor* output_min_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(1, {}, &output_min_tensor));\n output_min_tensor->flat()(0) = output_min;\n\n Tensor* output_max_tensor = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(2, {}, &output_max_tensor));\n output_max_tensor->flat()(0) = output_max;\n }", "project": "tensorflow", "hash": 115913159429277562366456709982634610677, "size": 111, "commit_id": "d6ed5bcfe1dcab9e85a4d39931bd18d99018e75b", "message": "Add missing validation in `QuantizedBatchNormWithGlobalNormalization`\n\nPiperOrigin-RevId: 370123451\nChange-Id: Id234d6dab1ec21230bb8e503dba30f899af87f33", "target": 0, "dataset": "other", "idx": 263524} {"func": "ImmutableConstantOp::ImmutableConstantOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context,\n context->GetAttr(kMemoryRegionNameAttr, ®ion_name_));\n OP_REQUIRES_OK(context, context->GetAttr(kDTypeAttr, &dtype_));\n OP_REQUIRES_OK(context, context->GetAttr(kShapeAttr, &shape_));\n}", "project": "tensorflow", "hash": 193263969189053696650270005931382566681, "size": 7, "commit_id": "4f663d4b8f0bec1b48da6fa091a7d29609980fa4", "message": "Allowlist certain data types to avoid a seg fault.\n\nPiperOrigin-RevId: 356326671\nChange-Id: I23b65b52e93798cb5a6744632d31b0f88c6b6b31", "target": 1, "dataset": "other", "idx": 197806} {"func": "ImmutableConstantOp::ImmutableConstantOp(OpKernelConstruction* context)\n : OpKernel(context) {\n OP_REQUIRES_OK(context,\n context->GetAttr(kMemoryRegionNameAttr, ®ion_name_));\n OP_REQUIRES_OK(context, context->GetAttr(kDTypeAttr, &dtype_));\n OP_REQUIRES(context, dtype_ != DT_RESOURCE && dtype_ != DT_VARIANT,\n errors::InvalidArgument(\n \"Resource and variant dtypes are invalid for this op.\"));\n OP_REQUIRES_OK(context, context->GetAttr(kShapeAttr, &shape_));\n}", "project": "tensorflow", "hash": 8861752768728197719914030896388110369, "size": 10, "commit_id": "4f663d4b8f0bec1b48da6fa091a7d29609980fa4", "message": "Allowlist certain data types to avoid a seg fault.\n\nPiperOrigin-RevId: 356326671\nChange-Id: I23b65b52e93798cb5a6744632d31b0f88c6b6b31", "target": 0, "dataset": "other", "idx": 264414} {"func": "void *UntrustedCacheMalloc::GetBuffer() {\n void **buffers = nullptr;\n void *buffer;\n bool is_pool_empty;\n\n {\n LockGuard spin_lock(&lock_);\n is_pool_empty = buffer_pool_.empty();\n if (is_pool_empty) {\n buffers =\n primitives::AllocateUntrustedBuffers(kPoolIncrement, kPoolEntrySize);\n for (int i = 0; i < kPoolIncrement; i++) {\n if (!buffers[i] ||\n !TrustedPrimitives::IsOutsideEnclave(buffers[i], kPoolEntrySize)) {\n abort();\n }\n buffer_pool_.push(buffers[i]);\n }\n }\n buffer = buffer_pool_.top();\n buffer_pool_.pop();\n busy_buffers_.insert(buffer);\n }\n\n if (is_pool_empty) {\n // Free memory held by the array of buffer pointers returned by\n // AllocateUntrustedBuffers.\n Free(buffers);\n }\n return buffer;\n}", "project": "asylo", "hash": 242278763062410738405430919405598678850, "size": 31, "commit_id": "a47ef55db2337d29de19c50cd29b0deb2871d31c", "message": "Fix vulnerability in UntrustedCacheMalloc\n\nThe pointer array is stored in untrusted memory, so we cannot trust the\nvalue even after validation. We should validate the pointer is pointing\nto untrusted memory after it's stored inside the enclave.\n\nPiperOrigin-RevId: 358474391\nChange-Id: I63cf6c251bdaf1b491dbf06cc0dcf77f7b141756", "target": 1, "dataset": "other", "idx": 197832} {"func": "void *UntrustedCacheMalloc::GetBuffer() {\n void **buffers = nullptr;\n void *buffer;\n bool is_pool_empty;\n\n {\n LockGuard spin_lock(&lock_);\n is_pool_empty = buffer_pool_.empty();\n if (is_pool_empty) {\n buffers =\n primitives::AllocateUntrustedBuffers(kPoolIncrement, kPoolEntrySize);\n for (int i = 0; i < kPoolIncrement; i++) {\n void *buf = buffers[i];\n if (!buf || !TrustedPrimitives::IsOutsideEnclave(buf, kPoolEntrySize)) {\n TrustedPrimitives::BestEffortAbort(\n \"Cached buffer is not outside the enclave\");\n }\n buffer_pool_.push(buf);\n }\n }\n buffer = buffer_pool_.top();\n buffer_pool_.pop();\n busy_buffers_.insert(buffer);\n }\n\n if (is_pool_empty) {\n // Free memory held by the array of buffer pointers returned by\n // AllocateUntrustedBuffers.\n Free(buffers);\n }\n return buffer;\n}", "project": "asylo", "hash": 49646276951412525923922242548482096096, "size": 32, "commit_id": "a47ef55db2337d29de19c50cd29b0deb2871d31c", "message": "Fix vulnerability in UntrustedCacheMalloc\n\nThe pointer array is stored in untrusted memory, so we cannot trust the\nvalue even after validation. We should validate the pointer is pointing\nto untrusted memory after it's stored inside the enclave.\n\nPiperOrigin-RevId: 358474391\nChange-Id: I63cf6c251bdaf1b491dbf06cc0dcf77f7b141756", "target": 0, "dataset": "other", "idx": 264754} {"func": "ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)\n{\n UINT8 n;\n UINT8* ptr;\n\n if (strcmp(im->mode, \"1\") == 0 && state->xsize > state->bytes * 8) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n } else if (strcmp(im->mode, \"P\") == 0 && state->xsize > state->bytes) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n\n ptr = buf;\n\n for (;;) {\n\n\tif (bytes < 1)\n\t return ptr - buf;\n\n\tif ((*ptr & 0xC0) == 0xC0) {\n\n\t /* Run */\n\t if (bytes < 2)\n\t\treturn ptr - buf;\n\n\t n = ptr[0] & 0x3F;\n\n\t while (n > 0) {\n\t\tif (state->x >= state->bytes) {\n\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t break;\n\t\t}\n\t\tstate->buffer[state->x++] = ptr[1];\n\t\tn--;\n\t }\n\n\t ptr += 2; bytes -= 2;\n\n\t} else {\n\n\t /* Literal */\n\t state->buffer[state->x++] = ptr[0];\n\t ptr++; bytes--;\n\n\t}\n\n\tif (state->x >= state->bytes) {\n if (state->bytes % state->xsize && state->bytes > state->xsize) {\n int bands = state->bytes / state->xsize;\n int stride = state->bytes / bands;\n int i;\n for (i=1; i< bands; i++) { // note -- skipping first band\n memmove(&state->buffer[i*state->xsize],\n &state->buffer[i*stride],\n state->xsize);\n }\n }\n\t /* Got a full line, unpack it */\n\t state->shuffle((UINT8*) im->image[state->y + state->yoff] +\n\t\t\t state->xoff * im->pixelsize, state->buffer,\n\t\t\t state->xsize);\n\n\t state->x = 0;\n\n\t if (++state->y >= state->ysize) {\n\t\t/* End of file (errcode = 0) */\n\t\treturn -1;\n\t }\n\t}\n\n }\n}", "project": "Pillow", "hash": 91336361060317802518241506144190852925, "size": 73, "commit_id": "6a83e4324738bb0452fbe8074a995b1c73f08de7", "message": "Fix OOB Access on PcxDecode.c", "target": 1, "dataset": "other", "idx": 197848} {"func": "ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)\n{\n UINT8 n;\n UINT8* ptr;\n\n if ((state->xsize * state->bits + 7) / 8 > state->bytes) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n\n ptr = buf;\n\n for (;;) {\n\n\tif (bytes < 1)\n\t return ptr - buf;\n\n\tif ((*ptr & 0xC0) == 0xC0) {\n\n\t /* Run */\n\t if (bytes < 2)\n\t\treturn ptr - buf;\n\n\t n = ptr[0] & 0x3F;\n\n\t while (n > 0) {\n\t\tif (state->x >= state->bytes) {\n\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t break;\n\t\t}\n\t\tstate->buffer[state->x++] = ptr[1];\n\t\tn--;\n\t }\n\n\t ptr += 2; bytes -= 2;\n\n\t} else {\n\n\t /* Literal */\n\t state->buffer[state->x++] = ptr[0];\n\t ptr++; bytes--;\n\n\t}\n\n\tif (state->x >= state->bytes) {\n if (state->bytes % state->xsize && state->bytes > state->xsize) {\n int bands = state->bytes / state->xsize;\n int stride = state->bytes / bands;\n int i;\n for (i=1; i< bands; i++) { // note -- skipping first band\n memmove(&state->buffer[i*state->xsize],\n &state->buffer[i*stride],\n state->xsize);\n }\n }\n\t /* Got a full line, unpack it */\n\t state->shuffle((UINT8*) im->image[state->y + state->yoff] +\n\t\t\t state->xoff * im->pixelsize, state->buffer,\n\t\t\t state->xsize);\n\n\t state->x = 0;\n\n\t if (++state->y >= state->ysize) {\n\t\t/* End of file (errcode = 0) */\n\t\treturn -1;\n\t }\n\t}\n\n }\n}", "project": "Pillow", "hash": 222319329232490867971448493669699061015, "size": 70, "commit_id": "6a83e4324738bb0452fbe8074a995b1c73f08de7", "message": "Fix OOB Access on PcxDecode.c", "target": 0, "dataset": "other", "idx": 265040} {"func": "GF_Err Media_RewriteODFrame(GF_MediaBox *mdia, GF_ISOSample *sample)\n{\n\tGF_Err e;\n\tGF_ODCodec *ODdecode;\n\tGF_ODCodec *ODencode;\n\tGF_ODCom *com;\n\n\t//the commands we proceed\n\tGF_ESDUpdate *esdU, *esdU2;\n\tGF_ESDRemove *esdR, *esdR2;\n\tGF_ODUpdate *odU, *odU2;\n\n\t//the desc they contain\n\tGF_ObjectDescriptor *od;\n\tGF_IsomObjectDescriptor *isom_od;\n\tGF_ESD *esd;\n\tGF_ES_ID_Ref *ref;\n\tGF_Descriptor *desc;\n\tGF_TrackReferenceTypeBox *mpod;\n\tu32 i, j, skipped;\n\n\tif (!mdia || !sample || !sample->data || !sample->dataLength) return GF_BAD_PARAM;\n\n\tmpod = NULL;\n\te = Track_FindRef(mdia->mediaTrack, GF_ISOM_BOX_TYPE_MPOD, &mpod);\n\tif (e) return e;\n\t//no references, nothing to do...\n\tif (!mpod || !mpod->trackIDs) return GF_OK;\n\n\tODdecode = gf_odf_codec_new();\n\tif (!ODdecode) return GF_OUT_OF_MEM;\n\tODencode = gf_odf_codec_new();\n\tif (!ODencode) {\n\t\tgf_odf_codec_del(ODdecode);\n\t\treturn GF_OUT_OF_MEM;\n\t}\n\te = gf_odf_codec_set_au(ODdecode, sample->data, sample->dataLength);\n\tif (e) goto err_exit;\n\te = gf_odf_codec_decode(ODdecode);\n\tif (e) goto err_exit;\n\n\twhile (1) {\n\t\tcom = gf_odf_codec_get_com(ODdecode);\n\t\tif (!com) break;\n\n\t\t//we only need to rewrite commands with ESDs inside: ESDUpdate and ODUpdate\n\t\tswitch (com->tag) {\n\t\tcase GF_ODF_OD_UPDATE_TAG:\n\t\t\todU = (GF_ODUpdate *) com;\n\t\t\todU2 = (GF_ODUpdate *) gf_odf_com_new(GF_ODF_OD_UPDATE_TAG);\n\n\t\t\ti=0;\n\t\t\twhile ((desc = (GF_Descriptor*)gf_list_enum(odU->objectDescriptors, &i))) {\n\t\t\t\tswitch (desc->tag) {\n\t\t\t\tcase GF_ODF_OD_TAG:\n\t\t\t\tcase GF_ODF_ISOM_OD_TAG:\n\t\t\t\t//IOD can be used in OD streams\n\t\t\t\tcase GF_ODF_ISOM_IOD_TAG:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t\t}\n\t\t\t\te = gf_odf_desc_copy(desc, (GF_Descriptor **)&isom_od);\n\t\t\t\tif (e) goto err_exit;\n\n\t\t\t\t//create our OD...\n\t\t\t\tif (desc->tag == GF_ODF_ISOM_IOD_TAG) {\n\t\t\t\t\tod = (GF_ObjectDescriptor *) gf_malloc(sizeof(GF_InitialObjectDescriptor));\n\t\t\t\t} else {\n\t\t\t\t\tod = (GF_ObjectDescriptor *) gf_malloc(sizeof(GF_ObjectDescriptor));\n\t\t\t\t}\n\t\t\t\tif (!od) {\n\t\t\t\t\te = GF_OUT_OF_MEM;\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\tod->ESDescriptors = gf_list_new();\n\t\t\t\t//and duplicate...\n\t\t\t\tod->objectDescriptorID = isom_od->objectDescriptorID;\n\t\t\t\tod->tag = GF_ODF_OD_TAG;\n\t\t\t\tod->URLString = isom_od->URLString;\n\t\t\t\tisom_od->URLString = NULL;\n\t\t\t\tod->extensionDescriptors = isom_od->extensionDescriptors;\n\t\t\t\tisom_od->extensionDescriptors = NULL;\n\t\t\t\tod->IPMP_Descriptors = isom_od->IPMP_Descriptors;\n\t\t\t\tisom_od->IPMP_Descriptors = NULL;\n\t\t\t\tod->OCIDescriptors = isom_od->OCIDescriptors;\n\t\t\t\tisom_od->OCIDescriptors = NULL;\n\n\t\t\t\t//init as IOD\n\t\t\t\tif (isom_od->tag == GF_ODF_ISOM_IOD_TAG) {\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->audio_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->audio_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->inlineProfileFlag = ((GF_IsomInitialObjectDescriptor *)isom_od)->inlineProfileFlag;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->graphics_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->graphics_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->OD_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->OD_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->scene_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->scene_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->visual_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->visual_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->IPMPToolList = ((GF_IsomInitialObjectDescriptor *)isom_od)->IPMPToolList;\n\t\t\t\t\t((GF_IsomInitialObjectDescriptor *)isom_od)->IPMPToolList = NULL;\n\t\t\t\t}\n\n\t\t\t\t//then rewrite the ESDesc\n\t\t\t\tj=0;\n\t\t\t\twhile ((ref = (GF_ES_ID_Ref*)gf_list_enum(isom_od->ES_ID_RefDescriptors, &j))) {\n\t\t\t\t\t//if the ref index is not valid, skip this desc...\n\t\t\t\t\tif (!mpod->trackIDs || gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1]) == NULL) continue;\n\t\t\t\t\t//OK, get the esd\n\t\t\t\t\te = GetESDForTime(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1], sample->DTS, &esd);\n\t\t\t\t\tif (!e) e = gf_odf_desc_add_desc((GF_Descriptor *) od, (GF_Descriptor *) esd);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)od);\n\t\t\t\t\t\tgf_odf_com_del((GF_ODCom **)&odU2);\n\t\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)isom_od);\n\t\t\t\t\t\tgf_odf_com_del((GF_ODCom **)&odU);\n\t\t\t\t\t\tgoto err_exit;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\t//delete our desc\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)isom_od);\n\t\t\t\tgf_list_add(odU2->objectDescriptors, od);\n\t\t\t}\n\t\t\t//clean a bit\n\t\t\tgf_odf_com_del((GF_ODCom **)&odU);\n\t\t\tgf_odf_codec_add_com(ODencode, (GF_ODCom *)odU2);\n\t\t\tbreak;\n\n\t\tcase GF_ODF_ESD_UPDATE_TAG:\n\t\t\tesdU = (GF_ESDUpdate *) com;\n\t\t\tesdU2 = (GF_ESDUpdate *) gf_odf_com_new(GF_ODF_ESD_UPDATE_TAG);\n\t\t\tesdU2->ODID = esdU->ODID;\n\t\t\ti=0;\n\t\t\twhile ((ref = (GF_ES_ID_Ref*)gf_list_enum(esdU->ESDescriptors, &i))) {\n\t\t\t\t//if the ref index is not valid, skip this desc...\n\t\t\t\tif (gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1]) == NULL) continue;\n\t\t\t\t//OK, get the esd\n\t\t\t\te = GetESDForTime(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1], sample->DTS, &esd);\n\t\t\t\tif (e) goto err_exit;\n\t\t\t\tgf_list_add(esdU2->ESDescriptors, esd);\n\t\t\t}\n\t\t\tgf_odf_com_del((GF_ODCom **)&esdU);\n\t\t\tgf_odf_codec_add_com(ODencode, (GF_ODCom *)esdU2);\n\t\t\tbreak;\n\n\t\t//brand new case: the ESRemove follows the same principle according to the spec...\n\t\tcase GF_ODF_ESD_REMOVE_REF_TAG:\n\t\t\t//both commands have the same structure, only the tags change\n\t\t\tesdR = (GF_ESDRemove *) com;\n\t\t\tesdR2 = (GF_ESDRemove *) gf_odf_com_new(GF_ODF_ESD_REMOVE_TAG);\n\t\t\tesdR2->ODID = esdR->ODID;\n\t\t\tesdR2->NbESDs = esdR->NbESDs;\n\t\t\t//alloc our stuff\n\t\t\tesdR2->ES_ID = (unsigned short*)gf_malloc(sizeof(u32) * esdR->NbESDs);\n\t\t\tif (!esdR2->ES_ID) {\n\t\t\t\te = GF_OUT_OF_MEM;\n\t\t\t\tgoto err_exit;\n\t\t\t}\n\t\t\tskipped = 0;\n\t\t\t//get the ES_ID in the mpod indicated in the ES_ID[]\n\t\t\tfor (i = 0; i < esdR->NbESDs; i++) {\n\t\t\t\t//if the ref index is not valid, remove this desc...\n\t\t\t\tif (gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[esdR->ES_ID[i] - 1]) == NULL) {\n\t\t\t\t\tskipped ++;\n\t\t\t\t} else {\n\t\t\t\t\t//the command in the file has the ref index of the trackID in the mpod\n\t\t\t\t\tesdR2->ES_ID[i - skipped] = mpod->trackIDs[esdR->ES_ID[i] - 1];\n\t\t\t\t}\n\t\t\t}\n\t\t\t//gf_realloc...\n\t\t\tif (skipped && (skipped != esdR2->NbESDs) ) {\n\t\t\t\tesdR2->NbESDs -= skipped;\n\t\t\t\tesdR2->ES_ID = (unsigned short*)gf_realloc(esdR2->ES_ID, sizeof(u32) * esdR2->NbESDs);\n\t\t\t}\n\t\t\tgf_odf_com_del((GF_ODCom **)&esdR);\n\t\t\tgf_odf_codec_add_com(ODencode, (GF_ODCom *)esdR2);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\te = gf_odf_codec_add_com(ODencode, com);\n\t\t\tif (e) goto err_exit;\n\t\t}\n\t}\n\t//encode our new AU\n\te = gf_odf_codec_encode(ODencode, 1);\n\tif (e) goto err_exit;\n\n\t//and set the buffer in the sample\n\tgf_free(sample->data);\n\tsample->data = NULL;\n\tsample->dataLength = 0;\n\te = gf_odf_codec_get_au(ODencode, &sample->data, &sample->dataLength);\n\nerr_exit:\n\tgf_odf_codec_del(ODdecode);\n\tgf_odf_codec_del(ODencode);\n\treturn e;\n}", "project": "gpac", "hash": 257511211780956322541197733348730262940, "size": 196, "commit_id": "f0ba83717b6e4d7a15a1676d1fe06152e199b011", "message": "fixed #1772 (fuzz)", "target": 1, "dataset": "other", "idx": 197890} {"func": "GF_Err Media_RewriteODFrame(GF_MediaBox *mdia, GF_ISOSample *sample)\n{\n\tGF_Err e;\n\tGF_ODCodec *ODdecode;\n\tGF_ODCodec *ODencode;\n\tGF_ODCom *com;\n\n\t//the commands we proceed\n\tGF_ESDUpdate *esdU, *esdU2;\n\tGF_ESDRemove *esdR, *esdR2;\n\tGF_ODUpdate *odU, *odU2;\n\n\t//the desc they contain\n\tGF_ObjectDescriptor *od;\n\tGF_IsomObjectDescriptor *isom_od;\n\tGF_ESD *esd;\n\tGF_ES_ID_Ref *ref;\n\tGF_Descriptor *desc;\n\tGF_TrackReferenceTypeBox *mpod;\n\tu32 i, j, skipped;\n\n\tif (!mdia || !sample || !sample->data || !sample->dataLength) return GF_BAD_PARAM;\n\n\tmpod = NULL;\n\te = Track_FindRef(mdia->mediaTrack, GF_ISOM_BOX_TYPE_MPOD, &mpod);\n\tif (e) return e;\n\t//no references, nothing to do...\n\tif (!mpod || !mpod->trackIDs) return GF_OK;\n\n\tODdecode = gf_odf_codec_new();\n\tif (!ODdecode) return GF_OUT_OF_MEM;\n\tODencode = gf_odf_codec_new();\n\tif (!ODencode) {\n\t\tgf_odf_codec_del(ODdecode);\n\t\treturn GF_OUT_OF_MEM;\n\t}\n\te = gf_odf_codec_set_au(ODdecode, sample->data, sample->dataLength);\n\tif (e) goto err_exit;\n\te = gf_odf_codec_decode(ODdecode);\n\tif (e) goto err_exit;\n\n\twhile (1) {\n\t\tcom = gf_odf_codec_get_com(ODdecode);\n\t\tif (!com) break;\n\n\t\t//we only need to rewrite commands with ESDs inside: ESDUpdate and ODUpdate\n\t\tswitch (com->tag) {\n\t\tcase GF_ODF_OD_UPDATE_TAG:\n\t\t\todU = (GF_ODUpdate *) com;\n\t\t\todU2 = (GF_ODUpdate *) gf_odf_com_new(GF_ODF_OD_UPDATE_TAG);\n\n\t\t\ti=0;\n\t\t\twhile ((desc = (GF_Descriptor*)gf_list_enum(odU->objectDescriptors, &i))) {\n\t\t\t\tswitch (desc->tag) {\n\t\t\t\tcase GF_ODF_OD_TAG:\n\t\t\t\tcase GF_ODF_ISOM_OD_TAG:\n\t\t\t\t//IOD can be used in OD streams\n\t\t\t\tcase GF_ODF_ISOM_IOD_TAG:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t\t}\n\t\t\t\te = gf_odf_desc_copy(desc, (GF_Descriptor **)&isom_od);\n\t\t\t\tif (e) goto err_exit;\n\n\t\t\t\t//create our OD...\n\t\t\t\tif (desc->tag == GF_ODF_ISOM_IOD_TAG) {\n\t\t\t\t\tod = (GF_ObjectDescriptor *) gf_malloc(sizeof(GF_InitialObjectDescriptor));\n\t\t\t\t} else {\n\t\t\t\t\tod = (GF_ObjectDescriptor *) gf_malloc(sizeof(GF_ObjectDescriptor));\n\t\t\t\t}\n\t\t\t\tif (!od) {\n\t\t\t\t\te = GF_OUT_OF_MEM;\n\t\t\t\t\tgoto err_exit;\n\t\t\t\t}\n\t\t\t\tod->ESDescriptors = gf_list_new();\n\t\t\t\t//and duplicate...\n\t\t\t\tod->objectDescriptorID = isom_od->objectDescriptorID;\n\t\t\t\tod->tag = GF_ODF_OD_TAG;\n\t\t\t\tod->URLString = isom_od->URLString;\n\t\t\t\tisom_od->URLString = NULL;\n\t\t\t\tod->extensionDescriptors = isom_od->extensionDescriptors;\n\t\t\t\tisom_od->extensionDescriptors = NULL;\n\t\t\t\tod->IPMP_Descriptors = isom_od->IPMP_Descriptors;\n\t\t\t\tisom_od->IPMP_Descriptors = NULL;\n\t\t\t\tod->OCIDescriptors = isom_od->OCIDescriptors;\n\t\t\t\tisom_od->OCIDescriptors = NULL;\n\n\t\t\t\t//init as IOD\n\t\t\t\tif (isom_od->tag == GF_ODF_ISOM_IOD_TAG) {\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->audio_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->audio_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->inlineProfileFlag = ((GF_IsomInitialObjectDescriptor *)isom_od)->inlineProfileFlag;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->graphics_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->graphics_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->OD_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->OD_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->scene_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->scene_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->visual_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->visual_profileAndLevel;\n\t\t\t\t\t((GF_InitialObjectDescriptor *)od)->IPMPToolList = ((GF_IsomInitialObjectDescriptor *)isom_od)->IPMPToolList;\n\t\t\t\t\t((GF_IsomInitialObjectDescriptor *)isom_od)->IPMPToolList = NULL;\n\t\t\t\t}\n\n\t\t\t\t//then rewrite the ESDesc\n\t\t\t\tj=0;\n\t\t\t\twhile ((ref = (GF_ES_ID_Ref*)gf_list_enum(isom_od->ES_ID_RefDescriptors, &j))) {\n\t\t\t\t\tif (!mpod->trackIDs || !ref->trackRef || (ref->trackRef>mpod->trackIDCount)) continue;\n\t\t\t\t\t//if the ref index is not valid, skip this desc...\n\t\t\t\t\tif (gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1]) == NULL) continue;\n\t\t\t\t\t//OK, get the esd\n\t\t\t\t\te = GetESDForTime(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1], sample->DTS, &esd);\n\t\t\t\t\tif (!e) e = gf_odf_desc_add_desc((GF_Descriptor *) od, (GF_Descriptor *) esd);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)od);\n\t\t\t\t\t\tgf_odf_com_del((GF_ODCom **)&odU2);\n\t\t\t\t\t\tgf_odf_desc_del((GF_Descriptor *)isom_od);\n\t\t\t\t\t\tgf_odf_com_del((GF_ODCom **)&odU);\n\t\t\t\t\t\tgoto err_exit;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\t//delete our desc\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)isom_od);\n\t\t\t\tgf_list_add(odU2->objectDescriptors, od);\n\t\t\t}\n\t\t\t//clean a bit\n\t\t\tgf_odf_com_del((GF_ODCom **)&odU);\n\t\t\tgf_odf_codec_add_com(ODencode, (GF_ODCom *)odU2);\n\t\t\tbreak;\n\n\t\tcase GF_ODF_ESD_UPDATE_TAG:\n\t\t\tesdU = (GF_ESDUpdate *) com;\n\t\t\tesdU2 = (GF_ESDUpdate *) gf_odf_com_new(GF_ODF_ESD_UPDATE_TAG);\n\t\t\tesdU2->ODID = esdU->ODID;\n\t\t\ti=0;\n\t\t\twhile ((ref = (GF_ES_ID_Ref*)gf_list_enum(esdU->ESDescriptors, &i))) {\n\t\t\t\tif (!mpod->trackIDs || !ref->trackRef || (ref->trackRef>mpod->trackIDCount)) continue;\n\t\t\t\t//if the ref index is not valid, skip this desc...\n\t\t\t\tif (gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1]) == NULL) continue;\n\t\t\t\t//OK, get the esd\n\t\t\t\te = GetESDForTime(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1], sample->DTS, &esd);\n\t\t\t\tif (e) goto err_exit;\n\t\t\t\tgf_list_add(esdU2->ESDescriptors, esd);\n\t\t\t}\n\t\t\tgf_odf_com_del((GF_ODCom **)&esdU);\n\t\t\tgf_odf_codec_add_com(ODencode, (GF_ODCom *)esdU2);\n\t\t\tbreak;\n\n\t\t//brand new case: the ESRemove follows the same principle according to the spec...\n\t\tcase GF_ODF_ESD_REMOVE_REF_TAG:\n\t\t\t//both commands have the same structure, only the tags change\n\t\t\tesdR = (GF_ESDRemove *) com;\n\t\t\tesdR2 = (GF_ESDRemove *) gf_odf_com_new(GF_ODF_ESD_REMOVE_TAG);\n\t\t\tesdR2->ODID = esdR->ODID;\n\t\t\tesdR2->NbESDs = esdR->NbESDs;\n\t\t\t//alloc our stuff\n\t\t\tesdR2->ES_ID = (unsigned short*)gf_malloc(sizeof(u32) * esdR->NbESDs);\n\t\t\tif (!esdR2->ES_ID) {\n\t\t\t\te = GF_OUT_OF_MEM;\n\t\t\t\tgoto err_exit;\n\t\t\t}\n\t\t\tskipped = 0;\n\t\t\t//get the ES_ID in the mpod indicated in the ES_ID[]\n\t\t\tfor (i = 0; i < esdR->NbESDs; i++) {\n\t\t\t\tif (!mpod->trackIDs || !esdR->ES_ID[i] || (esdR->ES_ID[i]>mpod->trackIDCount)) continue;\n\t\t\t\t//if the ref index is not valid, remove this desc...\n\t\t\t\tif (gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[esdR->ES_ID[i] - 1]) == NULL) {\n\t\t\t\t\tskipped ++;\n\t\t\t\t} else {\n\t\t\t\t\t//the command in the file has the ref index of the trackID in the mpod\n\t\t\t\t\tesdR2->ES_ID[i - skipped] = mpod->trackIDs[esdR->ES_ID[i] - 1];\n\t\t\t\t}\n\t\t\t}\n\t\t\t//gf_realloc...\n\t\t\tif (skipped && (skipped != esdR2->NbESDs) ) {\n\t\t\t\tesdR2->NbESDs -= skipped;\n\t\t\t\tesdR2->ES_ID = (unsigned short*)gf_realloc(esdR2->ES_ID, sizeof(u32) * esdR2->NbESDs);\n\t\t\t}\n\t\t\tgf_odf_com_del((GF_ODCom **)&esdR);\n\t\t\tgf_odf_codec_add_com(ODencode, (GF_ODCom *)esdR2);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\te = gf_odf_codec_add_com(ODencode, com);\n\t\t\tif (e) goto err_exit;\n\t\t}\n\t}\n\t//encode our new AU\n\te = gf_odf_codec_encode(ODencode, 1);\n\tif (e) goto err_exit;\n\n\t//and set the buffer in the sample\n\tgf_free(sample->data);\n\tsample->data = NULL;\n\tsample->dataLength = 0;\n\te = gf_odf_codec_get_au(ODencode, &sample->data, &sample->dataLength);\n\nerr_exit:\n\tgf_odf_codec_del(ODdecode);\n\tgf_odf_codec_del(ODencode);\n\treturn e;\n}", "project": "gpac", "hash": 70307577295047254971344546776198646014, "size": 199, "commit_id": "f0ba83717b6e4d7a15a1676d1fe06152e199b011", "message": "fixed #1772 (fuzz)", "target": 0, "dataset": "other", "idx": 265416} {"func": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n // Retrieve tensors (All should be allocated by now)\n const TfLiteTensor* output_shape;\n TF_LITE_ENSURE_OK(\n context, GetInputSafe(context, node, kOutputShapeTensor, &output_shape));\n const TfLiteTensor* weights;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kWeightsTensor, &weights));\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kDataInputTensor, &input));\n const TfLiteTensor* bias =\n (NumInputs(node) == 4)\n ? GetOptionalInputTensor(context, node, kBiasTensor)\n : nullptr;\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n OpData* data = reinterpret_cast(node->user_data);\n TfLiteTensor* col2im = data->has_col2im\n ? GetTemporary(context, node, data->col2im_index)\n : nullptr;\n TfLiteTensor* transposed_weights =\n data->weights_are_transposed\n ? GetTemporary(context, node, data->transposed_weights_index)\n : nullptr;\n const auto* params =\n reinterpret_cast(node->builtin_data);\n\n // Resize any deferred dynamic tensors\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context, ResizeTensor(context, output_shape, output));\n }\n if (data->has_col2im && IsDynamicTensor(col2im)) {\n TF_LITE_ENSURE_OK(context, ResizeCol2ImTensor(context, output_shape,\n weights, input, col2im));\n }\n\n // Get height and width of the output image.\n const int width = SizeOfDimension(output, 2);\n const int height = SizeOfDimension(output, 1);\n const int filter_width = SizeOfDimension(weights, 2);\n const int filter_height = SizeOfDimension(weights, 1);\n\n int unused_output_height, unused_output_width;\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width, 1, 1, height, width,\n filter_height, filter_width, params->padding, &unused_output_height,\n &unused_output_width);\n\n // Currently support float32, uint8, int8, int16.\n switch (input->type) {\n case kTfLiteFloat32: {\n // Only for GenericOptimized path, we use transposed weights.\n if (data->weights_are_transposed) {\n if (!IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n }\n EvalFloat(context, params, data, input, weights, bias,\n transposed_weights, col2im, output);\n break;\n }\n case kTfLiteUInt8: {\n TfLiteTensor* scratch_buffer;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scratch_tensor_index,\n &scratch_buffer));\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed) {\n if (!IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n }\n EvalQuantized(context, params, data, input, weights,\n transposed_weights, bias, col2im, output,\n scratch_buffer);\n break;\n }\n case kTfLiteInt8: {\n TfLiteTensor* scratch_buffer;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scratch_tensor_index,\n &scratch_buffer));\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed && !IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n EvalQuantizedPerChannel(context, params, data, input,\n weights, transposed_weights, bias,\n col2im, output, scratch_buffer);\n break;\n }\n case kTfLiteInt16: {\n TfLiteTensor* scratch_buffer;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scratch_tensor_index,\n &scratch_buffer));\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed && !IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n EvalQuantizedPerChannel16x8(context, params, data, input, weights,\n transposed_weights, bias, col2im, output,\n scratch_buffer);\n break;\n }\n default:\n context->ReportError(context, \"Type '%s' is not currently supported.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n}", "project": "tensorflow", "hash": 290740829738125502038333394047295607616, "size": 123, "commit_id": "801c1c6be5324219689c98e1bd3e0ca365ee834d", "message": "Fix another division by 0 in TFLite\n\nPiperOrigin-RevId: 370800181\nChange-Id: I924809166a6131f5075e6d45c455106538d755f9", "target": 1, "dataset": "other", "idx": 197892} {"func": "TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n // Retrieve tensors (All should be allocated by now)\n const TfLiteTensor* output_shape;\n TF_LITE_ENSURE_OK(\n context, GetInputSafe(context, node, kOutputShapeTensor, &output_shape));\n const TfLiteTensor* weights;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kWeightsTensor, &weights));\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context,\n GetInputSafe(context, node, kDataInputTensor, &input));\n const TfLiteTensor* bias =\n (NumInputs(node) == 4)\n ? GetOptionalInputTensor(context, node, kBiasTensor)\n : nullptr;\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n OpData* data = reinterpret_cast(node->user_data);\n TfLiteTensor* col2im = data->has_col2im\n ? GetTemporary(context, node, data->col2im_index)\n : nullptr;\n TfLiteTensor* transposed_weights =\n data->weights_are_transposed\n ? GetTemporary(context, node, data->transposed_weights_index)\n : nullptr;\n const auto* params =\n reinterpret_cast(node->builtin_data);\n\n // Prevent divisions by 0\n TF_LITE_ENSURE(context, params->stride_height > 0);\n TF_LITE_ENSURE(context, params->stride_width > 0);\n\n // Resize any deferred dynamic tensors\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context, ResizeTensor(context, output_shape, output));\n }\n if (data->has_col2im && IsDynamicTensor(col2im)) {\n TF_LITE_ENSURE_OK(context, ResizeCol2ImTensor(context, output_shape,\n weights, input, col2im));\n }\n\n // Get height and width of the output image.\n const int width = SizeOfDimension(output, 2);\n const int height = SizeOfDimension(output, 1);\n const int filter_width = SizeOfDimension(weights, 2);\n const int filter_height = SizeOfDimension(weights, 1);\n\n int unused_output_height, unused_output_width;\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width, 1, 1, height, width,\n filter_height, filter_width, params->padding, &unused_output_height,\n &unused_output_width);\n\n // Currently support float32, uint8, int8, int16.\n switch (input->type) {\n case kTfLiteFloat32: {\n // Only for GenericOptimized path, we use transposed weights.\n if (data->weights_are_transposed) {\n if (!IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n }\n EvalFloat(context, params, data, input, weights, bias,\n transposed_weights, col2im, output);\n break;\n }\n case kTfLiteUInt8: {\n TfLiteTensor* scratch_buffer;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scratch_tensor_index,\n &scratch_buffer));\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed) {\n if (!IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n }\n EvalQuantized(context, params, data, input, weights,\n transposed_weights, bias, col2im, output,\n scratch_buffer);\n break;\n }\n case kTfLiteInt8: {\n TfLiteTensor* scratch_buffer;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scratch_tensor_index,\n &scratch_buffer));\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed && !IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n EvalQuantizedPerChannel(context, params, data, input,\n weights, transposed_weights, bias,\n col2im, output, scratch_buffer);\n break;\n }\n case kTfLiteInt16: {\n TfLiteTensor* scratch_buffer;\n TF_LITE_ENSURE_OK(\n context, GetTemporarySafe(context, node, data->scratch_tensor_index,\n &scratch_buffer));\n if (IsDynamicTensor(scratch_buffer)) {\n TF_LITE_ENSURE_OK(context,\n ResizeTensor(context, output_shape, scratch_buffer));\n }\n if (data->weights_are_transposed && !IsConstantTensor(weights)) {\n ResizeAndTransposeWeights(context, weights, transposed_weights);\n }\n EvalQuantizedPerChannel16x8(context, params, data, input, weights,\n transposed_weights, bias, col2im, output,\n scratch_buffer);\n break;\n }\n default:\n context->ReportError(context, \"Type '%s' is not currently supported.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n}", "project": "tensorflow", "hash": 66934807467757635082995213425103966019, "size": 127, "commit_id": "801c1c6be5324219689c98e1bd3e0ca365ee834d", "message": "Fix another division by 0 in TFLite\n\nPiperOrigin-RevId: 370800181\nChange-Id: I924809166a6131f5075e6d45c455106538d755f9", "target": 0, "dataset": "other", "idx": 265428} {"func": "int ecall_restore(const char *input, uint64_t input_len, char **output,\n uint64_t *output_len) {\n if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input,\n input_len) ||\n !asylo::primitives::TrustedPrimitives::IsOutsideEnclave(\n output_len, sizeof(uint64_t))) {\n asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"ecall_restore: input/output found to not be in untrusted memory.\");\n }\n int result = 0;\n size_t tmp_output_len;\n try {\n result = asylo::Restore(input, static_cast(input_len), output,\n &tmp_output_len);\n } catch (...) {\n LOG(FATAL) << \"Uncaught exception in enclave\";\n }\n\n if (output_len) {\n *output_len = static_cast(tmp_output_len);\n }\n return result;\n}", "project": "asylo", "hash": 104108689796384044909836162554974524043, "size": 23, "commit_id": "382da2b8b09cbf928668a2445efb778f76bd9c8a", "message": "Check output of ecall_restore is outside enclave\n\nPiperOrigin-RevId: 334265380\nChange-Id: Ifbaead6bce56f01b2a4d69f53ca508d0138f6f61", "target": 1, "dataset": "other", "idx": 197910} {"func": "int ecall_restore(const char *input, uint64_t input_len, char **output,\n uint64_t *output_len) {\n if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input,\n input_len) ||\n !asylo::primitives::TrustedPrimitives::IsOutsideEnclave(\n output_len, sizeof(uint64_t)) ||\n !asylo::primitives::TrustedPrimitives::IsOutsideEnclave(output,\n *output_len)) {\n asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"ecall_restore: input/output found to not be in untrusted memory.\");\n }\n int result = 0;\n size_t tmp_output_len;\n try {\n result = asylo::Restore(input, static_cast(input_len), output,\n &tmp_output_len);\n } catch (...) {\n LOG(FATAL) << \"Uncaught exception in enclave\";\n }\n\n if (output_len) {\n *output_len = static_cast(tmp_output_len);\n }\n return result;\n}", "project": "asylo", "hash": 330875018941072471989270103810819584619, "size": 25, "commit_id": "382da2b8b09cbf928668a2445efb778f76bd9c8a", "message": "Check output of ecall_restore is outside enclave\n\nPiperOrigin-RevId: 334265380\nChange-Id: Ifbaead6bce56f01b2a4d69f53ca508d0138f6f61", "target": 0, "dataset": "other", "idx": 265529} {"func": "CString CWebSock::GetSkinPath(const CString& sSkinName) {\n CString sRet = CZNC::Get().GetZNCPath() + \"/webskins/\" + sSkinName;\n\n if (!CFile::IsDir(sRet)) {\n sRet = CZNC::Get().GetCurPath() + \"/webskins/\" + sSkinName;\n\n if (!CFile::IsDir(sRet)) {\n sRet = CString(_SKINDIR_) + \"/\" + sSkinName;\n }\n }\n\n return sRet + \"/\";\n}", "project": "znc", "hash": 235465360297438929701123024752111071031, "size": 13, "commit_id": "a4a5aeeb17d32937d8c7d743dae9a4cc755ce773", "message": "Don't let web skin name ../../../../ access files outside of usual skins directories.\n\nThanks for Jeriko One for finding and reporting this.", "target": 1, "dataset": "other", "idx": 197927} {"func": "CString CWebSock::GetSkinPath(const CString& sSkinName) {\n const CString sSkin = sSkinName.Replace_n(\"/\", \"_\").Replace_n(\".\", \"_\");\n\n CString sRet = CZNC::Get().GetZNCPath() + \"/webskins/\" + sSkin;\n\n if (!CFile::IsDir(sRet)) {\n sRet = CZNC::Get().GetCurPath() + \"/webskins/\" + sSkin;\n\n if (!CFile::IsDir(sRet)) {\n sRet = CString(_SKINDIR_) + \"/\" + sSkin;\n }\n }\n\n return sRet + \"/\";\n}", "project": "znc", "hash": 9744272250058996937416307326980903460, "size": 15, "commit_id": "a4a5aeeb17d32937d8c7d743dae9a4cc755ce773", "message": "Don't let web skin name ../../../../ access files outside of usual skins directories.\n\nThanks for Jeriko One for finding and reporting this.", "target": 0, "dataset": "other", "idx": 265791} {"func": "GF_Err gf_isom_set_extraction_slc(GF_ISOFile *the_file, u32 trackNumber, u32 StreamDescriptionIndex, const GF_SLConfig *slConfig)\n{\n\tGF_TrackBox *trak;\n\tGF_SampleEntryBox *entry;\n\tGF_Err e;\n\tGF_SLConfig **slc;\n\n\ttrak = gf_isom_get_track_from_file(the_file, trackNumber);\n\tif (!trak) return GF_BAD_PARAM;\n\n\te = Media_GetSampleDesc(trak->Media, StreamDescriptionIndex, &entry, NULL);\n\tif (e) return e;\n\n\t//we must be sure we are not using a remote ESD\n\tswitch (entry->type) {\n\tcase GF_ISOM_BOX_TYPE_MP4S:\n\t\tif (((GF_MPEGSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM;\n\t\tslc = & ((GF_MPEGSampleEntryBox *)entry)->slc;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_MP4A:\n\t\tif (((GF_MPEGAudioSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM;\n\t\tslc = & ((GF_MPEGAudioSampleEntryBox *)entry)->slc;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_MP4V:\n\t\tif (((GF_MPEGVisualSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM;\n\t\tslc = & ((GF_MPEGVisualSampleEntryBox *)entry)->slc;\n\t\tbreak;\n\tdefault:\n\t\treturn GF_BAD_PARAM;\n\t}\n\n\tif (*slc) {\n\t\tgf_odf_desc_del((GF_Descriptor *)*slc);\n\t\t*slc = NULL;\n\t}\n\tif (!slConfig) return GF_OK;\n\t//finally duplicate the SL\n\treturn gf_odf_desc_copy((GF_Descriptor *) slConfig, (GF_Descriptor **) slc);\n}", "project": "gpac", "hash": 24076123659296712931521214875422093085, "size": 39, "commit_id": "ebfa346eff05049718f7b80041093b4c5581c24e", "message": "fixed #1706", "target": 1, "dataset": "other", "idx": 197972} {"func": "GF_Err gf_isom_get_extraction_slc(GF_ISOFile *the_file, u32 trackNumber, u32 StreamDescriptionIndex, GF_SLConfig **slConfig)\n{\n\tGF_TrackBox *trak;\n\tGF_SampleEntryBox *entry;\n\tGF_Err e;\n\tGF_SLConfig *slc;\n\n\ttrak = gf_isom_get_track_from_file(the_file, trackNumber);\n\tif (!trak) return GF_BAD_PARAM;\n\n\te = Media_GetSampleDesc(trak->Media, StreamDescriptionIndex, &entry, NULL);\n\tif (e) return e;\n\n\t//we must be sure we are not using a remote ESD\n\tslc = NULL;\n\t*slConfig = NULL;\n\tswitch (entry->type) {\n\tcase GF_ISOM_BOX_TYPE_MP4S:\n\t\tif (((GF_MPEGSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM;\n\t\tslc = ((GF_MPEGSampleEntryBox *)entry)->slc;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_MP4A:\n\t\tif (((GF_MPEGAudioSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM;\n\t\tslc = ((GF_MPEGAudioSampleEntryBox *)entry)->slc;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_MP4V:\n\t\tif (((GF_MPEGVisualSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM;\n\t\tslc = ((GF_MPEGVisualSampleEntryBox *)entry)->slc;\n\t\tbreak;\n\tdefault:\n\t\treturn GF_BAD_PARAM;\n\t}\n\n\tif (!slc) return GF_OK;\n\t//finally duplicate the SL\n\treturn gf_odf_desc_copy((GF_Descriptor *) slc, (GF_Descriptor **) slConfig);\n}", "project": "gpac", "hash": 72759115469568498014505720549617618583, "size": 37, "commit_id": "ebfa346eff05049718f7b80041093b4c5581c24e", "message": "fixed #1706", "target": 0, "dataset": "other", "idx": 267342} {"func": "inline size_t codepoint_length(const char *s8, size_t l) {\n if (l) {\n auto b = static_cast(s8[0]);\n if ((b & 0x80) == 0) {\n return 1;\n } else if ((b & 0xE0) == 0xC0) {\n return 2;\n } else if ((b & 0xF0) == 0xE0) {\n return 3;\n } else if ((b & 0xF8) == 0xF0) {\n return 4;\n }\n }\n return 0;\n}", "project": "cpp-peglib", "hash": 242224596264463421605909250265556736943, "size": 15, "commit_id": "b3b29ce8f3acf3a32733d930105a17d7b0ba347e", "message": "Fix #122", "target": 1, "dataset": "other", "idx": 197987} {"func": "inline size_t codepoint_length(const char *s8, size_t l) {\n if (l) {\n auto b = static_cast(s8[0]);\n if ((b & 0x80) == 0) {\n return 1;\n } else if ((b & 0xE0) == 0xC0 && l >= 2) {\n return 2;\n } else if ((b & 0xF0) == 0xE0 && l >= 3) {\n return 3;\n } else if ((b & 0xF8) == 0xF0 && l >= 4) {\n return 4;\n }\n }\n return 0;\n}", "project": "cpp-peglib", "hash": 173436653321319195624342406646839908574, "size": 15, "commit_id": "b3b29ce8f3acf3a32733d930105a17d7b0ba347e", "message": "Fix #122", "target": 0, "dataset": "other", "idx": 267830} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor* reverse_index_map_t;\n const Tensor* grad_values_t;\n OP_REQUIRES_OK(context,\n context->input(\"reverse_index_map\", &reverse_index_map_t));\n OP_REQUIRES_OK(context, context->input(\"grad_values\", &grad_values_t));\n\n const CPUDevice& d = context->eigen_device();\n\n OP_REQUIRES(\n context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()),\n errors::InvalidArgument(\"reverse_index_map must be a vector, saw: \",\n reverse_index_map_t->shape().DebugString()));\n\n const auto reverse_index_map = reverse_index_map_t->vec();\n const auto grad_values = grad_values_t->vec();\n\n const int64 N = reverse_index_map_t->shape().dim_size(0);\n const int64 N_full = grad_values_t->shape().dim_size(0);\n\n Tensor* d_values_t;\n OP_REQUIRES_OK(context, context->allocate_output(\n \"d_values\", TensorShape({N}), &d_values_t));\n auto d_values = d_values_t->vec();\n Tensor* d_default_value_t;\n OP_REQUIRES_OK(context,\n context->allocate_output(\"d_default_value\", TensorShape({}),\n &d_default_value_t));\n T& d_default_value = d_default_value_t->scalar()();\n d_default_value = T();\n\n Tensor visited_t;\n OP_REQUIRES_OK(context, context->allocate_temp(\n DT_BOOL, TensorShape({N_full}), &visited_t));\n auto visited = visited_t.vec();\n visited.device(d) = visited.constant(false);\n\n for (int i = 0; i < N; ++i) {\n // Locate the index of the output of the forward prop associated\n // with this location in the input of the forward prop. Copy\n // the gradient into it. Mark it as visited.\n d_values(i) = grad_values(reverse_index_map(i));\n visited(reverse_index_map(i)) = true;\n }\n for (int j = 0; j < N_full; ++j) {\n // The default value gradient gets the accumulated remainder of\n // the backprop values (since the default value was used to fill\n // in these slots in the forward calculation).\n if (!visited(j)) {\n d_default_value += grad_values(j);\n }\n }\n }", "project": "tensorflow", "hash": 241621722999531832605599622432512754717, "size": 53, "commit_id": "390611e0d45c5793c7066110af37c8514e6a6c54", "message": "Fix heap buffer overflow in `tf.raw_ops.SparseFillEmptyRowsGrad`.\n\nAlso add tests as they were lacking\n\nPiperOrigin-RevId: 332566071\nChange-Id: I44277578e26ff5fb3fdb0dcbba6e91b2ec3e7859", "target": 1, "dataset": "other", "idx": 197988} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor* reverse_index_map_t;\n const Tensor* grad_values_t;\n OP_REQUIRES_OK(context,\n context->input(\"reverse_index_map\", &reverse_index_map_t));\n OP_REQUIRES_OK(context, context->input(\"grad_values\", &grad_values_t));\n\n const CPUDevice& d = context->eigen_device();\n\n OP_REQUIRES(\n context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()),\n errors::InvalidArgument(\"reverse_index_map must be a vector, saw: \",\n reverse_index_map_t->shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(grad_values_t->shape()),\n errors::InvalidArgument(\"grad_values must be a vector, saw: \",\n grad_values_t->shape().DebugString()));\n\n const auto reverse_index_map = reverse_index_map_t->vec();\n const auto grad_values = grad_values_t->vec();\n\n const int64 N = reverse_index_map_t->shape().dim_size(0);\n const int64 N_full = grad_values_t->shape().dim_size(0);\n\n Tensor* d_values_t;\n OP_REQUIRES_OK(context, context->allocate_output(\n \"d_values\", TensorShape({N}), &d_values_t));\n auto d_values = d_values_t->vec();\n Tensor* d_default_value_t;\n OP_REQUIRES_OK(context,\n context->allocate_output(\"d_default_value\", TensorShape({}),\n &d_default_value_t));\n T& d_default_value = d_default_value_t->scalar()();\n d_default_value = T();\n\n Tensor visited_t;\n OP_REQUIRES_OK(context, context->allocate_temp(\n DT_BOOL, TensorShape({N_full}), &visited_t));\n auto visited = visited_t.vec();\n visited.device(d) = visited.constant(false);\n\n for (int i = 0; i < N; ++i) {\n // Locate the index of the output of the forward prop associated\n // with this location in the input of the forward prop. Copy\n // the gradient into it. Mark it as visited.\n int64 reverse_index = reverse_index_map(i);\n OP_REQUIRES(\n context, 0 <= reverse_index && reverse_index < N_full,\n errors::InvalidArgument(\"Elements in reverse index must be in [0, \",\n N_full, \") but got \", reverse_index));\n d_values(i) = grad_values(reverse_index);\n visited(reverse_index) = true;\n }\n for (int j = 0; j < N_full; ++j) {\n // The default value gradient gets the accumulated remainder of\n // the backprop values (since the default value was used to fill\n // in these slots in the forward calculation).\n if (!visited(j)) {\n d_default_value += grad_values(j);\n }\n }\n }", "project": "tensorflow", "hash": 220172366288150634974249956340400544400, "size": 61, "commit_id": "390611e0d45c5793c7066110af37c8514e6a6c54", "message": "Fix heap buffer overflow in `tf.raw_ops.SparseFillEmptyRowsGrad`.\n\nAlso add tests as they were lacking\n\nPiperOrigin-RevId: 332566071\nChange-Id: I44277578e26ff5fb3fdb0dcbba6e91b2ec3e7859", "target": 0, "dataset": "other", "idx": 267831} {"func": "GF_Err stbl_AppendSize(GF_SampleTableBox *stbl, u32 size, u32 nb_pack)\n{\n\tu32 i;\n\tif (!nb_pack) nb_pack = 1;\n\n\tif (!stbl->SampleSize->sampleCount) {\n\t\tstbl->SampleSize->sampleSize = size;\n\t\tstbl->SampleSize->sampleCount += nb_pack;\n\t\treturn GF_OK;\n\t}\n\tif (stbl->SampleSize->sampleSize && (stbl->SampleSize->sampleSize==size)) {\n\t\tstbl->SampleSize->sampleCount += nb_pack;\n\t\treturn GF_OK;\n\t}\n\tif (!stbl->SampleSize->sizes || (stbl->SampleSize->sampleCount+nb_pack > stbl->SampleSize->alloc_size)) {\n\t\tBool init_table = (stbl->SampleSize->sizes==NULL) ? 1 : 0;\n\t\tALLOC_INC(stbl->SampleSize->alloc_size);\n\t\tif (stbl->SampleSize->sampleCount+nb_pack > stbl->SampleSize->alloc_size)\n\t\t\tstbl->SampleSize->alloc_size = stbl->SampleSize->sampleCount+nb_pack;\n\n\t\tstbl->SampleSize->sizes = (u32 *)gf_realloc(stbl->SampleSize->sizes, sizeof(u32)*stbl->SampleSize->alloc_size);\n\t\tif (!stbl->SampleSize->sizes) return GF_OUT_OF_MEM;\n\t\tmemset(&stbl->SampleSize->sizes[stbl->SampleSize->sampleCount], 0, sizeof(u32) * (stbl->SampleSize->alloc_size - stbl->SampleSize->sampleCount) );\n\n\t\tif (init_table) {\n\t\t\tfor (i=0; iSampleSize->sampleCount; i++)\n\t\t\t\tstbl->SampleSize->sizes[i] = stbl->SampleSize->sampleSize;\n\t\t}\n\t}\n\tstbl->SampleSize->sampleSize = 0;\n\tfor (i=0; iSampleSize->sizes[stbl->SampleSize->sampleCount+i] = size;\n\t}\n\tstbl->SampleSize->sampleCount += nb_pack;\n\tif (size > stbl->SampleSize->max_size)\n\t\tstbl->SampleSize->max_size = size;\n\tstbl->SampleSize->total_size += size;\n\tstbl->SampleSize->total_samples += nb_pack;\n\treturn GF_OK;\n}", "project": "gpac", "hash": 40626517707074933311961960171654671734, "size": 40, "commit_id": "77ed81c069e10b3861d88f72e1c6be1277ee7eae", "message": "fixed #1774 (fuzz)", "target": 1, "dataset": "other", "idx": 197993} {"func": "GF_Err stbl_AppendSize(GF_SampleTableBox *stbl, u32 size, u32 nb_pack)\n{\n\tu32 i;\n\tCHECK_PACK(GF_ISOM_INVALID_FILE)\n\n\tif (!stbl->SampleSize->sampleCount) {\n\t\tstbl->SampleSize->sampleSize = size;\n\t\tstbl->SampleSize->sampleCount += nb_pack;\n\t\treturn GF_OK;\n\t}\n\tif (stbl->SampleSize->sampleSize && (stbl->SampleSize->sampleSize==size)) {\n\t\tstbl->SampleSize->sampleCount += nb_pack;\n\t\treturn GF_OK;\n\t}\n\n\tif (!stbl->SampleSize->sizes || (stbl->SampleSize->sampleCount+nb_pack > stbl->SampleSize->alloc_size)) {\n\t\tBool init_table = (stbl->SampleSize->sizes==NULL) ? 1 : 0;\n\t\tALLOC_INC(stbl->SampleSize->alloc_size);\n\t\tif (stbl->SampleSize->sampleCount+nb_pack > stbl->SampleSize->alloc_size) {\n\t\t\tstbl->SampleSize->alloc_size = stbl->SampleSize->sampleCount+nb_pack;\n\t\t}\n\n\t\tstbl->SampleSize->sizes = (u32 *)gf_realloc(stbl->SampleSize->sizes, sizeof(u32)*stbl->SampleSize->alloc_size);\n\t\tif (!stbl->SampleSize->sizes) return GF_OUT_OF_MEM;\n\t\tmemset(&stbl->SampleSize->sizes[stbl->SampleSize->sampleCount], 0, sizeof(u32) * (stbl->SampleSize->alloc_size - stbl->SampleSize->sampleCount) );\n\n\t\tif (init_table) {\n\t\t\tfor (i=0; iSampleSize->sampleCount; i++)\n\t\t\t\tstbl->SampleSize->sizes[i] = stbl->SampleSize->sampleSize;\n\t\t}\n\t}\n\tstbl->SampleSize->sampleSize = 0;\n\tfor (i=0; iSampleSize->sizes[stbl->SampleSize->sampleCount+i] = size;\n\t}\n\tstbl->SampleSize->sampleCount += nb_pack;\n\tif (size > stbl->SampleSize->max_size)\n\t\tstbl->SampleSize->max_size = size;\n\tstbl->SampleSize->total_size += size;\n\tstbl->SampleSize->total_samples += nb_pack;\n\treturn GF_OK;\n}", "project": "gpac", "hash": 253799151103891324267945073818521020976, "size": 42, "commit_id": "77ed81c069e10b3861d88f72e1c6be1277ee7eae", "message": "fixed #1774 (fuzz)", "target": 0, "dataset": "other", "idx": 267899} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& x = context->input(0);\n const Tensor& y = context->input(1);\n const float min_x = context->input(2).flat()(0);\n const float max_x = context->input(3).flat()(0);\n const float min_y = context->input(4).flat()(0);\n const float max_y = context->input(5).flat()(0);\n\n BCast bcast(BCast::FromShape(x.shape()), BCast::FromShape(y.shape()));\n if (!bcast.IsValid()) {\n context->SetStatus(errors::InvalidArgument(\n \"Incompatible shapes: \", x.shape().DebugString(), \" vs. \",\n y.shape().DebugString()));\n return;\n }\n Tensor* z;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0, BCast::ToShape(bcast.output_shape()), &z));\n\n // Make sure that we have valid quantization ranges for the input buffers.\n // If the difference between the min and max is negative or zero, it makes\n // it hard to do meaningful intermediate operations on the values.\n OP_REQUIRES(context, (max_x > min_x),\n errors::InvalidArgument(\"max_x must be larger than min_x.\"));\n OP_REQUIRES(context, (max_y > min_y),\n errors::InvalidArgument(\"max_y must be larger than min_y.\"));\n const T* x_data = x.flat().data();\n const T* y_data = y.flat().data();\n Toutput* z_data = z->flat().data();\n\n // We want the range of the output to be symmetrical around zero so that\n // adding zero leaves the result unchanged, and to contain the largest of\n // the two input values with some room to spare.\n const float smallest_min = std::min(min_x, min_y);\n const float largest_max = std::max(max_x, max_y);\n const float biggest_range =\n std::max(std::abs(smallest_min), std::abs(largest_max));\n const float output_range = (biggest_range * (1 << 14));\n const float min_z_value = -output_range;\n const float max_z_value = output_range;\n\n const int ndims = bcast.x_reshape().size();\n if (ndims <= 1) {\n if (x.NumElements() == 1) {\n ScalarAddition(context, y_data, min_y, max_y,\n y.NumElements(), x_data[0], min_x, max_x,\n min_z_value, max_z_value, z_data);\n } else if (y.NumElements() == 1) {\n ScalarAddition(context, x_data, min_x, max_x,\n x.NumElements(), y_data[0], min_y, max_y,\n min_z_value, max_z_value, z_data);\n } else {\n VectorAddition(context, x_data, min_x, max_x, y_data, min_y,\n max_y, x.NumElements(), min_z_value,\n max_z_value, z_data);\n }\n } else if (ndims == 2) {\n const T* vector_data;\n int64 vector_num_elements;\n float vector_min;\n float vector_max;\n const T* tensor_data;\n int64 tensor_num_elements;\n float tensor_min;\n float tensor_max;\n if (x.NumElements() < y.NumElements()) {\n vector_data = x_data;\n vector_num_elements = x.NumElements();\n vector_min = min_x;\n vector_max = max_x;\n tensor_data = y_data;\n tensor_num_elements = y.NumElements();\n tensor_min = min_y;\n tensor_max = max_y;\n } else {\n vector_data = y_data;\n vector_num_elements = y.NumElements();\n vector_min = min_y;\n vector_max = max_y;\n tensor_data = x_data;\n tensor_num_elements = x.NumElements();\n tensor_min = min_x;\n tensor_max = max_x;\n }\n VectorTensorAddition(\n vector_data, vector_min, vector_max, vector_num_elements, tensor_data,\n tensor_min, tensor_max, tensor_num_elements, min_z_value, max_z_value,\n z_data);\n } else {\n LOG(INFO) << \"ndims=\" << ndims;\n LOG(INFO) << \"bcast.x_reshape()=\"\n << TensorShape(bcast.x_reshape()).DebugString();\n LOG(INFO) << \"bcast.y_reshape()=\"\n << TensorShape(bcast.y_reshape()).DebugString();\n LOG(INFO) << \"bcast.x_bcast()=\"\n << TensorShape(bcast.x_bcast()).DebugString();\n LOG(INFO) << \"bcast.y_bcast()=\"\n << TensorShape(bcast.y_bcast()).DebugString();\n\n context->SetStatus(errors::Unimplemented(\n \"Broadcast between \", context->input(0).shape().DebugString(),\n \" and \", context->input(1).shape().DebugString(),\n \" is not supported yet.\"));\n return;\n }\n\n Tensor* z_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &z_min));\n z_min->flat()(0) = min_z_value;\n\n Tensor* z_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &z_max));\n z_max->flat()(0) = max_z_value;\n }", "project": "tensorflow", "hash": 33107701774077650282967373677576892726, "size": 114, "commit_id": "744009c9e5cc5d0447f0dc39d055f917e1fd9e16", "message": "Validate work in `QuantizedAdd`, ensure at least one element.\n\nPiperOrigin-RevId: 370127996\nChange-Id: I57c6f3e01afdeada84737820a131590137463855", "target": 1, "dataset": "other", "idx": 198002} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& x = context->input(0);\n const Tensor& y = context->input(1);\n const float min_x = context->input(2).flat()(0);\n const float max_x = context->input(3).flat()(0);\n const float min_y = context->input(4).flat()(0);\n const float max_y = context->input(5).flat()(0);\n\n BCast bcast(BCast::FromShape(x.shape()), BCast::FromShape(y.shape()));\n if (!bcast.IsValid()) {\n context->SetStatus(errors::InvalidArgument(\n \"Incompatible shapes: \", x.shape().DebugString(), \" vs. \",\n y.shape().DebugString()));\n return;\n }\n Tensor* z;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0, BCast::ToShape(bcast.output_shape()), &z));\n\n // Make sure that we have valid quantization ranges for the input buffers.\n // If the difference between the min and max is negative or zero, it makes\n // it hard to do meaningful intermediate operations on the values.\n OP_REQUIRES(context, (max_x > min_x),\n errors::InvalidArgument(\"max_x must be larger than min_x.\"));\n OP_REQUIRES(context, (max_y > min_y),\n errors::InvalidArgument(\"max_y must be larger than min_y.\"));\n const T* x_data = x.flat().data();\n const T* y_data = y.flat().data();\n Toutput* z_data = z->flat().data();\n\n // We want the range of the output to be symmetrical around zero so that\n // adding zero leaves the result unchanged, and to contain the largest of\n // the two input values with some room to spare.\n const float smallest_min = std::min(min_x, min_y);\n const float largest_max = std::max(max_x, max_y);\n const float biggest_range =\n std::max(std::abs(smallest_min), std::abs(largest_max));\n const float output_range = (biggest_range * (1 << 14));\n const float min_z_value = -output_range;\n const float max_z_value = output_range;\n\n const int ndims = bcast.x_reshape().size();\n if (ndims <= 1) {\n if (x.NumElements() == 1) {\n ScalarAddition(context, y_data, min_y, max_y,\n y.NumElements(), x_data[0], min_x, max_x,\n min_z_value, max_z_value, z_data);\n } else if (y.NumElements() == 1) {\n ScalarAddition(context, x_data, min_x, max_x,\n x.NumElements(), y_data[0], min_y, max_y,\n min_z_value, max_z_value, z_data);\n } else {\n VectorAddition(context, x_data, min_x, max_x, y_data, min_y,\n max_y, x.NumElements(), min_z_value,\n max_z_value, z_data);\n }\n } else if (ndims == 2) {\n const T* vector_data;\n int64 vector_num_elements;\n float vector_min;\n float vector_max;\n const T* tensor_data;\n int64 tensor_num_elements;\n float tensor_min;\n float tensor_max;\n if (x.NumElements() < y.NumElements()) {\n vector_data = x_data;\n vector_num_elements = x.NumElements();\n vector_min = min_x;\n vector_max = max_x;\n tensor_data = y_data;\n tensor_num_elements = y.NumElements();\n tensor_min = min_y;\n tensor_max = max_y;\n } else {\n vector_data = y_data;\n vector_num_elements = y.NumElements();\n vector_min = min_y;\n vector_max = max_y;\n tensor_data = x_data;\n tensor_num_elements = x.NumElements();\n tensor_min = min_x;\n tensor_max = max_x;\n }\n OP_REQUIRES(context, vector_num_elements > 0,\n errors::InvalidArgument(\"Must have some elements to add\"));\n VectorTensorAddition(\n vector_data, vector_min, vector_max, vector_num_elements, tensor_data,\n tensor_min, tensor_max, tensor_num_elements, min_z_value, max_z_value,\n z_data);\n } else {\n LOG(INFO) << \"ndims=\" << ndims;\n LOG(INFO) << \"bcast.x_reshape()=\"\n << TensorShape(bcast.x_reshape()).DebugString();\n LOG(INFO) << \"bcast.y_reshape()=\"\n << TensorShape(bcast.y_reshape()).DebugString();\n LOG(INFO) << \"bcast.x_bcast()=\"\n << TensorShape(bcast.x_bcast()).DebugString();\n LOG(INFO) << \"bcast.y_bcast()=\"\n << TensorShape(bcast.y_bcast()).DebugString();\n\n context->SetStatus(errors::Unimplemented(\n \"Broadcast between \", context->input(0).shape().DebugString(),\n \" and \", context->input(1).shape().DebugString(),\n \" is not supported yet.\"));\n return;\n }\n\n Tensor* z_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &z_min));\n z_min->flat()(0) = min_z_value;\n\n Tensor* z_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &z_max));\n z_max->flat()(0) = max_z_value;\n }", "project": "tensorflow", "hash": 315245398897635072708517159831180331701, "size": 116, "commit_id": "744009c9e5cc5d0447f0dc39d055f917e1fd9e16", "message": "Validate work in `QuantizedAdd`, ensure at least one element.\n\nPiperOrigin-RevId: 370127996\nChange-Id: I57c6f3e01afdeada84737820a131590137463855", "target": 0, "dataset": "other", "idx": 267926} {"func": "void OneHotComputeImpl(const OneHotContext& op_context) {\n // prefix_dim_size == # of elements before the axis\n // depth == # of elements per axis\n // suffix_dim_size == # of elements after the axis\n int prefix_dim_size = 1;\n for (int i = 0; i < op_context.axis; ++i) {\n prefix_dim_size *= op_context.indices->dims->data[i];\n }\n const int suffix_dim_size = NumElements(op_context.indices) / prefix_dim_size;\n const int depth = *op_context.depth->data.i32;\n\n const T on_value = *GetTensorData(op_context.on_value);\n const T off_value = *GetTensorData(op_context.off_value);\n\n // View the indices as a matrix of size:\n // prefix_dim_size x suffix_dim_size\n // View the output as a matrix of size:\n // prefix_dim_size x depth x suffix_dim_size\n // Then the output is:\n // output(i, j, k) == (indices(i, k) == j) ? on : off\n T* output = GetTensorData(op_context.output);\n const TI* indices = GetTensorData(op_context.indices);\n for (int i = 0; i < prefix_dim_size; ++i) {\n for (int j = 0; j < depth; ++j) {\n for (int k = 0; k < suffix_dim_size; ++k, ++output) {\n *output = static_cast(indices[i * suffix_dim_size + k]) == j\n ? on_value\n : off_value;\n }\n }\n }\n}", "project": "tensorflow", "hash": 227621958541673910375815913303164077833, "size": 32, "commit_id": "3ebedd7e345453d68e279cfc3e4072648e5e12e5", "message": "Prevent division by 0 in OneHot implementation\n\nIf input indices is degenerate, the implementation would do a divide by zero. See https://github.com/tensorflow/tensorflow/blob/745d57df6d5e9bc568666a2a48ed8dd629c27241/tensorflow/lite/kernels/one_hot.cc#L68-L72\n\nPiperOrigin-RevId: 370966870\nChange-Id: Ie018337811c8016b5a1d3a277d00d5f2e19a2058", "target": 1, "dataset": "other", "idx": 198007} {"func": "void OneHotComputeImpl(const OneHotContext& op_context) {\n // prefix_dim_size == # of elements before the axis\n // depth == # of elements per axis\n // suffix_dim_size == # of elements after the axis\n int prefix_dim_size = 1;\n for (int i = 0; i < op_context.axis; ++i) {\n prefix_dim_size *= op_context.indices->dims->data[i];\n }\n if (prefix_dim_size == 0) {\n // If indices tensor is degenerate, return a degenerate tensor, just like\n // TensorFlow does.\n return;\n }\n const int suffix_dim_size = NumElements(op_context.indices) / prefix_dim_size;\n const int depth = *op_context.depth->data.i32;\n\n const T on_value = *GetTensorData(op_context.on_value);\n const T off_value = *GetTensorData(op_context.off_value);\n\n // View the indices as a matrix of size:\n // prefix_dim_size x suffix_dim_size\n // View the output as a matrix of size:\n // prefix_dim_size x depth x suffix_dim_size\n // Then the output is:\n // output(i, j, k) == (indices(i, k) == j) ? on : off\n T* output = GetTensorData(op_context.output);\n const TI* indices = GetTensorData(op_context.indices);\n for (int i = 0; i < prefix_dim_size; ++i) {\n for (int j = 0; j < depth; ++j) {\n for (int k = 0; k < suffix_dim_size; ++k, ++output) {\n *output = static_cast(indices[i * suffix_dim_size + k]) == j\n ? on_value\n : off_value;\n }\n }\n }\n}", "project": "tensorflow", "hash": 254202826454691860542754520195247330043, "size": 37, "commit_id": "3ebedd7e345453d68e279cfc3e4072648e5e12e5", "message": "Prevent division by 0 in OneHot implementation\n\nIf input indices is degenerate, the implementation would do a divide by zero. See https://github.com/tensorflow/tensorflow/blob/745d57df6d5e9bc568666a2a48ed8dd629c27241/tensorflow/lite/kernels/one_hot.cc#L68-L72\n\nPiperOrigin-RevId: 370966870\nChange-Id: Ie018337811c8016b5a1d3a277d00d5f2e19a2058", "target": 0, "dataset": "other", "idx": 267934} {"func": " void Compute(OpKernelContext* context) override {\n const int64 axis_input = context->input(0).scalar()();\n const Tensor& input_indices = context->input(1);\n const Tensor& input_values = context->input(2);\n const Tensor& input_shape = context->input(3);\n\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices.shape()),\n errors::InvalidArgument(\n \"Input indices should be a matrix but received shape \",\n input_indices.shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values.shape()),\n errors::InvalidArgument(\n \"Input values should be a vector but received shape \",\n input_indices.shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape.shape()),\n errors::InvalidArgument(\n \"Input shape should be a vector but received shape \",\n input_shape.shape().DebugString()));\n\n const int64 input_rank = input_shape.vec().size();\n const int64 axis = (axis_input < 0) ? input_rank + axis_input : axis_input;\n\n OP_REQUIRES(\n context, axis >= 0 && axis < input_rank,\n errors::InvalidArgument(\"Input axis should be in range [\", -input_rank,\n \", \", input_rank, \"), got \", axis_input));\n\n OP_REQUIRES(context,\n num_split_ >= 1 && num_split_ <= input_shape.vec()(axis),\n errors::InvalidArgument(\"Input num_split should be between 1 \"\n \"and the splitting dimension size (\",\n input_shape.vec()(axis),\n \"), got \", num_split_));\n\n sparse::SparseTensor sparse_tensor;\n OP_REQUIRES_OK(context,\n sparse::SparseTensor::Create(\n input_indices, input_values,\n TensorShape(input_shape.vec()), &sparse_tensor));\n\n std::vector outputs;\n OP_REQUIRES_OK(context, sparse::SparseTensor::Split(\n sparse_tensor, axis, num_split_, &outputs));\n\n for (int slice_index = 0; slice_index < num_split_; ++slice_index) {\n context->set_output(slice_index, outputs[slice_index].indices());\n context->set_output(slice_index + num_split_,\n outputs[slice_index].values());\n Tensor* shape = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\n slice_index + 2 * num_split_,\n {outputs[slice_index].dims()}, &shape));\n auto output_shape = outputs[slice_index].shape();\n for (int dim = 0; dim < outputs[slice_index].dims(); ++dim) {\n shape->vec()(dim) = output_shape[dim];\n }\n }\n }", "project": "tensorflow", "hash": 117534156949568730230637035600140974853, "size": 58, "commit_id": "4c0ee937c0f61c4fc5f5d32d9bb4c67428012a60", "message": "Prevent overflow in sparse op\n\nPiperOrigin-RevId: 372442006\nChange-Id: I60fe31cd7e56fb3501e97c63500caf902ddeee96", "target": 1, "dataset": "other", "idx": 198015} {"func": " void Compute(OpKernelContext* context) override {\n const int64 axis_input = context->input(0).scalar()();\n const Tensor& input_indices = context->input(1);\n const Tensor& input_values = context->input(2);\n const Tensor& input_shape = context->input(3);\n\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices.shape()),\n errors::InvalidArgument(\n \"Input indices should be a matrix but received shape \",\n input_indices.shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values.shape()),\n errors::InvalidArgument(\n \"Input values should be a vector but received shape \",\n input_indices.shape().DebugString()));\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape.shape()),\n errors::InvalidArgument(\n \"Input shape should be a vector but received shape \",\n input_shape.shape().DebugString()));\n\n const int64 input_rank = input_shape.vec().size();\n const int64 axis = (axis_input < 0) ? input_rank + axis_input : axis_input;\n\n OP_REQUIRES(\n context, axis >= 0 && axis < input_rank,\n errors::InvalidArgument(\"Input axis should be in range [\", -input_rank,\n \", \", input_rank, \"), got \", axis_input));\n\n OP_REQUIRES(context,\n num_split_ >= 1 && num_split_ <= input_shape.vec()(axis),\n errors::InvalidArgument(\"Input num_split should be between 1 \"\n \"and the splitting dimension size (\",\n input_shape.vec()(axis),\n \"), got \", num_split_));\n\n // Prevent overflow by constructing the dense shape separately\n TensorShape dense_shape;\n const auto input_shape_flat = input_shape.flat();\n for (int i = 0; i < input_shape.NumElements(); i++) {\n OP_REQUIRES_OK(context,\n dense_shape.AddDimWithStatus(input_shape_flat(i)));\n }\n\n sparse::SparseTensor sparse_tensor;\n OP_REQUIRES_OK(context,\n sparse::SparseTensor::Create(input_indices, input_values,\n dense_shape, &sparse_tensor));\n\n std::vector outputs;\n OP_REQUIRES_OK(context, sparse::SparseTensor::Split(\n sparse_tensor, axis, num_split_, &outputs));\n\n for (int slice_index = 0; slice_index < num_split_; ++slice_index) {\n context->set_output(slice_index, outputs[slice_index].indices());\n context->set_output(slice_index + num_split_,\n outputs[slice_index].values());\n Tensor* shape = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(\n slice_index + 2 * num_split_,\n {outputs[slice_index].dims()}, &shape));\n auto output_shape = outputs[slice_index].shape();\n for (int dim = 0; dim < outputs[slice_index].dims(); ++dim) {\n shape->vec()(dim) = output_shape[dim];\n }\n }\n }", "project": "tensorflow", "hash": 197793840772920757051167476588018697571, "size": 65, "commit_id": "4c0ee937c0f61c4fc5f5d32d9bb4c67428012a60", "message": "Prevent overflow in sparse op\n\nPiperOrigin-RevId: 372442006\nChange-Id: I60fe31cd7e56fb3501e97c63500caf902ddeee96", "target": 0, "dataset": "other", "idx": 268106} {"func": "GF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth)\n{\n\tu32 i, sceneT, odT, descIndex, size, size64;\n\tGF_InitialObjectDescriptor *iod;\n\tGF_SLConfig slc;\n\tGF_ISOSample *samp;\n\tBool remove_ocr;\n\tu8 *buffer;\n\tchar buf64[5000], sdpLine[5100];\n\n\n\tgf_isom_sdp_clean(file);\n\n\tif (bandwidth) {\n\t\tsprintf(buf64, \"b=AS:%d\", bandwidth);\n\t\tgf_isom_sdp_add_line(file, buf64);\n\t}\n //xtended attribute for copyright\n if (gf_sys_is_test_mode()) {\n sprintf(buf64, \"a=x-copyright: %s\", \"MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)\");\n } else {\n sprintf(buf64, \"a=x-copyright: MP4/3GP File hinted with GPAC %s - %s\", gf_gpac_version(), gf_gpac_copyright() );\n }\n\tgf_isom_sdp_add_line(file, buf64);\n\n\tif (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK;\n\n\todT = sceneT = 0;\n\tfor (i=0; iESDescriptors)) {\n\t\t\tesd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0);\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t\tgf_list_rem(iod->ESDescriptors, 0);\n\t\t}\n\n\n\t\t/*get OD esd, and embbed stream data if possible*/\n\t\tif (odT) {\n\t\t\tesd = gf_isom_get_esd(file, odT, 1);\n\t\t\tif (gf_isom_get_sample_count(file, odT)==1) {\n\t\t\t\tsamp = gf_isom_get_sample(file, odT, 1, &descIndex);\n\t\t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) {\n\t\t\t\t\tInitSL_NULL(&slc);\n\t\t\t\t\tslc.predefined = 0;\n\t\t\t\t\tslc.hasRandomAccessUnitsOnlyFlag = 1;\n\t\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT);\n\t\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t\t//set the SL for future extraction\n\t\t\t\t\tgf_isom_set_extraction_slc(file, odT, 1, &slc);\n\n\t\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\t\tbuf64[size64] = 0;\n\t\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-od-au;base64,%s\", buf64);\n\n\t\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\t\tsize64 = (u32) strlen(sdpLine)+1;\n\t\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * size64);\n\t\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t\t} else {\n\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_RTP, (\"[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\t\tis_ok = 0;\n\t\t\t\t}\n\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t}\n\t\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\t\t//OK, add this to our IOD\n\t\t\tgf_list_add(iod->ESDescriptors, esd);\n\t\t}\n\n\t\tesd = gf_isom_get_esd(file, sceneT, 1);\n\t\tif (gf_isom_get_sample_count(file, sceneT)==1) {\n\t\t\tsamp = gf_isom_get_sample(file, sceneT, 1, &descIndex);\n\t\t\tif (gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) {\n\n\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT);\n\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t//set the SL for future extraction\n\t\t\t\tgf_isom_set_extraction_slc(file, sceneT, 1, &slc);\n\t\t\t\t//encode in Base64 the sample\n\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\tbuf64[size64] = 0;\n\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-bifs-au;base64,%s\", buf64);\n\n\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1));\n\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\tis_ok = 0;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\tgf_list_add(iod->ESDescriptors, esd);\n\n\t\tif (is_ok) {\n\t\t\tu32 has_a, has_v, has_i_a, has_i_v;\n\t\t\thas_a = has_v = has_i_a = has_i_v = 0;\n\t\t\tfor (i=0; idecoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++;\n\t\t\t\t\telse has_v++;\n\t\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++;\n\t\t\t\t\telse has_a++;\n\t\t\t\t}\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)esd);\n\t\t\t}\n\t\t\t/*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/\n\t\t\tif (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) {\n\t\t\t\tsprintf(sdpLine, \"a=isma-compliance:1,1.0,1\");\n\t\t\t\tgf_isom_sdp_add_line(file, sdpLine);\n\t\t\t}\n\t\t}\n\t}\n\n\t//encode the IOD\n\tbuffer = NULL;\n\tsize = 0;\n\tgf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size);\n\tgf_odf_desc_del((GF_Descriptor *)iod);\n\n\t//encode in Base64 the iod\n\tsize64 = gf_base64_encode(buffer, size, buf64, 2000);\n\tbuf64[size64] = 0;\n\tgf_free(buffer);\n\n\tsprintf(sdpLine, \"a=mpeg4-iod:\\\"data:application/mpeg4-iod;base64,%s\\\"\", buf64);\n\tgf_isom_sdp_add_line(file, sdpLine);\n\n\treturn GF_OK;\n}", "project": "gpac", "hash": 223649118603140396935168133970864337311, "size": 173, "commit_id": "1653f31cf874eb6df964bea88d58d8e9b98b485e", "message": "fixed #1770 (fuzz)", "target": 1, "dataset": "other", "idx": 198018} {"func": "GF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth)\n{\n\tu32 i, sceneT, odT, descIndex, size, size64;\n\tGF_InitialObjectDescriptor *iod;\n\tGF_SLConfig slc;\n\tGF_ISOSample *samp;\n\tBool remove_ocr;\n\tu8 *buffer;\n\tchar buf64[5000], sdpLine[5100];\n\n\n\tgf_isom_sdp_clean(file);\n\n\tif (bandwidth) {\n\t\tsprintf(buf64, \"b=AS:%d\", bandwidth);\n\t\tgf_isom_sdp_add_line(file, buf64);\n\t}\n //xtended attribute for copyright\n if (gf_sys_is_test_mode()) {\n sprintf(buf64, \"a=x-copyright: %s\", \"MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)\");\n } else {\n sprintf(buf64, \"a=x-copyright: MP4/3GP File hinted with GPAC %s - %s\", gf_gpac_version(), gf_gpac_copyright() );\n }\n\tgf_isom_sdp_add_line(file, buf64);\n\n\tif (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK;\n\n\todT = sceneT = 0;\n\tfor (i=0; iESDescriptors)) {\n\t\t\tesd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0);\n\t\t\tgf_odf_desc_del((GF_Descriptor *) esd);\n\t\t\tgf_list_rem(iod->ESDescriptors, 0);\n\t\t}\n\n\n\t\t/*get OD esd, and embbed stream data if possible*/\n\t\tif (odT) {\n\t\t\tesd = gf_isom_get_esd(file, odT, 1);\n\t\t\tif (gf_isom_get_sample_count(file, odT)==1) {\n\t\t\t\tsamp = gf_isom_get_sample(file, odT, 1, &descIndex);\n\t\t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) {\n\t\t\t\t\tInitSL_NULL(&slc);\n\t\t\t\t\tslc.predefined = 0;\n\t\t\t\t\tslc.hasRandomAccessUnitsOnlyFlag = 1;\n\t\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT);\n\t\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t\t//set the SL for future extraction\n\t\t\t\t\tgf_isom_set_extraction_slc(file, odT, 1, &slc);\n\n\t\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\t\tbuf64[size64] = 0;\n\t\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-od-au;base64,%s\", buf64);\n\n\t\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\t\tsize64 = (u32) strlen(sdpLine)+1;\n\t\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * size64);\n\t\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t\t} else {\n\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_RTP, (\"[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\t\tis_ok = 0;\n\t\t\t\t}\n\t\t\t\tgf_isom_sample_del(&samp);\n\t\t\t}\n\t\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\t\t//OK, add this to our IOD\n\t\t\tgf_list_add(iod->ESDescriptors, esd);\n\t\t}\n\n\t\tesd = gf_isom_get_esd(file, sceneT, 1);\n\t\tif (gf_isom_get_sample_count(file, sceneT)==1) {\n\t\t\tsamp = gf_isom_get_sample(file, sceneT, 1, &descIndex);\n\t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) {\n\n\t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT);\n\t\t\t\tslc.OCRResolution = 1000;\n\t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;\n\t\t\t\tslc.startDTS = samp->DTS;\n\t\t\t\t//set the SL for future extraction\n\t\t\t\tgf_isom_set_extraction_slc(file, sceneT, 1, &slc);\n\t\t\t\t//encode in Base64 the sample\n\t\t\t\tsize64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000);\n\t\t\t\tbuf64[size64] = 0;\n\t\t\t\tsprintf(sdpLine, \"data:application/mpeg4-bifs-au;base64,%s\", buf64);\n\n\t\t\t\tesd->decoderConfig->avgBitrate = 0;\n\t\t\t\tesd->decoderConfig->bufferSizeDB = samp->dataLength;\n\t\t\t\tesd->decoderConfig->maxBitrate = 0;\n\t\t\t\tesd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1));\n\t\t\t\tstrcpy(esd->URLString, sdpLine);\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (\"[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\\n\"));\n\t\t\t\tis_ok = 0;\n\t\t\t}\n\t\t\tgf_isom_sample_del(&samp);\n\t\t}\n\t\tif (remove_ocr) esd->OCRESID = 0;\n\t\telse if (esd->OCRESID == esd->ESID) esd->OCRESID = 0;\n\n\t\tgf_list_add(iod->ESDescriptors, esd);\n\n\t\tif (is_ok) {\n\t\t\tu32 has_a, has_v, has_i_a, has_i_v;\n\t\t\thas_a = has_v = has_i_a = has_i_v = 0;\n\t\t\tfor (i=0; idecoderConfig->streamType==GF_STREAM_VISUAL) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++;\n\t\t\t\t\telse has_v++;\n\t\t\t\t} else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) {\n\t\t\t\t\tif (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++;\n\t\t\t\t\telse has_a++;\n\t\t\t\t}\n\t\t\t\tgf_odf_desc_del((GF_Descriptor *)esd);\n\t\t\t}\n\t\t\t/*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/\n\t\t\tif (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) {\n\t\t\t\tsprintf(sdpLine, \"a=isma-compliance:1,1.0,1\");\n\t\t\t\tgf_isom_sdp_add_line(file, sdpLine);\n\t\t\t}\n\t\t}\n\t}\n\n\t//encode the IOD\n\tbuffer = NULL;\n\tsize = 0;\n\tgf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size);\n\tgf_odf_desc_del((GF_Descriptor *)iod);\n\n\t//encode in Base64 the iod\n\tsize64 = gf_base64_encode(buffer, size, buf64, 2000);\n\tbuf64[size64] = 0;\n\tgf_free(buffer);\n\n\tsprintf(sdpLine, \"a=mpeg4-iod:\\\"data:application/mpeg4-iod;base64,%s\\\"\", buf64);\n\tgf_isom_sdp_add_line(file, sdpLine);\n\n\treturn GF_OK;\n}", "project": "gpac", "hash": 130544004901735494505112604949465488922, "size": 173, "commit_id": "1653f31cf874eb6df964bea88d58d8e9b98b485e", "message": "fixed #1770 (fuzz)", "target": 0, "dataset": "other", "idx": 268147} {"func": "Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst,\n int input_index) {\n DataType src_out = src->output_type(output_index);\n DataType dst_in = dst->input_type(input_index);\n if (!TypesCompatible(dst_in, src_out)) {\n return errors::InvalidArgument(\n \"Input \", input_index, \" of node \", dst->name(), \" was passed \",\n DataTypeString(src_out), \" from \", src->name(), \":\", output_index,\n \" incompatible with expected \", DataTypeString(dst_in), \".\");\n }\n g_->AddEdge(src, output_index, dst, input_index);\n return Status::OK();\n}", "project": "tensorflow", "hash": 119805169193765224854689007636694320603, "size": 13, "commit_id": "0cc38aaa4064fd9e79101994ce9872c6d91f816b", "message": "Prevent unitialized memory access in `GraphConstructor::MakeEdge`\n\nThe `MakeEdge` implementation assumes that there exists an output at `output_index` of `src` node and an input at `input_index` of `dst` node. However, if this is not the case this results in accessing data out of bounds. Because we are accessing an array that is a private member of a class and only in read only mode, this usually results only in unitialized memory access. However, it is reasonable to think that malicious users could manipulate these indexes to actually read data outside the class, thus resulting in information leakage and further exploits.\n\nPiperOrigin-RevId: 346343288\nChange-Id: I2127da27c2023d27f26efd39afa6c853385cab6f", "target": 1, "dataset": "other", "idx": 198049} {"func": "Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst,\n int input_index) {\n if (output_index >= src->num_outputs()) {\n return errors::InvalidArgument(\n \"Output \", output_index, \" of node \", src->name(),\n \" does not exist. Node only has \", src->num_outputs(), \" outputs.\");\n }\n if (input_index >= dst->num_inputs()) {\n return errors::InvalidArgument(\n \"Input \", input_index, \" of node \", dst->name(),\n \" does not exist. Node only has \", dst->num_inputs(), \" inputs.\");\n }\n\n DataType src_out = src->output_type(output_index);\n DataType dst_in = dst->input_type(input_index);\n if (!TypesCompatible(dst_in, src_out)) {\n return errors::InvalidArgument(\n \"Input \", input_index, \" of node \", dst->name(), \" was passed \",\n DataTypeString(src_out), \" from \", src->name(), \":\", output_index,\n \" incompatible with expected \", DataTypeString(dst_in), \".\");\n }\n g_->AddEdge(src, output_index, dst, input_index);\n return Status::OK();\n}", "project": "tensorflow", "hash": 213211601759384738680783148753824892622, "size": 24, "commit_id": "0cc38aaa4064fd9e79101994ce9872c6d91f816b", "message": "Prevent unitialized memory access in `GraphConstructor::MakeEdge`\n\nThe `MakeEdge` implementation assumes that there exists an output at `output_index` of `src` node and an input at `input_index` of `dst` node. However, if this is not the case this results in accessing data out of bounds. Because we are accessing an array that is a private member of a class and only in read only mode, this usually results only in unitialized memory access. However, it is reasonable to think that malicious users could manipulate these indexes to actually read data outside the class, thus resulting in information leakage and further exploits.\n\nPiperOrigin-RevId: 346343288\nChange-Id: I2127da27c2023d27f26efd39afa6c853385cab6f", "target": 0, "dataset": "other", "idx": 268323} {"func": "static int download(struct SPDBDownloader *pd) {\n\tSPDBDownloaderOpt *opt = pd->opt;\n\tchar *curl_cmd = NULL;\n\tchar *extractor_cmd = NULL;\n\tchar *abspath_to_archive = NULL;\n\tchar *abspath_to_file = NULL;\n\tchar *archive_name = NULL;\n\tsize_t archive_name_len = 0;\n\tchar *symbol_store_path = NULL;\n\tchar *dbg_file = NULL;\n\tchar *guid = NULL;\n\tchar *archive_name_escaped = NULL;\n\tchar *user_agent = NULL;\n\tchar *symbol_server = NULL;\n\n\tint res = 0;\n\tint cmd_ret;\n\tif (!opt->dbg_file || !*opt->dbg_file) {\n\t\t// no pdb debug file\n\t\treturn 0;\n\t}\n\tif (!checkCurl ()) {\n\t\treturn 0;\n\t}\n\t// dbg_file len is > 0\n\tarchive_name_len = strlen (opt->dbg_file);\n\tarchive_name = malloc (archive_name_len + 1);\n\tif (!archive_name) {\n\t\treturn 0;\n\t}\n\tmemcpy (archive_name, opt->dbg_file, archive_name_len + 1);\n\tarchive_name[archive_name_len - 1] = '_';\n\tsymbol_store_path = r_str_escape (opt->symbol_store_path);\n\tdbg_file = r_str_escape (opt->dbg_file);\n\tguid = r_str_escape (opt->guid);\n\tarchive_name_escaped = r_str_escape (archive_name);\n\tuser_agent = r_str_escape (opt->user_agent);\n\tsymbol_server = r_str_escape (opt->symbol_server);\n\n\tabspath_to_archive = r_str_newf (\"%s%s%s%s%s%s%s\",\n\t\t\t symbol_store_path, R_SYS_DIR,\n\t\t\t dbg_file, R_SYS_DIR,\n\t\t\t guid, R_SYS_DIR,\n\t\t\t archive_name_escaped);\n\n\tabspath_to_file = strdup (abspath_to_archive);\n\tabspath_to_file[strlen (abspath_to_file) - 1] = 'b';\n\tif (r_file_exists (abspath_to_file)) {\n\t\teprintf (\"File already downloaded.\\n\");\n\t\tR_FREE (user_agent);\n\t\tR_FREE (abspath_to_archive);\n\t\tR_FREE (archive_name_escaped);\n\t\tR_FREE (symbol_store_path);\n\t\tR_FREE (dbg_file);\n\t\tR_FREE (guid);\n\t\tR_FREE (archive_name);\n\t\tR_FREE (abspath_to_file);\n\t\tR_FREE (symbol_server);\n\t\treturn 1;\n\t}\n\n\tif (checkExtract () || opt->extract == 0) {\n\t\tres = 1;\n\n\t\tcurl_cmd = r_str_newf (\"curl -sfLA \\\"%s\\\" \\\"%s/%s/%s/%s\\\" --create-dirs -o \\\"%s\\\"\",\n\t\t user_agent,\n\t\t symbol_server,\n\t\t\t\t\t\t\t dbg_file,\n\t\t\t\t\t\t\t guid,\n\t\t archive_name_escaped,\n\t\t abspath_to_archive);\n#if __WINDOWS__\n\t\tconst char *cabextractor = \"expand\";\n\t\tconst char *format = \"%s %s %s\";\n\n\t\t// extractor_cmd -> %1 %2 %3\n\t\t// %1 - 'expand'\n\t\t// %2 - absolute path to archive\n\t\t// %3 - absolute path to file that will be dearchive\n\t\textractor_cmd = r_str_newf (format, cabextractor,\n\t\t\tabspath_to_archive, abspath_to_file);\n#else\n\t\tconst char *cabextractor = \"cabextract\";\n\t\tconst char *format = \"%s -d \\\"%s\\\" \\\"%s\\\"\";\n\t\tchar *abspath_to_dir = r_file_dirname (abspath_to_archive);\n\t\t// cabextract -d %1 %2\n\t\t// %1 - path to directory where to extract all files from cab archive\n\t\t// %2 - absolute path to cab archive\n\t\textractor_cmd = r_str_newf (format, cabextractor, abspath_to_dir, abspath_to_archive);\n\t\tR_FREE (abspath_to_dir);\n#endif\n\t\teprintf (\"Attempting to download compressed pdb in %s\\n\", abspath_to_archive);\n\t\tif ((cmd_ret = r_sys_cmd (curl_cmd) != 0)) {\n\t\t\teprintf(\"curl exited with error %d\\n\", cmd_ret);\n\t\t\tres = 0;\n\t\t}\n\t\teprintf (\"Attempting to decompress pdb\\n\");\n\t\tif (opt->extract > 0) {\n\t\t\tif (res && ((cmd_ret = r_sys_cmd (extractor_cmd)) != 0)) {\n\t\t\t\teprintf (\"cab extractor exited with error %d\\n\", cmd_ret);\n\t\t\t\tres = 0;\n\t\t\t}\n\t\t\tr_file_rm (abspath_to_archive);\n\t\t}\n\t\tR_FREE (curl_cmd);\n\t}\n\tif (res == 0) {\n\t\teprintf (\"Falling back to uncompressed pdb\\n\");\n\t\tres = 1;\n\n\t\tarchive_name_escaped[strlen (archive_name_escaped) - 1] = 'b';\n\n\t\tcurl_cmd = r_str_newf (\"curl -sfLA \\\"%s\\\" \\\"%s/%s/%s/%s\\\" --create-dirs -o \\\"%s\\\"\",\n\t\t opt->user_agent,\n\t\t opt->symbol_server,\n\t\t opt->dbg_file,\n\t\t opt->guid,\n\t\t archive_name_escaped,\n\t\t abspath_to_file);\n\t\teprintf (\"Attempting to download uncompressed pdb in %s\\n\", abspath_to_file);\n\t\tif ((cmd_ret = r_sys_cmd (curl_cmd) != 0)) {\n\t\t\teprintf(\"curl exited with error %d\\n\", cmd_ret);\n\t\t\tres = 0;\n\t\t}\n\t\tR_FREE (curl_cmd);\n\t}\n\tR_FREE (abspath_to_archive);\n\tR_FREE (abspath_to_file);\n\tR_FREE (archive_name);\n\tR_FREE (extractor_cmd);\n\tR_FREE (symbol_store_path);\n\tR_FREE (dbg_file);\n\tR_FREE (guid);\n\tR_FREE (archive_name_escaped);\n\tR_FREE (user_agent);\n\tR_FREE (symbol_server);\n\treturn res;\n}", "project": "radare2", "hash": 235350912544331798088834006772646860216, "size": 138, "commit_id": "04edfa82c1f3fa2bc3621ccdad2f93bdbf00e4f9", "message": "Fix command injection on PDB download (#16966)\n\n* Fix r_sys_mkdirp with absolute path on Windows\r\n* Fix build with --with-openssl\r\n* Use RBuffer in r_socket_http_answer()\r\n* r_socket_http_answer: Fix read for big responses\r\n* Implement r_str_escape_sh()\r\n* Cleanup r_socket_connect() on Windows\r\n* Fix socket being created without a protocol\r\n* Fix socket connect with SSL ##socket\r\n* Use select() in r_socket_ready()\r\n* Fix read failing if received only protocol answer\r\n* Fix double-free\r\n* r_socket_http_get: Fail if req. SSL with no support\r\n* Follow redirects in r_socket_http_answer()\r\n* Fix r_socket_http_get result length with R2_CURL=1\r\n* Also follow redirects\r\n* Avoid using curl for downloading PDBs\r\n* Use r_socket_http_get() on UNIXs\r\n* Use WinINet API on Windows for r_socket_http_get()\r\n* Fix command injection\r\n* Fix r_sys_cmd_str_full output for binary data\r\n* Validate GUID on PDB download\r\n* Pass depth to socket_http_get_recursive()\r\n* Remove 'r_' and '__' from static function names\r\n* Fix is_valid_guid\r\n* Fix for comments", "target": 1, "dataset": "other", "idx": 198095} {"func": "static int download(struct SPDBDownloader *pd) {\n\tSPDBDownloaderOpt *opt = pd->opt;\n\tint res = 0;\n\tint cmd_ret;\n\n\tif (!opt->dbg_file || !*opt->dbg_file) {\n\t\t// no pdb debug file\n\t\treturn 0;\n\t}\n\n\tchar *abspath_to_file = r_str_newf (\"%s%s%s%s%s%s%s\",\n\t\topt->symbol_store_path, R_SYS_DIR,\n\t\topt->dbg_file, R_SYS_DIR,\n\t\topt->guid, R_SYS_DIR,\n\t\topt->dbg_file);\n\n\tif (r_file_exists (abspath_to_file)) {\n\t\teprintf (\"File already downloaded.\\n\");\n\t\tfree (abspath_to_file);\n\t\treturn 1;\n\t}\n\n\tif (checkExtract () || opt->extract == 0) {\n\t\tchar *extractor_cmd = NULL;\n\t\tchar *archive_name = strdup (opt->dbg_file);\n\t\tarchive_name[strlen (archive_name) - 1] = '_';\n\t\tchar *abspath_to_archive = r_str_newf (\"%s%s%s%s%s%s%s\",\n\t\t\topt->symbol_store_path, R_SYS_DIR,\n\t\t\topt->dbg_file, R_SYS_DIR,\n\t\t\topt->guid, R_SYS_DIR,\n\t\t\tarchive_name);\n\n\t\teprintf (\"Attempting to download compressed pdb in %s\\n\", abspath_to_archive);\n\t\tchar *abs_arch_esc = r_str_escape_sh (abspath_to_archive);\n#if __WINDOWS__\n\t\tchar *abs_file_esc = r_str_escape_sh (abspath_to_file);\n\t\t// expand %1 %2\n\t\t// %1 - absolute path to archive\n\t\t// %2 - absolute path to file that will be dearchive\n\t\textractor_cmd = r_str_newf (\"expand \\\"%s\\\" \\\"%s\\\"\", abs_arch_esc, abs_file_esc);\n\t\tfree (abs_file_esc);\n#else\n\t\tchar *abspath_to_dir = r_file_dirname (abspath_to_archive);\n\t\tchar *abs_dir_esc = r_str_escape_sh (abspath_to_dir);\n\t\t// cabextract -d %1 %2\n\t\t// %1 - path to directory where to extract all files from cab archive\n\t\t// %2 - absolute path to cab archive\n\t\textractor_cmd = r_str_newf (\"cabextract -d \\\"%s\\\" \\\"%s\\\"\", abs_arch_esc, abs_dir_esc);\n\t\tfree (abs_dir_esc);\n\t\tfree (abspath_to_dir);\n#endif\n\t\tfree (abs_arch_esc);\n\t\tres = download_and_write (opt, archive_name);\n\n\t\tif (opt->extract > 0 && res) {\n\t\t\teprintf (\"Attempting to decompress pdb\\n\");\n\t\t\tif (res && ((cmd_ret = r_sys_cmd (extractor_cmd)) != 0)) {\n\t\t\t\teprintf (\"cab extractor exited with error %d\\n\", cmd_ret);\n\t\t\t\tres = 0;\n\t\t\t}\n\t\t\tr_file_rm (abspath_to_archive);\n\t\t}\n\t\tfree (archive_name);\n\t\tfree (abspath_to_archive);\n\t}\n\tif (res == 0) {\n\t\teprintf (\"Falling back to uncompressed pdb\\n\");\n\t\teprintf (\"Attempting to download uncompressed pdb in %s\\n\", abspath_to_file);\n\t\tres = download_and_write (opt, opt->dbg_file);\n\t}\n\tfree (abspath_to_file);\n\treturn res;\n}", "project": "radare2", "hash": 284642675192813296779193504141476552469, "size": 73, "commit_id": "04edfa82c1f3fa2bc3621ccdad2f93bdbf00e4f9", "message": "Fix command injection on PDB download (#16966)\n\n* Fix r_sys_mkdirp with absolute path on Windows\r\n* Fix build with --with-openssl\r\n* Use RBuffer in r_socket_http_answer()\r\n* r_socket_http_answer: Fix read for big responses\r\n* Implement r_str_escape_sh()\r\n* Cleanup r_socket_connect() on Windows\r\n* Fix socket being created without a protocol\r\n* Fix socket connect with SSL ##socket\r\n* Use select() in r_socket_ready()\r\n* Fix read failing if received only protocol answer\r\n* Fix double-free\r\n* r_socket_http_get: Fail if req. SSL with no support\r\n* Follow redirects in r_socket_http_answer()\r\n* Fix r_socket_http_get result length with R2_CURL=1\r\n* Also follow redirects\r\n* Avoid using curl for downloading PDBs\r\n* Use r_socket_http_get() on UNIXs\r\n* Use WinINet API on Windows for r_socket_http_get()\r\n* Fix command injection\r\n* Fix r_sys_cmd_str_full output for binary data\r\n* Validate GUID on PDB download\r\n* Pass depth to socket_http_get_recursive()\r\n* Remove 'r_' and '__' from static function names\r\n* Fix is_valid_guid\r\n* Fix for comments", "target": 0, "dataset": "other", "idx": 268829} {"func": "service_info *FindServiceEventURLPath(\n\tservice_table *table, const char *eventURLPath)\n{\n\tservice_info *finger = NULL;\n\turi_type parsed_url;\n\turi_type parsed_url_in;\n\n\tif (table &&\n\t\tparse_uri(eventURLPath, strlen(eventURLPath), &parsed_url_in) ==\n\t\t\tHTTP_SUCCESS) {\n\t\tfinger = table->serviceList;\n\t\twhile (finger) {\n\t\t\tif (finger->eventURL) {\n\t\t\t\tif (parse_uri(finger->eventURL,\n\t\t\t\t\t strlen(finger->eventURL),\n\t\t\t\t\t &parsed_url) == HTTP_SUCCESS) {\n\t\t\t\t\tif (!token_cmp(&parsed_url.pathquery,\n\t\t\t\t\t\t &parsed_url_in.pathquery)) {\n\t\t\t\t\t\treturn finger;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinger = finger->next;\n\t\t}\n\t}\n\n\treturn NULL;\n}", "project": "pupnp", "hash": 48140258843428848992487276517349841836, "size": 28, "commit_id": "c805c1de1141cb22f74c0d94dd5664bda37398e0", "message": "Fixes #177: NULL pointer dereference in FindServiceControlURLPath\n\nAlso fixes its dual bug in FindServiceEventURLPath.", "target": 1, "dataset": "other", "idx": 198108} {"func": "service_info *FindServiceEventURLPath(\n\tservice_table *table, const char *eventURLPath)\n{\n\tservice_info *finger = NULL;\n\turi_type parsed_url;\n\turi_type parsed_url_in;\n\n\tif (!table || !eventURLPath) {\n\t\treturn NULL;\n\t}\n\tif (parse_uri(eventURLPath, strlen(eventURLPath), &parsed_url_in) ==\n\t\tHTTP_SUCCESS) {\n\t\tfinger = table->serviceList;\n\t\twhile (finger) {\n\t\t\tif (finger->eventURL) {\n\t\t\t\tif (parse_uri(finger->eventURL,\n\t\t\t\t\t strlen(finger->eventURL),\n\t\t\t\t\t &parsed_url) == HTTP_SUCCESS) {\n\t\t\t\t\tif (!token_cmp(&parsed_url.pathquery,\n\t\t\t\t\t\t &parsed_url_in.pathquery)) {\n\t\t\t\t\t\treturn finger;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinger = finger->next;\n\t\t}\n\t}\n\n\treturn NULL;\n}", "project": "pupnp", "hash": 36856745095971474562957251675118738361, "size": 30, "commit_id": "c805c1de1141cb22f74c0d94dd5664bda37398e0", "message": "Fixes #177: NULL pointer dereference in FindServiceControlURLPath\n\nAlso fixes its dual bug in FindServiceEventURLPath.", "target": 0, "dataset": "other", "idx": 269104} {"func": "service_info *FindServiceControlURLPath(\n\tservice_table *table, const char *controlURLPath)\n{\n\tservice_info *finger = NULL;\n\turi_type parsed_url;\n\turi_type parsed_url_in;\n\n\tif (table && parse_uri(controlURLPath,\n\t\t\t strlen(controlURLPath),\n\t\t\t &parsed_url_in) == HTTP_SUCCESS) {\n\t\tfinger = table->serviceList;\n\t\twhile (finger) {\n\t\t\tif (finger->controlURL) {\n\t\t\t\tif (parse_uri(finger->controlURL,\n\t\t\t\t\t strlen(finger->controlURL),\n\t\t\t\t\t &parsed_url) == HTTP_SUCCESS) {\n\t\t\t\t\tif (!token_cmp(&parsed_url.pathquery,\n\t\t\t\t\t\t &parsed_url_in.pathquery)) {\n\t\t\t\t\t\treturn finger;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinger = finger->next;\n\t\t}\n\t}\n\n\treturn NULL;\n}", "project": "pupnp", "hash": 143022199409412141809012906075259083414, "size": 28, "commit_id": "c805c1de1141cb22f74c0d94dd5664bda37398e0", "message": "Fixes #177: NULL pointer dereference in FindServiceControlURLPath\n\nAlso fixes its dual bug in FindServiceEventURLPath.", "target": 1, "dataset": "other", "idx": 198109} {"func": "service_info *FindServiceControlURLPath(\n\tservice_table *table, const char *controlURLPath)\n{\n\tservice_info *finger = NULL;\n\turi_type parsed_url;\n\turi_type parsed_url_in;\n\n\tif (!table || !controlURLPath) {\n\t\treturn NULL;\n\t}\n\tif (parse_uri(controlURLPath, strlen(controlURLPath), &parsed_url_in) ==\n\t\tHTTP_SUCCESS) {\n\t\tfinger = table->serviceList;\n\t\twhile (finger) {\n\t\t\tif (finger->controlURL) {\n\t\t\t\tif (parse_uri(finger->controlURL,\n\t\t\t\t\t strlen(finger->controlURL),\n\t\t\t\t\t &parsed_url) == HTTP_SUCCESS) {\n\t\t\t\t\tif (!token_cmp(&parsed_url.pathquery,\n\t\t\t\t\t\t &parsed_url_in.pathquery)) {\n\t\t\t\t\t\treturn finger;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinger = finger->next;\n\t\t}\n\t}\n\n\treturn NULL;\n}", "project": "pupnp", "hash": 309107714980423598473483753401169639487, "size": 30, "commit_id": "c805c1de1141cb22f74c0d94dd5664bda37398e0", "message": "Fixes #177: NULL pointer dereference in FindServiceControlURLPath\n\nAlso fixes its dual bug in FindServiceEventURLPath.", "target": 0, "dataset": "other", "idx": 269101} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& x = context->input(0);\n const Tensor& y = context->input(1);\n const float min_x = context->input(2).flat()(0);\n const float max_x = context->input(3).flat()(0);\n const float min_y = context->input(4).flat()(0);\n const float max_y = context->input(5).flat()(0);\n\n BCast bcast(BCast::FromShape(x.shape()), BCast::FromShape(y.shape()));\n if (!bcast.IsValid()) {\n context->SetStatus(errors::InvalidArgument(\n \"Incompatible shapes: \", x.shape().DebugString(), \" vs. \",\n y.shape().DebugString()));\n return;\n }\n Tensor* z;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0, BCast::ToShape(bcast.output_shape()), &z));\n\n // Make sure that we have valid quantization ranges for the input buffers.\n // If the difference between the min and max is negative or zero, it makes\n // it hard to do meaningful intermediate operations on the values.\n OP_REQUIRES(context, (max_x > min_x),\n errors::InvalidArgument(\"max_x must be larger than min_a.\"));\n OP_REQUIRES(context, (max_y > min_y),\n errors::InvalidArgument(\"max_x must be larger than min_b.\"));\n const int32 offset_x = FloatToQuantizedUnclamped(0.0f, min_x, max_x);\n const int32 offset_y = FloatToQuantizedUnclamped(0.0f, min_y, max_y);\n const T* x_data = x.flat().data();\n const T* y_data = y.flat().data();\n Toutput* z_data = z->flat().data();\n\n const int ndims = bcast.x_reshape().size();\n if (ndims <= 1) {\n if (x.NumElements() == 1) {\n ScalarMultiply(context, y_data, offset_y, y.NumElements(),\n x_data[0], offset_x, z_data);\n } else if (y.NumElements() == 1) {\n ScalarMultiply(context, x_data, offset_x, x.NumElements(),\n y_data[0], offset_y, z_data);\n } else {\n VectorMultiply(context, x_data, offset_x, y_data, offset_y,\n x.NumElements(), z_data);\n }\n } else if (ndims == 2) {\n const T* vector_data;\n int64 vector_num_elements;\n int32 vector_offset;\n const T* tensor_data;\n int64 tensor_num_elements;\n int32 tensor_offset;\n if (x.NumElements() < y.NumElements()) {\n vector_data = x_data;\n vector_num_elements = x.NumElements();\n vector_offset = offset_x;\n tensor_data = y_data;\n tensor_num_elements = y.NumElements();\n tensor_offset = offset_y;\n } else {\n vector_data = y_data;\n vector_num_elements = y.NumElements();\n vector_offset = offset_y;\n tensor_data = x_data;\n tensor_num_elements = x.NumElements();\n tensor_offset = offset_x;\n }\n if (vector_num_elements == 0) {\n context->SetStatus(\n errors::InvalidArgument(\"vector must have at least 1 element\"));\n return;\n }\n VectorTensorMultiply(\n vector_data, vector_offset, vector_num_elements, tensor_data,\n tensor_offset, tensor_num_elements, z_data);\n } else {\n LOG(INFO) << \"ndims=\" << ndims;\n LOG(INFO) << \"bcast.x_reshape()=\"\n << TensorShape(bcast.x_reshape()).DebugString();\n LOG(INFO) << \"bcast.y_reshape()=\"\n << TensorShape(bcast.y_reshape()).DebugString();\n LOG(INFO) << \"bcast.x_bcast()=\"\n << TensorShape(bcast.x_bcast()).DebugString();\n LOG(INFO) << \"bcast.y_bcast()=\"\n << TensorShape(bcast.y_bcast()).DebugString();\n\n context->SetStatus(errors::Unimplemented(\n \"Broadcast between \", context->input(0).shape().DebugString(),\n \" and \", context->input(1).shape().DebugString(),\n \" is not supported yet.\"));\n return;\n }\n\n float min_z_value;\n float max_z_value;\n QuantizationRangeForMultiplication(\n min_x, max_x, min_y, max_y, &min_z_value, &max_z_value);\n Tensor* z_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &z_min));\n z_min->flat()(0) = min_z_value;\n\n Tensor* z_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &z_max));\n z_max->flat()(0) = max_z_value;\n }", "project": "tensorflow", "hash": 321222250988638329539662374382316933530, "size": 104, "commit_id": "efea03b38fb8d3b81762237dc85e579cc5fc6e87", "message": "Validate inputs to `QuantizedMul`\n\nPiperOrigin-RevId: 369756982\nChange-Id: I00d960cc3b9316fd7a86bd37a44e341c96e17624", "target": 1, "dataset": "other", "idx": 198110} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& x = context->input(0);\n const Tensor& y = context->input(1);\n auto& min_x_tensor = context->input(2);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(min_x_tensor.shape()),\n errors::InvalidArgument(\"min_x must be a scalar\"));\n const float min_x = min_x_tensor.flat()(0);\n auto& max_x_tensor = context->input(3);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(max_x_tensor.shape()),\n errors::InvalidArgument(\"max_x must be a scalar\"));\n const float max_x = max_x_tensor.flat()(0);\n auto& min_y_tensor = context->input(4);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(min_y_tensor.shape()),\n errors::InvalidArgument(\"min_y must be a scalar\"));\n const float min_y = min_y_tensor.flat()(0);\n auto& max_y_tensor = context->input(5);\n OP_REQUIRES(context, TensorShapeUtils::IsScalar(max_y_tensor.shape()),\n errors::InvalidArgument(\"max_y must be a scalar\"));\n const float max_y = max_y_tensor.flat()(0);\n\n BCast bcast(BCast::FromShape(x.shape()), BCast::FromShape(y.shape()));\n if (!bcast.IsValid()) {\n context->SetStatus(errors::InvalidArgument(\n \"Incompatible shapes: \", x.shape().DebugString(), \" vs. \",\n y.shape().DebugString()));\n return;\n }\n Tensor* z;\n OP_REQUIRES_OK(context, context->allocate_output(\n 0, BCast::ToShape(bcast.output_shape()), &z));\n\n // Make sure that we have valid quantization ranges for the input buffers.\n // If the difference between the min and max is negative or zero, it makes\n // it hard to do meaningful intermediate operations on the values.\n OP_REQUIRES(context, (max_x > min_x),\n errors::InvalidArgument(\"max_x must be larger than min_a.\"));\n OP_REQUIRES(context, (max_y > min_y),\n errors::InvalidArgument(\"max_x must be larger than min_b.\"));\n const int32 offset_x = FloatToQuantizedUnclamped(0.0f, min_x, max_x);\n const int32 offset_y = FloatToQuantizedUnclamped(0.0f, min_y, max_y);\n const T* x_data = x.flat().data();\n const T* y_data = y.flat().data();\n Toutput* z_data = z->flat().data();\n\n const int ndims = bcast.x_reshape().size();\n if (ndims <= 1) {\n if (x.NumElements() == 1) {\n ScalarMultiply(context, y_data, offset_y, y.NumElements(),\n x_data[0], offset_x, z_data);\n } else if (y.NumElements() == 1) {\n ScalarMultiply(context, x_data, offset_x, x.NumElements(),\n y_data[0], offset_y, z_data);\n } else {\n VectorMultiply(context, x_data, offset_x, y_data, offset_y,\n x.NumElements(), z_data);\n }\n } else if (ndims == 2) {\n const T* vector_data;\n int64 vector_num_elements;\n int32 vector_offset;\n const T* tensor_data;\n int64 tensor_num_elements;\n int32 tensor_offset;\n if (x.NumElements() < y.NumElements()) {\n vector_data = x_data;\n vector_num_elements = x.NumElements();\n vector_offset = offset_x;\n tensor_data = y_data;\n tensor_num_elements = y.NumElements();\n tensor_offset = offset_y;\n } else {\n vector_data = y_data;\n vector_num_elements = y.NumElements();\n vector_offset = offset_y;\n tensor_data = x_data;\n tensor_num_elements = x.NumElements();\n tensor_offset = offset_x;\n }\n if (vector_num_elements == 0) {\n context->SetStatus(\n errors::InvalidArgument(\"vector must have at least 1 element\"));\n return;\n }\n VectorTensorMultiply(\n vector_data, vector_offset, vector_num_elements, tensor_data,\n tensor_offset, tensor_num_elements, z_data);\n } else {\n LOG(INFO) << \"ndims=\" << ndims;\n LOG(INFO) << \"bcast.x_reshape()=\"\n << TensorShape(bcast.x_reshape()).DebugString();\n LOG(INFO) << \"bcast.y_reshape()=\"\n << TensorShape(bcast.y_reshape()).DebugString();\n LOG(INFO) << \"bcast.x_bcast()=\"\n << TensorShape(bcast.x_bcast()).DebugString();\n LOG(INFO) << \"bcast.y_bcast()=\"\n << TensorShape(bcast.y_bcast()).DebugString();\n\n context->SetStatus(errors::Unimplemented(\n \"Broadcast between \", context->input(0).shape().DebugString(),\n \" and \", context->input(1).shape().DebugString(),\n \" is not supported yet.\"));\n return;\n }\n\n float min_z_value;\n float max_z_value;\n QuantizationRangeForMultiplication(\n min_x, max_x, min_y, max_y, &min_z_value, &max_z_value);\n Tensor* z_min = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, {}, &z_min));\n z_min->flat()(0) = min_z_value;\n\n Tensor* z_max = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2, {}, &z_max));\n z_max->flat()(0) = max_z_value;\n }", "project": "tensorflow", "hash": 190937515744695115531252219907447927152, "size": 116, "commit_id": "efea03b38fb8d3b81762237dc85e579cc5fc6e87", "message": "Validate inputs to `QuantizedMul`\n\nPiperOrigin-RevId: 369756982\nChange-Id: I00d960cc3b9316fd7a86bd37a44e341c96e17624", "target": 0, "dataset": "other", "idx": 269121} {"func": "inline int MatchingDim(const RuntimeShape& shape1, int index1,\n const RuntimeShape& shape2, int index2) {\n TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2));\n return shape1.Dims(index1);\n}", "project": "tensorflow", "hash": 292684460118693762063488568821033472831, "size": 5, "commit_id": "8ee24e7949a203d234489f9da2c5bf45a7d5157d", "message": "[tflite] Ensure `MatchingDim` does not allow buffer overflow.\n\nWe check in `MatchingDim` that both arguments have the same dimensionality, however that is a `DCHECK` only enabled if building in debug mode. Hence, it could be possible to cause buffer overflows by passing in a tensor with larger dimensions as the second argument. To fix, we now make `MatchingDim` return the minimum of the two sizes.\n\nA much better fix would be to return a status object but that requires refactoring a large part of the codebase for minor benefits.\n\nPiperOrigin-RevId: 332526127\nChange-Id: If627d0d2c80a685217b6e0d1e64b0872dbf1c5e4", "target": 1, "dataset": "other", "idx": 198111} {"func": "inline int MatchingDim(const RuntimeShape& shape1, int index1,\n const RuntimeShape& shape2, int index2) {\n TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2));\n return std::min(shape1.Dims(index1), shape2.Dims(index2));\n}", "project": "tensorflow", "hash": 212828257128375980629692282330012667499, "size": 5, "commit_id": "8ee24e7949a203d234489f9da2c5bf45a7d5157d", "message": "[tflite] Ensure `MatchingDim` does not allow buffer overflow.\n\nWe check in `MatchingDim` that both arguments have the same dimensionality, however that is a `DCHECK` only enabled if building in debug mode. Hence, it could be possible to cause buffer overflows by passing in a tensor with larger dimensions as the second argument. To fix, we now make `MatchingDim` return the minimum of the two sizes.\n\nA much better fix would be to return a status object but that requires refactoring a large part of the codebase for minor benefits.\n\nPiperOrigin-RevId: 332526127\nChange-Id: If627d0d2c80a685217b6e0d1e64b0872dbf1c5e4", "target": 0, "dataset": "other", "idx": 269181} {"func": " void Compute(OpKernelContext* ctx) override {\n // This call processes inputs 1 and 2 to write output 0.\n ReshapeOp::Compute(ctx);\n\n const float input_min_float = ctx->input(2).flat()(0);\n const float input_max_float = ctx->input(3).flat()(0);\n Tensor* output_min = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_min));\n output_min->flat()(0) = input_min_float;\n\n Tensor* output_max = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(2, TensorShape({}), &output_max));\n output_max->flat()(0) = input_max_float;\n }", "project": "tensorflow", "hash": 138415375282410567846030933274549860111, "size": 14, "commit_id": "a324ac84e573fba362a5e53d4e74d5de6729933e", "message": "Validate arguments to `QuantizedReshape`.\n\nEnsure that validations from `Reshape` also terminate `QuantizedReshape` on failure.\n\nPiperOrigin-RevId: 369775421\nChange-Id: If8c5342267aceea65b7cb83a4b183304886f1ce8", "target": 1, "dataset": "other", "idx": 198140} {"func": " void Compute(OpKernelContext* ctx) override {\n // This call processes inputs 1 and 2 to write output 0.\n ReshapeOp::Compute(ctx);\n if (!ctx->status().ok()) {\n return;\n }\n\n const auto& input_min_float_tensor = ctx->input(2);\n const auto& input_min_float_shape = input_min_float_tensor.shape();\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsScalar(input_min_float_shape) ||\n (TensorShapeUtils::IsVector(input_min_float_shape) &&\n (input_min_float_shape.dim_size(0) == 1)),\n errors::InvalidArgument(\n \"input_min must be a scalar or a vector of 1 element\"));\n const float input_min_float = input_min_float_tensor.flat()(0);\n const auto& input_max_float_tensor = ctx->input(3);\n const auto& input_max_float_shape = input_max_float_tensor.shape();\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsScalar(input_max_float_shape) ||\n (TensorShapeUtils::IsVector(input_max_float_shape) &&\n (input_max_float_shape.dim_size(0) == 1)),\n errors::InvalidArgument(\n \"input_max must be a scalar or a vector of 1 element\"));\n const float input_max_float = input_max_float_tensor.flat()(0);\n\n Tensor* output_min = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_min));\n output_min->flat()(0) = input_min_float;\n\n Tensor* output_max = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(2, TensorShape({}), &output_max));\n output_max->flat()(0) = input_max_float;\n }", "project": "tensorflow", "hash": 159137396648765332305552157383255155319, "size": 34, "commit_id": "a324ac84e573fba362a5e53d4e74d5de6729933e", "message": "Validate arguments to `QuantizedReshape`.\n\nEnsure that validations from `Reshape` also terminate `QuantizedReshape` on failure.\n\nPiperOrigin-RevId: 369775421\nChange-Id: If8c5342267aceea65b7cb83a4b183304886f1ce8", "target": 0, "dataset": "other", "idx": 269702} {"func": "content::WebContents* WebContents::OpenURLFromTab(\n content::WebContents* source,\n const content::OpenURLParams& params) {\n if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {\n Emit(\"-new-window\", params.url, \"\", params.disposition, \"\", params.referrer,\n params.post_data);\n return nullptr;\n }\n\n // Give user a chance to cancel navigation.\n if (Emit(\"will-navigate\", params.url))\n return nullptr;\n\n // Don't load the URL if the web contents was marked as destroyed from a\n // will-navigate event listener\n if (IsDestroyed())\n return nullptr;\n\n return CommonWebContentsDelegate::OpenURLFromTab(source, params);\n}", "project": "electron", "hash": 266355652945031614418015863162348662454, "size": 20, "commit_id": "18613925610ba319da7f497b6deed85ad712c59b", "message": "refactor: wire will-navigate up to a navigation throttle instead of OpenURL (#25108)\n\n* refactor: wire will-navigate up to a navigation throttle instead of OpenURL (#25065)\r\n\r\n* refactor: wire will-navigate up to a navigation throttle instead of OpenURL\r\n\r\n* spec: add test for x-site _top navigation\r\n\r\n* chore: old code be old", "target": 1, "dataset": "other", "idx": 198143} {"func": "content::WebContents* WebContents::OpenURLFromTab(\n content::WebContents* source,\n const content::OpenURLParams& params) {\n if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {\n Emit(\"-new-window\", params.url, \"\", params.disposition, \"\", params.referrer,\n params.post_data);\n return nullptr;\n }\n\n if (IsDestroyed())\n return nullptr;\n\n return CommonWebContentsDelegate::OpenURLFromTab(source, params);\n}", "project": "electron", "hash": 49577923825265945582623513612554035537, "size": 14, "commit_id": "18613925610ba319da7f497b6deed85ad712c59b", "message": "refactor: wire will-navigate up to a navigation throttle instead of OpenURL (#25108)\n\n* refactor: wire will-navigate up to a navigation throttle instead of OpenURL (#25065)\r\n\r\n* refactor: wire will-navigate up to a navigation throttle instead of OpenURL\r\n\r\n* spec: add test for x-site _top navigation\r\n\r\n* chore: old code be old", "target": 0, "dataset": "other", "idx": 269738} {"func": "otError Commissioner::GeneratePskc(const char * aPassPhrase,\n const char * aNetworkName,\n const Mac::ExtendedPanId &aExtPanId,\n Pskc & aPskc)\n{\n otError error = OT_ERROR_NONE;\n const char *saltPrefix = \"Thread\";\n uint8_t salt[OT_PBKDF2_SALT_MAX_LEN];\n uint16_t saltLen = 0;\n\n VerifyOrExit((strlen(aPassPhrase) >= OT_COMMISSIONING_PASSPHRASE_MIN_SIZE) &&\n (strlen(aPassPhrase) <= OT_COMMISSIONING_PASSPHRASE_MAX_SIZE) &&\n (strlen(aNetworkName) <= OT_NETWORK_NAME_MAX_SIZE),\n error = OT_ERROR_INVALID_ARGS);\n\n memset(salt, 0, sizeof(salt));\n memcpy(salt, saltPrefix, strlen(saltPrefix));\n saltLen += static_cast(strlen(saltPrefix));\n\n memcpy(salt + saltLen, aExtPanId.m8, sizeof(aExtPanId));\n saltLen += OT_EXT_PAN_ID_SIZE;\n\n memcpy(salt + saltLen, aNetworkName, strlen(aNetworkName));\n saltLen += static_cast(strlen(aNetworkName));\n\n otPbkdf2Cmac(reinterpret_cast(aPassPhrase), static_cast(strlen(aPassPhrase)),\n reinterpret_cast(salt), saltLen, 16384, OT_PSKC_MAX_SIZE, aPskc.m8);\n\nexit:\n return error;\n}", "project": "openthread", "hash": 269174587310881469223710673598831931018, "size": 31, "commit_id": "c3a3a0c424322009fec3ab735fb20ce8f6e19e70", "message": "[commissioner] use strnlen instead of strlen (#4404)", "target": 1, "dataset": "other", "idx": 198147} {"func": "otError Commissioner::GeneratePskc(const char * aPassPhrase,\n const char * aNetworkName,\n const Mac::ExtendedPanId &aExtPanId,\n Pskc & aPskc)\n{\n otError error = OT_ERROR_NONE;\n const char saltPrefix[] = \"Thread\";\n uint8_t salt[OT_PBKDF2_SALT_MAX_LEN];\n uint16_t saltLen = 0;\n uint16_t passphraseLen;\n uint8_t networkNameLen;\n\n passphraseLen = static_cast(strnlen(aPassPhrase, OT_COMMISSIONING_PASSPHRASE_MAX_SIZE + 1));\n networkNameLen = static_cast(strnlen(aNetworkName, OT_NETWORK_NAME_MAX_SIZE + 1));\n\n VerifyOrExit((passphraseLen >= OT_COMMISSIONING_PASSPHRASE_MIN_SIZE) &&\n (passphraseLen <= OT_COMMISSIONING_PASSPHRASE_MAX_SIZE) &&\n (networkNameLen <= OT_NETWORK_NAME_MAX_SIZE),\n error = OT_ERROR_INVALID_ARGS);\n\n memset(salt, 0, sizeof(salt));\n memcpy(salt, saltPrefix, sizeof(saltPrefix) - 1);\n saltLen += static_cast(sizeof(saltPrefix) - 1);\n\n memcpy(salt + saltLen, aExtPanId.m8, sizeof(aExtPanId));\n saltLen += OT_EXT_PAN_ID_SIZE;\n\n memcpy(salt + saltLen, aNetworkName, networkNameLen);\n saltLen += networkNameLen;\n\n otPbkdf2Cmac(reinterpret_cast(aPassPhrase), passphraseLen, reinterpret_cast(salt),\n saltLen, 16384, OT_PSKC_MAX_SIZE, aPskc.m8);\n\nexit:\n return error;\n}", "project": "openthread", "hash": 130996794969779372185141123675944404951, "size": 36, "commit_id": "c3a3a0c424322009fec3ab735fb20ce8f6e19e70", "message": "[commissioner] use strnlen instead of strlen (#4404)", "target": 0, "dataset": "other", "idx": 269900} {"func": "static int decode_slice_header(H264Context *h, H264Context *h0)\n{\n unsigned int first_mb_in_slice;\n unsigned int pps_id;\n int ret;\n unsigned int slice_type, tmp, i, j;\n int last_pic_structure, last_pic_droppable;\n int must_reinit;\n int needs_reinit = 0;\n int field_pic_flag, bottom_field_flag;\n\n h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;\n h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;\n\n first_mb_in_slice = get_ue_golomb_long(&h->gb);\n\n if (first_mb_in_slice == 0) { // FIXME better field boundary detection\n if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {\n field_end(h, 1);\n }\n\n h0->current_slice = 0;\n if (!h0->first_field) {\n if (h->cur_pic_ptr && !h->droppable) {\n ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,\n h->picture_structure == PICT_BOTTOM_FIELD);\n }\n h->cur_pic_ptr = NULL;\n }\n }\n\n slice_type = get_ue_golomb_31(&h->gb);\n if (slice_type > 9) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"slice type too large (%d) at %d %d\\n\",\n slice_type, h->mb_x, h->mb_y);\n return AVERROR_INVALIDDATA;\n }\n if (slice_type > 4) {\n slice_type -= 5;\n h->slice_type_fixed = 1;\n } else\n h->slice_type_fixed = 0;\n\n slice_type = golomb_to_pict_type[slice_type];\n h->slice_type = slice_type;\n h->slice_type_nos = slice_type & 3;\n\n if (h->nal_unit_type == NAL_IDR_SLICE &&\n h->slice_type_nos != AV_PICTURE_TYPE_I) {\n av_log(h->avctx, AV_LOG_ERROR, \"A non-intra slice in an IDR NAL unit.\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n // to make a few old functions happy, it's wrong though\n h->pict_type = h->slice_type;\n\n pps_id = get_ue_golomb(&h->gb);\n if (pps_id >= MAX_PPS_COUNT) {\n av_log(h->avctx, AV_LOG_ERROR, \"pps_id %d out of range\\n\", pps_id);\n return AVERROR_INVALIDDATA;\n }\n if (!h0->pps_buffers[pps_id]) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"non-existing PPS %u referenced\\n\",\n pps_id);\n return AVERROR_INVALIDDATA;\n }\n if (h0->au_pps_id >= 0 && pps_id != h0->au_pps_id) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"PPS change from %d to %d forbidden\\n\",\n h0->au_pps_id, pps_id);\n return AVERROR_INVALIDDATA;\n }\n h->pps = *h0->pps_buffers[pps_id];\n\n if (!h0->sps_buffers[h->pps.sps_id]) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"non-existing SPS %u referenced\\n\",\n h->pps.sps_id);\n return AVERROR_INVALIDDATA;\n }\n\n if (h->pps.sps_id != h->current_sps_id ||\n h0->sps_buffers[h->pps.sps_id]->new) {\n h0->sps_buffers[h->pps.sps_id]->new = 0;\n\n h->current_sps_id = h->pps.sps_id;\n h->sps = *h0->sps_buffers[h->pps.sps_id];\n\n if (h->mb_width != h->sps.mb_width ||\n h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||\n h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||\n h->cur_chroma_format_idc != h->sps.chroma_format_idc\n )\n needs_reinit = 1;\n\n if (h->bit_depth_luma != h->sps.bit_depth_luma ||\n h->chroma_format_idc != h->sps.chroma_format_idc) {\n h->bit_depth_luma = h->sps.bit_depth_luma;\n h->chroma_format_idc = h->sps.chroma_format_idc;\n needs_reinit = 1;\n }\n if ((ret = h264_set_parameter_from_sps(h)) < 0)\n return ret;\n }\n\n h->avctx->profile = ff_h264_get_profile(&h->sps);\n h->avctx->level = h->sps.level_idc;\n h->avctx->refs = h->sps.ref_frame_count;\n\n must_reinit = (h->context_initialized &&\n ( 16*h->sps.mb_width != h->avctx->coded_width\n || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height\n || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma\n || h->cur_chroma_format_idc != h->sps.chroma_format_idc\n || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)\n || h->mb_width != h->sps.mb_width\n || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)\n ));\n if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))\n must_reinit = 1;\n\n h->mb_width = h->sps.mb_width;\n h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);\n h->mb_num = h->mb_width * h->mb_height;\n h->mb_stride = h->mb_width + 1;\n\n h->b_stride = h->mb_width * 4;\n\n h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p\n\n h->width = 16 * h->mb_width;\n h->height = 16 * h->mb_height;\n\n ret = init_dimensions(h);\n if (ret < 0)\n return ret;\n\n if (h->sps.video_signal_type_present_flag) {\n h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG\n : AVCOL_RANGE_MPEG;\n if (h->sps.colour_description_present_flag) {\n if (h->avctx->colorspace != h->sps.colorspace)\n needs_reinit = 1;\n h->avctx->color_primaries = h->sps.color_primaries;\n h->avctx->color_trc = h->sps.color_trc;\n h->avctx->colorspace = h->sps.colorspace;\n }\n }\n\n if (h->context_initialized &&\n (h->width != h->avctx->coded_width ||\n h->height != h->avctx->coded_height ||\n must_reinit ||\n needs_reinit)) {\n if (h != h0) {\n av_log(h->avctx, AV_LOG_ERROR, \"changing width/height on \"\n \"slice %d\\n\", h0->current_slice + 1);\n return AVERROR_INVALIDDATA;\n }\n\n flush_change(h);\n\n if ((ret = get_pixel_format(h, 1)) < 0)\n return ret;\n h->avctx->pix_fmt = ret;\n\n av_log(h->avctx, AV_LOG_INFO, \"Reinit context to %dx%d, \"\n \"pix_fmt: %s\\n\", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));\n\n if ((ret = h264_slice_header_init(h, 1)) < 0) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"h264_slice_header_init() failed\\n\");\n return ret;\n }\n }\n if (!h->context_initialized) {\n if (h != h0) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Cannot (re-)initialize context during parallel decoding.\\n\");\n return AVERROR_PATCHWELCOME;\n }\n\n if ((ret = get_pixel_format(h, 1)) < 0)\n return ret;\n h->avctx->pix_fmt = ret;\n\n if ((ret = h264_slice_header_init(h, 0)) < 0) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"h264_slice_header_init() failed\\n\");\n return ret;\n }\n }\n\n if (h == h0 && h->dequant_coeff_pps != pps_id) {\n h->dequant_coeff_pps = pps_id;\n init_dequant_tables(h);\n }\n\n h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);\n\n h->mb_mbaff = 0;\n h->mb_aff_frame = 0;\n last_pic_structure = h0->picture_structure;\n last_pic_droppable = h0->droppable;\n h->droppable = h->nal_ref_idc == 0;\n if (h->sps.frame_mbs_only_flag) {\n h->picture_structure = PICT_FRAME;\n } else {\n if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {\n av_log(h->avctx, AV_LOG_ERROR, \"This stream was generated by a broken encoder, invalid 8x8 inference\\n\");\n return -1;\n }\n field_pic_flag = get_bits1(&h->gb);\n if (field_pic_flag) {\n bottom_field_flag = get_bits1(&h->gb);\n h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;\n } else {\n h->picture_structure = PICT_FRAME;\n h->mb_aff_frame = h->sps.mb_aff;\n }\n }\n h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;\n\n if (h0->current_slice != 0) {\n if (last_pic_structure != h->picture_structure ||\n last_pic_droppable != h->droppable) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Changing field mode (%d -> %d) between slices is not allowed\\n\",\n last_pic_structure, h->picture_structure);\n h->picture_structure = last_pic_structure;\n h->droppable = last_pic_droppable;\n return AVERROR_INVALIDDATA;\n } else if (!h0->cur_pic_ptr) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"unset cur_pic_ptr on %d. slice\\n\",\n h0->current_slice + 1);\n return AVERROR_INVALIDDATA;\n }\n } else {\n /* Shorten frame num gaps so we don't have to allocate reference\n * frames just to throw them away */\n if (h->frame_num != h->prev_frame_num) {\n int unwrap_prev_frame_num = h->prev_frame_num;\n int max_frame_num = 1 << h->sps.log2_max_frame_num;\n\n if (unwrap_prev_frame_num > h->frame_num)\n unwrap_prev_frame_num -= max_frame_num;\n\n if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {\n unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;\n if (unwrap_prev_frame_num < 0)\n unwrap_prev_frame_num += max_frame_num;\n\n h->prev_frame_num = unwrap_prev_frame_num;\n }\n }\n\n /* See if we have a decoded first field looking for a pair...\n * Here, we're using that to see if we should mark previously\n * decode frames as \"finished\".\n * We have to do that before the \"dummy\" in-between frame allocation,\n * since that can modify h->cur_pic_ptr. */\n if (h0->first_field) {\n assert(h0->cur_pic_ptr);\n assert(h0->cur_pic_ptr->f.buf[0]);\n assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);\n\n /* Mark old field/frame as completed */\n if (h0->cur_pic_ptr->tf.owner == h0->avctx) {\n ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,\n last_pic_structure == PICT_BOTTOM_FIELD);\n }\n\n /* figure out if we have a complementary field pair */\n if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {\n /* Previous field is unmatched. Don't display it, but let it\n * remain for reference if marked as such. */\n if (last_pic_structure != PICT_FRAME) {\n ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,\n last_pic_structure == PICT_TOP_FIELD);\n }\n } else {\n if (h0->cur_pic_ptr->frame_num != h->frame_num) {\n /* This and previous field were reference, but had\n * different frame_nums. Consider this field first in\n * pair. Throw away previous field except for reference\n * purposes. */\n if (last_pic_structure != PICT_FRAME) {\n ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,\n last_pic_structure == PICT_TOP_FIELD);\n }\n } else {\n /* Second field in complementary pair */\n if (!((last_pic_structure == PICT_TOP_FIELD &&\n h->picture_structure == PICT_BOTTOM_FIELD) ||\n (last_pic_structure == PICT_BOTTOM_FIELD &&\n h->picture_structure == PICT_TOP_FIELD))) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Invalid field mode combination %d/%d\\n\",\n last_pic_structure, h->picture_structure);\n h->picture_structure = last_pic_structure;\n h->droppable = last_pic_droppable;\n return AVERROR_INVALIDDATA;\n } else if (last_pic_droppable != h->droppable) {\n avpriv_request_sample(h->avctx,\n \"Found reference and non-reference fields in the same frame, which\");\n h->picture_structure = last_pic_structure;\n h->droppable = last_pic_droppable;\n return AVERROR_PATCHWELCOME;\n }\n }\n }\n }\n\n while (h->frame_num != h->prev_frame_num && !h0->first_field &&\n h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {\n Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;\n av_log(h->avctx, AV_LOG_DEBUG, \"Frame num gap %d %d\\n\",\n h->frame_num, h->prev_frame_num);\n if (!h->sps.gaps_in_frame_num_allowed_flag)\n for(i=0; ilast_pocs); i++)\n h->last_pocs[i] = INT_MIN;\n ret = h264_frame_start(h);\n if (ret < 0) {\n h0->first_field = 0;\n return ret;\n }\n\n h->prev_frame_num++;\n h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;\n h->cur_pic_ptr->frame_num = h->prev_frame_num;\n ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);\n ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);\n ret = ff_generate_sliding_window_mmcos(h, 1);\n if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))\n return ret;\n ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);\n if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))\n return ret;\n /* Error concealment: If a ref is missing, copy the previous ref\n * in its place.\n * FIXME: Avoiding a memcpy would be nice, but ref handling makes\n * many assumptions about there being no actual duplicates.\n * FIXME: This does not copy padding for out-of-frame motion\n * vectors. Given we are concealing a lost frame, this probably\n * is not noticeable by comparison, but it should be fixed. */\n if (h->short_ref_count) {\n if (prev) {\n av_image_copy(h->short_ref[0]->f.data,\n h->short_ref[0]->f.linesize,\n (const uint8_t **)prev->f.data,\n prev->f.linesize,\n h->avctx->pix_fmt,\n h->mb_width * 16,\n h->mb_height * 16);\n h->short_ref[0]->poc = prev->poc + 2;\n }\n h->short_ref[0]->frame_num = h->prev_frame_num;\n }\n }\n\n /* See if we have a decoded first field looking for a pair...\n * We're using that to see whether to continue decoding in that\n * frame, or to allocate a new one. */\n if (h0->first_field) {\n assert(h0->cur_pic_ptr);\n assert(h0->cur_pic_ptr->f.buf[0]);\n assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);\n\n /* figure out if we have a complementary field pair */\n if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {\n /* Previous field is unmatched. Don't display it, but let it\n * remain for reference if marked as such. */\n h0->cur_pic_ptr = NULL;\n h0->first_field = FIELD_PICTURE(h);\n } else {\n if (h0->cur_pic_ptr->frame_num != h->frame_num) {\n ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,\n h0->picture_structure==PICT_BOTTOM_FIELD);\n /* This and the previous field had different frame_nums.\n * Consider this field first in pair. Throw away previous\n * one except for reference purposes. */\n h0->first_field = 1;\n h0->cur_pic_ptr = NULL;\n } else {\n /* Second field in complementary pair */\n h0->first_field = 0;\n }\n }\n } else {\n /* Frame or first field in a potentially complementary pair */\n h0->first_field = FIELD_PICTURE(h);\n }\n\n if (!FIELD_PICTURE(h) || h0->first_field) {\n if (h264_frame_start(h) < 0) {\n h0->first_field = 0;\n return AVERROR_INVALIDDATA;\n }\n } else {\n release_unused_pictures(h, 0);\n }\n /* Some macroblocks can be accessed before they're available in case\n * of lost slices, MBAFF or threading. */\n if (FIELD_PICTURE(h)) {\n for(i = (h->picture_structure == PICT_BOTTOM_FIELD); imb_height; i++)\n memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));\n } else {\n memset(h->slice_table, -1,\n (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));\n }\n h0->last_slice_type = -1;\n }\n if (h != h0 && (ret = clone_slice(h, h0)) < 0)\n return ret;\n\n /* can't be in alloc_tables because linesize isn't known there.\n * FIXME: redo bipred weight to not require extra buffer? */\n for (i = 0; i < h->slice_context_count; i++)\n if (h->thread_context[i]) {\n ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);\n if (ret < 0)\n return ret;\n }\n\n h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup\n\n av_assert1(h->mb_num == h->mb_width * h->mb_height);\n if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||\n first_mb_in_slice >= h->mb_num) {\n av_log(h->avctx, AV_LOG_ERROR, \"first_mb_in_slice overflow\\n\");\n return AVERROR_INVALIDDATA;\n }\n h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;\n h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<\n FIELD_OR_MBAFF_PICTURE(h);\n if (h->picture_structure == PICT_BOTTOM_FIELD)\n h->resync_mb_y = h->mb_y = h->mb_y + 1;\n av_assert1(h->mb_y < h->mb_height);\n\n if (h->picture_structure == PICT_FRAME) {\n h->curr_pic_num = h->frame_num;\n h->max_pic_num = 1 << h->sps.log2_max_frame_num;\n } else {\n h->curr_pic_num = 2 * h->frame_num + 1;\n h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);\n }\n\n if (h->nal_unit_type == NAL_IDR_SLICE)\n get_ue_golomb(&h->gb); /* idr_pic_id */\n\n if (h->sps.poc_type == 0) {\n h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);\n\n if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)\n h->delta_poc_bottom = get_se_golomb(&h->gb);\n }\n\n if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {\n h->delta_poc[0] = get_se_golomb(&h->gb);\n\n if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)\n h->delta_poc[1] = get_se_golomb(&h->gb);\n }\n\n ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);\n\n if (h->pps.redundant_pic_cnt_present)\n h->redundant_pic_count = get_ue_golomb(&h->gb);\n\n ret = ff_set_ref_count(h);\n if (ret < 0)\n return ret;\n\n if (slice_type != AV_PICTURE_TYPE_I &&\n (h0->current_slice == 0 ||\n slice_type != h0->last_slice_type ||\n memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {\n\n ff_h264_fill_default_ref_list(h);\n }\n\n if (h->slice_type_nos != AV_PICTURE_TYPE_I) {\n ret = ff_h264_decode_ref_pic_list_reordering(h);\n if (ret < 0) {\n h->ref_count[1] = h->ref_count[0] = 0;\n return ret;\n }\n }\n\n if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||\n (h->pps.weighted_bipred_idc == 1 &&\n h->slice_type_nos == AV_PICTURE_TYPE_B))\n ff_pred_weight_table(h);\n else if (h->pps.weighted_bipred_idc == 2 &&\n h->slice_type_nos == AV_PICTURE_TYPE_B) {\n implicit_weight_table(h, -1);\n } else {\n h->use_weight = 0;\n for (i = 0; i < 2; i++) {\n h->luma_weight_flag[i] = 0;\n h->chroma_weight_flag[i] = 0;\n }\n }\n\n // If frame-mt is enabled, only update mmco tables for the first slice\n // in a field. Subsequent slices can temporarily clobber h->mmco_index\n // or h->mmco, which will cause ref list mix-ups and decoding errors\n // further down the line. This may break decoding if the first slice is\n // corrupt, thus we only do this if frame-mt is enabled.\n if (h->nal_ref_idc) {\n ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,\n !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||\n h0->current_slice == 0);\n if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))\n return AVERROR_INVALIDDATA;\n }\n\n if (FRAME_MBAFF(h)) {\n ff_h264_fill_mbaff_ref_list(h);\n\n if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {\n implicit_weight_table(h, 0);\n implicit_weight_table(h, 1);\n }\n }\n\n if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)\n ff_h264_direct_dist_scale_factor(h);\n ff_h264_direct_ref_list_init(h);\n\n if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {\n tmp = get_ue_golomb_31(&h->gb);\n if (tmp > 2) {\n av_log(h->avctx, AV_LOG_ERROR, \"cabac_init_idc overflow\\n\");\n return AVERROR_INVALIDDATA;\n }\n h->cabac_init_idc = tmp;\n }\n\n h->last_qscale_diff = 0;\n tmp = h->pps.init_qp + get_se_golomb(&h->gb);\n if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {\n av_log(h->avctx, AV_LOG_ERROR, \"QP %u out of range\\n\", tmp);\n return AVERROR_INVALIDDATA;\n }\n h->qscale = tmp;\n h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);\n h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);\n // FIXME qscale / qp ... stuff\n if (h->slice_type == AV_PICTURE_TYPE_SP)\n get_bits1(&h->gb); /* sp_for_switch_flag */\n if (h->slice_type == AV_PICTURE_TYPE_SP ||\n h->slice_type == AV_PICTURE_TYPE_SI)\n get_se_golomb(&h->gb); /* slice_qs_delta */\n\n h->deblocking_filter = 1;\n h->slice_alpha_c0_offset = 52;\n h->slice_beta_offset = 52;\n if (h->pps.deblocking_filter_parameters_present) {\n tmp = get_ue_golomb_31(&h->gb);\n if (tmp > 2) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"deblocking_filter_idc %u out of range\\n\", tmp);\n return AVERROR_INVALIDDATA;\n }\n h->deblocking_filter = tmp;\n if (h->deblocking_filter < 2)\n h->deblocking_filter ^= 1; // 1<->0\n\n if (h->deblocking_filter) {\n h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;\n h->slice_beta_offset += get_se_golomb(&h->gb) << 1;\n if (h->slice_alpha_c0_offset > 104U ||\n h->slice_beta_offset > 104U) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"deblocking filter parameters %d %d out of range\\n\",\n h->slice_alpha_c0_offset, h->slice_beta_offset);\n return AVERROR_INVALIDDATA;\n }\n }\n }\n\n if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||\n (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&\n h->slice_type_nos != AV_PICTURE_TYPE_I) ||\n (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&\n h->slice_type_nos == AV_PICTURE_TYPE_B) ||\n (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&\n h->nal_ref_idc == 0))\n h->deblocking_filter = 0;\n\n if (h->deblocking_filter == 1 && h0->max_contexts > 1) {\n if (h->avctx->flags2 & CODEC_FLAG2_FAST) {\n /* Cheat slightly for speed:\n * Do not bother to deblock across slices. */\n h->deblocking_filter = 2;\n } else {\n h0->max_contexts = 1;\n if (!h0->single_decode_warning) {\n av_log(h->avctx, AV_LOG_INFO,\n \"Cannot parallelize deblocking type 1, decoding such frames in sequential order\\n\");\n h0->single_decode_warning = 1;\n }\n if (h != h0) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Deblocking switched inside frame.\\n\");\n return 1;\n }\n }\n }\n h->qp_thresh = 15 + 52 -\n FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -\n FFMAX3(0,\n h->pps.chroma_qp_index_offset[0],\n h->pps.chroma_qp_index_offset[1]) +\n 6 * (h->sps.bit_depth_luma - 8);\n\n h0->last_slice_type = slice_type;\n memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));\n h->slice_num = ++h0->current_slice;\n\n if (h->slice_num)\n h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;\n if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y\n && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y\n && h->slice_num >= MAX_SLICES) {\n //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case\n av_log(h->avctx, AV_LOG_WARNING, \"Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\\n\", h->slice_num, MAX_SLICES);\n }\n\n for (j = 0; j < 2; j++) {\n int id_list[16];\n int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];\n for (i = 0; i < 16; i++) {\n id_list[i] = 60;\n if (j < h->list_count && i < h->ref_count[j] &&\n h->ref_list[j][i].f.buf[0]) {\n int k;\n AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;\n for (k = 0; k < h->short_ref_count; k++)\n if (h->short_ref[k]->f.buf[0]->buffer == buf) {\n id_list[i] = k;\n break;\n }\n for (k = 0; k < h->long_ref_count; k++)\n if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {\n id_list[i] = h->short_ref_count + k;\n break;\n }\n }\n }\n\n ref2frm[0] =\n ref2frm[1] = -1;\n for (i = 0; i < 16; i++)\n ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);\n ref2frm[18 + 0] =\n ref2frm[18 + 1] = -1;\n for (i = 16; i < 48; i++)\n ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +\n (h->ref_list[j][i].reference & 3);\n }\n\n if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0];\n if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0];\n h->er.ref_count = h->ref_count[0];\n h0->au_pps_id = pps_id;\n\n if (h->avctx->debug & FF_DEBUG_PICT_INFO) {\n av_log(h->avctx, AV_LOG_DEBUG,\n \"slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\\n\",\n h->slice_num,\n (h->picture_structure == PICT_FRAME ? \"F\" : h->picture_structure == PICT_TOP_FIELD ? \"T\" : \"B\"),\n first_mb_in_slice,\n av_get_picture_type_char(h->slice_type),\n h->slice_type_fixed ? \" fix\" : \"\",\n h->nal_unit_type == NAL_IDR_SLICE ? \" IDR\" : \"\",\n pps_id, h->frame_num,\n h->cur_pic_ptr->field_poc[0],\n h->cur_pic_ptr->field_poc[1],\n h->ref_count[0], h->ref_count[1],\n h->qscale,\n h->deblocking_filter,\n h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,\n h->use_weight,\n h->use_weight == 1 && h->use_weight_chroma ? \"c\" : \"\",\n h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? \"SPAT\" : \"TEMP\") : \"\");\n }\n\n return 0;\n}", "project": "FFmpeg", "hash": 24783762682806170514184972114597660646, "size": 694, "commit_id": "8a3b85f3a7952c54a2c36ba1797f7e0cde9f85aa", "message": "avcodec/h264: update current_sps & sps->new only after the whole slice header decoder and init code finished\n\nThis avoids them being cleared before the full initialization finished\n\nFixes out of array read\nFixes: asan_heap-oob_f0c5e6_7071_cov_1605985132_mov_h264_aac__Demo_FlagOfOurFathers.mov\nFound-by: Mateusz \"j00ru\" Jurczyk and Gynvael Coldwind\nSigned-off-by: Michael Niedermayer ", "target": 1, "dataset": "other", "idx": 198173} {"func": "static int decode_slice_header(H264Context *h, H264Context *h0)\n{\n unsigned int first_mb_in_slice;\n unsigned int pps_id;\n int ret;\n unsigned int slice_type, tmp, i, j;\n int last_pic_structure, last_pic_droppable;\n int must_reinit;\n int needs_reinit = 0;\n int field_pic_flag, bottom_field_flag;\n\n h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;\n h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;\n\n first_mb_in_slice = get_ue_golomb_long(&h->gb);\n\n if (first_mb_in_slice == 0) { // FIXME better field boundary detection\n if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {\n field_end(h, 1);\n }\n\n h0->current_slice = 0;\n if (!h0->first_field) {\n if (h->cur_pic_ptr && !h->droppable) {\n ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,\n h->picture_structure == PICT_BOTTOM_FIELD);\n }\n h->cur_pic_ptr = NULL;\n }\n }\n\n slice_type = get_ue_golomb_31(&h->gb);\n if (slice_type > 9) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"slice type too large (%d) at %d %d\\n\",\n slice_type, h->mb_x, h->mb_y);\n return AVERROR_INVALIDDATA;\n }\n if (slice_type > 4) {\n slice_type -= 5;\n h->slice_type_fixed = 1;\n } else\n h->slice_type_fixed = 0;\n\n slice_type = golomb_to_pict_type[slice_type];\n h->slice_type = slice_type;\n h->slice_type_nos = slice_type & 3;\n\n if (h->nal_unit_type == NAL_IDR_SLICE &&\n h->slice_type_nos != AV_PICTURE_TYPE_I) {\n av_log(h->avctx, AV_LOG_ERROR, \"A non-intra slice in an IDR NAL unit.\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n // to make a few old functions happy, it's wrong though\n h->pict_type = h->slice_type;\n\n pps_id = get_ue_golomb(&h->gb);\n if (pps_id >= MAX_PPS_COUNT) {\n av_log(h->avctx, AV_LOG_ERROR, \"pps_id %d out of range\\n\", pps_id);\n return AVERROR_INVALIDDATA;\n }\n if (!h0->pps_buffers[pps_id]) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"non-existing PPS %u referenced\\n\",\n pps_id);\n return AVERROR_INVALIDDATA;\n }\n if (h0->au_pps_id >= 0 && pps_id != h0->au_pps_id) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"PPS change from %d to %d forbidden\\n\",\n h0->au_pps_id, pps_id);\n return AVERROR_INVALIDDATA;\n }\n h->pps = *h0->pps_buffers[pps_id];\n\n if (!h0->sps_buffers[h->pps.sps_id]) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"non-existing SPS %u referenced\\n\",\n h->pps.sps_id);\n return AVERROR_INVALIDDATA;\n }\n\n if (h->pps.sps_id != h->current_sps_id ||\n h0->sps_buffers[h->pps.sps_id]->new) {\n\n h->sps = *h0->sps_buffers[h->pps.sps_id];\n\n if (h->mb_width != h->sps.mb_width ||\n h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||\n h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||\n h->cur_chroma_format_idc != h->sps.chroma_format_idc\n )\n needs_reinit = 1;\n\n if (h->bit_depth_luma != h->sps.bit_depth_luma ||\n h->chroma_format_idc != h->sps.chroma_format_idc) {\n h->bit_depth_luma = h->sps.bit_depth_luma;\n h->chroma_format_idc = h->sps.chroma_format_idc;\n needs_reinit = 1;\n }\n if ((ret = h264_set_parameter_from_sps(h)) < 0)\n return ret;\n }\n\n h->avctx->profile = ff_h264_get_profile(&h->sps);\n h->avctx->level = h->sps.level_idc;\n h->avctx->refs = h->sps.ref_frame_count;\n\n must_reinit = (h->context_initialized &&\n ( 16*h->sps.mb_width != h->avctx->coded_width\n || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height\n || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma\n || h->cur_chroma_format_idc != h->sps.chroma_format_idc\n || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)\n || h->mb_width != h->sps.mb_width\n || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)\n ));\n if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))\n must_reinit = 1;\n\n h->mb_width = h->sps.mb_width;\n h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);\n h->mb_num = h->mb_width * h->mb_height;\n h->mb_stride = h->mb_width + 1;\n\n h->b_stride = h->mb_width * 4;\n\n h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p\n\n h->width = 16 * h->mb_width;\n h->height = 16 * h->mb_height;\n\n ret = init_dimensions(h);\n if (ret < 0)\n return ret;\n\n if (h->sps.video_signal_type_present_flag) {\n h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG\n : AVCOL_RANGE_MPEG;\n if (h->sps.colour_description_present_flag) {\n if (h->avctx->colorspace != h->sps.colorspace)\n needs_reinit = 1;\n h->avctx->color_primaries = h->sps.color_primaries;\n h->avctx->color_trc = h->sps.color_trc;\n h->avctx->colorspace = h->sps.colorspace;\n }\n }\n\n if (h->context_initialized &&\n (h->width != h->avctx->coded_width ||\n h->height != h->avctx->coded_height ||\n must_reinit ||\n needs_reinit)) {\n if (h != h0) {\n av_log(h->avctx, AV_LOG_ERROR, \"changing width/height on \"\n \"slice %d\\n\", h0->current_slice + 1);\n return AVERROR_INVALIDDATA;\n }\n\n flush_change(h);\n\n if ((ret = get_pixel_format(h, 1)) < 0)\n return ret;\n h->avctx->pix_fmt = ret;\n\n av_log(h->avctx, AV_LOG_INFO, \"Reinit context to %dx%d, \"\n \"pix_fmt: %s\\n\", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));\n\n if ((ret = h264_slice_header_init(h, 1)) < 0) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"h264_slice_header_init() failed\\n\");\n return ret;\n }\n }\n if (!h->context_initialized) {\n if (h != h0) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Cannot (re-)initialize context during parallel decoding.\\n\");\n return AVERROR_PATCHWELCOME;\n }\n\n if ((ret = get_pixel_format(h, 1)) < 0)\n return ret;\n h->avctx->pix_fmt = ret;\n\n if ((ret = h264_slice_header_init(h, 0)) < 0) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"h264_slice_header_init() failed\\n\");\n return ret;\n }\n }\n\n if (h == h0 && h->dequant_coeff_pps != pps_id) {\n h->dequant_coeff_pps = pps_id;\n init_dequant_tables(h);\n }\n\n h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);\n\n h->mb_mbaff = 0;\n h->mb_aff_frame = 0;\n last_pic_structure = h0->picture_structure;\n last_pic_droppable = h0->droppable;\n h->droppable = h->nal_ref_idc == 0;\n if (h->sps.frame_mbs_only_flag) {\n h->picture_structure = PICT_FRAME;\n } else {\n if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {\n av_log(h->avctx, AV_LOG_ERROR, \"This stream was generated by a broken encoder, invalid 8x8 inference\\n\");\n return -1;\n }\n field_pic_flag = get_bits1(&h->gb);\n if (field_pic_flag) {\n bottom_field_flag = get_bits1(&h->gb);\n h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;\n } else {\n h->picture_structure = PICT_FRAME;\n h->mb_aff_frame = h->sps.mb_aff;\n }\n }\n h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;\n\n if (h0->current_slice != 0) {\n if (last_pic_structure != h->picture_structure ||\n last_pic_droppable != h->droppable) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Changing field mode (%d -> %d) between slices is not allowed\\n\",\n last_pic_structure, h->picture_structure);\n h->picture_structure = last_pic_structure;\n h->droppable = last_pic_droppable;\n return AVERROR_INVALIDDATA;\n } else if (!h0->cur_pic_ptr) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"unset cur_pic_ptr on %d. slice\\n\",\n h0->current_slice + 1);\n return AVERROR_INVALIDDATA;\n }\n } else {\n /* Shorten frame num gaps so we don't have to allocate reference\n * frames just to throw them away */\n if (h->frame_num != h->prev_frame_num) {\n int unwrap_prev_frame_num = h->prev_frame_num;\n int max_frame_num = 1 << h->sps.log2_max_frame_num;\n\n if (unwrap_prev_frame_num > h->frame_num)\n unwrap_prev_frame_num -= max_frame_num;\n\n if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {\n unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;\n if (unwrap_prev_frame_num < 0)\n unwrap_prev_frame_num += max_frame_num;\n\n h->prev_frame_num = unwrap_prev_frame_num;\n }\n }\n\n /* See if we have a decoded first field looking for a pair...\n * Here, we're using that to see if we should mark previously\n * decode frames as \"finished\".\n * We have to do that before the \"dummy\" in-between frame allocation,\n * since that can modify h->cur_pic_ptr. */\n if (h0->first_field) {\n assert(h0->cur_pic_ptr);\n assert(h0->cur_pic_ptr->f.buf[0]);\n assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);\n\n /* Mark old field/frame as completed */\n if (h0->cur_pic_ptr->tf.owner == h0->avctx) {\n ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,\n last_pic_structure == PICT_BOTTOM_FIELD);\n }\n\n /* figure out if we have a complementary field pair */\n if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {\n /* Previous field is unmatched. Don't display it, but let it\n * remain for reference if marked as such. */\n if (last_pic_structure != PICT_FRAME) {\n ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,\n last_pic_structure == PICT_TOP_FIELD);\n }\n } else {\n if (h0->cur_pic_ptr->frame_num != h->frame_num) {\n /* This and previous field were reference, but had\n * different frame_nums. Consider this field first in\n * pair. Throw away previous field except for reference\n * purposes. */\n if (last_pic_structure != PICT_FRAME) {\n ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,\n last_pic_structure == PICT_TOP_FIELD);\n }\n } else {\n /* Second field in complementary pair */\n if (!((last_pic_structure == PICT_TOP_FIELD &&\n h->picture_structure == PICT_BOTTOM_FIELD) ||\n (last_pic_structure == PICT_BOTTOM_FIELD &&\n h->picture_structure == PICT_TOP_FIELD))) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Invalid field mode combination %d/%d\\n\",\n last_pic_structure, h->picture_structure);\n h->picture_structure = last_pic_structure;\n h->droppable = last_pic_droppable;\n return AVERROR_INVALIDDATA;\n } else if (last_pic_droppable != h->droppable) {\n avpriv_request_sample(h->avctx,\n \"Found reference and non-reference fields in the same frame, which\");\n h->picture_structure = last_pic_structure;\n h->droppable = last_pic_droppable;\n return AVERROR_PATCHWELCOME;\n }\n }\n }\n }\n\n while (h->frame_num != h->prev_frame_num && !h0->first_field &&\n h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {\n Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;\n av_log(h->avctx, AV_LOG_DEBUG, \"Frame num gap %d %d\\n\",\n h->frame_num, h->prev_frame_num);\n if (!h->sps.gaps_in_frame_num_allowed_flag)\n for(i=0; ilast_pocs); i++)\n h->last_pocs[i] = INT_MIN;\n ret = h264_frame_start(h);\n if (ret < 0) {\n h0->first_field = 0;\n return ret;\n }\n\n h->prev_frame_num++;\n h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;\n h->cur_pic_ptr->frame_num = h->prev_frame_num;\n ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);\n ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);\n ret = ff_generate_sliding_window_mmcos(h, 1);\n if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))\n return ret;\n ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);\n if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))\n return ret;\n /* Error concealment: If a ref is missing, copy the previous ref\n * in its place.\n * FIXME: Avoiding a memcpy would be nice, but ref handling makes\n * many assumptions about there being no actual duplicates.\n * FIXME: This does not copy padding for out-of-frame motion\n * vectors. Given we are concealing a lost frame, this probably\n * is not noticeable by comparison, but it should be fixed. */\n if (h->short_ref_count) {\n if (prev) {\n av_image_copy(h->short_ref[0]->f.data,\n h->short_ref[0]->f.linesize,\n (const uint8_t **)prev->f.data,\n prev->f.linesize,\n h->avctx->pix_fmt,\n h->mb_width * 16,\n h->mb_height * 16);\n h->short_ref[0]->poc = prev->poc + 2;\n }\n h->short_ref[0]->frame_num = h->prev_frame_num;\n }\n }\n\n /* See if we have a decoded first field looking for a pair...\n * We're using that to see whether to continue decoding in that\n * frame, or to allocate a new one. */\n if (h0->first_field) {\n assert(h0->cur_pic_ptr);\n assert(h0->cur_pic_ptr->f.buf[0]);\n assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);\n\n /* figure out if we have a complementary field pair */\n if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {\n /* Previous field is unmatched. Don't display it, but let it\n * remain for reference if marked as such. */\n h0->cur_pic_ptr = NULL;\n h0->first_field = FIELD_PICTURE(h);\n } else {\n if (h0->cur_pic_ptr->frame_num != h->frame_num) {\n ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,\n h0->picture_structure==PICT_BOTTOM_FIELD);\n /* This and the previous field had different frame_nums.\n * Consider this field first in pair. Throw away previous\n * one except for reference purposes. */\n h0->first_field = 1;\n h0->cur_pic_ptr = NULL;\n } else {\n /* Second field in complementary pair */\n h0->first_field = 0;\n }\n }\n } else {\n /* Frame or first field in a potentially complementary pair */\n h0->first_field = FIELD_PICTURE(h);\n }\n\n if (!FIELD_PICTURE(h) || h0->first_field) {\n if (h264_frame_start(h) < 0) {\n h0->first_field = 0;\n return AVERROR_INVALIDDATA;\n }\n } else {\n release_unused_pictures(h, 0);\n }\n /* Some macroblocks can be accessed before they're available in case\n * of lost slices, MBAFF or threading. */\n if (FIELD_PICTURE(h)) {\n for(i = (h->picture_structure == PICT_BOTTOM_FIELD); imb_height; i++)\n memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));\n } else {\n memset(h->slice_table, -1,\n (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));\n }\n h0->last_slice_type = -1;\n }\n if (h != h0 && (ret = clone_slice(h, h0)) < 0)\n return ret;\n\n /* can't be in alloc_tables because linesize isn't known there.\n * FIXME: redo bipred weight to not require extra buffer? */\n for (i = 0; i < h->slice_context_count; i++)\n if (h->thread_context[i]) {\n ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);\n if (ret < 0)\n return ret;\n }\n\n h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup\n\n av_assert1(h->mb_num == h->mb_width * h->mb_height);\n if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||\n first_mb_in_slice >= h->mb_num) {\n av_log(h->avctx, AV_LOG_ERROR, \"first_mb_in_slice overflow\\n\");\n return AVERROR_INVALIDDATA;\n }\n h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;\n h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<\n FIELD_OR_MBAFF_PICTURE(h);\n if (h->picture_structure == PICT_BOTTOM_FIELD)\n h->resync_mb_y = h->mb_y = h->mb_y + 1;\n av_assert1(h->mb_y < h->mb_height);\n\n if (h->picture_structure == PICT_FRAME) {\n h->curr_pic_num = h->frame_num;\n h->max_pic_num = 1 << h->sps.log2_max_frame_num;\n } else {\n h->curr_pic_num = 2 * h->frame_num + 1;\n h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);\n }\n\n if (h->nal_unit_type == NAL_IDR_SLICE)\n get_ue_golomb(&h->gb); /* idr_pic_id */\n\n if (h->sps.poc_type == 0) {\n h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);\n\n if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)\n h->delta_poc_bottom = get_se_golomb(&h->gb);\n }\n\n if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {\n h->delta_poc[0] = get_se_golomb(&h->gb);\n\n if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)\n h->delta_poc[1] = get_se_golomb(&h->gb);\n }\n\n ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);\n\n if (h->pps.redundant_pic_cnt_present)\n h->redundant_pic_count = get_ue_golomb(&h->gb);\n\n ret = ff_set_ref_count(h);\n if (ret < 0)\n return ret;\n\n if (slice_type != AV_PICTURE_TYPE_I &&\n (h0->current_slice == 0 ||\n slice_type != h0->last_slice_type ||\n memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {\n\n ff_h264_fill_default_ref_list(h);\n }\n\n if (h->slice_type_nos != AV_PICTURE_TYPE_I) {\n ret = ff_h264_decode_ref_pic_list_reordering(h);\n if (ret < 0) {\n h->ref_count[1] = h->ref_count[0] = 0;\n return ret;\n }\n }\n\n if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||\n (h->pps.weighted_bipred_idc == 1 &&\n h->slice_type_nos == AV_PICTURE_TYPE_B))\n ff_pred_weight_table(h);\n else if (h->pps.weighted_bipred_idc == 2 &&\n h->slice_type_nos == AV_PICTURE_TYPE_B) {\n implicit_weight_table(h, -1);\n } else {\n h->use_weight = 0;\n for (i = 0; i < 2; i++) {\n h->luma_weight_flag[i] = 0;\n h->chroma_weight_flag[i] = 0;\n }\n }\n\n // If frame-mt is enabled, only update mmco tables for the first slice\n // in a field. Subsequent slices can temporarily clobber h->mmco_index\n // or h->mmco, which will cause ref list mix-ups and decoding errors\n // further down the line. This may break decoding if the first slice is\n // corrupt, thus we only do this if frame-mt is enabled.\n if (h->nal_ref_idc) {\n ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,\n !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||\n h0->current_slice == 0);\n if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))\n return AVERROR_INVALIDDATA;\n }\n\n if (FRAME_MBAFF(h)) {\n ff_h264_fill_mbaff_ref_list(h);\n\n if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {\n implicit_weight_table(h, 0);\n implicit_weight_table(h, 1);\n }\n }\n\n if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)\n ff_h264_direct_dist_scale_factor(h);\n ff_h264_direct_ref_list_init(h);\n\n if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {\n tmp = get_ue_golomb_31(&h->gb);\n if (tmp > 2) {\n av_log(h->avctx, AV_LOG_ERROR, \"cabac_init_idc overflow\\n\");\n return AVERROR_INVALIDDATA;\n }\n h->cabac_init_idc = tmp;\n }\n\n h->last_qscale_diff = 0;\n tmp = h->pps.init_qp + get_se_golomb(&h->gb);\n if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {\n av_log(h->avctx, AV_LOG_ERROR, \"QP %u out of range\\n\", tmp);\n return AVERROR_INVALIDDATA;\n }\n h->qscale = tmp;\n h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);\n h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);\n // FIXME qscale / qp ... stuff\n if (h->slice_type == AV_PICTURE_TYPE_SP)\n get_bits1(&h->gb); /* sp_for_switch_flag */\n if (h->slice_type == AV_PICTURE_TYPE_SP ||\n h->slice_type == AV_PICTURE_TYPE_SI)\n get_se_golomb(&h->gb); /* slice_qs_delta */\n\n h->deblocking_filter = 1;\n h->slice_alpha_c0_offset = 52;\n h->slice_beta_offset = 52;\n if (h->pps.deblocking_filter_parameters_present) {\n tmp = get_ue_golomb_31(&h->gb);\n if (tmp > 2) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"deblocking_filter_idc %u out of range\\n\", tmp);\n return AVERROR_INVALIDDATA;\n }\n h->deblocking_filter = tmp;\n if (h->deblocking_filter < 2)\n h->deblocking_filter ^= 1; // 1<->0\n\n if (h->deblocking_filter) {\n h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;\n h->slice_beta_offset += get_se_golomb(&h->gb) << 1;\n if (h->slice_alpha_c0_offset > 104U ||\n h->slice_beta_offset > 104U) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"deblocking filter parameters %d %d out of range\\n\",\n h->slice_alpha_c0_offset, h->slice_beta_offset);\n return AVERROR_INVALIDDATA;\n }\n }\n }\n\n if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||\n (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&\n h->slice_type_nos != AV_PICTURE_TYPE_I) ||\n (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&\n h->slice_type_nos == AV_PICTURE_TYPE_B) ||\n (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&\n h->nal_ref_idc == 0))\n h->deblocking_filter = 0;\n\n if (h->deblocking_filter == 1 && h0->max_contexts > 1) {\n if (h->avctx->flags2 & CODEC_FLAG2_FAST) {\n /* Cheat slightly for speed:\n * Do not bother to deblock across slices. */\n h->deblocking_filter = 2;\n } else {\n h0->max_contexts = 1;\n if (!h0->single_decode_warning) {\n av_log(h->avctx, AV_LOG_INFO,\n \"Cannot parallelize deblocking type 1, decoding such frames in sequential order\\n\");\n h0->single_decode_warning = 1;\n }\n if (h != h0) {\n av_log(h->avctx, AV_LOG_ERROR,\n \"Deblocking switched inside frame.\\n\");\n return 1;\n }\n }\n }\n h->qp_thresh = 15 + 52 -\n FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -\n FFMAX3(0,\n h->pps.chroma_qp_index_offset[0],\n h->pps.chroma_qp_index_offset[1]) +\n 6 * (h->sps.bit_depth_luma - 8);\n\n h0->last_slice_type = slice_type;\n memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));\n h->slice_num = ++h0->current_slice;\n\n if (h->slice_num)\n h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;\n if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y\n && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y\n && h->slice_num >= MAX_SLICES) {\n //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case\n av_log(h->avctx, AV_LOG_WARNING, \"Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\\n\", h->slice_num, MAX_SLICES);\n }\n\n for (j = 0; j < 2; j++) {\n int id_list[16];\n int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];\n for (i = 0; i < 16; i++) {\n id_list[i] = 60;\n if (j < h->list_count && i < h->ref_count[j] &&\n h->ref_list[j][i].f.buf[0]) {\n int k;\n AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;\n for (k = 0; k < h->short_ref_count; k++)\n if (h->short_ref[k]->f.buf[0]->buffer == buf) {\n id_list[i] = k;\n break;\n }\n for (k = 0; k < h->long_ref_count; k++)\n if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {\n id_list[i] = h->short_ref_count + k;\n break;\n }\n }\n }\n\n ref2frm[0] =\n ref2frm[1] = -1;\n for (i = 0; i < 16; i++)\n ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);\n ref2frm[18 + 0] =\n ref2frm[18 + 1] = -1;\n for (i = 16; i < 48; i++)\n ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +\n (h->ref_list[j][i].reference & 3);\n }\n\n if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0];\n if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0];\n h->er.ref_count = h->ref_count[0];\n h0->au_pps_id = pps_id;\n h->sps.new =\n h0->sps_buffers[h->pps.sps_id]->new = 0;\n h->current_sps_id = h->pps.sps_id;\n\n if (h->avctx->debug & FF_DEBUG_PICT_INFO) {\n av_log(h->avctx, AV_LOG_DEBUG,\n \"slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\\n\",\n h->slice_num,\n (h->picture_structure == PICT_FRAME ? \"F\" : h->picture_structure == PICT_TOP_FIELD ? \"T\" : \"B\"),\n first_mb_in_slice,\n av_get_picture_type_char(h->slice_type),\n h->slice_type_fixed ? \" fix\" : \"\",\n h->nal_unit_type == NAL_IDR_SLICE ? \" IDR\" : \"\",\n pps_id, h->frame_num,\n h->cur_pic_ptr->field_poc[0],\n h->cur_pic_ptr->field_poc[1],\n h->ref_count[0], h->ref_count[1],\n h->qscale,\n h->deblocking_filter,\n h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,\n h->use_weight,\n h->use_weight == 1 && h->use_weight_chroma ? \"c\" : \"\",\n h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? \"SPAT\" : \"TEMP\") : \"\");\n }\n\n return 0;\n}", "project": "FFmpeg", "hash": 200232776860561206754163513001485909644, "size": 695, "commit_id": "8a3b85f3a7952c54a2c36ba1797f7e0cde9f85aa", "message": "avcodec/h264: update current_sps & sps->new only after the whole slice header decoder and init code finished\n\nThis avoids them being cleared before the full initialization finished\n\nFixes out of array read\nFixes: asan_heap-oob_f0c5e6_7071_cov_1605985132_mov_h264_aac__Demo_FlagOfOurFathers.mov\nFound-by: Mateusz \"j00ru\" Jurczyk and Gynvael Coldwind\nSigned-off-by: Michael Niedermayer ", "target": 0, "dataset": "other", "idx": 270122} {"func": "Status KernelAndDeviceOp::Run(\n ScopedStepContainer* step_container, const EagerKernelArgs& inputs,\n std::vector* outputs,\n CancellationManager* cancellation_manager,\n const absl::optional& remote_func_params) {\n OpKernelContext::Params params;\n params.device = device_;\n params.frame_iter = FrameAndIter(0, 0);\n params.inputs = inputs.GetTensorValues();\n params.op_kernel = kernel_.get();\n params.resource_manager = device_->resource_manager();\n params.input_alloc_attrs = &input_alloc_attrs_;\n params.output_attr_array = output_alloc_attrs_.data();\n params.function_library = flr_;\n params.slice_reader_cache = &slice_reader_cache_;\n params.rendezvous = rendezvous_;\n OpExecutionState* op_execution_state = nullptr;\n\n CancellationManager default_cancellation_manager;\n if (cancellation_manager) {\n params.cancellation_manager = cancellation_manager;\n } else if (kernel_->is_deferred()) {\n op_execution_state = new OpExecutionState;\n params.cancellation_manager = &op_execution_state->cancellation_manager;\n params.inc_num_deferred_ops_function = [op_execution_state]() {\n op_execution_state->Ref();\n };\n params.dec_num_deferred_ops_function = [op_execution_state]() {\n op_execution_state->Unref();\n };\n } else {\n params.cancellation_manager = &default_cancellation_manager;\n }\n\n params.log_memory = log_memory_;\n\n params.runner = get_runner();\n\n params.step_container =\n step_container == nullptr ? &step_container_ : step_container;\n auto step_container_cleanup = gtl::MakeCleanup([step_container, this] {\n if (step_container == nullptr) {\n this->step_container_.CleanUp();\n }\n });\n\n params.collective_executor =\n collective_executor_ ? collective_executor_->get() : nullptr;\n\n OpKernelContext context(¶ms);\n\n {\n port::ScopedFlushDenormal flush;\n port::ScopedSetRound round(FE_TONEAREST);\n // 'AnnotatedTraceMe' will trace both scheduling time on host and execution\n // time on device of the OpKernel.\n profiler::AnnotatedTraceMe activity(\n [&] { return kernel_->TraceString(context, /*verbose=*/false); },\n profiler::TraceMeLevel::kInfo);\n device_->Compute(kernel_.get(), &context);\n }\n\n // Clean up execution op_execution_state if deferred ops aren't running.\n if (op_execution_state != nullptr) {\n op_execution_state->Unref();\n }\n\n if (!context.status().ok()) return context.status();\n\n if (outputs != nullptr) {\n outputs->clear();\n for (int i = 0; i < context.num_outputs(); ++i) {\n outputs->push_back(Tensor(*context.mutable_output(i)));\n }\n }\n return Status::OK();\n}", "project": "tensorflow", "hash": 268532713607530076905202853458432555638, "size": 77, "commit_id": "da8558533d925694483d2c136a9220d6d49d843c", "message": "Fix undefined behavior in `tf.raw_ops.Switch` in eager mode.\n\nPiperOrigin-RevId: 332578058\nChange-Id: I9727571d2f21476b10d8aa27c1b7176564b76ac9", "target": 1, "dataset": "other", "idx": 198174} {"func": "Status KernelAndDeviceOp::Run(\n ScopedStepContainer* step_container, const EagerKernelArgs& inputs,\n std::vector* outputs,\n CancellationManager* cancellation_manager,\n const absl::optional& remote_func_params) {\n OpKernelContext::Params params;\n params.device = device_;\n params.frame_iter = FrameAndIter(0, 0);\n params.inputs = inputs.GetTensorValues();\n params.op_kernel = kernel_.get();\n params.resource_manager = device_->resource_manager();\n params.input_alloc_attrs = &input_alloc_attrs_;\n params.output_attr_array = output_alloc_attrs_.data();\n params.function_library = flr_;\n params.slice_reader_cache = &slice_reader_cache_;\n params.rendezvous = rendezvous_;\n OpExecutionState* op_execution_state = nullptr;\n\n CancellationManager default_cancellation_manager;\n if (cancellation_manager) {\n params.cancellation_manager = cancellation_manager;\n } else if (kernel_->is_deferred()) {\n op_execution_state = new OpExecutionState;\n params.cancellation_manager = &op_execution_state->cancellation_manager;\n params.inc_num_deferred_ops_function = [op_execution_state]() {\n op_execution_state->Ref();\n };\n params.dec_num_deferred_ops_function = [op_execution_state]() {\n op_execution_state->Unref();\n };\n } else {\n params.cancellation_manager = &default_cancellation_manager;\n }\n\n params.log_memory = log_memory_;\n\n params.runner = get_runner();\n\n params.step_container =\n step_container == nullptr ? &step_container_ : step_container;\n auto step_container_cleanup = gtl::MakeCleanup([step_container, this] {\n if (step_container == nullptr) {\n this->step_container_.CleanUp();\n }\n });\n\n params.collective_executor =\n collective_executor_ ? collective_executor_->get() : nullptr;\n\n OpKernelContext context(¶ms);\n\n {\n port::ScopedFlushDenormal flush;\n port::ScopedSetRound round(FE_TONEAREST);\n // 'AnnotatedTraceMe' will trace both scheduling time on host and execution\n // time on device of the OpKernel.\n profiler::AnnotatedTraceMe activity(\n [&] { return kernel_->TraceString(context, /*verbose=*/false); },\n profiler::TraceMeLevel::kInfo);\n device_->Compute(kernel_.get(), &context);\n }\n\n // Clean up execution op_execution_state if deferred ops aren't running.\n if (op_execution_state != nullptr) {\n op_execution_state->Unref();\n }\n\n if (!context.status().ok()) return context.status();\n\n if (outputs != nullptr) {\n outputs->clear();\n for (int i = 0; i < context.num_outputs(); ++i) {\n const auto* output_tensor = context.mutable_output(i);\n if (output_tensor != nullptr) {\n outputs->push_back(Tensor(*output_tensor));\n } else {\n outputs->push_back(Tensor());\n }\n }\n }\n return Status::OK();\n}", "project": "tensorflow", "hash": 159214455117997485478071511420441997014, "size": 82, "commit_id": "da8558533d925694483d2c136a9220d6d49d843c", "message": "Fix undefined behavior in `tf.raw_ops.Switch` in eager mode.\n\nPiperOrigin-RevId: 332578058\nChange-Id: I9727571d2f21476b10d8aa27c1b7176564b76ac9", "target": 0, "dataset": "other", "idx": 270145} {"func": " void Compute(OpKernelContext* ctx) override {\n const auto splits = ctx->input(0).flat();\n const auto values = ctx->input(1).flat();\n const Tensor& size_t = ctx->input(2);\n const auto weights = ctx->input(3).flat();\n const int64 weights_size = weights.size();\n\n Tidx size = size_t.scalar()();\n OP_REQUIRES(\n ctx, size >= 0,\n errors::InvalidArgument(\"size (\", size, \") must be non-negative\"));\n\n int num_rows = splits.size() - 1;\n int num_values = values.size();\n int batch_idx = 0;\n\n Tensor* out_t;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, TensorShape({num_rows, size}), &out_t));\n functor::SetZeroFunctor fill;\n fill(ctx->eigen_device(), out_t->flat());\n const auto out = out_t->matrix();\n\n for (int idx = 0; idx < num_values; ++idx) {\n while (idx >= splits(batch_idx)) {\n batch_idx++;\n }\n Tidx bin = values(idx);\n OP_REQUIRES(ctx, bin >= 0,\n errors::InvalidArgument(\"Input must be non-negative\"));\n if (bin < size) {\n if (binary_output_) {\n out(batch_idx - 1, bin) = T(1);\n } else {\n T value = (weights_size > 0) ? weights(idx) : T(1);\n out(batch_idx - 1, bin) += value;\n }\n }\n }\n }", "project": "tensorflow", "hash": 98707188461233797046371132573913629241, "size": 40, "commit_id": "eebb96c2830d48597d055d247c0e9aebaea94cd5", "message": "Fix an invalid address vulnerability in `tf.raw_ops.RaggedBincount`.\n\nPiperOrigin-RevId: 368293153\nChange-Id: I4b4e493d3fd05e7dc55a55de3a041a80a4f275c3", "target": 1, "dataset": "other", "idx": 198180} {"func": " void Compute(OpKernelContext* ctx) override {\n const auto splits = ctx->input(0).flat();\n const auto values = ctx->input(1).flat();\n const Tensor& size_t = ctx->input(2);\n const auto weights = ctx->input(3).flat();\n const int64 weights_size = weights.size();\n\n Tidx size = size_t.scalar()();\n OP_REQUIRES(\n ctx, size >= 0,\n errors::InvalidArgument(\"size (\", size, \") must be non-negative\"));\n\n int num_rows = splits.size() - 1;\n int num_values = values.size();\n int batch_idx = 0;\n\n OP_REQUIRES(ctx, splits(0) == 0,\n errors::InvalidArgument(\"Splits must start with 0, not with \",\n splits(0)));\n\n OP_REQUIRES(ctx, splits(num_rows) == num_values,\n errors::InvalidArgument(\n \"Splits must end with the number of values, got \",\n splits(num_rows), \" instead of \", num_values));\n\n Tensor* out_t;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, TensorShape({num_rows, size}), &out_t));\n functor::SetZeroFunctor fill;\n fill(ctx->eigen_device(), out_t->flat());\n const auto out = out_t->matrix();\n\n for (int idx = 0; idx < num_values; ++idx) {\n while (idx >= splits(batch_idx)) {\n batch_idx++;\n }\n Tidx bin = values(idx);\n OP_REQUIRES(ctx, bin >= 0,\n errors::InvalidArgument(\"Input must be non-negative\"));\n if (bin < size) {\n if (binary_output_) {\n out(batch_idx - 1, bin) = T(1);\n } else {\n T value = (weights_size > 0) ? weights(idx) : T(1);\n out(batch_idx - 1, bin) += value;\n }\n }\n }\n }", "project": "tensorflow", "hash": 127889019311252322646574831716871048286, "size": 49, "commit_id": "eebb96c2830d48597d055d247c0e9aebaea94cd5", "message": "Fix an invalid address vulnerability in `tf.raw_ops.RaggedBincount`.\n\nPiperOrigin-RevId: 368293153\nChange-Id: I4b4e493d3fd05e7dc55a55de3a041a80a4f275c3", "target": 0, "dataset": "other", "idx": 270171} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor* input_indices;\n const Tensor* input_values;\n const Tensor* input_shape;\n SparseTensorsMap* map;\n\n OP_REQUIRES_OK(context, context->input(\"sparse_indices\", &input_indices));\n OP_REQUIRES_OK(context, context->input(\"sparse_values\", &input_values));\n OP_REQUIRES_OK(context, context->input(\"sparse_shape\", &input_shape));\n OP_REQUIRES_OK(context, GetMap(context, true /* is_writing */, &map));\n\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be a matrix but received shape \",\n input_indices->shape().DebugString()));\n\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values->shape()),\n errors::InvalidArgument(\n \"Input values should be a vector but received shape \",\n input_values->shape().DebugString()));\n\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape->shape()),\n errors::InvalidArgument(\n \"Input shape should be a vector but received shape \",\n input_shape->shape().DebugString()));\n\n int rank = input_shape->NumElements();\n\n OP_REQUIRES(\n context, rank > 1,\n errors::InvalidArgument(\n \"Rank of input SparseTensor should be > 1, but saw rank: \", rank));\n\n TensorShape tensor_input_shape(input_shape->vec());\n gtl::InlinedVector std_order(rank);\n std::iota(std_order.begin(), std_order.end(), 0);\n SparseTensor input_st;\n OP_REQUIRES_OK(context, SparseTensor::Create(*input_indices, *input_values,\n tensor_input_shape, std_order,\n &input_st));\n\n auto input_shape_t = input_shape->vec();\n const int64 N = input_shape_t(0);\n\n Tensor sparse_handles(DT_INT64, TensorShape({N}));\n auto sparse_handles_t = sparse_handles.vec();\n\n OP_REQUIRES_OK(context, input_st.IndicesValid());\n\n // We can generate the output shape proto string now, for all\n // minibatch entries.\n TensorShape output_shape;\n OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(\n input_shape_t.data() + 1,\n input_shape->NumElements() - 1, &output_shape));\n\n // Get groups by minibatch dimension\n std::unordered_set visited;\n sparse::GroupIterable minibatch = input_st.group({0});\n for (const auto& subset : minibatch) {\n const int64 b = subset.group()[0];\n visited.insert(b);\n OP_REQUIRES(\n context, b > -1 && b < N,\n errors::InvalidArgument(\n \"Received unexpected column 0 value in input SparseTensor: \", b,\n \" < 0 or >= N (= \", N, \")\"));\n\n const auto indices = subset.indices();\n const auto values = subset.values();\n const int64 num_entries = values.size();\n\n Tensor output_indices = Tensor(DT_INT64, {num_entries, rank - 1});\n Tensor output_values = Tensor(DataTypeToEnum::value, {num_entries});\n\n auto output_indices_t = output_indices.matrix();\n auto output_values_t = output_values.vec();\n\n for (int i = 0; i < num_entries; ++i) {\n for (int d = 1; d < rank; ++d) {\n output_indices_t(i, d - 1) = indices(i, d);\n }\n output_values_t(i) = values(i);\n }\n\n SparseTensor st_i;\n OP_REQUIRES_OK(context,\n SparseTensor::Create(output_indices, output_values,\n output_shape, &st_i));\n int64 handle;\n OP_REQUIRES_OK(context, map->AddSparseTensor(context, st_i, &handle));\n sparse_handles_t(b) = handle;\n }\n\n // Fill in any gaps; we must provide an empty ST for batch entries\n // the grouper didn't find.\n if (visited.size() < N) {\n Tensor empty_indices(DT_INT64, {0, rank - 1});\n Tensor empty_values(DataTypeToEnum::value, {0});\n SparseTensor empty_st;\n OP_REQUIRES_OK(context, SparseTensor::Create(empty_indices, empty_values,\n output_shape, &empty_st));\n\n for (int64 b = 0; b < N; ++b) {\n // We skipped this batch entry.\n if (visited.find(b) == visited.end()) {\n int64 handle;\n OP_REQUIRES_OK(context,\n map->AddSparseTensor(context, empty_st, &handle));\n sparse_handles_t(b) = handle;\n }\n }\n }\n\n context->set_output(0, sparse_handles);\n }", "project": "tensorflow", "hash": 334418536661201182685376817370728187459, "size": 116, "commit_id": "69c68ecbb24dff3fa0e46da0d16c821a2dd22d7c", "message": "Fix overflow CHECK issue with `tf.raw_ops.AddManySparseToTensorsMap`.\n\nPiperOrigin-RevId: 369492969\nChange-Id: I1d70d6c0c92e3d7a25bc3b3aa2a0c0ac9688bf81", "target": 1, "dataset": "other", "idx": 198191} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor* input_indices;\n const Tensor* input_values;\n const Tensor* input_shape;\n SparseTensorsMap* map;\n\n OP_REQUIRES_OK(context, context->input(\"sparse_indices\", &input_indices));\n OP_REQUIRES_OK(context, context->input(\"sparse_values\", &input_values));\n OP_REQUIRES_OK(context, context->input(\"sparse_shape\", &input_shape));\n OP_REQUIRES_OK(context, GetMap(context, true /* is_writing */, &map));\n\n OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be a matrix but received shape \",\n input_indices->shape().DebugString()));\n\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values->shape()),\n errors::InvalidArgument(\n \"Input values should be a vector but received shape \",\n input_values->shape().DebugString()));\n\n OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape->shape()),\n errors::InvalidArgument(\n \"Input shape should be a vector but received shape \",\n input_shape->shape().DebugString()));\n\n int rank = input_shape->NumElements();\n\n OP_REQUIRES(\n context, rank > 1,\n errors::InvalidArgument(\n \"Rank of input SparseTensor should be > 1, but saw rank: \", rank));\n\n auto input_shape_vec = input_shape->vec();\n int new_num_elements = 1;\n bool overflow_ocurred = false;\n for (int i = 0; i < input_shape_vec.size(); i++) {\n new_num_elements =\n MultiplyWithoutOverflow(new_num_elements, input_shape_vec(i));\n if (new_num_elements < 0) {\n overflow_ocurred = true;\n }\n }\n\n OP_REQUIRES(\n context, !overflow_ocurred,\n errors::Internal(\"Encountered overflow from large input shape.\"));\n\n TensorShape tensor_input_shape(input_shape_vec);\n gtl::InlinedVector std_order(rank);\n std::iota(std_order.begin(), std_order.end(), 0);\n SparseTensor input_st;\n OP_REQUIRES_OK(context, SparseTensor::Create(*input_indices, *input_values,\n tensor_input_shape, std_order,\n &input_st));\n\n const int64 N = input_shape_vec(0);\n\n Tensor sparse_handles(DT_INT64, TensorShape({N}));\n auto sparse_handles_t = sparse_handles.vec();\n\n OP_REQUIRES_OK(context, input_st.IndicesValid());\n\n // We can generate the output shape proto string now, for all\n // minibatch entries.\n TensorShape output_shape;\n OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(\n input_shape_vec.data() + 1,\n input_shape->NumElements() - 1, &output_shape));\n\n // Get groups by minibatch dimension\n std::unordered_set visited;\n sparse::GroupIterable minibatch = input_st.group({0});\n for (const auto& subset : minibatch) {\n const int64 b = subset.group()[0];\n visited.insert(b);\n OP_REQUIRES(\n context, b > -1 && b < N,\n errors::InvalidArgument(\n \"Received unexpected column 0 value in input SparseTensor: \", b,\n \" < 0 or >= N (= \", N, \")\"));\n\n const auto indices = subset.indices();\n const auto values = subset.values();\n const int64 num_entries = values.size();\n\n Tensor output_indices = Tensor(DT_INT64, {num_entries, rank - 1});\n Tensor output_values = Tensor(DataTypeToEnum::value, {num_entries});\n\n auto output_indices_t = output_indices.matrix();\n auto output_values_t = output_values.vec();\n\n for (int i = 0; i < num_entries; ++i) {\n for (int d = 1; d < rank; ++d) {\n output_indices_t(i, d - 1) = indices(i, d);\n }\n output_values_t(i) = values(i);\n }\n\n SparseTensor st_i;\n OP_REQUIRES_OK(context,\n SparseTensor::Create(output_indices, output_values,\n output_shape, &st_i));\n int64 handle;\n OP_REQUIRES_OK(context, map->AddSparseTensor(context, st_i, &handle));\n sparse_handles_t(b) = handle;\n }\n\n // Fill in any gaps; we must provide an empty ST for batch entries\n // the grouper didn't find.\n if (visited.size() < N) {\n Tensor empty_indices(DT_INT64, {0, rank - 1});\n Tensor empty_values(DataTypeToEnum::value, {0});\n SparseTensor empty_st;\n OP_REQUIRES_OK(context, SparseTensor::Create(empty_indices, empty_values,\n output_shape, &empty_st));\n\n for (int64 b = 0; b < N; ++b) {\n // We skipped this batch entry.\n if (visited.find(b) == visited.end()) {\n int64 handle;\n OP_REQUIRES_OK(context,\n map->AddSparseTensor(context, empty_st, &handle));\n sparse_handles_t(b) = handle;\n }\n }\n }\n\n context->set_output(0, sparse_handles);\n }", "project": "tensorflow", "hash": 89479228034469738692764404438746447809, "size": 130, "commit_id": "69c68ecbb24dff3fa0e46da0d16c821a2dd22d7c", "message": "Fix overflow CHECK issue with `tf.raw_ops.AddManySparseToTensorsMap`.\n\nPiperOrigin-RevId: 369492969\nChange-Id: I1d70d6c0c92e3d7a25bc3b3aa2a0c0ac9688bf81", "target": 0, "dataset": "other", "idx": 270289} {"func": "static int parse_playlist(HLSContext *c, const char *url,\n struct playlist *pls, AVIOContext *in)\n{\n int ret = 0, is_segment = 0, is_variant = 0;\n int64_t duration = 0;\n enum KeyType key_type = KEY_NONE;\n uint8_t iv[16] = \"\";\n int has_iv = 0;\n char key[MAX_URL_SIZE] = \"\";\n char line[MAX_URL_SIZE];\n const char *ptr;\n int close_in = 0;\n int64_t seg_offset = 0;\n int64_t seg_size = -1;\n uint8_t *new_url = NULL;\n struct variant_info variant_info;\n char tmp_str[MAX_URL_SIZE];\n struct segment *cur_init_section = NULL;\n\n if (!in) {\n#if 1\n AVDictionary *opts = NULL;\n close_in = 1;\n /* Some HLS servers don't like being sent the range header */\n av_dict_set(&opts, \"seekable\", \"0\", 0);\n\n // broker prior HTTP options that should be consistent across requests\n av_dict_set(&opts, \"user-agent\", c->user_agent, 0);\n av_dict_set(&opts, \"cookies\", c->cookies, 0);\n av_dict_set(&opts, \"headers\", c->headers, 0);\n\n ret = avio_open2(&in, url, AVIO_FLAG_READ,\n c->interrupt_callback, &opts);\n av_dict_free(&opts);\n if (ret < 0)\n return ret;\n#else\n ret = open_in(c, &in, url);\n if (ret < 0)\n return ret;\n close_in = 1;\n#endif\n }\n\n if (av_opt_get(in, \"location\", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)\n url = new_url;\n\n read_chomp_line(in, line, sizeof(line));\n if (strcmp(line, \"#EXTM3U\")) {\n ret = AVERROR_INVALIDDATA;\n goto fail;\n }\n\n if (pls) {\n free_segment_list(pls);\n pls->finished = 0;\n pls->type = PLS_TYPE_UNSPECIFIED;\n }\n while (!avio_feof(in)) {\n read_chomp_line(in, line, sizeof(line));\n if (av_strstart(line, \"#EXT-X-STREAM-INF:\", &ptr)) {\n is_variant = 1;\n memset(&variant_info, 0, sizeof(variant_info));\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,\n &variant_info);\n } else if (av_strstart(line, \"#EXT-X-KEY:\", &ptr)) {\n struct key_info info = {{0}};\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,\n &info);\n key_type = KEY_NONE;\n has_iv = 0;\n if (!strcmp(info.method, \"AES-128\"))\n key_type = KEY_AES_128;\n if (!strcmp(info.method, \"SAMPLE-AES\"))\n key_type = KEY_SAMPLE_AES;\n if (!strncmp(info.iv, \"0x\", 2) || !strncmp(info.iv, \"0X\", 2)) {\n ff_hex_to_data(iv, info.iv + 2);\n has_iv = 1;\n }\n av_strlcpy(key, info.uri, sizeof(key));\n } else if (av_strstart(line, \"#EXT-X-MEDIA:\", &ptr)) {\n struct rendition_info info = {{0}};\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,\n &info);\n new_rendition(c, &info, url);\n } else if (av_strstart(line, \"#EXT-X-TARGETDURATION:\", &ptr)) {\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n pls->target_duration = atoi(ptr) * AV_TIME_BASE;\n } else if (av_strstart(line, \"#EXT-X-MEDIA-SEQUENCE:\", &ptr)) {\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n pls->start_seq_no = atoi(ptr);\n } else if (av_strstart(line, \"#EXT-X-PLAYLIST-TYPE:\", &ptr)) {\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n if (!strcmp(ptr, \"EVENT\"))\n pls->type = PLS_TYPE_EVENT;\n else if (!strcmp(ptr, \"VOD\"))\n pls->type = PLS_TYPE_VOD;\n } else if (av_strstart(line, \"#EXT-X-MAP:\", &ptr)) {\n struct init_section_info info = {{0}};\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,\n &info);\n cur_init_section = new_init_section(pls, &info, url);\n } else if (av_strstart(line, \"#EXT-X-ENDLIST\", &ptr)) {\n if (pls)\n pls->finished = 1;\n } else if (av_strstart(line, \"#EXTINF:\", &ptr)) {\n is_segment = 1;\n duration = atof(ptr) * AV_TIME_BASE;\n } else if (av_strstart(line, \"#EXT-X-BYTERANGE:\", &ptr)) {\n seg_size = atoi(ptr);\n ptr = strchr(ptr, '@');\n if (ptr)\n seg_offset = atoi(ptr+1);\n } else if (av_strstart(line, \"#\", NULL)) {\n continue;\n } else if (line[0]) {\n if (is_variant) {\n if (!new_variant(c, &variant_info, line, url)) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n is_variant = 0;\n }\n if (is_segment) {\n struct segment *seg;\n if (!pls) {\n if (!new_variant(c, 0, url, NULL)) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n pls = c->playlists[c->n_playlists - 1];\n }\n seg = av_malloc(sizeof(struct segment));\n if (!seg) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n seg->duration = duration;\n seg->key_type = key_type;\n if (has_iv) {\n memcpy(seg->iv, iv, sizeof(iv));\n } else {\n int seq = pls->start_seq_no + pls->n_segments;\n memset(seg->iv, 0, sizeof(seg->iv));\n AV_WB32(seg->iv + 12, seq);\n }\n\n if (key_type != KEY_NONE) {\n ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);\n seg->key = av_strdup(tmp_str);\n if (!seg->key) {\n av_free(seg);\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n } else {\n seg->key = NULL;\n }\n\n ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);\n seg->url = av_strdup(tmp_str);\n if (!seg->url) {\n av_free(seg->key);\n av_free(seg);\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n\n dynarray_add(&pls->segments, &pls->n_segments, seg);\n is_segment = 0;\n\n seg->size = seg_size;\n if (seg_size >= 0) {\n seg->url_offset = seg_offset;\n seg_offset += seg_size;\n seg_size = -1;\n } else {\n seg->url_offset = 0;\n seg_offset = 0;\n }\n\n seg->init_section = cur_init_section;\n }\n }\n }\n if (pls)\n pls->last_load_time = av_gettime_relative();\n\nfail:\n av_free(new_url);\n if (close_in)\n avio_close(in);\n return ret;\n}", "project": "FFmpeg", "hash": 322685302452455197251925283777640246074, "size": 203, "commit_id": "6959358683c7533f586c07a766acc5fe9544d8b2", "message": "avformat/hls: check segment duration value of EXTINF\n\nfix ticket: 8673\nset the default EXTINF duration to 1ms if duration is smaller than 1ms\n\nSigned-off-by: Steven Liu \n(cherry picked from commit 9dfb19baeb86a8bb02c53a441682c6e9a6e104cc)", "target": 1, "dataset": "other", "idx": 198208} {"func": "static int parse_playlist(HLSContext *c, const char *url,\n struct playlist *pls, AVIOContext *in)\n{\n int ret = 0, is_segment = 0, is_variant = 0;\n int64_t duration = 0;\n enum KeyType key_type = KEY_NONE;\n uint8_t iv[16] = \"\";\n int has_iv = 0;\n char key[MAX_URL_SIZE] = \"\";\n char line[MAX_URL_SIZE];\n const char *ptr;\n int close_in = 0;\n int64_t seg_offset = 0;\n int64_t seg_size = -1;\n uint8_t *new_url = NULL;\n struct variant_info variant_info;\n char tmp_str[MAX_URL_SIZE];\n struct segment *cur_init_section = NULL;\n\n if (!in) {\n#if 1\n AVDictionary *opts = NULL;\n close_in = 1;\n /* Some HLS servers don't like being sent the range header */\n av_dict_set(&opts, \"seekable\", \"0\", 0);\n\n // broker prior HTTP options that should be consistent across requests\n av_dict_set(&opts, \"user-agent\", c->user_agent, 0);\n av_dict_set(&opts, \"cookies\", c->cookies, 0);\n av_dict_set(&opts, \"headers\", c->headers, 0);\n\n ret = avio_open2(&in, url, AVIO_FLAG_READ,\n c->interrupt_callback, &opts);\n av_dict_free(&opts);\n if (ret < 0)\n return ret;\n#else\n ret = open_in(c, &in, url);\n if (ret < 0)\n return ret;\n close_in = 1;\n#endif\n }\n\n if (av_opt_get(in, \"location\", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)\n url = new_url;\n\n read_chomp_line(in, line, sizeof(line));\n if (strcmp(line, \"#EXTM3U\")) {\n ret = AVERROR_INVALIDDATA;\n goto fail;\n }\n\n if (pls) {\n free_segment_list(pls);\n pls->finished = 0;\n pls->type = PLS_TYPE_UNSPECIFIED;\n }\n while (!avio_feof(in)) {\n read_chomp_line(in, line, sizeof(line));\n if (av_strstart(line, \"#EXT-X-STREAM-INF:\", &ptr)) {\n is_variant = 1;\n memset(&variant_info, 0, sizeof(variant_info));\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,\n &variant_info);\n } else if (av_strstart(line, \"#EXT-X-KEY:\", &ptr)) {\n struct key_info info = {{0}};\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,\n &info);\n key_type = KEY_NONE;\n has_iv = 0;\n if (!strcmp(info.method, \"AES-128\"))\n key_type = KEY_AES_128;\n if (!strcmp(info.method, \"SAMPLE-AES\"))\n key_type = KEY_SAMPLE_AES;\n if (!strncmp(info.iv, \"0x\", 2) || !strncmp(info.iv, \"0X\", 2)) {\n ff_hex_to_data(iv, info.iv + 2);\n has_iv = 1;\n }\n av_strlcpy(key, info.uri, sizeof(key));\n } else if (av_strstart(line, \"#EXT-X-MEDIA:\", &ptr)) {\n struct rendition_info info = {{0}};\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,\n &info);\n new_rendition(c, &info, url);\n } else if (av_strstart(line, \"#EXT-X-TARGETDURATION:\", &ptr)) {\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n pls->target_duration = atoi(ptr) * AV_TIME_BASE;\n } else if (av_strstart(line, \"#EXT-X-MEDIA-SEQUENCE:\", &ptr)) {\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n pls->start_seq_no = atoi(ptr);\n } else if (av_strstart(line, \"#EXT-X-PLAYLIST-TYPE:\", &ptr)) {\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n if (!strcmp(ptr, \"EVENT\"))\n pls->type = PLS_TYPE_EVENT;\n else if (!strcmp(ptr, \"VOD\"))\n pls->type = PLS_TYPE_VOD;\n } else if (av_strstart(line, \"#EXT-X-MAP:\", &ptr)) {\n struct init_section_info info = {{0}};\n ret = ensure_playlist(c, &pls, url);\n if (ret < 0)\n goto fail;\n ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,\n &info);\n cur_init_section = new_init_section(pls, &info, url);\n } else if (av_strstart(line, \"#EXT-X-ENDLIST\", &ptr)) {\n if (pls)\n pls->finished = 1;\n } else if (av_strstart(line, \"#EXTINF:\", &ptr)) {\n is_segment = 1;\n duration = atof(ptr) * AV_TIME_BASE;\n } else if (av_strstart(line, \"#EXT-X-BYTERANGE:\", &ptr)) {\n seg_size = atoi(ptr);\n ptr = strchr(ptr, '@');\n if (ptr)\n seg_offset = atoi(ptr+1);\n } else if (av_strstart(line, \"#\", NULL)) {\n continue;\n } else if (line[0]) {\n if (is_variant) {\n if (!new_variant(c, &variant_info, line, url)) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n is_variant = 0;\n }\n if (is_segment) {\n struct segment *seg;\n if (!pls) {\n if (!new_variant(c, 0, url, NULL)) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n pls = c->playlists[c->n_playlists - 1];\n }\n seg = av_malloc(sizeof(struct segment));\n if (!seg) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n if (has_iv) {\n memcpy(seg->iv, iv, sizeof(iv));\n } else {\n int seq = pls->start_seq_no + pls->n_segments;\n memset(seg->iv, 0, sizeof(seg->iv));\n AV_WB32(seg->iv + 12, seq);\n }\n\n if (key_type != KEY_NONE) {\n ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);\n seg->key = av_strdup(tmp_str);\n if (!seg->key) {\n av_free(seg);\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n } else {\n seg->key = NULL;\n }\n\n ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);\n seg->url = av_strdup(tmp_str);\n if (!seg->url) {\n av_free(seg->key);\n av_free(seg);\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n\n if (duration < 0.001 * AV_TIME_BASE) {\n duration = 0.001 * AV_TIME_BASE;\n }\n seg->duration = duration;\n seg->key_type = key_type;\n dynarray_add(&pls->segments, &pls->n_segments, seg);\n is_segment = 0;\n\n seg->size = seg_size;\n if (seg_size >= 0) {\n seg->url_offset = seg_offset;\n seg_offset += seg_size;\n seg_size = -1;\n } else {\n seg->url_offset = 0;\n seg_offset = 0;\n }\n\n seg->init_section = cur_init_section;\n }\n }\n }\n if (pls)\n pls->last_load_time = av_gettime_relative();\n\nfail:\n av_free(new_url);\n if (close_in)\n avio_close(in);\n return ret;\n}", "project": "FFmpeg", "hash": 143241207040584752751126445822656075184, "size": 206, "commit_id": "6959358683c7533f586c07a766acc5fe9544d8b2", "message": "avformat/hls: check segment duration value of EXTINF\n\nfix ticket: 8673\nset the default EXTINF duration to 1ms if duration is smaller than 1ms\n\nSigned-off-by: Steven Liu \n(cherry picked from commit 9dfb19baeb86a8bb02c53a441682c6e9a6e104cc)", "target": 0, "dataset": "other", "idx": 270450} {"func": "static int cardos_have_2048bit_package(sc_card_t *card)\n{\n\tsc_apdu_t apdu;\n u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];\n int r;\n\tconst u8 *p = rbuf, *q;\n\tsize_t len, tlen = 0, ilen = 0;\n\n\tsc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, 0x88);\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);\n\tapdu.lc = 0;\n\tapdu.le = 256;\n\tr = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(card->ctx, r, \"APDU transmit failed\");\n\n\tif ((len = apdu.resplen) == 0)\n\t\t/* looks like no package has been installed */\n\t\treturn 0;\n\n\twhile (len != 0) {\n\t\tp = sc_asn1_find_tag(card->ctx, p, len, 0xe1, &tlen);\n\t\tif (p == NULL)\n\t\t\treturn 0;\n\t\tq = sc_asn1_find_tag(card->ctx, p, tlen, 0x01, &ilen);\n\t\tif (q == NULL || ilen != 4)\n\t\t\treturn 0;\n\t\tif (q[0] == 0x1c)\n\t\t\treturn 1;\n\t\tp += tlen;\n\t\tlen -= tlen + 2;\n\t}\n\n\treturn 0;\n}", "project": "OpenSC", "hash": 92357617617140958826267024638443033197, "size": 35, "commit_id": "1252aca9f10771ef5ba8405e73cf2da50827958f", "message": "cardos: Correctly calculate the left bytes to avoid buffer overrun\n\nThanks oss-fuzz\n\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=29912", "target": 1, "dataset": "other", "idx": 198234} {"func": "static int cardos_have_2048bit_package(sc_card_t *card)\n{\n\tsc_apdu_t apdu;\n u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];\n int r;\n\tconst u8 *p = rbuf, *q, *pp;\n\tsize_t len, tlen = 0, ilen = 0;\n\n\tsc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, 0x88);\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);\n\tapdu.lc = 0;\n\tapdu.le = 256;\n\tr = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(card->ctx, r, \"APDU transmit failed\");\n\n\tif ((len = apdu.resplen) == 0)\n\t\t/* looks like no package has been installed */\n\t\treturn 0;\n\n\twhile (len != 0) {\n\t\tpp = sc_asn1_find_tag(card->ctx, p, len, 0xe1, &tlen);\n\t\tif (pp == NULL)\n\t\t\treturn 0;\n\t\tq = sc_asn1_find_tag(card->ctx, pp, tlen, 0x01, &ilen);\n\t\tif (q == NULL || ilen != 4)\n\t\t\treturn 0;\n\t\tif (q[0] == 0x1c)\n\t\t\treturn 1;\n\t\tp += tlen;\n\t\tlen -= tlen + 2;\n\t}\n\n\treturn 0;\n}", "project": "OpenSC", "hash": 331177212470604586059658277731450158649, "size": 35, "commit_id": "1252aca9f10771ef5ba8405e73cf2da50827958f", "message": "cardos: Correctly calculate the left bytes to avoid buffer overrun\n\nThanks oss-fuzz\n\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=29912", "target": 0, "dataset": "other", "idx": 270673} {"func": "GF_Err latm_dmx_process(GF_Filter *filter)\n{\n\tGF_LATMDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck, *dst_pck;\n\tu32 pos;\n\tu8 *data, *output;\n\tu32 pck_size, prev_pck_size;\n\tu64 cts = GF_FILTER_NO_TS;\n\n\tif (ctx->in_error)\n\t\treturn ctx->in_error;\n\n\t//always reparse duration\n\tif (!ctx->duration.num)\n\t\tlatm_dmx_check_dur(filter, ctx);\n\n\tif (ctx->opid && !ctx->is_playing)\n\t\treturn GF_OK;\n\n\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tif (!ctx->latm_buffer_size) {\n\t\t\t\tif (ctx->opid)\n\t\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = NULL;\n\t\t\t\treturn GF_EOS;\n\t\t\t}\n\t\t} else {\n\t\t\treturn GF_OK;\n\t\t}\n\t}\n\n\tdata = (char *) gf_filter_pck_get_data(pck, &pck_size);\n\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (ctx->timescale && pck) {\n\t\tcts = gf_filter_pck_get_cts(pck);\n\t}\n\n\tprev_pck_size = ctx->latm_buffer_size;\n\n\tif (pck && !ctx->resume_from) {\n\t\tif (ctx->latm_buffer_size + pck_size > ctx->latm_buffer_alloc) {\n\t\t\tctx->latm_buffer_alloc = ctx->latm_buffer_size + pck_size;\n\t\t\tctx->latm_buffer = gf_realloc(ctx->latm_buffer, ctx->latm_buffer_alloc);\n\t\t}\n\t\tmemcpy(ctx->latm_buffer + ctx->latm_buffer_size, data, pck_size);\n\t\tctx->latm_buffer_size += pck_size;\n\t}\n\n\tif (!ctx->bs) ctx->bs = gf_bs_new(ctx->latm_buffer, ctx->latm_buffer_size, GF_BITSTREAM_READ);\n\telse gf_bs_reassign_buffer(ctx->bs, ctx->latm_buffer, ctx->latm_buffer_size);\n\n\tif (ctx->resume_from) {\n\t\tgf_bs_seek(ctx->bs, ctx->resume_from-1);\n\t\tctx->resume_from = 0;\n\t}\n\n\tif (cts == GF_FILTER_NO_TS)\n\t\tprev_pck_size = 0;\n\n\n\twhile (1) {\n\t\tpos = (u32) gf_bs_get_position(ctx->bs);\n\t\tu8 latm_buffer[4096];\n\t\tu32 latm_frame_size = 4096;\n\t\tif (!latm_dmx_sync_frame_bs(ctx->bs,&ctx->acfg, &latm_frame_size, latm_buffer, NULL)) break;\n\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_samples_at_seek = (u64) (ctx->start_range * GF_M4ASampleRates[ctx->sr_idx]);\n\t\t\tif (ctx->cts + ctx->dts_inc >= nb_samples_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + ctx->dts_inc) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}\n\n\t\tlatm_dmx_check_pid(filter, ctx);\n\n\t\tif (!ctx->is_playing) {\n\t\t\tctx->resume_from = pos+1;\n\t\t\treturn GF_OK;\n\t\t}\n\n\t\tif (!ctx->in_seek) {\n\t\t\tGF_FilterSAPType sap = GF_FILTER_SAP_1;\n\n\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, latm_frame_size, &output);\n\t\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);\n\n\t\t\tmemcpy(output, latm_buffer, latm_frame_size);\n\n\t\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\t\tgf_filter_pck_set_duration(dst_pck, ctx->dts_inc);\n\t\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\n\t\t\t/*xHE-AAC, check RAP*/\n\t\t\tif (ctx->acfg.base_object_type==GF_CODECID_USAC) {\n\t\t\t\tif (latm_frame_size && (output[0] & 0x80) && !ctx->prev_sap) {\n\t\t\t\t\tsap = GF_FILTER_SAP_1;\n\t\t\t\t\tctx->prev_sap = GF_TRUE;\n\t\t\t\t} else {\n\t\t\t\t\tsap = GF_FILTER_SAP_NONE;\n\t\t\t\t\tctx->prev_sap = GF_FALSE;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgf_filter_pck_set_sap(dst_pck, sap);\n\n\t\t\tgf_filter_pck_send(dst_pck);\n\t\t}\n\t\tlatm_dmx_update_cts(ctx);\n\n\t\tif (prev_pck_size) {\n\t\t\tpos = (u32) gf_bs_get_position(ctx->bs);\n\t\t\tif (prev_pck_size<=pos) {\n\t\t\t\tprev_pck_size=0;\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = pck;\n\t\t\t\tif (pck)\n\t\t\t\t\tgf_filter_pck_ref_props(&ctx->src_pck);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (pck) {\n\t\tpos = (u32) gf_bs_get_position(ctx->bs);\n\t\tassert(ctx->latm_buffer_size >= pos);\n\t\tmemmove(ctx->latm_buffer, ctx->latm_buffer+pos, ctx->latm_buffer_size - pos);\n\t\tctx->latm_buffer_size -= pos;\n\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\tassert(!ctx->resume_from);\n\t} else {\n\t\tctx->latm_buffer_size = 0;\n\t\treturn latm_dmx_process(filter);\n\t}\n\treturn GF_OK;\n}", "project": "gpac", "hash": 129393460693122238437209841613363417813, "size": 138, "commit_id": "b2db2f99b4c30f96e17b9a14537c776da6cb5dca", "message": "fixed #1728", "target": 1, "dataset": "other", "idx": 198278} {"func": "GF_Err latm_dmx_process(GF_Filter *filter)\n{\n\tGF_LATMDmxCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck, *dst_pck;\n\tu32 pos;\n\tu8 *data=NULL, *output;\n\tu32 pck_size=0, prev_pck_size;\n\tu64 cts = GF_FILTER_NO_TS;\n\n\tif (ctx->in_error)\n\t\treturn ctx->in_error;\n\n\t//always reparse duration\n\tif (!ctx->duration.num)\n\t\tlatm_dmx_check_dur(filter, ctx);\n\n\tif (ctx->opid && !ctx->is_playing)\n\t\treturn GF_OK;\n\n\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tif (!ctx->latm_buffer_size) {\n\t\t\t\tif (ctx->opid)\n\t\t\t\t\tgf_filter_pid_set_eos(ctx->opid);\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = NULL;\n\t\t\t\treturn GF_EOS;\n\t\t\t}\n\t\t} else {\n\t\t\treturn GF_OK;\n\t\t}\n\t} else {\n\t\tdata = (char *) gf_filter_pck_get_data(pck, &pck_size);\n\t}\n\n\t//input pid sets some timescale - we flushed pending data , update cts\n\tif (ctx->timescale && pck) {\n\t\tcts = gf_filter_pck_get_cts(pck);\n\t}\n\n\tprev_pck_size = ctx->latm_buffer_size;\n\n\tif (pck && !ctx->resume_from) {\n\t\tif (ctx->latm_buffer_size + pck_size > ctx->latm_buffer_alloc) {\n\t\t\tctx->latm_buffer_alloc = ctx->latm_buffer_size + pck_size;\n\t\t\tctx->latm_buffer = gf_realloc(ctx->latm_buffer, ctx->latm_buffer_alloc);\n\t\t}\n\t\tmemcpy(ctx->latm_buffer + ctx->latm_buffer_size, data, pck_size);\n\t\tctx->latm_buffer_size += pck_size;\n\t}\n\n\tif (!ctx->bs) ctx->bs = gf_bs_new(ctx->latm_buffer, ctx->latm_buffer_size, GF_BITSTREAM_READ);\n\telse gf_bs_reassign_buffer(ctx->bs, ctx->latm_buffer, ctx->latm_buffer_size);\n\n\tif (ctx->resume_from) {\n\t\tgf_bs_seek(ctx->bs, ctx->resume_from-1);\n\t\tctx->resume_from = 0;\n\t}\n\n\tif (cts == GF_FILTER_NO_TS)\n\t\tprev_pck_size = 0;\n\n\n\twhile (1) {\n\t\tpos = (u32) gf_bs_get_position(ctx->bs);\n\t\tu8 latm_buffer[4096];\n\t\tu32 latm_frame_size = 4096;\n\t\tif (!latm_dmx_sync_frame_bs(ctx->bs,&ctx->acfg, &latm_frame_size, latm_buffer, NULL)) break;\n\n\t\tif (ctx->in_seek) {\n\t\t\tu64 nb_samples_at_seek = (u64) (ctx->start_range * GF_M4ASampleRates[ctx->sr_idx]);\n\t\t\tif (ctx->cts + ctx->dts_inc >= nb_samples_at_seek) {\n\t\t\t\t//u32 samples_to_discard = (ctx->cts + ctx->dts_inc) - nb_samples_at_seek;\n\t\t\t\tctx->in_seek = GF_FALSE;\n\t\t\t}\n\t\t}\n\n\t\tlatm_dmx_check_pid(filter, ctx);\n\n\t\tif (!ctx->is_playing) {\n\t\t\tctx->resume_from = pos+1;\n\t\t\treturn GF_OK;\n\t\t}\n\n\t\tif (!ctx->in_seek) {\n\t\t\tGF_FilterSAPType sap = GF_FILTER_SAP_1;\n\n\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid, latm_frame_size, &output);\n\t\t\tif (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck);\n\n\t\t\tmemcpy(output, latm_buffer, latm_frame_size);\n\n\t\t\tgf_filter_pck_set_cts(dst_pck, ctx->cts);\n\t\t\tgf_filter_pck_set_duration(dst_pck, ctx->dts_inc);\n\t\t\tgf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE);\n\n\t\t\t/*xHE-AAC, check RAP*/\n\t\t\tif (ctx->acfg.base_object_type==GF_CODECID_USAC) {\n\t\t\t\tif (latm_frame_size && (output[0] & 0x80) && !ctx->prev_sap) {\n\t\t\t\t\tsap = GF_FILTER_SAP_1;\n\t\t\t\t\tctx->prev_sap = GF_TRUE;\n\t\t\t\t} else {\n\t\t\t\t\tsap = GF_FILTER_SAP_NONE;\n\t\t\t\t\tctx->prev_sap = GF_FALSE;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgf_filter_pck_set_sap(dst_pck, sap);\n\n\t\t\tgf_filter_pck_send(dst_pck);\n\t\t}\n\t\tlatm_dmx_update_cts(ctx);\n\n\t\tif (prev_pck_size) {\n\t\t\tpos = (u32) gf_bs_get_position(ctx->bs);\n\t\t\tif (prev_pck_size<=pos) {\n\t\t\t\tprev_pck_size=0;\n\t\t\t\tif (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck);\n\t\t\t\tctx->src_pck = pck;\n\t\t\t\tif (pck)\n\t\t\t\t\tgf_filter_pck_ref_props(&ctx->src_pck);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (pck) {\n\t\tpos = (u32) gf_bs_get_position(ctx->bs);\n\t\tassert(ctx->latm_buffer_size >= pos);\n\t\tmemmove(ctx->latm_buffer, ctx->latm_buffer+pos, ctx->latm_buffer_size - pos);\n\t\tctx->latm_buffer_size -= pos;\n\t\tgf_filter_pid_drop_packet(ctx->ipid);\n\t\tassert(!ctx->resume_from);\n\t} else {\n\t\tctx->latm_buffer_size = 0;\n\t\treturn latm_dmx_process(filter);\n\t}\n\treturn GF_OK;\n}", "project": "gpac", "hash": 10482263121380563115286320698149929915, "size": 138, "commit_id": "b2db2f99b4c30f96e17b9a14537c776da6cb5dca", "message": "fixed #1728", "target": 0, "dataset": "other", "idx": 271474} {"func": "static GF_Err gf_isom_parse_movie_boxes_internal(GF_ISOFile *mov, u32 *boxType, u64 *bytesMissing, Bool progressive_mode)\n{\n\tGF_Box *a;\n\tu64 totSize, mdat_end=0;\n\tGF_Err e = GF_OK;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\tif (mov->single_moof_mode && mov->single_moof_state == 2) {\n\t\treturn e;\n\t}\n\n\t/*restart from where we stopped last*/\n\ttotSize = mov->current_top_box_start;\n\tif (mov->bytes_removed) {\n\t\tassert(totSize >= mov->bytes_removed);\n\t\ttotSize -= mov->bytes_removed;\n\t}\n\tgf_bs_seek(mov->movieFileMap->bs, totSize);\n#endif\n\n\n\t/*while we have some data, parse our boxes*/\n\twhile (gf_bs_available(mov->movieFileMap->bs)) {\n\t\t*bytesMissing = 0;\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Parsing a top-level box at position %d\\n\", mov->current_top_box_start));\n#endif\n\n\t\te = gf_isom_parse_root_box(&a, mov->movieFileMap->bs, boxType, bytesMissing, progressive_mode);\n\n\t\tif (e >= 0) {\n\n\t\t} else if (e == GF_ISOM_INCOMPLETE_FILE) {\n\t\t\t/*our mdat is uncomplete, only valid for READ ONLY files...*/\n\t\t\tif (mov->openMode != GF_ISOM_OPEN_READ) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete MDAT while file is not read-only\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tif ((mov->openMode == GF_ISOM_OPEN_READ) && !progressive_mode) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete file while reading for dump - aborting parsing\\n\"));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn e;\n\t\t} else {\n\t\t\treturn e;\n\t\t}\n\n\t\tswitch (a->type) {\n\t\t/*MOOV box*/\n\t\tcase GF_ISOM_BOX_TYPE_MOOV:\n\t\t\tif (mov->moov) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate MOOV detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->moov = (GF_MovieBox *)a;\n\t\t\tmov->original_moov_offset = mov->current_top_box_start;\n\t\t\t/*set our pointer to the movie*/\n\t\t\tmov->moov->mov = mov;\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (mov->moov->mvex) mov->moov->mvex->mov = mov;\n\n#ifdef GF_ENABLE_CTRN\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tgf_isom_setup_traf_inheritance(mov);\n\t\t\t}\n#endif\n\n#endif\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\n\t\t\ttotSize += a->size;\n\n if (!mov->moov->mvhd) {\n GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MovieHeaderBox\\n\"));\n return GF_ISOM_INVALID_FILE;\n }\n\n if (mov->meta) {\n\t\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\t}\n\n\t\t\t//dump senc info in dump mode\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\n\t\t\t\t\tif (trak->sample_encryption) {\n\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, NULL, trak->sample_encryption);\n\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\t\t\t\t\tif (trak->Media->information->sampleTable->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(trak->Media->information->sampleTable->child_boxes, trak->Media->information->sampleTable->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n if (mdat_end && mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n gf_isom_push_mdat_end(mov, mdat_end);\n mdat_end=0;\n }\n\t\t\tbreak;\n\n\t\t/*META box*/\n\t\tcase GF_ISOM_BOX_TYPE_META:\n\t\t\tif (mov->meta) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate META detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->meta = (GF_MetaBox *)a;\n\t\t\tmov->original_meta_offset = mov->current_top_box_start;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) {\n\t\t\t\treturn e;\n\t\t\t}\n\t\t\ttotSize += a->size;\n if (mov->moov) {\n\t\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*we only keep the MDAT in READ for dump purposes*/\n\t\tcase GF_ISOM_BOX_TYPE_MDAT:\n\t\t\tif (!mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tif (mov->openMode == GF_ISOM_OPEN_READ) {\n\t\t\t\tif (!mov->mdat) {\n\t\t\t\t\tmov->mdat = (GF_MediaDataBox *) a;\n\t\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\treturn e;\n\t\t\t\t\t}\n\t\t\t\t}\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\t\telse if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) gf_list_add(mov->TopBoxes, a);\n#endif\n\t\t\t\telse gf_isom_box_del(a); //in other modes we don't care\n\n\n\t\t\t\tif (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n mdat_end = gf_bs_get_position(mov->movieFileMap->bs);\n if (mov->moov) {\n gf_isom_push_mdat_end(mov, mdat_end);\n mdat_end=0;\n }\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*if we don't have any MDAT yet, create one (edit-write mode)\n\t\t\tWe only work with one mdat, but we're puting it at the place\n\t\t\tof the first mdat found when opening a file for editing*/\n\t\t\telse if (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\t\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\tif (e) {\n\t\t\t\t\treturn e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GF_ISOM_BOX_TYPE_FTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->brand) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'ftyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->brand = (GF_FileTypeBox *)a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_OTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->otyp) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'otyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tmov->otyp = (GF_Box *)a;\n\t\t\t\ttotSize += a->size;\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else {\n\t\t\t\tGF_FileTypeBox *brand = (GF_FileTypeBox *) gf_isom_box_find_child(a->child_boxes, GF_ISOM_BOX_TYPE_FTYP);\n\t\t\t\tif (brand) {\n\t\t\t\t\ts32 pos;\n\t\t\t\t\tgf_list_del_item(a->child_boxes, brand);\n\t\t\t\t\tpos = gf_list_del_item(mov->TopBoxes, mov->brand);\n\t\t\t\t\tgf_isom_box_del((GF_Box *) mov->brand);\n\t\t\t\t\tmov->brand = brand;\n\t\t\t\t\tif (pos<0) pos=0;\n\t\t\t\t\tgf_list_insert(mov->TopBoxes, brand, pos);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PDIN:\n\t\t\t/*ONE AND ONLY ONE PDIN*/\n\t\t\tif (mov->pdin) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'pdin'' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->pdin = (GF_ProgressiveDownloadBox *) a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tcase GF_ISOM_BOX_TYPE_STYP:\n\t\t{\n\t\t\tu32 brand = ((GF_FileTypeBox *)a)->majorBrand;\n\t\t\tswitch (brand) {\n\t\t\tcase GF_ISOM_BRAND_SISX:\n\t\t\tcase GF_ISOM_BRAND_RISX:\n\t\t\tcase GF_ISOM_BRAND_SSSS:\n\t\t\t\tmov->is_index_segment = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t/*fall-through*/\n\n\t\tcase GF_ISOM_BOX_TYPE_SIDX:\n\t\tcase GF_ISOM_BOX_TYPE_SSIX:\n\t\t\tif (mov->moov && !mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else if (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) && (mov->openMode!=GF_ISOM_OPEN_KEEP_FRAGMENTS)\n\t\t\t) {\n\t\t\t\tif (a->type==GF_ISOM_BOX_TYPE_SIDX) {\n\t\t\t\t\tif (mov->root_sidx) gf_isom_box_del( (GF_Box *) mov->root_sidx);\n\t\t\t\t\tmov->root_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\t\tmov->sidx_start_offset = mov->current_top_box_start;\n\t\t\t\t\tmov->sidx_end_offset = gf_bs_get_position(mov->movieFileMap->bs);\n\n\t\t\t\t}\n\t\t\t\telse if (a->type==GF_ISOM_BOX_TYPE_STYP) {\n\t\t\t\t\tmov->styp_start_offset = mov->current_top_box_start;\n\n\t\t\t\t\tif (mov->seg_styp) gf_isom_box_del(mov->seg_styp);\n\t\t\t\t\tmov->seg_styp = a;\n\t\t\t\t} else if (a->type==GF_ISOM_BOX_TYPE_SSIX) {\n\t\t\t\t\tif (mov->seg_ssix) gf_isom_box_del(mov->seg_ssix);\n\t\t\t\t\tmov->seg_ssix = a;\n\t\t\t\t} else {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t}\n\t\t\t\tgf_isom_push_mdat_end(mov, mov->current_top_box_start);\n\t\t\t} else if (!mov->NextMoofNumber && (a->type==GF_ISOM_BOX_TYPE_SIDX)) {\n\t\t\t\tif (mov->main_sidx) gf_isom_box_del( (GF_Box *) mov->main_sidx);\n\t\t\t\tmov->main_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\tmov->main_sidx_end_pos = mov->current_top_box_start + a->size;\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_MOOF:\n\t\t\t//no support for inplace rewrite for fragmented files\n\t\t\tgf_isom_disable_inplace_rewrite(mov);\n\t\t\tif (!mov->moov) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Movie fragment but no moov (yet) - possibly broken parsing!\\n\"));\n\t\t\t}\n\t\t\tif (mov->single_moof_mode) {\n\t\t\t\tmov->single_moof_state++;\n\t\t\t\tif (mov->single_moof_state > 1) {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t}\n\t\t\t}\n\t\t\t((GF_MovieFragmentBox *)a)->mov = mov;\n\n\t\t\ttotSize += a->size;\n\t\t\tmov->moof = (GF_MovieFragmentBox *) a;\n\n\t\t\t/*some smooth streaming streams contain a SDTP under the TRAF: this is incorrect, convert it*/\n\t\t\tFixTrackID(mov);\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tFixSDTPInTRAF(mov->moof);\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\tGF_TrackFragmentBox *traf = (GF_TrackFragmentBox *)gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\tif (traf->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(traf->child_boxes, traf->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*read & debug: store at root level*/\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tgf_list_add(mov->TopBoxes, a);\n\t\t\t\t/*also update pointers to trex for debug*/\n\t\t\t\tif (mov->moov) {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->tfhd && mov->moov->mvex && mov->moov->mvex->TrackExList) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = gf_isom_get_track_from_id(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\tu32 j=0;\n\t\t\t\t\t\t\twhile ((traf->trex = (GF_TrackExtendsBox*)gf_list_enum(mov->moov->mvex->TrackExList, &j))) {\n\t\t\t\t\t\t\t\tif (traf->trex->trackID == traf->tfhd->trackID) {\n\t\t\t\t\t\t\t\t\tif (!traf->trex->track) traf->trex->track = trak;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttraf->trex = NULL;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//we should only parse senc/psec when no saiz/saio is present, otherwise we fetch the info directly\n\t\t\t\t\t\tif (traf->trex && traf->tfhd && traf->trex->track && traf->sample_encryption) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = GetTrackbyID(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = traf->tfhd->sample_desc_index ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;\n\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, traf, traf->sample_encryption);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->sample_encryption) {\n\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, NULL, traf, traf->sample_encryption);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t} else if (mov->openMode==GF_ISOM_OPEN_KEEP_FRAGMENTS) {\n\t\t\t\tmov->NextMoofNumber = mov->moof->mfhd->sequence_number+1;\n\t\t\t\tmov->moof = NULL;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\t/*merge all info*/\n\t\t\t\te = MergeFragment((GF_MovieFragmentBox *)a, mov);\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\n\t\t\t//done with moov\n\t\t\tif (mov->root_sidx) {\n\t\t\t\tgf_isom_box_del((GF_Box *) mov->root_sidx);\n\t\t\t\tmov->root_sidx = NULL;\n\t\t\t}\n\t\t\tif (mov->root_ssix) {\n\t\t\t\tgf_isom_box_del(mov->seg_ssix);\n\t\t\t\tmov->root_ssix = NULL;\n\t\t\t}\n\t\t\tif (mov->seg_styp) {\n\t\t\t\tgf_isom_box_del(mov->seg_styp);\n\t\t\t\tmov->seg_styp = NULL;\n\t\t\t}\n\t\t\tmov->sidx_start_offset = 0;\n\t\t\tmov->sidx_end_offset = 0;\n\t\t\tmov->styp_start_offset = 0;\n\t\t\tbreak;\n#endif\n\t\tcase GF_ISOM_BOX_TYPE_UNKNOWN:\n\t\t{\n\t\t\tGF_UnknownBox *box = (GF_UnknownBox*)a;\n\t\t\tif (box->original_4cc == GF_ISOM_BOX_TYPE_JP) {\n\t\t\t\tu8 *c = (u8 *) box->data;\n\t\t\t\tif ((box->dataSize==4) && (GF_4CC(c[0],c[1],c[2],c[3])==(u32)0x0D0A870A))\n\t\t\t\t\tmov->is_jp2 = 1;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PRFT:\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (!(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\t//keep the last one read\n\t\t\t\tif (mov->last_producer_ref_time)\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\telse\n\t\t\t\t\tmov->last_producer_ref_time = (GF_ProducerReferenceTimeBox *)a;\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\t\t//fallthrough\n\n\t\tdefault:\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\t\t}\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*remember where we left, in case we append an entire number of movie fragments*/\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n#endif\n\t}\n\n\t/*we need at least moov or meta*/\n\tif (!mov->moov && !mov->meta\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t && !mov->moof && !mov->is_index_segment\n#endif\n\t ) {\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\t/*we MUST have movie header*/\n\tif (!gf_opts_get_bool(\"core\", \"no-check\")) {\n\t\tif (mov->moov && !mov->moov->mvhd) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MVHD in MOOV!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\t\t/*we MUST have meta handler*/\n\t\tif (mov->meta && !mov->meta->handler) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing handler in META!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\t}\n\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\n\tif (mov->moov) {\n\t\t/*set the default interleaving time*/\n\t\tmov->interleavingTime = mov->moov->mvhd->timeScale;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*in edit mode with successfully loaded fragments, delete all fragment signaling since\n\t\tfile is no longer fragmented*/\n\t\tif ((mov->openMode > GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS) && mov->moov->mvex) {\n\t\t\tgf_isom_box_del_parent(&mov->moov->child_boxes, (GF_Box *)mov->moov->mvex);\n\t\t\tmov->moov->mvex = NULL;\n\t\t}\n#endif\n\n\t}\n\n\t//create a default mdat if none was found\n\tif (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\tif (e) return e;\n\t}\n#endif /*GPAC_DISABLE_ISOM_WRITE*/\n\n\treturn GF_OK;\n}", "project": "gpac", "hash": 86450605193316092897460625068419387462, "size": 474, "commit_id": "fe5155cf047252d1c4cb91602048bfa682af0ea7", "message": "fixed #1783 (fuzz)", "target": 1, "dataset": "other", "idx": 198286} {"func": "static GF_Err gf_isom_parse_movie_boxes_internal(GF_ISOFile *mov, u32 *boxType, u64 *bytesMissing, Bool progressive_mode)\n{\n\tGF_Box *a;\n\tu64 totSize, mdat_end=0;\n\tGF_Err e = GF_OK;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\tif (mov->single_moof_mode && mov->single_moof_state == 2) {\n\t\treturn e;\n\t}\n\n\t/*restart from where we stopped last*/\n\ttotSize = mov->current_top_box_start;\n\tif (mov->bytes_removed) {\n\t\tassert(totSize >= mov->bytes_removed);\n\t\ttotSize -= mov->bytes_removed;\n\t}\n\tgf_bs_seek(mov->movieFileMap->bs, totSize);\n#endif\n\n\n\t/*while we have some data, parse our boxes*/\n\twhile (gf_bs_available(mov->movieFileMap->bs)) {\n\t\t*bytesMissing = 0;\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n\t\tGF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (\"[iso file] Parsing a top-level box at position %d\\n\", mov->current_top_box_start));\n#endif\n\n\t\te = gf_isom_parse_root_box(&a, mov->movieFileMap->bs, boxType, bytesMissing, progressive_mode);\n\n\t\tif (e >= 0) {\n\n\t\t} else if (e == GF_ISOM_INCOMPLETE_FILE) {\n\t\t\t/*our mdat is uncomplete, only valid for READ ONLY files...*/\n\t\t\tif (mov->openMode != GF_ISOM_OPEN_READ) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete MDAT while file is not read-only\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tif ((mov->openMode == GF_ISOM_OPEN_READ) && !progressive_mode) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Incomplete file while reading for dump - aborting parsing\\n\"));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn e;\n\t\t} else {\n\t\t\treturn e;\n\t\t}\n\n\t\tswitch (a->type) {\n\t\t/*MOOV box*/\n\t\tcase GF_ISOM_BOX_TYPE_MOOV:\n\t\t\tif (mov->moov) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate MOOV detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->moov = (GF_MovieBox *)a;\n\t\t\tmov->original_moov_offset = mov->current_top_box_start;\n\t\t\t/*set our pointer to the movie*/\n\t\t\tmov->moov->mov = mov;\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (mov->moov->mvex) mov->moov->mvex->mov = mov;\n\n#ifdef GF_ENABLE_CTRN\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tgf_isom_setup_traf_inheritance(mov);\n\t\t\t}\n#endif\n\n#endif\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\n\t\t\ttotSize += a->size;\n\n if (!mov->moov->mvhd) {\n GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MovieHeaderBox\\n\"));\n return GF_ISOM_INVALID_FILE;\n }\n\n if (mov->meta) {\n\t\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\t}\n\n\t\t\t//dump senc info in dump mode\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\n\t\t\t\t\tif (trak->sample_encryption) {\n\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, NULL, trak->sample_encryption);\n\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoov->trackList); k++) {\n\t\t\t\t\tGF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);\n\t\t\t\t\tif (trak->Media->information->sampleTable->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(trak->Media->information->sampleTable->child_boxes, trak->Media->information->sampleTable->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n if (mdat_end && mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n gf_isom_push_mdat_end(mov, mdat_end);\n mdat_end=0;\n }\n\t\t\tbreak;\n\n\t\t/*META box*/\n\t\tcase GF_ISOM_BOX_TYPE_META:\n\t\t\tif (mov->meta) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate META detected!\\n\"));\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->meta = (GF_MetaBox *)a;\n\t\t\tmov->original_meta_offset = mov->current_top_box_start;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) {\n\t\t\t\treturn e;\n\t\t\t}\n\t\t\ttotSize += a->size;\n if (mov->moov) {\n\t\t\t\tgf_isom_meta_restore_items_ref(mov, mov->meta);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t/*we only keep the MDAT in READ for dump purposes*/\n\t\tcase GF_ISOM_BOX_TYPE_MDAT:\n\t\t\tif (!mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tif (mov->openMode == GF_ISOM_OPEN_READ) {\n\t\t\t\tif (!mov->mdat) {\n\t\t\t\t\tmov->mdat = (GF_MediaDataBox *) a;\n\t\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\treturn e;\n\t\t\t\t\t}\n\t\t\t\t}\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\t\telse if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) gf_list_add(mov->TopBoxes, a);\n#endif\n\t\t\t\telse gf_isom_box_del(a); //in other modes we don't care\n\n\n\t\t\t\tif (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {\n mdat_end = gf_bs_get_position(mov->movieFileMap->bs);\n if (mov->moov) {\n gf_isom_push_mdat_end(mov, mdat_end);\n mdat_end=0;\n }\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*if we don't have any MDAT yet, create one (edit-write mode)\n\t\t\tWe only work with one mdat, but we're puting it at the place\n\t\t\tof the first mdat found when opening a file for editing*/\n\t\t\telse if (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\t\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\t\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\t\t\tif (e) {\n\t\t\t\t\treturn e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GF_ISOM_BOX_TYPE_FTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->brand) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'ftyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->brand = (GF_FileTypeBox *)a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_OTYP:\n\t\t\t/*ONE AND ONLY ONE FTYP*/\n\t\t\tif (mov->otyp) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'otyp' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tmov->otyp = (GF_Box *)a;\n\t\t\t\ttotSize += a->size;\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else {\n\t\t\t\tGF_FileTypeBox *brand = (GF_FileTypeBox *) gf_isom_box_find_child(a->child_boxes, GF_ISOM_BOX_TYPE_FTYP);\n\t\t\t\tif (brand) {\n\t\t\t\t\ts32 pos;\n\t\t\t\t\tgf_list_del_item(a->child_boxes, brand);\n\t\t\t\t\tpos = gf_list_del_item(mov->TopBoxes, mov->brand);\n\t\t\t\t\tgf_isom_box_del((GF_Box *) mov->brand);\n\t\t\t\t\tmov->brand = brand;\n\t\t\t\t\tif (pos<0) pos=0;\n\t\t\t\t\tgf_list_insert(mov->TopBoxes, brand, pos);\n\t\t\t\t}\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PDIN:\n\t\t\t/*ONE AND ONLY ONE PDIN*/\n\t\t\tif (mov->pdin) {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Duplicate 'pdin'' detected!\\n\"));\n\t\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t\t}\n\t\t\tmov->pdin = (GF_ProgressiveDownloadBox *) a;\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\tcase GF_ISOM_BOX_TYPE_STYP:\n\t\t{\n\t\t\tu32 brand = ((GF_FileTypeBox *)a)->majorBrand;\n\t\t\tswitch (brand) {\n\t\t\tcase GF_ISOM_BRAND_SISX:\n\t\t\tcase GF_ISOM_BRAND_RISX:\n\t\t\tcase GF_ISOM_BRAND_SSSS:\n\t\t\t\tmov->is_index_segment = GF_TRUE;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t/*fall-through*/\n\n\t\tcase GF_ISOM_BOX_TYPE_SIDX:\n\t\tcase GF_ISOM_BOX_TYPE_SSIX:\n\t\t\tif (mov->moov && !mov->first_data_toplevel_offset) {\n\t\t\t\tmov->first_data_toplevel_offset = mov->current_top_box_start;\n\t\t\t\tmov->first_data_toplevel_size = a->size;\n\t\t\t}\n\t\t\ttotSize += a->size;\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t} else if (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) && (mov->openMode!=GF_ISOM_OPEN_KEEP_FRAGMENTS)\n\t\t\t) {\n\t\t\t\tif (a->type==GF_ISOM_BOX_TYPE_SIDX) {\n\t\t\t\t\tif (mov->root_sidx) gf_isom_box_del( (GF_Box *) mov->root_sidx);\n\t\t\t\t\tmov->root_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\t\tmov->sidx_start_offset = mov->current_top_box_start;\n\t\t\t\t\tmov->sidx_end_offset = gf_bs_get_position(mov->movieFileMap->bs);\n\n\t\t\t\t}\n\t\t\t\telse if (a->type==GF_ISOM_BOX_TYPE_STYP) {\n\t\t\t\t\tmov->styp_start_offset = mov->current_top_box_start;\n\n\t\t\t\t\tif (mov->seg_styp) gf_isom_box_del(mov->seg_styp);\n\t\t\t\t\tmov->seg_styp = a;\n\t\t\t\t} else if (a->type==GF_ISOM_BOX_TYPE_SSIX) {\n\t\t\t\t\tif (mov->seg_ssix) gf_isom_box_del(mov->seg_ssix);\n\t\t\t\t\tmov->seg_ssix = a;\n\t\t\t\t} else {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t}\n\t\t\t\tgf_isom_push_mdat_end(mov, mov->current_top_box_start);\n\t\t\t} else if (!mov->NextMoofNumber && (a->type==GF_ISOM_BOX_TYPE_SIDX)) {\n\t\t\t\tif (mov->main_sidx) gf_isom_box_del( (GF_Box *) mov->main_sidx);\n\t\t\t\tmov->main_sidx = (GF_SegmentIndexBox *) a;\n\t\t\t\tmov->main_sidx_end_pos = mov->current_top_box_start + a->size;\n\t\t\t} else {\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_MOOF:\n\t\t\t//no support for inplace rewrite for fragmented files\n\t\t\tgf_isom_disable_inplace_rewrite(mov);\n\t\t\tif (!mov->moov) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Movie fragment but no moov (yet) - possibly broken parsing!\\n\"));\n\t\t\t}\n\t\t\tif (mov->single_moof_mode) {\n\t\t\t\tmov->single_moof_state++;\n\t\t\t\tif (mov->single_moof_state > 1) {\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t}\n\t\t\t}\n\t\t\t((GF_MovieFragmentBox *)a)->mov = mov;\n\n\t\t\ttotSize += a->size;\n\t\t\tmov->moof = (GF_MovieFragmentBox *) a;\n\n\t\t\t/*some smooth streaming streams contain a SDTP under the TRAF: this is incorrect, convert it*/\n\t\t\tFixTrackID(mov);\n\t\t\tif (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\tFixSDTPInTRAF(mov->moof);\n\t\t\t} else {\n\t\t\t\tu32 k;\n\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\tGF_TrackFragmentBox *traf = (GF_TrackFragmentBox *)gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\tif (traf->sampleGroups) {\n\t\t\t\t\t\tconvert_compact_sample_groups(traf->child_boxes, traf->sampleGroups);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*read & debug: store at root level*/\n\t\t\tif (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {\n\t\t\t\tu32 k;\n\t\t\t\tgf_list_add(mov->TopBoxes, a);\n\t\t\t\t/*also update pointers to trex for debug*/\n\t\t\t\tif (mov->moov) {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->tfhd && mov->moov->mvex && mov->moov->mvex->TrackExList) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = gf_isom_get_track_from_id(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\tu32 j=0;\n\t\t\t\t\t\t\twhile ((traf->trex = (GF_TrackExtendsBox*)gf_list_enum(mov->moov->mvex->TrackExList, &j))) {\n\t\t\t\t\t\t\t\tif (traf->trex->trackID == traf->tfhd->trackID) {\n\t\t\t\t\t\t\t\t\tif (!traf->trex->track) traf->trex->track = trak;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttraf->trex = NULL;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//we should only parse senc/psec when no saiz/saio is present, otherwise we fetch the info directly\n\t\t\t\t\t\tif (traf->trex && traf->tfhd && traf->trex->track && traf->sample_encryption) {\n\t\t\t\t\t\t\tGF_TrackBox *trak = GetTrackbyID(mov->moov, traf->tfhd->trackID);\n\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = traf->tfhd->sample_desc_index ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;\n\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, trak, traf, traf->sample_encryption);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t\ttrak->current_traf_stsd_idx = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor (k=0; kmoof->TrackList); k++) {\n\t\t\t\t\t\tGF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);\n\t\t\t\t\t\tif (traf->sample_encryption) {\n\t\t\t\t\t\t\te = senc_Parse(mov->movieFileMap->bs, NULL, traf, traf->sample_encryption);\n\t\t\t\t\t\t\tif (e) return e;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t} else if (mov->openMode==GF_ISOM_OPEN_KEEP_FRAGMENTS) {\n\t\t\t\tmov->NextMoofNumber = mov->moof->mfhd->sequence_number+1;\n\t\t\t\tmov->moof = NULL;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\t/*merge all info*/\n\t\t\t\te = MergeFragment((GF_MovieFragmentBox *)a, mov);\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\n\t\t\t//done with moov\n\t\t\tif (mov->root_sidx) {\n\t\t\t\tgf_isom_box_del((GF_Box *) mov->root_sidx);\n\t\t\t\tmov->root_sidx = NULL;\n\t\t\t}\n\t\t\tif (mov->root_ssix) {\n\t\t\t\tgf_isom_box_del(mov->seg_ssix);\n\t\t\t\tmov->root_ssix = NULL;\n\t\t\t}\n\t\t\tif (mov->seg_styp) {\n\t\t\t\tgf_isom_box_del(mov->seg_styp);\n\t\t\t\tmov->seg_styp = NULL;\n\t\t\t}\n\t\t\tmov->sidx_start_offset = 0;\n\t\t\tmov->sidx_end_offset = 0;\n\t\t\tmov->styp_start_offset = 0;\n\t\t\tbreak;\n#endif\n\t\tcase GF_ISOM_BOX_TYPE_UNKNOWN:\n\t\t{\n\t\t\tGF_UnknownBox *box = (GF_UnknownBox*)a;\n\t\t\tif (box->original_4cc == GF_ISOM_BOX_TYPE_JP) {\n\t\t\t\tu8 *c = (u8 *) box->data;\n\t\t\t\tif ((box->dataSize==4) && (GF_4CC(c[0],c[1],c[2],c[3])==(u32)0x0D0A870A))\n\t\t\t\t\tmov->is_jp2 = 1;\n\t\t\t\tgf_isom_box_del(a);\n\t\t\t} else {\n\t\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\t\tcase GF_ISOM_BOX_TYPE_PRFT:\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t\t\tif (!(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {\n\t\t\t\t//keep the last one read\n\t\t\t\tif (mov->last_producer_ref_time)\n\t\t\t\t\tgf_isom_box_del(a);\n\t\t\t\telse\n\t\t\t\t\tmov->last_producer_ref_time = (GF_ProducerReferenceTimeBox *)a;\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\t\t//fallthrough\n\n\t\tdefault:\n\t\t\ttotSize += a->size;\n\t\t\te = gf_list_add(mov->TopBoxes, a);\n\t\t\tif (e) return e;\n\t\t\tbreak;\n\t\t}\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*remember where we left, in case we append an entire number of movie fragments*/\n\t\tmov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;\n#endif\n\t}\n\n\t/*we need at least moov or meta*/\n\tif (!mov->moov && !mov->meta\n#ifndef GPAC_DISABLE_ISOM_FRAGMENTS\n\t && !mov->moof && !mov->is_index_segment\n#endif\n\t ) {\n\t\treturn GF_ISOM_INCOMPLETE_FILE;\n\t}\n\t/*we MUST have movie header*/\n\tif (!gf_opts_get_bool(\"core\", \"no-check\")) {\n\t\tif (mov->moov && !mov->moov->mvhd) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing MVHD in MOOV!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\n\t\t/*we MUST have meta handler*/\n\t\tif (mov->meta && !mov->meta->handler) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing handler in META!\\n\"));\n\t\t\treturn GF_ISOM_INVALID_FILE;\n\t\t}\n\t}\n\n#ifndef GPAC_DISABLE_ISOM_WRITE\n\n\tif (mov->moov) {\n\t\t/*set the default interleaving time*/\n\t\tmov->interleavingTime = mov->moov->mvhd->timeScale;\n\n#ifndef\tGPAC_DISABLE_ISOM_FRAGMENTS\n\t\t/*in edit mode with successfully loaded fragments, delete all fragment signaling since\n\t\tfile is no longer fragmented*/\n\t\tif ((mov->openMode > GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS) && mov->moov->mvex) {\n\t\t\tgf_isom_box_del_parent(&mov->moov->child_boxes, (GF_Box *)mov->moov->mvex);\n\t\t\tmov->moov->mvex = NULL;\n\t\t}\n#endif\n\n\t}\n\n\t//create a default mdat if none was found\n\tif (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {\n\t\tmov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);\n\t\tif (!mov->mdat) return GF_OUT_OF_MEM;\n\t\te = gf_list_add(mov->TopBoxes, mov->mdat);\n\t\tif (e) return e;\n\t}\n#endif /*GPAC_DISABLE_ISOM_WRITE*/\n\n\treturn GF_OK;\n}", "project": "gpac", "hash": 61440798691784431491544950992000959629, "size": 475, "commit_id": "fe5155cf047252d1c4cb91602048bfa682af0ea7", "message": "fixed #1783 (fuzz)", "target": 0, "dataset": "other", "idx": 271715} {"func": "multi_process_incoming_link(struct multi_context *m, struct multi_instance *instance, const unsigned int mpp_flags)\n{\n struct gc_arena gc = gc_new();\n\n struct context *c;\n struct mroute_addr src, dest;\n unsigned int mroute_flags;\n struct multi_instance *mi;\n bool ret = true;\n bool floated = false;\n\n if (m->pending)\n {\n return true;\n }\n\n if (!instance)\n {\n#ifdef MULTI_DEBUG_EVENT_LOOP\n printf(\"TCP/UDP -> TUN [%d]\\n\", BLEN(&m->top.c2.buf));\n#endif\n multi_set_pending(m, multi_get_create_instance_udp(m, &floated));\n }\n else\n {\n multi_set_pending(m, instance);\n }\n\n if (m->pending)\n {\n set_prefix(m->pending);\n\n /* get instance context */\n c = &m->pending->context;\n\n if (!instance)\n {\n /* transfer packet pointer from top-level context buffer to instance */\n c->c2.buf = m->top.c2.buf;\n\n /* transfer from-addr from top-level context buffer to instance */\n if (!floated)\n {\n c->c2.from = m->top.c2.from;\n }\n }\n\n if (BLEN(&c->c2.buf) > 0)\n {\n struct link_socket_info *lsi;\n const uint8_t *orig_buf;\n\n /* decrypt in instance context */\n\n perf_push(PERF_PROC_IN_LINK);\n lsi = get_link_socket_info(c);\n orig_buf = c->c2.buf.data;\n if (process_incoming_link_part1(c, lsi, floated))\n {\n if (floated)\n {\n multi_process_float(m, m->pending);\n }\n\n process_incoming_link_part2(c, lsi, orig_buf);\n }\n perf_pop();\n\n if (TUNNEL_TYPE(m->top.c1.tuntap) == DEV_TYPE_TUN)\n {\n /* extract packet source and dest addresses */\n mroute_flags = mroute_extract_addr_from_packet(&src,\n &dest,\n NULL,\n NULL,\n 0,\n &c->c2.to_tun,\n DEV_TYPE_TUN);\n\n /* drop packet if extract failed */\n if (!(mroute_flags & MROUTE_EXTRACT_SUCCEEDED))\n {\n c->c2.to_tun.len = 0;\n }\n /* make sure that source address is associated with this client */\n else if (multi_get_instance_by_virtual_addr(m, &src, true) != m->pending)\n {\n /* IPv6 link-local address (fe80::xxx)? */\n if ( (src.type & MR_ADDR_MASK) == MR_ADDR_IPV6\n && IN6_IS_ADDR_LINKLOCAL(&src.v6.addr) )\n {\n /* do nothing, for now. TODO: add address learning */\n }\n else\n {\n msg(D_MULTI_DROPPED, \"MULTI: bad source address from client [%s], packet dropped\",\n mroute_addr_print(&src, &gc));\n }\n c->c2.to_tun.len = 0;\n }\n /* client-to-client communication enabled? */\n else if (m->enable_c2c)\n {\n /* multicast? */\n if (mroute_flags & MROUTE_EXTRACT_MCAST)\n {\n /* for now, treat multicast as broadcast */\n multi_bcast(m, &c->c2.to_tun, m->pending, NULL, 0);\n }\n else /* possible client to client routing */\n {\n ASSERT(!(mroute_flags & MROUTE_EXTRACT_BCAST));\n mi = multi_get_instance_by_virtual_addr(m, &dest, true);\n\n /* if dest addr is a known client, route to it */\n if (mi)\n {\n#ifdef ENABLE_PF\n if (!pf_c2c_test(&c->c2.pf, c->c2.tls_multi,\n &mi->context.c2.pf,\n mi->context.c2.tls_multi,\n \"tun_c2c\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> client[%s] packet dropped by TUN packet filter\",\n mi_prefix(mi));\n }\n else\n#endif\n {\n multi_unicast(m, &c->c2.to_tun, mi);\n register_activity(c, BLEN(&c->c2.to_tun));\n }\n c->c2.to_tun.len = 0;\n }\n }\n }\n#ifdef ENABLE_PF\n if (c->c2.to_tun.len && !pf_addr_test(&c->c2.pf, c, &dest,\n \"tun_dest_addr\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> addr[%s] packet dropped by TUN packet filter\",\n mroute_addr_print_ex(&dest, MAPF_SHOW_ARP, &gc));\n c->c2.to_tun.len = 0;\n }\n#endif\n }\n else if (TUNNEL_TYPE(m->top.c1.tuntap) == DEV_TYPE_TAP)\n {\n uint16_t vid = 0;\n#ifdef ENABLE_PF\n struct mroute_addr edest;\n mroute_addr_reset(&edest);\n#endif\n\n if (m->top.options.vlan_tagging)\n {\n if (vlan_is_tagged(&c->c2.to_tun))\n {\n /* Drop VLAN-tagged frame. */\n msg(D_VLAN_DEBUG, \"dropping incoming VLAN-tagged frame\");\n c->c2.to_tun.len = 0;\n }\n else\n {\n vid = c->options.vlan_pvid;\n }\n }\n /* extract packet source and dest addresses */\n mroute_flags = mroute_extract_addr_from_packet(&src,\n &dest,\n NULL,\n#ifdef ENABLE_PF\n &edest,\n#else\n NULL,\n#endif\n vid,\n &c->c2.to_tun,\n DEV_TYPE_TAP);\n\n if (mroute_flags & MROUTE_EXTRACT_SUCCEEDED)\n {\n if (multi_learn_addr(m, m->pending, &src, 0) == m->pending)\n {\n /* check for broadcast */\n if (m->enable_c2c)\n {\n if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUTE_EXTRACT_MCAST))\n {\n multi_bcast(m, &c->c2.to_tun, m->pending, NULL,\n vid);\n }\n else /* try client-to-client routing */\n {\n mi = multi_get_instance_by_virtual_addr(m, &dest, false);\n\n /* if dest addr is a known client, route to it */\n if (mi)\n {\n#ifdef ENABLE_PF\n if (!pf_c2c_test(&c->c2.pf, c->c2.tls_multi,\n &mi->context.c2.pf,\n mi->context.c2.tls_multi,\n \"tap_c2c\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> client[%s] packet dropped by TAP packet filter\",\n mi_prefix(mi));\n }\n else\n#endif\n {\n multi_unicast(m, &c->c2.to_tun, mi);\n register_activity(c, BLEN(&c->c2.to_tun));\n }\n c->c2.to_tun.len = 0;\n }\n }\n }\n#ifdef ENABLE_PF\n if (c->c2.to_tun.len && !pf_addr_test(&c->c2.pf, c,\n &edest,\n \"tap_dest_addr\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> addr[%s] packet dropped by TAP packet filter\",\n mroute_addr_print_ex(&edest, MAPF_SHOW_ARP, &gc));\n c->c2.to_tun.len = 0;\n }\n#endif\n }\n else\n {\n msg(D_MULTI_DROPPED, \"MULTI: bad source address from client [%s], packet dropped\",\n mroute_addr_print(&src, &gc));\n c->c2.to_tun.len = 0;\n }\n }\n else\n {\n c->c2.to_tun.len = 0;\n }\n }\n }\n\n /* postprocess and set wakeup */\n ret = multi_process_post(m, m->pending, mpp_flags);\n\n clear_prefix();\n }\n\n gc_free(&gc);\n return ret;\n}", "project": "openvpn", "hash": 227170740362661013093459332997021567710, "size": 252, "commit_id": "37bc691e7d26ea4eb61a8a434ebd7a9ae76225ab", "message": "Fix illegal client float (CVE-2020-11810)\n\nThere is a time frame between allocating peer-id and initializing data\nchannel key (which is performed on receiving push request or on async\npush-reply) in which the existing peer-id float checks do not work right.\n\nIf a \"rogue\" data channel packet arrives during that time frame from\nanother address and with same peer-id, this would cause client to float\nto that new address. This is because:\n\n - tls_pre_decrypt() sets packet length to zero if\n data channel key has not been initialized, which leads to\n\n - openvpn_decrypt() returns true if packet length is zero,\n which leads to\n\n - process_incoming_link_part1() returns true, which\n calls multi_process_float(), which commits float\n\nNote that problem doesn't happen when data channel key is initialized,\nsince in this case openvpn_decrypt() returns false.\n\nThe net effect of this behaviour is that the VPN session for the\n\"victim client\" is broken. Since the \"attacker client\" does not have\nsuitable keys, it can not inject or steal VPN traffic from the other\nsession. The time window is small and it can not be used to attack\na specific client's session, unless some other way is found to make it\ndisconnect and reconnect first.\n\nCVE-2020-11810 has been assigned to acknowledge this risk.\n\nFix illegal float by adding buffer length check (\"is this packet still\nconsidered valid\") before calling multi_process_float().\n\nTrac: #1272\nCVE: 2020-11810\n\nSigned-off-by: Lev Stipakov \nAcked-by: Arne Schwabe \nAcked-by: Antonio Quartulli \nAcked-by: Gert Doering \nMessage-Id: <20200415073017.22839-1-lstipakov@gmail.com>\nURL: https://www.mail-archive.com/openvpn-devel@lists.sourceforge.net/msg19720.html\nSigned-off-by: Gert Doering ", "target": 1, "dataset": "other", "idx": 198315} {"func": "multi_process_incoming_link(struct multi_context *m, struct multi_instance *instance, const unsigned int mpp_flags)\n{\n struct gc_arena gc = gc_new();\n\n struct context *c;\n struct mroute_addr src, dest;\n unsigned int mroute_flags;\n struct multi_instance *mi;\n bool ret = true;\n bool floated = false;\n\n if (m->pending)\n {\n return true;\n }\n\n if (!instance)\n {\n#ifdef MULTI_DEBUG_EVENT_LOOP\n printf(\"TCP/UDP -> TUN [%d]\\n\", BLEN(&m->top.c2.buf));\n#endif\n multi_set_pending(m, multi_get_create_instance_udp(m, &floated));\n }\n else\n {\n multi_set_pending(m, instance);\n }\n\n if (m->pending)\n {\n set_prefix(m->pending);\n\n /* get instance context */\n c = &m->pending->context;\n\n if (!instance)\n {\n /* transfer packet pointer from top-level context buffer to instance */\n c->c2.buf = m->top.c2.buf;\n\n /* transfer from-addr from top-level context buffer to instance */\n if (!floated)\n {\n c->c2.from = m->top.c2.from;\n }\n }\n\n if (BLEN(&c->c2.buf) > 0)\n {\n struct link_socket_info *lsi;\n const uint8_t *orig_buf;\n\n /* decrypt in instance context */\n\n perf_push(PERF_PROC_IN_LINK);\n lsi = get_link_socket_info(c);\n orig_buf = c->c2.buf.data;\n if (process_incoming_link_part1(c, lsi, floated))\n {\n /* nonzero length means that we have a valid, decrypted packed */\n if (floated && c->c2.buf.len > 0)\n {\n multi_process_float(m, m->pending);\n }\n\n process_incoming_link_part2(c, lsi, orig_buf);\n }\n perf_pop();\n\n if (TUNNEL_TYPE(m->top.c1.tuntap) == DEV_TYPE_TUN)\n {\n /* extract packet source and dest addresses */\n mroute_flags = mroute_extract_addr_from_packet(&src,\n &dest,\n NULL,\n NULL,\n 0,\n &c->c2.to_tun,\n DEV_TYPE_TUN);\n\n /* drop packet if extract failed */\n if (!(mroute_flags & MROUTE_EXTRACT_SUCCEEDED))\n {\n c->c2.to_tun.len = 0;\n }\n /* make sure that source address is associated with this client */\n else if (multi_get_instance_by_virtual_addr(m, &src, true) != m->pending)\n {\n /* IPv6 link-local address (fe80::xxx)? */\n if ( (src.type & MR_ADDR_MASK) == MR_ADDR_IPV6\n && IN6_IS_ADDR_LINKLOCAL(&src.v6.addr) )\n {\n /* do nothing, for now. TODO: add address learning */\n }\n else\n {\n msg(D_MULTI_DROPPED, \"MULTI: bad source address from client [%s], packet dropped\",\n mroute_addr_print(&src, &gc));\n }\n c->c2.to_tun.len = 0;\n }\n /* client-to-client communication enabled? */\n else if (m->enable_c2c)\n {\n /* multicast? */\n if (mroute_flags & MROUTE_EXTRACT_MCAST)\n {\n /* for now, treat multicast as broadcast */\n multi_bcast(m, &c->c2.to_tun, m->pending, NULL, 0);\n }\n else /* possible client to client routing */\n {\n ASSERT(!(mroute_flags & MROUTE_EXTRACT_BCAST));\n mi = multi_get_instance_by_virtual_addr(m, &dest, true);\n\n /* if dest addr is a known client, route to it */\n if (mi)\n {\n#ifdef ENABLE_PF\n if (!pf_c2c_test(&c->c2.pf, c->c2.tls_multi,\n &mi->context.c2.pf,\n mi->context.c2.tls_multi,\n \"tun_c2c\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> client[%s] packet dropped by TUN packet filter\",\n mi_prefix(mi));\n }\n else\n#endif\n {\n multi_unicast(m, &c->c2.to_tun, mi);\n register_activity(c, BLEN(&c->c2.to_tun));\n }\n c->c2.to_tun.len = 0;\n }\n }\n }\n#ifdef ENABLE_PF\n if (c->c2.to_tun.len && !pf_addr_test(&c->c2.pf, c, &dest,\n \"tun_dest_addr\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> addr[%s] packet dropped by TUN packet filter\",\n mroute_addr_print_ex(&dest, MAPF_SHOW_ARP, &gc));\n c->c2.to_tun.len = 0;\n }\n#endif\n }\n else if (TUNNEL_TYPE(m->top.c1.tuntap) == DEV_TYPE_TAP)\n {\n uint16_t vid = 0;\n#ifdef ENABLE_PF\n struct mroute_addr edest;\n mroute_addr_reset(&edest);\n#endif\n\n if (m->top.options.vlan_tagging)\n {\n if (vlan_is_tagged(&c->c2.to_tun))\n {\n /* Drop VLAN-tagged frame. */\n msg(D_VLAN_DEBUG, \"dropping incoming VLAN-tagged frame\");\n c->c2.to_tun.len = 0;\n }\n else\n {\n vid = c->options.vlan_pvid;\n }\n }\n /* extract packet source and dest addresses */\n mroute_flags = mroute_extract_addr_from_packet(&src,\n &dest,\n NULL,\n#ifdef ENABLE_PF\n &edest,\n#else\n NULL,\n#endif\n vid,\n &c->c2.to_tun,\n DEV_TYPE_TAP);\n\n if (mroute_flags & MROUTE_EXTRACT_SUCCEEDED)\n {\n if (multi_learn_addr(m, m->pending, &src, 0) == m->pending)\n {\n /* check for broadcast */\n if (m->enable_c2c)\n {\n if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUTE_EXTRACT_MCAST))\n {\n multi_bcast(m, &c->c2.to_tun, m->pending, NULL,\n vid);\n }\n else /* try client-to-client routing */\n {\n mi = multi_get_instance_by_virtual_addr(m, &dest, false);\n\n /* if dest addr is a known client, route to it */\n if (mi)\n {\n#ifdef ENABLE_PF\n if (!pf_c2c_test(&c->c2.pf, c->c2.tls_multi,\n &mi->context.c2.pf,\n mi->context.c2.tls_multi,\n \"tap_c2c\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> client[%s] packet dropped by TAP packet filter\",\n mi_prefix(mi));\n }\n else\n#endif\n {\n multi_unicast(m, &c->c2.to_tun, mi);\n register_activity(c, BLEN(&c->c2.to_tun));\n }\n c->c2.to_tun.len = 0;\n }\n }\n }\n#ifdef ENABLE_PF\n if (c->c2.to_tun.len && !pf_addr_test(&c->c2.pf, c,\n &edest,\n \"tap_dest_addr\"))\n {\n msg(D_PF_DROPPED, \"PF: client -> addr[%s] packet dropped by TAP packet filter\",\n mroute_addr_print_ex(&edest, MAPF_SHOW_ARP, &gc));\n c->c2.to_tun.len = 0;\n }\n#endif\n }\n else\n {\n msg(D_MULTI_DROPPED, \"MULTI: bad source address from client [%s], packet dropped\",\n mroute_addr_print(&src, &gc));\n c->c2.to_tun.len = 0;\n }\n }\n else\n {\n c->c2.to_tun.len = 0;\n }\n }\n }\n\n /* postprocess and set wakeup */\n ret = multi_process_post(m, m->pending, mpp_flags);\n\n clear_prefix();\n }\n\n gc_free(&gc);\n return ret;\n}", "project": "openvpn", "hash": 293548728228125118158520364779443227300, "size": 253, "commit_id": "37bc691e7d26ea4eb61a8a434ebd7a9ae76225ab", "message": "Fix illegal client float (CVE-2020-11810)\n\nThere is a time frame between allocating peer-id and initializing data\nchannel key (which is performed on receiving push request or on async\npush-reply) in which the existing peer-id float checks do not work right.\n\nIf a \"rogue\" data channel packet arrives during that time frame from\nanother address and with same peer-id, this would cause client to float\nto that new address. This is because:\n\n - tls_pre_decrypt() sets packet length to zero if\n data channel key has not been initialized, which leads to\n\n - openvpn_decrypt() returns true if packet length is zero,\n which leads to\n\n - process_incoming_link_part1() returns true, which\n calls multi_process_float(), which commits float\n\nNote that problem doesn't happen when data channel key is initialized,\nsince in this case openvpn_decrypt() returns false.\n\nThe net effect of this behaviour is that the VPN session for the\n\"victim client\" is broken. Since the \"attacker client\" does not have\nsuitable keys, it can not inject or steal VPN traffic from the other\nsession. The time window is small and it can not be used to attack\na specific client's session, unless some other way is found to make it\ndisconnect and reconnect first.\n\nCVE-2020-11810 has been assigned to acknowledge this risk.\n\nFix illegal float by adding buffer length check (\"is this packet still\nconsidered valid\") before calling multi_process_float().\n\nTrac: #1272\nCVE: 2020-11810\n\nSigned-off-by: Lev Stipakov \nAcked-by: Arne Schwabe \nAcked-by: Antonio Quartulli \nAcked-by: Gert Doering \nMessage-Id: <20200415073017.22839-1-lstipakov@gmail.com>\nURL: https://www.mail-archive.com/openvpn-devel@lists.sourceforge.net/msg19720.html\nSigned-off-by: Gert Doering ", "target": 0, "dataset": "other", "idx": 272280} {"func": "GF_Err MergeTrack(GF_TrackBox *trak, GF_TrackFragmentBox *traf, GF_MovieFragmentBox *moof_box, u64 moof_offset, s32 compressed_diff, u64 *cumulated_offset, Bool is_first_merge)\n{\n\tu32 i, j, chunk_size, track_num;\n\tu64 base_offset, data_offset, traf_duration;\n\tu32 def_duration, DescIndex, def_size, def_flags;\n\tu32 duration, size, flags, prev_trun_data_offset, sample_index;\n\tu8 pad, sync;\n\tu16 degr;\n\tBool first_samp_in_traf=GF_TRUE;\n\tBool store_traf_map=GF_FALSE;\n\tu8 *moof_template=NULL;\n\tu32 moof_template_size=0;\n\tBool is_seg_start = GF_FALSE;\n\tu64 seg_start=0, sidx_start=0, sidx_end=0, frag_start=0, last_dts=0;\n\tGF_TrackFragmentRunBox *trun;\n\tGF_TrunEntry *ent;\n#ifdef GF_ENABLE_CTRN\n\tGF_TrackFragmentBox *traf_ref = NULL;\n#endif\n\n\tGF_Err stbl_AppendTime(GF_SampleTableBox *stbl, u32 duration, u32 nb_pack);\n\tGF_Err stbl_AppendSize(GF_SampleTableBox *stbl, u32 size, u32 nb_pack);\n\tGF_Err stbl_AppendChunk(GF_SampleTableBox *stbl, u64 offset);\n\tGF_Err stbl_AppendSampleToChunk(GF_SampleTableBox *stbl, u32 DescIndex, u32 samplesInChunk);\n\tGF_Err stbl_AppendCTSOffset(GF_SampleTableBox *stbl, s32 CTSOffset);\n\tGF_Err stbl_AppendRAP(GF_SampleTableBox *stbl, u8 isRap);\n\tGF_Err stbl_AppendPadding(GF_SampleTableBox *stbl, u8 padding);\n\tGF_Err stbl_AppendDegradation(GF_SampleTableBox *stbl, u16 DegradationPriority);\n\n\tif (trak->Header->trackID != traf->tfhd->trackID) return GF_OK;\n\tif (!trak->Media->information->sampleTable\n\t\t|| !trak->Media->information->sampleTable->SampleSize\n\t\t|| !trak->Media->information->sampleTable->TimeToSample\n\t\t|| !trak->Media->information->sampleTable->SampleToChunk\n\t\t|| !trak->Media->information->sampleTable->ChunkOffset\n\t) {\n\t\treturn GF_ISOM_INVALID_FILE;\n\t}\n\n\tif (!traf->trex->track)\n\t\ttraf->trex->track = trak;\n\n\t//setup all our defaults\n\tDescIndex = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_DESC) ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;\n\tif (!DescIndex) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] default sample description set to 0, likely broken ! Fixing to 1\\n\" ));\n\t\tDescIndex = 1;\n\t} else if (DescIndex > gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] default sample description set to %d but only %d sample description(s), likely broken ! Fixing to 1\\n\", DescIndex, gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes)));\n\t\tDescIndex = 1;\n\t}\n#ifdef GF_ENABLE_CTRN\n\tif (traf->trex->inherit_from_traf_id) {\n\t\tu32 traf_count = gf_list_count(moof_box->TrackList);\n\t\tfor (i=0; iTrackList, i);\n\t\t\tif (atraf->tfhd && atraf->tfhd->trackID==traf->trex->inherit_from_traf_id) {\n\t\t\t\ttraf_ref = atraf;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n\tdef_duration = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_DUR) ? traf->tfhd->def_sample_duration : traf->trex->def_sample_duration;\n\tdef_size = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_SIZE) ? traf->tfhd->def_sample_size : traf->trex->def_sample_size;\n\tdef_flags = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) ? traf->tfhd->def_sample_flags : traf->trex->def_sample_flags;\n\n\t//locate base offset, by default use moof (dash-like)\n\tbase_offset = moof_offset;\n\t//explicit base offset, use it\n\tif (traf->tfhd->flags & GF_ISOM_TRAF_BASE_OFFSET)\n\t\tbase_offset = traf->tfhd->base_data_offset;\n\t//no moof offset and no explicit offset, the offset is the end of the last written chunk of\n\t//the previous traf. For the first traf, *cumulated_offset is actually moof offset\n\telse if (!(traf->tfhd->flags & GF_ISOM_MOOF_BASE_OFFSET))\n\t\tbase_offset = *cumulated_offset;\n\n\tchunk_size = 0;\n\tprev_trun_data_offset = 0;\n\tdata_offset = 0;\n\ttraf_duration = 0;\n\n\t/*in playback mode*/\n\tif (traf->tfdt && is_first_merge) {\n#ifndef GPAC_DISABLE_LOG\n\t\tif (trak->moov->mov->NextMoofNumber && trak->present_in_scalable_segment && trak->sample_count_at_seg_start && (trak->dts_at_seg_start != traf->tfdt->baseMediaDecodeTime)) {\n\t\t\ts32 drift = (s32) ((s64) traf->tfdt->baseMediaDecodeTime - (s64)trak->dts_at_seg_start);\n\t\t\tif (drift<0) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Warning: TFDT timing \"LLD\" less than cumulated timing \"LLD\" - using tfdt\\n\", traf->tfdt->baseMediaDecodeTime, trak->dts_at_seg_start ));\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"[iso file] TFDT timing \"LLD\" higher than cumulated timing \"LLD\" (last sample got extended in duration)\\n\", traf->tfdt->baseMediaDecodeTime, trak->dts_at_seg_start ));\n\t\t\t}\n\t\t}\n#endif\n\t\ttrak->dts_at_seg_start = traf->tfdt->baseMediaDecodeTime;\n\t}\n\telse if (traf->tfxd) {\n\t\ttrak->dts_at_seg_start = traf->tfxd->absolute_time_in_track_timescale;\n\t}\n\n\tif (traf->tfxd) {\n\t\ttrak->last_tfxd_value = traf->tfxd->absolute_time_in_track_timescale;\n\t\ttrak->last_tfxd_value += traf->tfxd->fragment_duration_in_track_timescale;\n\t}\n\tif (traf->tfrf) {\n\t\tif (trak->tfrf) gf_isom_box_del_parent(&trak->child_boxes, (GF_Box *)trak->tfrf);\n\t\ttrak->tfrf = traf->tfrf;\n\t\tgf_list_del_item(traf->child_boxes, traf->tfrf);\n\t\tgf_list_add(trak->child_boxes, trak->tfrf);\n\t}\n\n\tif (trak->moov->mov->signal_frag_bounds) {\n\t\tstore_traf_map = GF_TRUE;\n\t\tif (is_first_merge) {\n\t\t\tGF_MovieFragmentBox *moof_clone = NULL;\n\t\t\tgf_isom_box_freeze_order((GF_Box *)moof_box);\n\t\t\tgf_isom_clone_box((GF_Box *)moof_box, (GF_Box **)&moof_clone);\n\n\t\t\tif (moof_clone) {\n\t\t\t\tGF_BitStream *bs;\n\t\t\t\tfor (i=0; iTrackList); i++) {\n\t\t\t\t\tGF_TrackFragmentBox *traf_clone = gf_list_get(moof_clone->TrackList, i);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->TrackRuns);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sampleGroups);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sampleGroupsDescription);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sub_samples);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sai_offsets);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sai_sizes);\n\t\t\t\t\tif (traf_clone->sample_encryption) {\n\t\t\t\t\t\tgf_isom_box_del_parent(&traf_clone->child_boxes, (GF_Box *) traf_clone->sample_encryption);\n\t\t\t\t\t\ttraf_clone->sample_encryption = NULL;\n\t\t\t\t\t}\n\t\t\t\t\tif (traf_clone->sdtp) {\n\t\t\t\t\t\tgf_isom_box_del_parent(&traf_clone->child_boxes, (GF_Box *) traf_clone->sdtp);\n\t\t\t\t\t\ttraf_clone->sdtp = NULL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_isom_box_size((GF_Box *)moof_clone);\n\t\t\t\tbs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\n\t\t\t\tif (trak->moov->mov->seg_styp) {\n\t\t\t\t\tgf_isom_box_size(trak->moov->mov->seg_styp);\n\t\t\t\t\tgf_isom_box_write(trak->moov->mov->seg_styp, bs);\n\t\t\t\t}\n\t\t\t\tif (trak->moov->mov->root_sidx) {\n\t\t\t\t\tgf_isom_box_size((GF_Box *)trak->moov->mov->root_sidx);\n\t\t\t\t\tgf_isom_box_write((GF_Box *)trak->moov->mov->root_sidx, bs);\n\t\t\t\t}\n\t\t\t\tif (trak->moov->mov->seg_ssix) {\n\t\t\t\t\tgf_isom_box_size(trak->moov->mov->seg_ssix);\n\t\t\t\t\tgf_isom_box_write(trak->moov->mov->seg_ssix, bs);\n\t\t\t\t}\n\t\t\t\tgf_isom_box_write((GF_Box *)moof_clone, bs);\n\t\t\t\tgf_isom_box_del((GF_Box*)moof_clone);\n\n\t\t\t\tgf_bs_get_content(bs, &moof_template, &moof_template_size);\n\t\t\t\tgf_bs_del(bs);\n\t\t\t}\n\t\t}\n\t\tif (trak->moov->mov->seg_styp) {\n\t\t\tis_seg_start = GF_TRUE;\n\t\t\tseg_start = trak->moov->mov->styp_start_offset;\n\t\t}\n\t\tif (trak->moov->mov->root_sidx) {\n\t\t\tis_seg_start = GF_TRUE;\n\t\t\tsidx_start = trak->moov->mov->sidx_start_offset;\n\t\t\tsidx_end = trak->moov->mov->sidx_end_offset;\n\t\t\tif (! seg_start || (sidx_startmoov->mov->current_top_box_start;\n\t}\n\telse if (trak->moov->mov->store_traf_map) {\n\t\tstore_traf_map = GF_TRUE;\n\t}\n\n\n\tsample_index = 0;\n\ti=0;\n\twhile ((trun = (GF_TrackFragmentRunBox *)gf_list_enum(traf->TrackRuns, &i))) {\n\t\t//merge the run\n\t\tfor (j=0; jsample_count; j++) {\n\t\t\tGF_Err e;\n\t\t\ts32 cts_offset=0;\n\t\t\tif (jnb_samples) {\n\t\t\t\tent = &trun->samples[j];\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Track %d doesn't have enough trun entries (%d) compared to sample count (%d) in run\\n\", traf->trex->trackID, trun->nb_samples, trun->sample_count ));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsize = def_size;\n\t\t\tduration = def_duration;\n\t\t\tflags = def_flags;\n\n\t\t\t//CTS - if flag not set (trun or ctrn) defaults to 0 which is the base value after alloc\n\t\t\t//we just need to overrite its value if inherited\n\t\t\tcts_offset = ent->CTS_Offset;\n\n#ifdef GF_ENABLE_CTRN\n\t\t\tif (trun->use_ctrn) {\n\t\t\t\tif (!j && (trun->ctrn_flags & GF_ISOM_CTRN_FIRST_SAMPLE) ) {\n\t\t\t\t\tif (trun->ctrn_first_dur) duration = ent->Duration;\n\t\t\t\t\tif (trun->ctrn_first_size) size = ent->size;\n\t\t\t\t\tif (trun->ctrn_first_ctts) flags = ent->flags;\n\t\t\t\t} else {\n\t\t\t\t\tif (trun->ctrn_dur) duration = ent->Duration;\n\t\t\t\t\tif (trun->ctrn_size) size = ent->size;\n\t\t\t\t\tif (trun->ctrn_sample_flags) flags = ent->flags;\n\t\t\t\t}\n\t\t\t\t/*re-override*/\n\t\t\t\tif (trun->ctrn_flags & 0xF0) {\n\t\t\t\t\tGF_TrunEntry *ref_entry;\n\t\t\t\t\tif (!traf_ref) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Track %d use traf inheritance to track ID %d but reference traf not found\\n\", traf->trex->trackID, traf->trex->inherit_from_traf_id ));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tref_entry = traf_get_sample_entry(traf_ref, sample_index);\n\t\t\t\t\tif (!ref_entry) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Track %d use traf inheritance but sample %d not found in reference traf\\n\", traf->trex->trackID, sample_index+1 ));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_DUR)\n\t\t\t\t\t\tduration = ref_entry->Duration;\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_SIZE)\n\t\t\t\t\t\tsize = ref_entry->size;\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_FLAGS)\n\t\t\t\t\t\tflags = ref_entry->flags;\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_CTSO)\n\t\t\t\t\t\tcts_offset = ref_entry->CTS_Offset;\n\t\t\t\t}\n\n\t\t\t} else\n#endif\n\t\t\t{\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_DURATION) duration = ent->Duration;\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_SIZE) size = ent->size;\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_FLAGS) {\n\t\t\t\t\tflags = ent->flags;\n\t\t\t\t} else if (!j && (trun->flags & GF_ISOM_TRUN_FIRST_FLAG)) {\n\t\t\t\t\tflags = trun->first_sample_flags;\n\t\t\t\t}\n\t\t\t}\n\t\t\tsample_index++;\n\t\t\t/*store the resolved value in case we have inheritance*/\n\t\t\tent->size = size;\n\t\t\tent->Duration = duration;\n\t\t\tent->flags = flags;\n\t\t\tent->CTS_Offset = cts_offset;\n\n\t\t\tlast_dts += duration;\n\n\t\t\t//add size first\n\t\t\tif (!trak->Media->information->sampleTable->SampleSize) {\n\t\t\t\ttrak->Media->information->sampleTable->SampleSize = (GF_SampleSizeBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STSZ);\n\t\t\t\tif (!trak->Media->information->sampleTable->SampleSize)\n\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t}\n\t\t\te = stbl_AppendSize(trak->Media->information->sampleTable, size, ent->nb_pack);\n\t\t\tif (e) return e;\n\n\t\t\t//then TS\n\t\t\tif (!trak->Media->information->sampleTable->TimeToSample) {\n\t\t\t\ttrak->Media->information->sampleTable->TimeToSample = (GF_TimeToSampleBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STTS);\n\t\t\t\tif (!trak->Media->information->sampleTable->TimeToSample)\n\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t}\n\t\t\te = stbl_AppendTime(trak->Media->information->sampleTable, duration, ent->nb_pack);\n\t\t\tif (e) return e;\n\n\t\t\t//add chunk on first sample\n\t\t\tif (!j) {\n\t\t\t\tu64 final_offset;\n\t\t\t\tdata_offset = base_offset;\n\t\t\t\t//we have an explicit data offset for this trun\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_DATA_OFFSET) {\n\t\t\t\t\tdata_offset += trun->data_offset;\n\t\t\t\t\t/*reset chunk size since data is now relative to this trun*/\n\t\t\t\t\tchunk_size = 0;\n\t\t\t\t\t/*remember this data offset for following trun*/\n\t\t\t\t\tprev_trun_data_offset = trun->data_offset;\n\t\t\t\t\t/*if mdat is located after the moof, and the moof was compressed, adjust offset\n\t\t\t\t\totherwise the offset does not need adjustment*/\n\t\t\t\t\tif (trun->data_offset>=0) {\n\t\t\t\t\t\tdata_offset -= compressed_diff;\n\t\t\t\t\t\tprev_trun_data_offset -= compressed_diff;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//we had an explicit data offset for the previous trun, use it + chunk size\n\t\t\t\telse if (prev_trun_data_offset) {\n\t\t\t\t\t/*data offset is previous chunk size plus previous offset of the trun*/\n\t\t\t\t\tdata_offset += prev_trun_data_offset + chunk_size;\n\t\t\t\t}\n\t\t\t\t//no explicit data offset, continuous data after last data in previous chunk\n\t\t\t\telse {\n\t\t\t\t\tdata_offset += chunk_size;\n\t\t\t\t\t//data offset of first trun in first traf, adjust if compressed moof\n\t\t\t\t\tif ((i==1) && (trun->data_offset>=0)) {\n\t\t\t\t\t\tdata_offset -= compressed_diff;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfinal_offset = data_offset;\n\t\t\t\t//adjust offset if moov was also compressed and we are still in the same file\n\t\t\t\t//so that later call to gf_isom_get_sample properly adjust back the offset\n\t\t\t\tif (trak->moov->compressed_diff) {\n\t\t\t\t\tfinal_offset += trak->moov->compressed_diff;\n\t\t\t\t}\n\n\t\t\t\tif (!trak->Media->information->sampleTable->ChunkOffset) {\n\t\t\t\t\ttrak->Media->information->sampleTable->ChunkOffset = gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STCO);\n\t\t\t\t\tif (!trak->Media->information->sampleTable->ChunkOffset)\n\t\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t\t}\n\t\t\t\te = stbl_AppendChunk(trak->Media->information->sampleTable, final_offset);\n\t\t\t\tif (e) return e;\n\t\t\t\t//then sampleToChunk\n\t\t\t\tif (!trak->Media->information->sampleTable->SampleToChunk) {\n\t\t\t\t\ttrak->Media->information->sampleTable->SampleToChunk = (GF_SampleToChunkBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STSC);\n\t\t\t\t\tif (!trak->Media->information->sampleTable->SampleToChunk)\n\t\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t\t}\n\t\t\t\te = stbl_AppendSampleToChunk(trak->Media->information->sampleTable,\n\t\t\t\t DescIndex, trun->sample_count);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t\tchunk_size += size;\n\n\t\t\tif (store_traf_map && first_samp_in_traf) {\n\t\t\t\tfirst_samp_in_traf = GF_FALSE;\n\t\t\t\te = stbl_AppendTrafMap(trak->Media->information->sampleTable, is_seg_start, seg_start, frag_start, moof_template, moof_template_size, sidx_start, sidx_end);\n\t\t\t\tif (e) return e;\n\t\t\t\t//do not deallocate, the memory is now owned by traf map\n\t\t\t\tmoof_template = NULL;\n\t\t\t\tmoof_template_size = 0;\n\t\t\t}\n\t\t\tif (ent->nb_pack>1) {\n\t\t\t\tj+= ent->nb_pack-1;\n\t\t\t\ttraf_duration += ent->nb_pack*duration;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttraf_duration += duration;\n\n\t\t\te = stbl_AppendCTSOffset(trak->Media->information->sampleTable, cts_offset);\n\t\t\tif (e) return e;\n\t\t\t//flags\n\t\t\tsync = GF_ISOM_GET_FRAG_SYNC(flags);\n\t\t\tif (trak->Media->information->sampleTable->no_sync_found && sync) {\n\t\t\t\ttrak->Media->information->sampleTable->no_sync_found = 0;\n\t\t\t}\n\t\t\te = stbl_AppendRAP(trak->Media->information->sampleTable, sync);\n\t\t\tif (e) return e;\n\t\t\tpad = GF_ISOM_GET_FRAG_PAD(flags);\n\t\t\tif (pad) {\n\t\t\t\te = stbl_AppendPadding(trak->Media->information->sampleTable, pad);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t\tdegr = GF_ISOM_GET_FRAG_DEG(flags);\n\t\t\tif (degr) {\n\t\t\t\te = stbl_AppendDegradation(trak->Media->information->sampleTable, degr);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t\te = stbl_AppendDependencyType(trak->Media->information->sampleTable, GF_ISOM_GET_FRAG_LEAD(flags), GF_ISOM_GET_FRAG_DEPENDS(flags), GF_ISOM_GET_FRAG_DEPENDED(flags), GF_ISOM_GET_FRAG_REDUNDANT(flags));\n\t\t\tif (e) return e;\n\t\t}\n\t}\n\n\tif (trak->moov->mov->is_smooth && !traf->tfdt && !traf->tfxd) {\n\t\tif (is_first_merge)\n\t\t\ttrak->dts_at_seg_start = trak->dts_at_next_seg_start;\n\t\ttrak->dts_at_next_seg_start += last_dts;\n\t}\n\tif (traf_duration && trak->editBox && trak->editBox->editList) {\n\t\tfor (i=0; ieditBox->editList->entryList); i++) {\n\t\t\tGF_EdtsEntry *edts_e = gf_list_get(trak->editBox->editList->entryList, i);\n\t\t\tif (edts_e->was_empty_dur) {\n\t\t\t\tu64 extend_dur = traf_duration;\n\t\t\t\textend_dur *= trak->moov->mvhd->timeScale;\n\t\t\t\textend_dur /= trak->Media->mediaHeader->timeScale;\n\t\t\t\tedts_e->segmentDuration += extend_dur;\n\t\t\t}\n\t\t\telse if (!edts_e->segmentDuration) {\n\t\t\t\tedts_e->was_empty_dur = GF_TRUE;\n\t\t\t\tif ((s64) traf_duration > edts_e->mediaTime)\n\t\t\t\t\ttraf_duration -= edts_e->mediaTime;\n\t\t\t\telse\n\t\t\t\t\ttraf_duration = 0;\n\n\t\t\t\tedts_e->segmentDuration = traf_duration;\n\t\t\t\tedts_e->segmentDuration *= trak->moov->mvhd->timeScale;\n\t\t\t\tedts_e->segmentDuration /= trak->Media->mediaHeader->timeScale;\n\t\t\t}\n\n\t\t}\n\t}\n\n\t//in any case, update the cumulated offset\n\t//this will handle hypothetical files mixing MOOF offset and implicit non-moof offset\n\t*cumulated_offset = data_offset + chunk_size;\n\n\t/*merge sample groups*/\n\tif (traf->sampleGroups) {\n\t\tGF_List *groups;\n\t\tGF_List *groupDescs;\n\t\tBool is_identical_sgpd = GF_TRUE;\n\t\tu32 *new_idx = NULL, new_idx_count=0;\n\n\t\tif (!trak->Media->information->sampleTable->sampleGroups)\n\t\t\ttrak->Media->information->sampleTable->sampleGroups = gf_list_new();\n\n\t\tif (!trak->Media->information->sampleTable->sampleGroupsDescription)\n\t\t\ttrak->Media->information->sampleTable->sampleGroupsDescription = gf_list_new();\n\n\t\tgroupDescs = trak->Media->information->sampleTable->sampleGroupsDescription;\n\t\tfor (i=0; isampleGroupsDescription); i++) {\n\t\t\tGF_SampleGroupDescriptionBox *new_sgdesc = NULL;\n\t\t\tGF_SampleGroupDescriptionBox *sgdesc = gf_list_get(traf->sampleGroupsDescription, i);\n\t\t\tfor (j=0; jgrouping_type==sgdesc->grouping_type) break;\n\t\t\t\tnew_sgdesc = NULL;\n\t\t\t}\n\t\t\t/*new description, move it to our sample table*/\n\t\t\tif (!new_sgdesc) {\n\t\t\t\tgf_list_add(groupDescs, sgdesc);\n\t\t\t\tgf_list_add(trak->Media->information->sampleTable->child_boxes, sgdesc);\n\t\t\t\tgf_list_rem(traf->sampleGroupsDescription, i);\n\t\t\t\tgf_list_del_item(traf->child_boxes, sgdesc);\n\t\t\t\ti--;\n\t\t\t}\n\t\t\t/*merge descriptions*/\n\t\t\telse {\n\t\t\t\tu32 count;\n\n\t\t\t\tis_identical_sgpd = gf_isom_is_identical_sgpd(new_sgdesc, sgdesc, 0);\n\t\t\t\tif (is_identical_sgpd)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tnew_idx_count = gf_list_count(sgdesc->group_descriptions);\n\t\t\t\tnew_idx = (u32 *)gf_malloc(new_idx_count * sizeof(u32));\n\t\t\t\tif (!new_idx) return GF_OUT_OF_MEM;\n\n\t\t\t\tcount = 0;\n\t\t\t\twhile (gf_list_count(sgdesc->group_descriptions)) {\n\t\t\t\t\tvoid *sgpd_entry = gf_list_get(sgdesc->group_descriptions, 0);\n\t\t\t\t\tBool new_entry = GF_TRUE;\n\n\t\t\t\t\tfor (j = 0; j < gf_list_count(new_sgdesc->group_descriptions); j++) {\n\t\t\t\t\t\tvoid *ptr = gf_list_get(new_sgdesc->group_descriptions, j);\n\t\t\t\t\t\tif (gf_isom_is_identical_sgpd(sgpd_entry, ptr, new_sgdesc->grouping_type)) {\n\t\t\t\t\t\t\tnew_idx[count] = j + 1;\n\t\t\t\t\t\t\tcount ++;\n\t\t\t\t\t\t\tnew_entry = GF_FALSE;\n\t\t\t\t\t\t\tgf_free(sgpd_entry);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (new_entry) {\n\t\t\t\t\t\tgf_list_add(new_sgdesc->group_descriptions, sgpd_entry);\n\t\t\t\t\t\tnew_idx[count] = gf_list_count(new_sgdesc->group_descriptions);\n\t\t\t\t\t\tcount ++;\n\t\t\t\t\t}\n\n\t\t\t\t\tgf_list_rem(sgdesc->group_descriptions, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tgroups = trak->Media->information->sampleTable->sampleGroups;\n\t\tfor (i=0; isampleGroups); i++) {\n\t\t\tGF_SampleGroupBox *stbl_group = NULL;\n\t\t\tGF_SampleGroupBox *frag_group = gf_list_get(traf->sampleGroups, i);\n\n\n\t\t\tfor (j=0; jgrouping_type==stbl_group->grouping_type) && (frag_group->grouping_type_parameter==stbl_group->grouping_type_parameter))\n\t\t\t\t\tbreak;\n\t\t\t\tstbl_group = NULL;\n\t\t\t}\n\t\t\tif (!stbl_group) {\n\t\t\t\tstbl_group = (GF_SampleGroupBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_SBGP);\n\t\t\t\tif (!stbl_group) return GF_OUT_OF_MEM;\n\t\t\t\tstbl_group->grouping_type = frag_group->grouping_type;\n\t\t\t\tstbl_group->grouping_type_parameter = frag_group->grouping_type_parameter;\n\t\t\t\tstbl_group->version = frag_group->version;\n\t\t\t\tgf_list_add(groups, stbl_group);\n\t\t\t}\n\n\t\t\tif (is_identical_sgpd) {\n\t\t\t\t//adjust sgpd index: in traf index start at 0x1001\n\t\t\t\tfor (j = 0; j < frag_group->entry_count; j++)\n\t\t\t\t\tfrag_group->sample_entries[j].group_description_index &= 0x0FFFF;\n\t\t\t\tif (frag_group->entry_count && stbl_group->entry_count &&\n\t\t\t\t (frag_group->sample_entries[0].group_description_index==stbl_group->sample_entries[stbl_group->entry_count-1].group_description_index)\n\t\t\t\t ) {\n\t\t\t\t\tstbl_group->sample_entries[stbl_group->entry_count - 1].sample_count += frag_group->sample_entries[0].sample_count;\n\t\t\t\t\tif (frag_group->entry_count>1) {\n\t\t\t\t\t\tstbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count - 1));\n\t\t\t\t\t\tmemcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[1], sizeof(GF_SampleGroupEntry) * (frag_group->entry_count - 1));\n\t\t\t\t\t\tstbl_group->entry_count += frag_group->entry_count - 1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tstbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count));\n\t\t\t\t\tmemcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[0], sizeof(GF_SampleGroupEntry) * frag_group->entry_count);\n\t\t\t\t\tstbl_group->entry_count += frag_group->entry_count;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count));\n\t\t\t\t//adjust sgpd index\n\t\t\t\tfor (j = 0; j < frag_group->entry_count; j++) {\n\t\t\t\t\tu32 sgidx = frag_group->sample_entries[j].group_description_index;\n\t\t\t\t\tif (sgidx > 0x10000) {\n\t\t\t\t\t\tsgidx -= 0x10001;\n\t\t\t\t\t\tif (sgidx>=new_idx_count) {\n\t\t\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[isobmf] corrupted sample group index in fragment %d but only %d group descriptions in fragment\\n\", sgidx, new_idx_count));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfrag_group->sample_entries[j].group_description_index = new_idx[sgidx];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmemcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[0], sizeof(GF_SampleGroupEntry) * frag_group->entry_count);\n\t\t\t\tstbl_group->entry_count += frag_group->entry_count;\n\t\t\t}\n\t\t}\n\n\t\tif (new_idx) gf_free(new_idx);\n\t}\n\n\t/*content is encrypted*/\n\ttrack_num = gf_isom_get_tracknum_from_id(trak->moov, trak->Header->trackID);\n\tif (gf_isom_is_cenc_media(trak->moov->mov, track_num, DescIndex)\n\t\t|| traf->sample_encryption) {\n\t\t/*Merge sample auxiliary encryption information*/\n\t\tGF_SampleEncryptionBox *senc = NULL;\n\t\tu32 scheme_type;\n\t\tgf_isom_get_cenc_info(trak->moov->mov, track_num, DescIndex, NULL, &scheme_type, NULL);\n\n\t\tif (traf->sample_encryption) {\n\t\t\tfor (i = 0; i < gf_list_count(trak->Media->information->sampleTable->child_boxes); i++) {\n\t\t\t\tGF_Box *a = (GF_Box *)gf_list_get(trak->Media->information->sampleTable->child_boxes, i);\n\t\t\t\tif (a->type != traf->sample_encryption->type) continue;\n\n\t\t\t\tif ((a->type ==GF_ISOM_BOX_TYPE_UUID) && (((GF_UUIDBox *)a)->internal_4cc == GF_ISOM_BOX_UUID_PSEC)) {\n\t\t\t\t\tsenc = (GF_SampleEncryptionBox *)a;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if (a->type ==GF_ISOM_BOX_TYPE_SENC) {\n\t\t\t\t\tsenc = (GF_SampleEncryptionBox *)a;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!senc && trak->sample_encryption)\n\t\t\t\tsenc = trak->sample_encryption;\n\n\t\t\tif (!senc) {\n\t\t\t\tif (traf->sample_encryption->piff_type==1) {\n\t\t\t\t\tsenc = (GF_SampleEncryptionBox *)gf_isom_create_piff_psec_box(1, 0x2, 0, 0, NULL);\n\t\t\t\t} else {\n\t\t\t\t\tsenc = gf_isom_create_samp_enc_box(1, 0x2);\n\t\t\t\t}\n\n\t\t\t\tif (!trak->Media->information->sampleTable->child_boxes) trak->Media->information->sampleTable->child_boxes = gf_list_new();\n\n\t\t\t\ttrak->sample_encryption = senc;\n\t\t\t\tif (!trak->child_boxes) trak->child_boxes = gf_list_new();\n\t\t\t\tgf_list_add(trak->child_boxes, senc);\n\t\t\t}\n\t\t}\n\n\t\t/*get sample auxiliary information by saiz/saio rather than by parsing senc box*/\n\t\tif (gf_isom_cenc_has_saiz_saio_traf(traf, scheme_type)) {\n\t\t\tu32 nb_saio;\n\t\t\tu32 aux_info_type;\n\t\t\tu64 offset;\n\t\t\tGF_Err e;\n\t\t\tBool is_encrypted;\n\t\t\tGF_SampleAuxiliaryInfoOffsetBox *saio = NULL;\n\t\t\tGF_SampleAuxiliaryInfoSizeBox *saiz = NULL;\n\n\t\t\toffset = nb_saio = 0;\n\n\t\t\tfor (i = 0; i < gf_list_count(traf->sai_offsets); i++) {\n\t\t\t\tsaio = (GF_SampleAuxiliaryInfoOffsetBox *)gf_list_get(traf->sai_offsets, i);\n\t\t\t\taux_info_type = saio->aux_info_type;\n\t\t\t\tif (!aux_info_type) aux_info_type = scheme_type;\n\n\t\t\t\t/*if we have only 1 sai_offsets, assume that its type is cenc*/\n\t\t\t\tif ((aux_info_type == GF_ISOM_CENC_SCHEME) || (aux_info_type == GF_ISOM_CBC_SCHEME) ||\n\t\t\t\t\t(aux_info_type == GF_ISOM_CENS_SCHEME) || (aux_info_type == GF_ISOM_CBCS_SCHEME) ||\n\t\t\t\t\t(gf_list_count(traf->sai_offsets) == 1)) {\n\t\t\t\t\toffset = saio->offsets[0] + moof_offset;\n\t\t\t\t\tnb_saio = saio->entry_count;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (i = 0; i < gf_list_count(traf->sai_sizes); i++) {\n\t\t\t\tsaiz = (GF_SampleAuxiliaryInfoSizeBox *)gf_list_get(traf->sai_sizes, i);\n\t\t\t\taux_info_type = saiz->aux_info_type;\n\t\t\t\tif (!aux_info_type) aux_info_type = scheme_type;\n\t\t\t\t/*if we have only 1 sai_sizes, assume that its type is cenc*/\n\t\t\t\tif ((aux_info_type == GF_ISOM_CENC_SCHEME) || (aux_info_type == GF_ISOM_CBC_SCHEME) ||\n\t\t\t\t\t(aux_info_type == GF_ISOM_CENS_SCHEME) || (aux_info_type == GF_ISOM_CBCS_SCHEME) ||\n\t\t\t\t\t(gf_list_count(traf->sai_sizes) == 1)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (saiz && saio && senc) {\n\t\t\t\tfor (i = 0; i < saiz->sample_count; i++) {\n\t\t\t\t\tGF_CENCSampleAuxInfo *sai;\n\t\t\t\t\tconst u8 *key_info=NULL;\n\t\t\t\t\tu32 key_info_size;\n\t\t\t\t\tu64 cur_position;\n\t\t\t\t\tif (nb_saio != 1)\n\t\t\t\t\t\toffset = saio->offsets[i] + moof_offset;\n\t\t\t\t\tsize = saiz->default_sample_info_size ? saiz->default_sample_info_size : saiz->sample_info_size[i];\n\n\t\t\t\t\tcur_position = gf_bs_get_position(trak->moov->mov->movieFileMap->bs);\n\t\t\t\t\tgf_bs_seek(trak->moov->mov->movieFileMap->bs, offset);\n\n\t\t\t\t\tGF_SAFEALLOC(sai, GF_CENCSampleAuxInfo);\n\t\t\t\t\tif (!sai) return GF_OUT_OF_MEM;\n\n\t\t\t\t\te = gf_isom_get_sample_cenc_info_internal(trak, traf, senc, i+1, &is_encrypted, NULL, NULL, &key_info, &key_info_size);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[isobmf] could not get cenc info for sample %d: %s\\n\", i+1, gf_error_to_string(e) ));\n\t\t\t\t\t\treturn e;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (is_encrypted) {\n\t\t\t\t\t\tsai->cenc_data_size = size;\n\t\t\t\t\t\tsai->cenc_data = gf_malloc(sizeof(u8)*size);\n\t\t\t\t\t\tif (!sai->cenc_data) return GF_OUT_OF_MEM;\n\t\t\t\t\t\tgf_bs_read_data(trak->moov->mov->movieFileMap->bs, sai->cenc_data, sai->cenc_data_size);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsai->isNotProtected=1;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (key_info) {\n\t\t\t\t\t\t//not multikey\n\t\t\t\t\t\tif (!key_info[0]) {\n\t\t\t\t\t\t\t//size greater than IV\n\t\t\t\t\t\t\tif (size > key_info[3])\n\t\t\t\t\t\t\t\tsenc->flags = 0x00000002;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//multikey, always use subsamples\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsenc->flags = 0x00000002;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\n\t\t\t\t\tgf_bs_seek(trak->moov->mov->movieFileMap->bs, cur_position);\n\n\t\t\t\t\tgf_list_add(senc->samp_aux_info, sai);\n\n\t\t\t\t\te = gf_isom_cenc_merge_saiz_saio(senc, trak->Media->information->sampleTable, offset, size);\n\t\t\t\t\tif (e) return e;\n\t\t\t\t\tif (nb_saio == 1)\n\t\t\t\t\t\toffset += size;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (traf->sample_encryption) {\n\t\t\tsenc_Parse(trak->moov->mov->movieFileMap->bs, trak, traf, traf->sample_encryption);\n\t\t\ttrak->sample_encryption->AlgorithmID = traf->sample_encryption->AlgorithmID;\n\t\t\tif (!trak->sample_encryption->IV_size)\n\t\t\t\ttrak->sample_encryption->IV_size = traf->sample_encryption->IV_size;\n\t\t\tif (!trak->sample_encryption->samp_aux_info) trak->sample_encryption->samp_aux_info = gf_list_new();\n\t\t\tgf_list_transfer(trak->sample_encryption->samp_aux_info, traf->sample_encryption->samp_aux_info);\n\t\t\tif (traf->sample_encryption->flags & 0x00000002)\n\t\t\t\ttrak->sample_encryption->flags |= 0x00000002;\n\t\t}\n\t}\n\treturn GF_OK;\n}", "project": "gpac", "hash": 149457244667447276186807458417399459366, "size": 677, "commit_id": "df8fffd839fe5ae9acd82d26fd48280a397411d9", "message": "fixed #1736", "target": 1, "dataset": "other", "idx": 198316} {"func": "GF_Err MergeTrack(GF_TrackBox *trak, GF_TrackFragmentBox *traf, GF_MovieFragmentBox *moof_box, u64 moof_offset, s32 compressed_diff, u64 *cumulated_offset, Bool is_first_merge)\n{\n\tu32 i, j, chunk_size, track_num;\n\tu64 base_offset, data_offset, traf_duration;\n\tu32 def_duration, DescIndex, def_size, def_flags;\n\tu32 duration, size, flags, prev_trun_data_offset, sample_index;\n\tu8 pad, sync;\n\tu16 degr;\n\tBool first_samp_in_traf=GF_TRUE;\n\tBool store_traf_map=GF_FALSE;\n\tu8 *moof_template=NULL;\n\tu32 moof_template_size=0;\n\tBool is_seg_start = GF_FALSE;\n\tu64 seg_start=0, sidx_start=0, sidx_end=0, frag_start=0, last_dts=0;\n\tGF_TrackFragmentRunBox *trun;\n\tGF_TrunEntry *ent;\n#ifdef GF_ENABLE_CTRN\n\tGF_TrackFragmentBox *traf_ref = NULL;\n#endif\n\n\tGF_Err stbl_AppendTime(GF_SampleTableBox *stbl, u32 duration, u32 nb_pack);\n\tGF_Err stbl_AppendSize(GF_SampleTableBox *stbl, u32 size, u32 nb_pack);\n\tGF_Err stbl_AppendChunk(GF_SampleTableBox *stbl, u64 offset);\n\tGF_Err stbl_AppendSampleToChunk(GF_SampleTableBox *stbl, u32 DescIndex, u32 samplesInChunk);\n\tGF_Err stbl_AppendCTSOffset(GF_SampleTableBox *stbl, s32 CTSOffset);\n\tGF_Err stbl_AppendRAP(GF_SampleTableBox *stbl, u8 isRap);\n\tGF_Err stbl_AppendPadding(GF_SampleTableBox *stbl, u8 padding);\n\tGF_Err stbl_AppendDegradation(GF_SampleTableBox *stbl, u16 DegradationPriority);\n\n\tif (trak->Header->trackID != traf->tfhd->trackID) return GF_OK;\n\tif (!trak->Media->information->sampleTable\n\t\t|| !trak->Media->information->sampleTable->SampleSize\n\t\t|| !trak->Media->information->sampleTable->TimeToSample\n\t\t|| !trak->Media->information->sampleTable->SampleToChunk\n\t\t|| !trak->Media->information->sampleTable->ChunkOffset\n\t) {\n\t\treturn GF_ISOM_INVALID_FILE;\n\t}\n\n\tif (!traf->trex->track)\n\t\ttraf->trex->track = trak;\n\n\t//setup all our defaults\n\tDescIndex = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_DESC) ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;\n\tif (!DescIndex) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] default sample description set to 0, likely broken ! Fixing to 1\\n\" ));\n\t\tDescIndex = 1;\n\t} else if (DescIndex > gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes)) {\n\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] default sample description set to %d but only %d sample description(s), likely broken ! Fixing to 1\\n\", DescIndex, gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes)));\n\t\tDescIndex = 1;\n\t}\n#ifdef GF_ENABLE_CTRN\n\tif (traf->trex->inherit_from_traf_id) {\n\t\tu32 traf_count = gf_list_count(moof_box->TrackList);\n\t\tfor (i=0; iTrackList, i);\n\t\t\tif (atraf->tfhd && atraf->tfhd->trackID==traf->trex->inherit_from_traf_id) {\n\t\t\t\ttraf_ref = atraf;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n\tdef_duration = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_DUR) ? traf->tfhd->def_sample_duration : traf->trex->def_sample_duration;\n\tdef_size = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_SIZE) ? traf->tfhd->def_sample_size : traf->trex->def_sample_size;\n\tdef_flags = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) ? traf->tfhd->def_sample_flags : traf->trex->def_sample_flags;\n\n\t//locate base offset, by default use moof (dash-like)\n\tbase_offset = moof_offset;\n\t//explicit base offset, use it\n\tif (traf->tfhd->flags & GF_ISOM_TRAF_BASE_OFFSET)\n\t\tbase_offset = traf->tfhd->base_data_offset;\n\t//no moof offset and no explicit offset, the offset is the end of the last written chunk of\n\t//the previous traf. For the first traf, *cumulated_offset is actually moof offset\n\telse if (!(traf->tfhd->flags & GF_ISOM_MOOF_BASE_OFFSET))\n\t\tbase_offset = *cumulated_offset;\n\n\tchunk_size = 0;\n\tprev_trun_data_offset = 0;\n\tdata_offset = 0;\n\ttraf_duration = 0;\n\n\t/*in playback mode*/\n\tif (traf->tfdt && is_first_merge) {\n#ifndef GPAC_DISABLE_LOG\n\t\tif (trak->moov->mov->NextMoofNumber && trak->present_in_scalable_segment && trak->sample_count_at_seg_start && (trak->dts_at_seg_start != traf->tfdt->baseMediaDecodeTime)) {\n\t\t\ts32 drift = (s32) ((s64) traf->tfdt->baseMediaDecodeTime - (s64)trak->dts_at_seg_start);\n\t\t\tif (drift<0) {\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] Warning: TFDT timing \"LLD\" less than cumulated timing \"LLD\" - using tfdt\\n\", traf->tfdt->baseMediaDecodeTime, trak->dts_at_seg_start ));\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (\"[iso file] TFDT timing \"LLD\" higher than cumulated timing \"LLD\" (last sample got extended in duration)\\n\", traf->tfdt->baseMediaDecodeTime, trak->dts_at_seg_start ));\n\t\t\t}\n\t\t}\n#endif\n\t\ttrak->dts_at_seg_start = traf->tfdt->baseMediaDecodeTime;\n\t}\n\telse if (traf->tfxd) {\n\t\ttrak->dts_at_seg_start = traf->tfxd->absolute_time_in_track_timescale;\n\t}\n\n\tif (traf->tfxd) {\n\t\ttrak->last_tfxd_value = traf->tfxd->absolute_time_in_track_timescale;\n\t\ttrak->last_tfxd_value += traf->tfxd->fragment_duration_in_track_timescale;\n\t}\n\tif (traf->tfrf) {\n\t\tif (trak->tfrf) gf_isom_box_del_parent(&trak->child_boxes, (GF_Box *)trak->tfrf);\n\t\ttrak->tfrf = traf->tfrf;\n\t\tgf_list_del_item(traf->child_boxes, traf->tfrf);\n\t\tgf_list_add(trak->child_boxes, trak->tfrf);\n\t}\n\n\tif (trak->moov->mov->signal_frag_bounds) {\n\t\tstore_traf_map = GF_TRUE;\n\t\tif (is_first_merge) {\n\t\t\tGF_MovieFragmentBox *moof_clone = NULL;\n\t\t\tgf_isom_box_freeze_order((GF_Box *)moof_box);\n\t\t\tgf_isom_clone_box((GF_Box *)moof_box, (GF_Box **)&moof_clone);\n\n\t\t\tif (moof_clone) {\n\t\t\t\tGF_BitStream *bs;\n\t\t\t\tfor (i=0; iTrackList); i++) {\n\t\t\t\t\tGF_TrackFragmentBox *traf_clone = gf_list_get(moof_clone->TrackList, i);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->TrackRuns);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sampleGroups);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sampleGroupsDescription);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sub_samples);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sai_offsets);\n\t\t\t\t\tgf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sai_sizes);\n\t\t\t\t\tif (traf_clone->sample_encryption) {\n\t\t\t\t\t\tgf_isom_box_del_parent(&traf_clone->child_boxes, (GF_Box *) traf_clone->sample_encryption);\n\t\t\t\t\t\ttraf_clone->sample_encryption = NULL;\n\t\t\t\t\t}\n\t\t\t\t\tif (traf_clone->sdtp) {\n\t\t\t\t\t\tgf_isom_box_del_parent(&traf_clone->child_boxes, (GF_Box *) traf_clone->sdtp);\n\t\t\t\t\t\ttraf_clone->sdtp = NULL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgf_isom_box_size((GF_Box *)moof_clone);\n\t\t\t\tbs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\n\t\t\t\tif (trak->moov->mov->seg_styp) {\n\t\t\t\t\tgf_isom_box_size(trak->moov->mov->seg_styp);\n\t\t\t\t\tgf_isom_box_write(trak->moov->mov->seg_styp, bs);\n\t\t\t\t}\n\t\t\t\tif (trak->moov->mov->root_sidx) {\n\t\t\t\t\tgf_isom_box_size((GF_Box *)trak->moov->mov->root_sidx);\n\t\t\t\t\tgf_isom_box_write((GF_Box *)trak->moov->mov->root_sidx, bs);\n\t\t\t\t}\n\t\t\t\tif (trak->moov->mov->seg_ssix) {\n\t\t\t\t\tgf_isom_box_size(trak->moov->mov->seg_ssix);\n\t\t\t\t\tgf_isom_box_write(trak->moov->mov->seg_ssix, bs);\n\t\t\t\t}\n\t\t\t\tgf_isom_box_write((GF_Box *)moof_clone, bs);\n\t\t\t\tgf_isom_box_del((GF_Box*)moof_clone);\n\n\t\t\t\tgf_bs_get_content(bs, &moof_template, &moof_template_size);\n\t\t\t\tgf_bs_del(bs);\n\t\t\t}\n\t\t}\n\t\tif (trak->moov->mov->seg_styp) {\n\t\t\tis_seg_start = GF_TRUE;\n\t\t\tseg_start = trak->moov->mov->styp_start_offset;\n\t\t}\n\t\tif (trak->moov->mov->root_sidx) {\n\t\t\tis_seg_start = GF_TRUE;\n\t\t\tsidx_start = trak->moov->mov->sidx_start_offset;\n\t\t\tsidx_end = trak->moov->mov->sidx_end_offset;\n\t\t\tif (! seg_start || (sidx_startmoov->mov->current_top_box_start;\n\t}\n\telse if (trak->moov->mov->store_traf_map) {\n\t\tstore_traf_map = GF_TRUE;\n\t}\n\n\n\tsample_index = 0;\n\ti=0;\n\twhile ((trun = (GF_TrackFragmentRunBox *)gf_list_enum(traf->TrackRuns, &i))) {\n\t\t//merge the run\n\t\tfor (j=0; jsample_count; j++) {\n\t\t\tGF_Err e;\n\t\t\ts32 cts_offset=0;\n\t\t\tif (jnb_samples) {\n\t\t\t\tent = &trun->samples[j];\n\t\t\t} else {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Track %d doesn't have enough trun entries (%d) compared to sample count (%d) in run\\n\", traf->trex->trackID, trun->nb_samples, trun->sample_count ));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsize = def_size;\n\t\t\tduration = def_duration;\n\t\t\tflags = def_flags;\n\n\t\t\t//CTS - if flag not set (trun or ctrn) defaults to 0 which is the base value after alloc\n\t\t\t//we just need to overrite its value if inherited\n\t\t\tcts_offset = ent->CTS_Offset;\n\n#ifdef GF_ENABLE_CTRN\n\t\t\tif (trun->use_ctrn) {\n\t\t\t\tif (!j && (trun->ctrn_flags & GF_ISOM_CTRN_FIRST_SAMPLE) ) {\n\t\t\t\t\tif (trun->ctrn_first_dur) duration = ent->Duration;\n\t\t\t\t\tif (trun->ctrn_first_size) size = ent->size;\n\t\t\t\t\tif (trun->ctrn_first_ctts) flags = ent->flags;\n\t\t\t\t} else {\n\t\t\t\t\tif (trun->ctrn_dur) duration = ent->Duration;\n\t\t\t\t\tif (trun->ctrn_size) size = ent->size;\n\t\t\t\t\tif (trun->ctrn_sample_flags) flags = ent->flags;\n\t\t\t\t}\n\t\t\t\t/*re-override*/\n\t\t\t\tif (trun->ctrn_flags & 0xF0) {\n\t\t\t\t\tGF_TrunEntry *ref_entry;\n\t\t\t\t\tif (!traf_ref) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Track %d use traf inheritance to track ID %d but reference traf not found\\n\", traf->trex->trackID, traf->trex->inherit_from_traf_id ));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tref_entry = traf_get_sample_entry(traf_ref, sample_index);\n\t\t\t\t\tif (!ref_entry) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Track %d use traf inheritance but sample %d not found in reference traf\\n\", traf->trex->trackID, sample_index+1 ));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_DUR)\n\t\t\t\t\t\tduration = ref_entry->Duration;\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_SIZE)\n\t\t\t\t\t\tsize = ref_entry->size;\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_FLAGS)\n\t\t\t\t\t\tflags = ref_entry->flags;\n\t\t\t\t\tif (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_CTSO)\n\t\t\t\t\t\tcts_offset = ref_entry->CTS_Offset;\n\t\t\t\t}\n\n\t\t\t} else\n#endif\n\t\t\t{\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_DURATION) duration = ent->Duration;\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_SIZE) size = ent->size;\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_FLAGS) {\n\t\t\t\t\tflags = ent->flags;\n\t\t\t\t} else if (!j && (trun->flags & GF_ISOM_TRUN_FIRST_FLAG)) {\n\t\t\t\t\tflags = trun->first_sample_flags;\n\t\t\t\t}\n\t\t\t}\n\t\t\tsample_index++;\n\t\t\t/*store the resolved value in case we have inheritance*/\n\t\t\tent->size = size;\n\t\t\tent->Duration = duration;\n\t\t\tent->flags = flags;\n\t\t\tent->CTS_Offset = cts_offset;\n\n\t\t\tlast_dts += duration;\n\n\t\t\t//add size first\n\t\t\tif (!trak->Media->information->sampleTable->SampleSize) {\n\t\t\t\ttrak->Media->information->sampleTable->SampleSize = (GF_SampleSizeBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STSZ);\n\t\t\t\tif (!trak->Media->information->sampleTable->SampleSize)\n\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t}\n\t\t\te = stbl_AppendSize(trak->Media->information->sampleTable, size, ent->nb_pack);\n\t\t\tif (e) return e;\n\n\t\t\t//then TS\n\t\t\tif (!trak->Media->information->sampleTable->TimeToSample) {\n\t\t\t\ttrak->Media->information->sampleTable->TimeToSample = (GF_TimeToSampleBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STTS);\n\t\t\t\tif (!trak->Media->information->sampleTable->TimeToSample)\n\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t}\n\t\t\te = stbl_AppendTime(trak->Media->information->sampleTable, duration, ent->nb_pack);\n\t\t\tif (e) return e;\n\n\t\t\t//add chunk on first sample\n\t\t\tif (!j) {\n\t\t\t\tu64 final_offset;\n\t\t\t\tdata_offset = base_offset;\n\t\t\t\t//we have an explicit data offset for this trun\n\t\t\t\tif (trun->flags & GF_ISOM_TRUN_DATA_OFFSET) {\n\t\t\t\t\tdata_offset += trun->data_offset;\n\t\t\t\t\t/*reset chunk size since data is now relative to this trun*/\n\t\t\t\t\tchunk_size = 0;\n\t\t\t\t\t/*remember this data offset for following trun*/\n\t\t\t\t\tprev_trun_data_offset = trun->data_offset;\n\t\t\t\t\t/*if mdat is located after the moof, and the moof was compressed, adjust offset\n\t\t\t\t\totherwise the offset does not need adjustment*/\n\t\t\t\t\tif (trun->data_offset>=0) {\n\t\t\t\t\t\tdata_offset -= compressed_diff;\n\t\t\t\t\t\tprev_trun_data_offset -= compressed_diff;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//we had an explicit data offset for the previous trun, use it + chunk size\n\t\t\t\telse if (prev_trun_data_offset) {\n\t\t\t\t\t/*data offset is previous chunk size plus previous offset of the trun*/\n\t\t\t\t\tdata_offset += prev_trun_data_offset + chunk_size;\n\t\t\t\t}\n\t\t\t\t//no explicit data offset, continuous data after last data in previous chunk\n\t\t\t\telse {\n\t\t\t\t\tdata_offset += chunk_size;\n\t\t\t\t\t//data offset of first trun in first traf, adjust if compressed moof\n\t\t\t\t\tif ((i==1) && (trun->data_offset>=0)) {\n\t\t\t\t\t\tdata_offset -= compressed_diff;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfinal_offset = data_offset;\n\t\t\t\t//adjust offset if moov was also compressed and we are still in the same file\n\t\t\t\t//so that later call to gf_isom_get_sample properly adjust back the offset\n\t\t\t\tif (trak->moov->compressed_diff) {\n\t\t\t\t\tfinal_offset += trak->moov->compressed_diff;\n\t\t\t\t}\n\n\t\t\t\tif (!trak->Media->information->sampleTable->ChunkOffset) {\n\t\t\t\t\ttrak->Media->information->sampleTable->ChunkOffset = gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STCO);\n\t\t\t\t\tif (!trak->Media->information->sampleTable->ChunkOffset)\n\t\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t\t}\n\t\t\t\te = stbl_AppendChunk(trak->Media->information->sampleTable, final_offset);\n\t\t\t\tif (e) return e;\n\t\t\t\t//then sampleToChunk\n\t\t\t\tif (!trak->Media->information->sampleTable->SampleToChunk) {\n\t\t\t\t\ttrak->Media->information->sampleTable->SampleToChunk = (GF_SampleToChunkBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STSC);\n\t\t\t\t\tif (!trak->Media->information->sampleTable->SampleToChunk)\n\t\t\t\t\t\treturn GF_OUT_OF_MEM;\n\t\t\t\t}\n\t\t\t\te = stbl_AppendSampleToChunk(trak->Media->information->sampleTable,\n\t\t\t\t DescIndex, trun->sample_count);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t\tchunk_size += size;\n\n\t\t\tif (store_traf_map && first_samp_in_traf) {\n\t\t\t\tfirst_samp_in_traf = GF_FALSE;\n\t\t\t\te = stbl_AppendTrafMap(trak->Media->information->sampleTable, is_seg_start, seg_start, frag_start, moof_template, moof_template_size, sidx_start, sidx_end);\n\t\t\t\tif (e) return e;\n\t\t\t\t//do not deallocate, the memory is now owned by traf map\n\t\t\t\tmoof_template = NULL;\n\t\t\t\tmoof_template_size = 0;\n\t\t\t}\n\t\t\tif (ent->nb_pack>1) {\n\t\t\t\tj+= ent->nb_pack-1;\n\t\t\t\ttraf_duration += ent->nb_pack*duration;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttraf_duration += duration;\n\n\t\t\te = stbl_AppendCTSOffset(trak->Media->information->sampleTable, cts_offset);\n\t\t\tif (e) return e;\n\t\t\t//flags\n\t\t\tsync = GF_ISOM_GET_FRAG_SYNC(flags);\n\t\t\tif (trak->Media->information->sampleTable->no_sync_found && sync) {\n\t\t\t\ttrak->Media->information->sampleTable->no_sync_found = 0;\n\t\t\t}\n\t\t\te = stbl_AppendRAP(trak->Media->information->sampleTable, sync);\n\t\t\tif (e) return e;\n\t\t\tpad = GF_ISOM_GET_FRAG_PAD(flags);\n\t\t\tif (pad) {\n\t\t\t\te = stbl_AppendPadding(trak->Media->information->sampleTable, pad);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t\tdegr = GF_ISOM_GET_FRAG_DEG(flags);\n\t\t\tif (degr) {\n\t\t\t\te = stbl_AppendDegradation(trak->Media->information->sampleTable, degr);\n\t\t\t\tif (e) return e;\n\t\t\t}\n\t\t\te = stbl_AppendDependencyType(trak->Media->information->sampleTable, GF_ISOM_GET_FRAG_LEAD(flags), GF_ISOM_GET_FRAG_DEPENDS(flags), GF_ISOM_GET_FRAG_DEPENDED(flags), GF_ISOM_GET_FRAG_REDUNDANT(flags));\n\t\t\tif (e) return e;\n\t\t}\n\t}\n\n\tif (trak->moov->mov->is_smooth && !traf->tfdt && !traf->tfxd) {\n\t\tif (is_first_merge)\n\t\t\ttrak->dts_at_seg_start = trak->dts_at_next_seg_start;\n\t\ttrak->dts_at_next_seg_start += last_dts;\n\t}\n\tif (traf_duration && trak->editBox && trak->editBox->editList) {\n\t\tfor (i=0; ieditBox->editList->entryList); i++) {\n\t\t\tGF_EdtsEntry *edts_e = gf_list_get(trak->editBox->editList->entryList, i);\n\t\t\tif (edts_e->was_empty_dur) {\n\t\t\t\tu64 extend_dur = traf_duration;\n\t\t\t\textend_dur *= trak->moov->mvhd->timeScale;\n\t\t\t\textend_dur /= trak->Media->mediaHeader->timeScale;\n\t\t\t\tedts_e->segmentDuration += extend_dur;\n\t\t\t}\n\t\t\telse if (!edts_e->segmentDuration) {\n\t\t\t\tedts_e->was_empty_dur = GF_TRUE;\n\t\t\t\tif ((s64) traf_duration > edts_e->mediaTime)\n\t\t\t\t\ttraf_duration -= edts_e->mediaTime;\n\t\t\t\telse\n\t\t\t\t\ttraf_duration = 0;\n\n\t\t\t\tedts_e->segmentDuration = traf_duration;\n\t\t\t\tedts_e->segmentDuration *= trak->moov->mvhd->timeScale;\n\t\t\t\tedts_e->segmentDuration /= trak->Media->mediaHeader->timeScale;\n\t\t\t}\n\n\t\t}\n\t}\n\n\t//in any case, update the cumulated offset\n\t//this will handle hypothetical files mixing MOOF offset and implicit non-moof offset\n\t*cumulated_offset = data_offset + chunk_size;\n\n\t/*merge sample groups*/\n\tif (traf->sampleGroups) {\n\t\tGF_List *groups;\n\t\tGF_List *groupDescs;\n\t\tBool is_identical_sgpd = GF_TRUE;\n\t\tu32 *new_idx = NULL, new_idx_count=0;\n\n\t\tif (!trak->Media->information->sampleTable->sampleGroups)\n\t\t\ttrak->Media->information->sampleTable->sampleGroups = gf_list_new();\n\n\t\tif (!trak->Media->information->sampleTable->sampleGroupsDescription)\n\t\t\ttrak->Media->information->sampleTable->sampleGroupsDescription = gf_list_new();\n\n\t\tgroupDescs = trak->Media->information->sampleTable->sampleGroupsDescription;\n\t\tfor (i=0; isampleGroupsDescription); i++) {\n\t\t\tGF_SampleGroupDescriptionBox *new_sgdesc = NULL;\n\t\t\tGF_SampleGroupDescriptionBox *sgdesc = gf_list_get(traf->sampleGroupsDescription, i);\n\t\t\tfor (j=0; jgrouping_type==sgdesc->grouping_type) break;\n\t\t\t\tnew_sgdesc = NULL;\n\t\t\t}\n\t\t\t/*new description, move it to our sample table*/\n\t\t\tif (!new_sgdesc) {\n\t\t\t\tgf_list_add(groupDescs, sgdesc);\n\t\t\t\tgf_list_add(trak->Media->information->sampleTable->child_boxes, sgdesc);\n\t\t\t\tgf_list_rem(traf->sampleGroupsDescription, i);\n\t\t\t\tgf_list_del_item(traf->child_boxes, sgdesc);\n\t\t\t\ti--;\n\t\t\t}\n\t\t\t/*merge descriptions*/\n\t\t\telse {\n\t\t\t\tu32 count;\n\n\t\t\t\tis_identical_sgpd = gf_isom_is_identical_sgpd(new_sgdesc, sgdesc, 0);\n\t\t\t\tif (is_identical_sgpd)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tnew_idx_count = gf_list_count(sgdesc->group_descriptions);\n\t\t\t\tnew_idx = (u32 *)gf_malloc(new_idx_count * sizeof(u32));\n\t\t\t\tif (!new_idx) return GF_OUT_OF_MEM;\n\n\t\t\t\tcount = 0;\n\t\t\t\twhile (gf_list_count(sgdesc->group_descriptions)) {\n\t\t\t\t\tvoid *sgpd_entry = gf_list_get(sgdesc->group_descriptions, 0);\n\t\t\t\t\tBool new_entry = GF_TRUE;\n\n\t\t\t\t\tfor (j = 0; j < gf_list_count(new_sgdesc->group_descriptions); j++) {\n\t\t\t\t\t\tvoid *ptr = gf_list_get(new_sgdesc->group_descriptions, j);\n\t\t\t\t\t\tif (gf_isom_is_identical_sgpd(sgpd_entry, ptr, new_sgdesc->grouping_type)) {\n\t\t\t\t\t\t\tnew_idx[count] = j + 1;\n\t\t\t\t\t\t\tcount ++;\n\t\t\t\t\t\t\tnew_entry = GF_FALSE;\n\t\t\t\t\t\t\tgf_free(sgpd_entry);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (new_entry) {\n\t\t\t\t\t\tgf_list_add(new_sgdesc->group_descriptions, sgpd_entry);\n\t\t\t\t\t\tnew_idx[count] = gf_list_count(new_sgdesc->group_descriptions);\n\t\t\t\t\t\tcount ++;\n\t\t\t\t\t}\n\n\t\t\t\t\tgf_list_rem(sgdesc->group_descriptions, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tgroups = trak->Media->information->sampleTable->sampleGroups;\n\t\tfor (i=0; isampleGroups); i++) {\n\t\t\tGF_SampleGroupBox *stbl_group = NULL;\n\t\t\tGF_SampleGroupBox *frag_group = gf_list_get(traf->sampleGroups, i);\n\n\n\t\t\tfor (j=0; jgrouping_type==stbl_group->grouping_type) && (frag_group->grouping_type_parameter==stbl_group->grouping_type_parameter))\n\t\t\t\t\tbreak;\n\t\t\t\tstbl_group = NULL;\n\t\t\t}\n\t\t\tif (!stbl_group) {\n\t\t\t\tstbl_group = (GF_SampleGroupBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_SBGP);\n\t\t\t\tif (!stbl_group) return GF_OUT_OF_MEM;\n\t\t\t\tstbl_group->grouping_type = frag_group->grouping_type;\n\t\t\t\tstbl_group->grouping_type_parameter = frag_group->grouping_type_parameter;\n\t\t\t\tstbl_group->version = frag_group->version;\n\t\t\t\tgf_list_add(groups, stbl_group);\n\t\t\t}\n\n\t\t\tif (is_identical_sgpd) {\n\t\t\t\t//adjust sgpd index: in traf index start at 0x1001\n\t\t\t\tfor (j = 0; j < frag_group->entry_count; j++)\n\t\t\t\t\tfrag_group->sample_entries[j].group_description_index &= 0x0FFFF;\n\t\t\t\tif (frag_group->entry_count && stbl_group->entry_count &&\n\t\t\t\t (frag_group->sample_entries[0].group_description_index==stbl_group->sample_entries[stbl_group->entry_count-1].group_description_index)\n\t\t\t\t ) {\n\t\t\t\t\tstbl_group->sample_entries[stbl_group->entry_count - 1].sample_count += frag_group->sample_entries[0].sample_count;\n\t\t\t\t\tif (frag_group->entry_count>1) {\n\t\t\t\t\t\tstbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count - 1));\n\t\t\t\t\t\tmemcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[1], sizeof(GF_SampleGroupEntry) * (frag_group->entry_count - 1));\n\t\t\t\t\t\tstbl_group->entry_count += frag_group->entry_count - 1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tstbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count));\n\t\t\t\t\tmemcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[0], sizeof(GF_SampleGroupEntry) * frag_group->entry_count);\n\t\t\t\t\tstbl_group->entry_count += frag_group->entry_count;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count));\n\t\t\t\t//adjust sgpd index\n\t\t\t\tfor (j = 0; j < frag_group->entry_count; j++) {\n\t\t\t\t\tu32 sgidx = frag_group->sample_entries[j].group_description_index;\n\t\t\t\t\tif (sgidx > 0x10000) {\n\t\t\t\t\t\tsgidx -= 0x10001;\n\t\t\t\t\t\tif (sgidx>=new_idx_count) {\n\t\t\t\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[isobmf] corrupted sample group index in fragment %d but only %d group descriptions in fragment\\n\", sgidx, new_idx_count));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfrag_group->sample_entries[j].group_description_index = new_idx[sgidx];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmemcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[0], sizeof(GF_SampleGroupEntry) * frag_group->entry_count);\n\t\t\t\tstbl_group->entry_count += frag_group->entry_count;\n\t\t\t}\n\t\t}\n\n\t\tif (new_idx) gf_free(new_idx);\n\t}\n\n\t/*content is encrypted*/\n\ttrack_num = gf_isom_get_tracknum_from_id(trak->moov, trak->Header->trackID);\n\tif (gf_isom_is_cenc_media(trak->moov->mov, track_num, DescIndex)\n\t\t|| traf->sample_encryption) {\n\t\t/*Merge sample auxiliary encryption information*/\n\t\tGF_SampleEncryptionBox *senc = NULL;\n\t\tu32 scheme_type;\n\t\tgf_isom_get_cenc_info(trak->moov->mov, track_num, DescIndex, NULL, &scheme_type, NULL);\n\n\t\tif (traf->sample_encryption) {\n\t\t\tfor (i = 0; i < gf_list_count(trak->Media->information->sampleTable->child_boxes); i++) {\n\t\t\t\tGF_Box *a = (GF_Box *)gf_list_get(trak->Media->information->sampleTable->child_boxes, i);\n\t\t\t\tif (a->type != traf->sample_encryption->type) continue;\n\n\t\t\t\tif ((a->type ==GF_ISOM_BOX_TYPE_UUID) && (((GF_UUIDBox *)a)->internal_4cc == GF_ISOM_BOX_UUID_PSEC)) {\n\t\t\t\t\tsenc = (GF_SampleEncryptionBox *)a;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if (a->type ==GF_ISOM_BOX_TYPE_SENC) {\n\t\t\t\t\tsenc = (GF_SampleEncryptionBox *)a;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!senc && trak->sample_encryption)\n\t\t\t\tsenc = trak->sample_encryption;\n\n\t\t\tif (!senc) {\n\t\t\t\tif (traf->sample_encryption->piff_type==1) {\n\t\t\t\t\tsenc = (GF_SampleEncryptionBox *)gf_isom_create_piff_psec_box(1, 0x2, 0, 0, NULL);\n\t\t\t\t} else {\n\t\t\t\t\tsenc = gf_isom_create_samp_enc_box(1, 0x2);\n\t\t\t\t}\n\n\t\t\t\tif (!trak->Media->information->sampleTable->child_boxes) trak->Media->information->sampleTable->child_boxes = gf_list_new();\n\n\t\t\t\ttrak->sample_encryption = senc;\n\t\t\t\tif (!trak->child_boxes) trak->child_boxes = gf_list_new();\n\t\t\t\tgf_list_add(trak->child_boxes, senc);\n\t\t\t}\n\t\t}\n\n\t\t/*get sample auxiliary information by saiz/saio rather than by parsing senc box*/\n\t\tif (gf_isom_cenc_has_saiz_saio_traf(traf, scheme_type)) {\n\t\t\tu32 nb_saio;\n\t\t\tu32 aux_info_type;\n\t\t\tu64 offset;\n\t\t\tGF_Err e;\n\t\t\tBool is_encrypted;\n\t\t\tGF_SampleAuxiliaryInfoOffsetBox *saio = NULL;\n\t\t\tGF_SampleAuxiliaryInfoSizeBox *saiz = NULL;\n\n\t\t\toffset = nb_saio = 0;\n\n\t\t\tfor (i = 0; i < gf_list_count(traf->sai_offsets); i++) {\n\t\t\t\tsaio = (GF_SampleAuxiliaryInfoOffsetBox *)gf_list_get(traf->sai_offsets, i);\n\t\t\t\taux_info_type = saio->aux_info_type;\n\t\t\t\tif (!aux_info_type) aux_info_type = scheme_type;\n\n\t\t\t\t/*if we have only 1 sai_offsets, assume that its type is cenc*/\n\t\t\t\tif ((aux_info_type == GF_ISOM_CENC_SCHEME) || (aux_info_type == GF_ISOM_CBC_SCHEME) ||\n\t\t\t\t\t(aux_info_type == GF_ISOM_CENS_SCHEME) || (aux_info_type == GF_ISOM_CBCS_SCHEME) ||\n\t\t\t\t\t(gf_list_count(traf->sai_offsets) == 1)) {\n\t\t\t\t\tif (saio->offsets && saio->entry_count) {\n\t\t\t\t\t\toffset = saio->offsets[0] + moof_offset;\n\t\t\t\t\t\tnb_saio = saio->entry_count;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsaio = NULL;\n\t\t\t}\n\t\t\tfor (i = 0; i < gf_list_count(traf->sai_sizes); i++) {\n\t\t\t\tsaiz = (GF_SampleAuxiliaryInfoSizeBox *)gf_list_get(traf->sai_sizes, i);\n\t\t\t\taux_info_type = saiz->aux_info_type;\n\t\t\t\tif (!aux_info_type) aux_info_type = scheme_type;\n\t\t\t\t/*if we have only 1 sai_sizes, assume that its type is cenc*/\n\t\t\t\tif ((aux_info_type == GF_ISOM_CENC_SCHEME) || (aux_info_type == GF_ISOM_CBC_SCHEME) ||\n\t\t\t\t\t(aux_info_type == GF_ISOM_CENS_SCHEME) || (aux_info_type == GF_ISOM_CBCS_SCHEME) ||\n\t\t\t\t\t(gf_list_count(traf->sai_sizes) == 1)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsaiz = NULL;\n\t\t\t}\n\t\t\tif (saiz && saio && senc) {\n\t\t\t\tfor (i = 0; i < saiz->sample_count; i++) {\n\t\t\t\t\tGF_CENCSampleAuxInfo *sai;\n\t\t\t\t\tconst u8 *key_info=NULL;\n\t\t\t\t\tu32 key_info_size;\n\t\t\t\t\tu64 cur_position;\n\t\t\t\t\tif (nb_saio != 1)\n\t\t\t\t\t\toffset = saio->offsets[i] + moof_offset;\n\t\t\t\t\tsize = saiz->default_sample_info_size ? saiz->default_sample_info_size : saiz->sample_info_size[i];\n\n\t\t\t\t\tcur_position = gf_bs_get_position(trak->moov->mov->movieFileMap->bs);\n\t\t\t\t\tgf_bs_seek(trak->moov->mov->movieFileMap->bs, offset);\n\n\t\t\t\t\tGF_SAFEALLOC(sai, GF_CENCSampleAuxInfo);\n\t\t\t\t\tif (!sai) return GF_OUT_OF_MEM;\n\n\t\t\t\t\te = gf_isom_get_sample_cenc_info_internal(trak, traf, senc, i+1, &is_encrypted, NULL, NULL, &key_info, &key_info_size);\n\t\t\t\t\tif (e) {\n\t\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[isobmf] could not get cenc info for sample %d: %s\\n\", i+1, gf_error_to_string(e) ));\n\t\t\t\t\t\treturn e;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (is_encrypted) {\n\t\t\t\t\t\tsai->cenc_data_size = size;\n\t\t\t\t\t\tsai->cenc_data = gf_malloc(sizeof(u8)*size);\n\t\t\t\t\t\tif (!sai->cenc_data) return GF_OUT_OF_MEM;\n\t\t\t\t\t\tgf_bs_read_data(trak->moov->mov->movieFileMap->bs, sai->cenc_data, sai->cenc_data_size);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsai->isNotProtected=1;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (key_info) {\n\t\t\t\t\t\t//not multikey\n\t\t\t\t\t\tif (!key_info[0]) {\n\t\t\t\t\t\t\t//size greater than IV\n\t\t\t\t\t\t\tif (size > key_info[3])\n\t\t\t\t\t\t\t\tsenc->flags = 0x00000002;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//multikey, always use subsamples\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsenc->flags = 0x00000002;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\n\t\t\t\t\tgf_bs_seek(trak->moov->mov->movieFileMap->bs, cur_position);\n\n\t\t\t\t\tgf_list_add(senc->samp_aux_info, sai);\n\n\t\t\t\t\te = gf_isom_cenc_merge_saiz_saio(senc, trak->Media->information->sampleTable, offset, size);\n\t\t\t\t\tif (e) return e;\n\t\t\t\t\tif (nb_saio == 1)\n\t\t\t\t\t\toffset += size;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (traf->sample_encryption) {\n\t\t\tsenc_Parse(trak->moov->mov->movieFileMap->bs, trak, traf, traf->sample_encryption);\n\t\t\ttrak->sample_encryption->AlgorithmID = traf->sample_encryption->AlgorithmID;\n\t\t\tif (!trak->sample_encryption->IV_size)\n\t\t\t\ttrak->sample_encryption->IV_size = traf->sample_encryption->IV_size;\n\t\t\tif (!trak->sample_encryption->samp_aux_info) trak->sample_encryption->samp_aux_info = gf_list_new();\n\t\t\tgf_list_transfer(trak->sample_encryption->samp_aux_info, traf->sample_encryption->samp_aux_info);\n\t\t\tif (traf->sample_encryption->flags & 0x00000002)\n\t\t\t\ttrak->sample_encryption->flags |= 0x00000002;\n\t\t}\n\t}\n\treturn GF_OK;\n}", "project": "gpac", "hash": 303288141822567692112362620916464223543, "size": 681, "commit_id": "df8fffd839fe5ae9acd82d26fd48280a397411d9", "message": "fixed #1736", "target": 0, "dataset": "other", "idx": 272325} {"func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n int axis = params->axis;\n int num_inputs = node->inputs->size;\n\n // The number of dimensions of the input tensors must match, and all\n // dimensions except 'axis' must be equal.\n const TfLiteTensor* t0;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &t0));\n TfLiteType input_type = t0->type;\n if (axis < 0) axis += t0->dims->size;\n TF_LITE_ENSURE(context, axis >= 0);\n TF_LITE_ENSURE(context, axis < t0->dims->size);\n\n TF_LITE_ENSURE_EQ(context, params->activation, kTfLiteActNone);\n TF_LITE_ENSURE(context,\n input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 ||\n input_type == kTfLiteInt8 || input_type == kTfLiteInt16 ||\n input_type == kTfLiteInt32 || input_type == kTfLiteInt64 ||\n input_type == kTfLiteBool);\n\n // Output dimensions will match input dimensions, except 'axis', which\n // will be the sum of inputs\n int sum_axis = t0->dims->data[axis];\n for (int i = 1; i < num_inputs; ++i) {\n const TfLiteTensor* t;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t));\n TF_LITE_ENSURE_EQ(context, t->dims->size, t0->dims->size);\n TF_LITE_ENSURE_EQ(context, t->type, input_type);\n for (int d = 0; d < t0->dims->size; ++d) {\n if (d == axis) {\n sum_axis += t->dims->data[axis];\n } else {\n TF_LITE_ENSURE_EQ(context, t->dims->data[d], t0->dims->data[d]);\n }\n }\n }\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(t0->dims->size);\n for (int d = 0; d < t0->dims->size; ++d) {\n output_size->data[d] = (d == axis) ? sum_axis : t0->dims->data[d];\n }\n\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, input_type);\n\n if (input_type == kTfLiteInt8) {\n // Make sure there is no re-scaling needed for Int8 quantized kernel. This\n // is a restriction we introduced to Int8 kernels.\n VectorOfTensors all_inputs(*context, *node->inputs);\n for (int i = 0; i < node->inputs->size; ++i) {\n const TfLiteTensor* t;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t));\n TF_LITE_ENSURE_EQ(context, t->params.scale, output->params.scale);\n TF_LITE_ENSURE_EQ(context, t->params.zero_point,\n output->params.zero_point);\n }\n }\n\n if (input_type == kTfLiteInt16) {\n // Make sure that all Int16 inputs have a null zero-point.\n for (int i = 0; i < node->inputs->size; ++i) {\n const TfLiteTensor* t = GetInput(context, node, i);\n TF_LITE_ENSURE_EQ(context, t->params.zero_point, 0);\n }\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);\n }\n\n return context->ResizeTensor(context, output, output_size);\n}", "project": "tensorflow", "hash": 92324200070320272661822081558700268693, "size": 72, "commit_id": "4253f96a58486ffe84b61c0415bb234a4632ee73", "message": "Fix integer overflow in TFLite concat\n\nPiperOrigin-RevId: 371013841\nChange-Id: I6a4782ce7ca753e23ff31e7fb6aeb7f9d412cd29", "target": 1, "dataset": "other", "idx": 198349} {"func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n int axis = params->axis;\n int num_inputs = node->inputs->size;\n\n // The number of dimensions of the input tensors must match, and all\n // dimensions except 'axis' must be equal.\n const TfLiteTensor* t0;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &t0));\n TfLiteType input_type = t0->type;\n if (axis < 0) axis += t0->dims->size;\n TF_LITE_ENSURE(context, axis >= 0);\n TF_LITE_ENSURE(context, axis < t0->dims->size);\n\n TF_LITE_ENSURE_EQ(context, params->activation, kTfLiteActNone);\n TF_LITE_ENSURE(context,\n input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 ||\n input_type == kTfLiteInt8 || input_type == kTfLiteInt16 ||\n input_type == kTfLiteInt32 || input_type == kTfLiteInt64 ||\n input_type == kTfLiteBool);\n\n // Output dimensions will match input dimensions, except 'axis', which\n // will be the sum of inputs\n int sum_axis = t0->dims->data[axis];\n for (int i = 1; i < num_inputs; ++i) {\n const TfLiteTensor* t;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t));\n TF_LITE_ENSURE_EQ(context, t->dims->size, t0->dims->size);\n TF_LITE_ENSURE_EQ(context, t->type, input_type);\n for (int d = 0; d < t0->dims->size; ++d) {\n if (d == axis) {\n // Avoid integer overflow in sum_axis below\n TF_LITE_ENSURE(context, t->dims->data[axis] >= 0);\n TF_LITE_ENSURE(context, t->dims->data[axis] <=\n std::numeric_limits::max() - sum_axis);\n sum_axis += t->dims->data[axis];\n } else {\n TF_LITE_ENSURE_EQ(context, t->dims->data[d], t0->dims->data[d]);\n }\n }\n }\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(t0->dims->size);\n for (int d = 0; d < t0->dims->size; ++d) {\n output_size->data[d] = (d == axis) ? sum_axis : t0->dims->data[d];\n }\n\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, input_type);\n\n if (input_type == kTfLiteInt8) {\n // Make sure there is no re-scaling needed for Int8 quantized kernel. This\n // is a restriction we introduced to Int8 kernels.\n VectorOfTensors all_inputs(*context, *node->inputs);\n for (int i = 0; i < node->inputs->size; ++i) {\n const TfLiteTensor* t;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t));\n TF_LITE_ENSURE_EQ(context, t->params.scale, output->params.scale);\n TF_LITE_ENSURE_EQ(context, t->params.zero_point,\n output->params.zero_point);\n }\n }\n\n if (input_type == kTfLiteInt16) {\n // Make sure that all Int16 inputs have a null zero-point.\n for (int i = 0; i < node->inputs->size; ++i) {\n const TfLiteTensor* t = GetInput(context, node, i);\n TF_LITE_ENSURE_EQ(context, t->params.zero_point, 0);\n }\n TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);\n }\n\n return context->ResizeTensor(context, output, output_size);\n}", "project": "tensorflow", "hash": 173727750294110908854288838016785698395, "size": 76, "commit_id": "4253f96a58486ffe84b61c0415bb234a4632ee73", "message": "Fix integer overflow in TFLite concat\n\nPiperOrigin-RevId: 371013841\nChange-Id: I6a4782ce7ca753e23ff31e7fb6aeb7f9d412cd29", "target": 0, "dataset": "other", "idx": 273050} {"func": "\tPong(const std::string& cookie, const std::string& server = \"\")\n\t\t: ClientProtocol::Message(\"PONG\", ServerInstance->Config->GetServerName())\n\t{\n\t\tPushParamRef(ServerInstance->Config->GetServerName());\n\t\tif (!server.empty())\n\t\t\tPushParamRef(server);\n\t\tPushParamRef(cookie);\n\t}", "project": "inspircd", "hash": 261166146508544882843094418005234060063, "size": 8, "commit_id": "4350a11c663b0d75f8119743bffb7736d87abd4d", "message": "Fix sending malformed pong messages in some cases.", "target": 1, "dataset": "other", "idx": 198370} {"func": "\tPong(const std::string& cookie, const std::string& server = \"\")\n\t\t: ClientProtocol::Message(\"PONG\", ServerInstance->Config->GetServerName())\n\t{\n\t\tif (server.empty())\n\t\t\tPushParamRef(ServerInstance->Config->GetServerName());\n\t\telse\n\t\t\tPushParam(server);\n\t\tPushParamRef(cookie);\n\t}", "project": "inspircd", "hash": 221906848297919622116301621609254196785, "size": 9, "commit_id": "4350a11c663b0d75f8119743bffb7736d87abd4d", "message": "Fix sending malformed pong messages in some cases.", "target": 0, "dataset": "other", "idx": 273215} {"func": "static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx,\n CodedBitstreamFragment *frag,\n int header)\n{\n AVBufferRef *data_ref;\n uint8_t *data;\n size_t data_size;\n int unit, start, end, marker, next_start, next_marker;\n int err, i, j, length;\n\n if (frag->data_size < 4) {\n // Definitely too short to be meaningful.\n return AVERROR_INVALIDDATA;\n }\n\n for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++);\n if (i > 0) {\n av_log(ctx->log_ctx, AV_LOG_WARNING, \"Discarding %d bytes at \"\n \"beginning of image.\\n\", i);\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size && frag->data[i]) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no SOI marker found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n if (marker != JPEG_MARKER_SOI) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: first \"\n \"marker is %02x, should be SOI.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no image content found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n start = i + 1;\n\n for (unit = 0;; unit++) {\n if (marker == JPEG_MARKER_EOI) {\n break;\n } else if (marker == JPEG_MARKER_SOS) {\n for (i = start; i + 1 < frag->data_size; i++) {\n if (frag->data[i] != 0xff)\n continue;\n end = i;\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n if (frag->data[i] == 0x00)\n continue;\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n break;\n }\n } else {\n i = start;\n if (i + 2 > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n length = AV_RB16(frag->data + i);\n if (i + length > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker segment.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n end = start + length;\n\n i = end;\n if (frag->data[i] != 0xff) {\n next_marker = -1;\n } else {\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n }\n }\n\n if (marker == JPEG_MARKER_SOS) {\n length = AV_RB16(frag->data + start);\n\n data_ref = NULL;\n data = av_malloc(end - start +\n AV_INPUT_BUFFER_PADDING_SIZE);\n if (!data)\n return AVERROR(ENOMEM);\n\n memcpy(data, frag->data + start, length);\n for (i = start + length, j = length; i < end; i++, j++) {\n if (frag->data[i] == 0xff) {\n while (frag->data[i] == 0xff)\n ++i;\n data[j] = 0xff;\n } else {\n data[j] = frag->data[i];\n }\n }\n data_size = j;\n\n memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);\n\n } else {\n data = frag->data + start;\n data_size = end - start;\n data_ref = frag->data_ref;\n }\n\n err = ff_cbs_insert_unit_data(ctx, frag, unit, marker,\n data, data_size, data_ref);\n if (err < 0) {\n if (!data_ref)\n av_freep(&data);\n return err;\n }\n\n if (next_marker == -1)\n break;\n marker = next_marker;\n start = next_start;\n }\n\n return 0;\n}", "project": "FFmpeg", "hash": 97423740291215508096520627238927806950, "size": 136, "commit_id": "a3a3730b5456ca00587455004d40c047f7b20a99", "message": "avcodec/cbs_jpeg: Check length for SOS\n\nFixes: out of array access\nFixes: 19734/clusterfuzz-testcase-minimized-ffmpeg_BSF_TRACE_HEADERS_fuzzer-5673507031875584\nFixes: 19353/clusterfuzz-testcase-minimized-ffmpeg_BSF_TRACE_HEADERS_fuzzer-5703944462663680\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nSigned-off-by: Michael Niedermayer \n(cherry picked from commit 1812352d767ccf5431aa440123e2e260a4db2726)\nSigned-off-by: Michael Niedermayer ", "target": 1, "dataset": "other", "idx": 198372} {"func": "static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx,\n CodedBitstreamFragment *frag,\n int header)\n{\n AVBufferRef *data_ref;\n uint8_t *data;\n size_t data_size;\n int unit, start, end, marker, next_start, next_marker;\n int err, i, j, length;\n\n if (frag->data_size < 4) {\n // Definitely too short to be meaningful.\n return AVERROR_INVALIDDATA;\n }\n\n for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++);\n if (i > 0) {\n av_log(ctx->log_ctx, AV_LOG_WARNING, \"Discarding %d bytes at \"\n \"beginning of image.\\n\", i);\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size && frag->data[i]) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no SOI marker found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n if (marker != JPEG_MARKER_SOI) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: first \"\n \"marker is %02x, should be SOI.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no image content found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n start = i + 1;\n\n for (unit = 0;; unit++) {\n if (marker == JPEG_MARKER_EOI) {\n break;\n } else if (marker == JPEG_MARKER_SOS) {\n for (i = start; i + 1 < frag->data_size; i++) {\n if (frag->data[i] != 0xff)\n continue;\n end = i;\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n if (frag->data[i] == 0x00)\n continue;\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n break;\n }\n } else {\n i = start;\n if (i + 2 > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n length = AV_RB16(frag->data + i);\n if (i + length > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker segment.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n end = start + length;\n\n i = end;\n if (frag->data[i] != 0xff) {\n next_marker = -1;\n } else {\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n }\n }\n\n if (marker == JPEG_MARKER_SOS) {\n length = AV_RB16(frag->data + start);\n\n if (length > end - start)\n return AVERROR_INVALIDDATA;\n\n data_ref = NULL;\n data = av_malloc(end - start +\n AV_INPUT_BUFFER_PADDING_SIZE);\n if (!data)\n return AVERROR(ENOMEM);\n\n memcpy(data, frag->data + start, length);\n for (i = start + length, j = length; i < end; i++, j++) {\n if (frag->data[i] == 0xff) {\n while (frag->data[i] == 0xff)\n ++i;\n data[j] = 0xff;\n } else {\n data[j] = frag->data[i];\n }\n }\n data_size = j;\n\n memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);\n\n } else {\n data = frag->data + start;\n data_size = end - start;\n data_ref = frag->data_ref;\n }\n\n err = ff_cbs_insert_unit_data(ctx, frag, unit, marker,\n data, data_size, data_ref);\n if (err < 0) {\n if (!data_ref)\n av_freep(&data);\n return err;\n }\n\n if (next_marker == -1)\n break;\n marker = next_marker;\n start = next_start;\n }\n\n return 0;\n}", "project": "FFmpeg", "hash": 182498168350715750569467212904850217645, "size": 139, "commit_id": "a3a3730b5456ca00587455004d40c047f7b20a99", "message": "avcodec/cbs_jpeg: Check length for SOS\n\nFixes: out of array access\nFixes: 19734/clusterfuzz-testcase-minimized-ffmpeg_BSF_TRACE_HEADERS_fuzzer-5673507031875584\nFixes: 19353/clusterfuzz-testcase-minimized-ffmpeg_BSF_TRACE_HEADERS_fuzzer-5703944462663680\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nSigned-off-by: Michael Niedermayer \n(cherry picked from commit 1812352d767ccf5431aa440123e2e260a4db2726)\nSigned-off-by: Michael Niedermayer ", "target": 0, "dataset": "other", "idx": 273279} {"func": "TfLiteStatus ResizeOutput(TfLiteContext* context, const TfLiteTensor* input,\n const TfLiteTensor* axis, TfLiteTensor* output) {\n int axis_value;\n // Retrive all 8 bytes when axis type is kTfLiteInt64 to avoid data loss.\n if (axis->type == kTfLiteInt64) {\n axis_value = static_cast(*GetTensorData(axis));\n } else {\n axis_value = *GetTensorData(axis);\n }\n if (axis_value < 0) {\n axis_value += NumDimensions(input);\n }\n\n // Copy the input dimensions to output except the axis dimension.\n TfLiteIntArray* output_dims = TfLiteIntArrayCreate(NumDimensions(input) - 1);\n int j = 0;\n for (int i = 0; i < NumDimensions(input); ++i) {\n if (i != axis_value) {\n output_dims->data[j] = SizeOfDimension(input, i);\n ++j;\n }\n }\n return context->ResizeTensor(context, output, output_dims);\n}", "project": "tensorflow", "hash": 85730760625429324821980003967303687262, "size": 24, "commit_id": "c59c37e7b2d563967da813fa50fe20b21f4da683", "message": "Prevent array write out-of-bounds.\n\nIf user passes an invalid axis, then we copy one too many dimensions to the output in the loop below these checks. Even if we didn't do that, there will be further issues with an invalid axis, so we check for that right now.\n\nPiperOrigin-RevId: 371023299\nChange-Id: I9eca37ffc2b29e8e48710f500701270ef0790224", "target": 1, "dataset": "other", "idx": 198396} {"func": "TfLiteStatus ResizeOutput(TfLiteContext* context, const TfLiteTensor* input,\n const TfLiteTensor* axis, TfLiteTensor* output) {\n int axis_value;\n // Retrive all 8 bytes when axis type is kTfLiteInt64 to avoid data loss.\n if (axis->type == kTfLiteInt64) {\n axis_value = static_cast(*GetTensorData(axis));\n } else {\n axis_value = *GetTensorData(axis);\n }\n if (axis_value < 0) {\n axis_value += NumDimensions(input);\n }\n\n TF_LITE_ENSURE(context, axis_value >= 0);\n TF_LITE_ENSURE(context, axis_value < NumDimensions(input));\n\n // Copy the input dimensions to output except the axis dimension.\n TfLiteIntArray* output_dims = TfLiteIntArrayCreate(NumDimensions(input) - 1);\n int j = 0;\n for (int i = 0; i < NumDimensions(input); ++i) {\n if (i != axis_value) {\n output_dims->data[j] = SizeOfDimension(input, i);\n ++j;\n }\n }\n return context->ResizeTensor(context, output, output_dims);\n}", "project": "tensorflow", "hash": 224958909197921227858368302688275106543, "size": 27, "commit_id": "c59c37e7b2d563967da813fa50fe20b21f4da683", "message": "Prevent array write out-of-bounds.\n\nIf user passes an invalid axis, then we copy one too many dimensions to the output in the loop below these checks. Even if we didn't do that, there will be further issues with an invalid axis, so we check for that right now.\n\nPiperOrigin-RevId: 371023299\nChange-Id: I9eca37ffc2b29e8e48710f500701270ef0790224", "target": 0, "dataset": "other", "idx": 273769} {"func": "mrb_realloc(mrb_state *mrb, void *p, size_t len)\n{\n void *p2;\n\n p2 = mrb_realloc_simple(mrb, p, len);\n if (len == 0) return p2;\n if (p2 == NULL) {\n mrb_free(mrb, p);\n mrb->gc.out_of_memory = TRUE;\n mrb_raise_nomemory(mrb);\n }\n else {\n mrb->gc.out_of_memory = FALSE;\n }\n\n return p2;\n}", "project": "mruby", "hash": 162088573447200069676744299327088726317, "size": 17, "commit_id": "97319697c8f9f6ff27b32589947e1918e3015503", "message": "Cancel 9cdf439\n\nShould not free the pointer in `realloc` since it can cause\nuse-after-free problem.", "target": 1, "dataset": "other", "idx": 198402} {"func": "mrb_realloc(mrb_state *mrb, void *p, size_t len)\n{\n void *p2;\n\n p2 = mrb_realloc_simple(mrb, p, len);\n if (len == 0) return p2;\n if (p2 == NULL) {\n mrb->gc.out_of_memory = TRUE;\n mrb_raise_nomemory(mrb);\n }\n else {\n mrb->gc.out_of_memory = FALSE;\n }\n\n return p2;\n}", "project": "mruby", "hash": 233155307309393879841958010235802131920, "size": 16, "commit_id": "97319697c8f9f6ff27b32589947e1918e3015503", "message": "Cancel 9cdf439\n\nShould not free the pointer in `realloc` since it can cause\nuse-after-free problem.", "target": 0, "dataset": "other", "idx": 274032} {"func": " Status GetFirstDimensionSize(OpKernelContext* context, INDEX_TYPE* result) {\n const Tensor first_partition_tensor =\n context->input(kFirstPartitionInputIndex);\n const RowPartitionType first_partition_type = row_partition_types_[0];\n switch (first_partition_type) {\n case RowPartitionType::FIRST_DIM_SIZE:\n *result = first_partition_tensor.scalar()();\n return Status::OK();\n case RowPartitionType::VALUE_ROWIDS:\n return errors::InvalidArgument(\n \"Cannot handle VALUE_ROWIDS in first dimension.\");\n case RowPartitionType::ROW_SPLITS:\n *result = first_partition_tensor.shape().dim_size(0) - 1;\n return Status::OK();\n default:\n return errors::InvalidArgument(\n \"Cannot handle type \",\n RowPartitionTypeToString(first_partition_type));\n }\n }", "project": "tensorflow", "hash": 8875073086629769890154937833779819001, "size": 20, "commit_id": "301ae88b331d37a2a16159b65b255f4f9eb39314", "message": "Fix null ptr deref in tf.raw_ops.RaggedTensorToTensor\n\nPiperOrigin-RevId: 384257511\nChange-Id: I0484ad285039d132d6c41b284a7fcdd2b774a38e", "target": 1, "dataset": "other", "idx": 198407} {"func": " Status GetFirstDimensionSize(OpKernelContext* context, INDEX_TYPE* result) {\n const Tensor first_partition_tensor =\n context->input(kFirstPartitionInputIndex);\n if (row_partition_types_.empty()) {\n return errors::InvalidArgument(\"No row_partition_types given.\");\n }\n const RowPartitionType first_partition_type = row_partition_types_[0];\n switch (first_partition_type) {\n case RowPartitionType::FIRST_DIM_SIZE:\n *result = first_partition_tensor.scalar()();\n return Status::OK();\n case RowPartitionType::VALUE_ROWIDS:\n return errors::InvalidArgument(\n \"Cannot handle VALUE_ROWIDS in first dimension.\");\n case RowPartitionType::ROW_SPLITS:\n *result = first_partition_tensor.shape().dim_size(0) - 1;\n return Status::OK();\n default:\n return errors::InvalidArgument(\n \"Cannot handle type \",\n RowPartitionTypeToString(first_partition_type));\n }\n }", "project": "tensorflow", "hash": 111412195870420450026567644267237811330, "size": 23, "commit_id": "301ae88b331d37a2a16159b65b255f4f9eb39314", "message": "Fix null ptr deref in tf.raw_ops.RaggedTensorToTensor\n\nPiperOrigin-RevId: 384257511\nChange-Id: I0484ad285039d132d6c41b284a7fcdd2b774a38e", "target": 0, "dataset": "other", "idx": 274041} {"func": " void Compute(OpKernelContext *ctx) override {\n // (0) validations\n const Tensor *a_indices, *b_indices, *a_values_t, *b_values_t, *a_shape,\n *b_shape, *thresh_t;\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_indices\", &a_indices));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_indices\", &b_indices));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsMatrix(a_indices->shape()) &&\n TensorShapeUtils::IsMatrix(b_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be matrices but received shapes: \",\n a_indices->shape().DebugString(), \" and \",\n b_indices->shape().DebugString()));\n const int64 a_nnz = a_indices->dim_size(0);\n const int64 b_nnz = b_indices->dim_size(0);\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_values\", &a_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_values\", &b_values_t));\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_values_t->shape()) &&\n TensorShapeUtils::IsVector(b_values_t->shape()),\n errors::InvalidArgument(\n \"Input values should be vectors but received shapes: \",\n a_values_t->shape().DebugString(), \" and \",\n b_values_t->shape().DebugString()));\n auto a_values = ctx->input(1).vec();\n auto b_values = ctx->input(4).vec();\n OP_REQUIRES(\n ctx, a_values.size() == a_nnz && b_values.size() == b_nnz,\n errors::InvalidArgument(\"Expected \", a_nnz, \" and \", b_nnz,\n \" non-empty input values, got \",\n a_values.size(), \" and \", b_values.size()));\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_shape\", &a_shape));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_shape\", &b_shape));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_shape->shape()) &&\n TensorShapeUtils::IsVector(b_shape->shape()),\n errors::InvalidArgument(\n \"Input shapes should be a vector but received shapes \",\n a_shape->shape().DebugString(), \" and \",\n b_shape->shape().DebugString()));\n OP_REQUIRES(\n ctx, a_shape->IsSameSize(*b_shape),\n errors::InvalidArgument(\n \"Operands do not have the same ranks; got shapes: \",\n a_shape->SummarizeValue(10), \" and \", b_shape->SummarizeValue(10)));\n const auto a_shape_flat = a_shape->flat();\n const auto b_shape_flat = b_shape->flat();\n for (int i = 0; i < a_shape->NumElements(); ++i) {\n OP_REQUIRES(ctx, a_shape_flat(i) == b_shape_flat(i),\n errors::InvalidArgument(\n \"Operands' shapes do not match: got \", a_shape_flat(i),\n \" and \", b_shape_flat(i), \" for dimension \", i));\n }\n\n OP_REQUIRES_OK(ctx, ctx->input(\"thresh\", &thresh_t));\n OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(thresh_t->shape()),\n errors::InvalidArgument(\n \"The magnitude threshold must be a scalar: got shape \",\n thresh_t->shape().DebugString()));\n // std::abs() so that it works for complex{64,128} values as well\n const Treal thresh = thresh_t->scalar()();\n\n // (1) do a pass over inputs, and append values and indices to vectors\n auto a_indices_mat = a_indices->matrix();\n auto b_indices_mat = b_indices->matrix();\n std::vector> entries_to_copy; // from_a?, idx\n entries_to_copy.reserve(a_nnz + b_nnz);\n std::vector out_values;\n const int num_dims = a_shape->dim_size(0);\n\n OP_REQUIRES(ctx, num_dims > 0,\n errors::InvalidArgument(\"Invalid input_a shape. Received: \",\n a_shape->DebugString()));\n\n // The input and output sparse tensors are assumed to be ordered along\n // increasing dimension number.\n int64 i = 0, j = 0;\n T s;\n while (i < a_nnz && j < b_nnz) {\n switch (sparse::DimComparator::cmp(a_indices_mat, b_indices_mat, i, j,\n num_dims)) {\n case -1:\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(a_values(i));\n ++i;\n break;\n case 0:\n s = a_values(i) + b_values(j);\n if (thresh <= std::abs(s)) {\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(s);\n }\n ++i;\n ++j;\n break;\n case 1:\n entries_to_copy.emplace_back(false, j);\n out_values.push_back(b_values(j));\n ++j;\n break;\n }\n }\n\n#define HANDLE_LEFTOVERS(A_OR_B, IDX, IS_A) \\\n while (IDX < A_OR_B##_nnz) { \\\n entries_to_copy.emplace_back(IS_A, IDX); \\\n out_values.push_back(A_OR_B##_values(IDX)); \\\n ++IDX; \\\n }\n\n // at most one of these calls appends new values\n HANDLE_LEFTOVERS(a, i, true);\n HANDLE_LEFTOVERS(b, j, false);\n#undef HANDLE_LEFTOVERS\n\n // (2) allocate and fill output tensors\n const int64 sum_nnz = out_values.size();\n Tensor *out_indices_t, *out_values_t;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}),\n &out_indices_t));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &out_values_t));\n auto out_indices_mat = out_indices_t->matrix();\n auto out_values_flat = out_values_t->vec();\n\n for (i = 0; i < sum_nnz; ++i) {\n const bool from_a = entries_to_copy[i].first;\n const int64 idx = entries_to_copy[i].second;\n out_indices_mat.chip<0>(i) =\n from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx);\n }\n if (sum_nnz > 0) {\n std::copy_n(out_values.begin(), sum_nnz, &out_values_flat(0));\n }\n ctx->set_output(2, *a_shape);\n }", "project": "tensorflow", "hash": 49579086162774256975067637533248462719, "size": 141, "commit_id": "41727ff06111117bdf86b37db198217fd7a143cc", "message": "Validate that a and b are proper sparse tensors\n\nPiperOrigin-RevId: 373248068\nChange-Id: I0a2041a0747901b3f00387a6a3bce9bca6b0b3b1", "target": 1, "dataset": "other", "idx": 198409} {"func": " void Compute(OpKernelContext *ctx) override {\n // (0) validations\n const Tensor *a_indices, *b_indices, *a_values_t, *b_values_t, *a_shape,\n *b_shape, *thresh_t;\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_indices\", &a_indices));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_indices\", &b_indices));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsMatrix(a_indices->shape()) &&\n TensorShapeUtils::IsMatrix(b_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be matrices but received shapes: \",\n a_indices->shape().DebugString(), \" and \",\n b_indices->shape().DebugString()));\n const int64 a_nnz = a_indices->dim_size(0);\n const int64 b_nnz = b_indices->dim_size(0);\n const int num_dims = a_indices->dim_size(1);\n OP_REQUIRES(ctx, b_indices->dim_size(1) == num_dims,\n errors::InvalidArgument(\n \"Input indices must have the same dimension, got \",\n num_dims, \" and \", b_indices->dim_size(1)));\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_values\", &a_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_values\", &b_values_t));\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_values_t->shape()) &&\n TensorShapeUtils::IsVector(b_values_t->shape()),\n errors::InvalidArgument(\n \"Input values should be vectors but received shapes: \",\n a_values_t->shape().DebugString(), \" and \",\n b_values_t->shape().DebugString()));\n auto a_values = ctx->input(1).vec();\n auto b_values = ctx->input(4).vec();\n OP_REQUIRES(\n ctx, a_values.size() == a_nnz && b_values.size() == b_nnz,\n errors::InvalidArgument(\"Expected \", a_nnz, \" and \", b_nnz,\n \" non-empty input values, got \",\n a_values.size(), \" and \", b_values.size()));\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_shape\", &a_shape));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_shape\", &b_shape));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_shape->shape()) &&\n TensorShapeUtils::IsVector(b_shape->shape()),\n errors::InvalidArgument(\n \"Input shapes should be a vector but received shapes \",\n a_shape->shape().DebugString(), \" and \",\n b_shape->shape().DebugString()));\n OP_REQUIRES(\n ctx, a_shape->NumElements() == num_dims,\n errors::InvalidArgument(\"Second dimension of a_indices and length of \"\n \"a_shape must match, got \",\n num_dims, \" and \", a_shape->NumElements()));\n OP_REQUIRES(ctx, num_dims > 0,\n errors::InvalidArgument(\"Tesors must not be empty\"));\n OP_REQUIRES(\n ctx, a_shape->IsSameSize(*b_shape),\n errors::InvalidArgument(\n \"Operands do not have the same ranks; got shapes: \",\n a_shape->SummarizeValue(10), \" and \", b_shape->SummarizeValue(10)));\n const auto a_shape_flat = a_shape->flat();\n const auto b_shape_flat = b_shape->flat();\n for (int i = 0; i < a_shape->NumElements(); ++i) {\n OP_REQUIRES(ctx, a_shape_flat(i) == b_shape_flat(i),\n errors::InvalidArgument(\n \"Operands' shapes do not match: got \", a_shape_flat(i),\n \" and \", b_shape_flat(i), \" for dimension \", i));\n }\n\n OP_REQUIRES_OK(ctx, ctx->input(\"thresh\", &thresh_t));\n OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(thresh_t->shape()),\n errors::InvalidArgument(\n \"The magnitude threshold must be a scalar: got shape \",\n thresh_t->shape().DebugString()));\n // std::abs() so that it works for complex{64,128} values as well\n const Treal thresh = thresh_t->scalar()();\n\n // (1) do a pass over inputs, and append values and indices to vectors\n auto a_indices_mat = a_indices->matrix();\n auto b_indices_mat = b_indices->matrix();\n std::vector> entries_to_copy; // from_a?, idx\n entries_to_copy.reserve(a_nnz + b_nnz);\n std::vector out_values;\n\n // The input and output sparse tensors are assumed to be ordered along\n // increasing dimension number.\n int64 i = 0, j = 0;\n T s;\n while (i < a_nnz && j < b_nnz) {\n switch (sparse::DimComparator::cmp(a_indices_mat, b_indices_mat, i, j,\n num_dims)) {\n case -1:\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(a_values(i));\n ++i;\n break;\n case 0:\n s = a_values(i) + b_values(j);\n if (thresh <= std::abs(s)) {\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(s);\n }\n ++i;\n ++j;\n break;\n case 1:\n entries_to_copy.emplace_back(false, j);\n out_values.push_back(b_values(j));\n ++j;\n break;\n }\n }\n\n#define HANDLE_LEFTOVERS(A_OR_B, IDX, IS_A) \\\n while (IDX < A_OR_B##_nnz) { \\\n entries_to_copy.emplace_back(IS_A, IDX); \\\n out_values.push_back(A_OR_B##_values(IDX)); \\\n ++IDX; \\\n }\n\n // at most one of these calls appends new values\n HANDLE_LEFTOVERS(a, i, true);\n HANDLE_LEFTOVERS(b, j, false);\n#undef HANDLE_LEFTOVERS\n\n // (2) allocate and fill output tensors\n const int64 sum_nnz = out_values.size();\n Tensor *out_indices_t, *out_values_t;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}),\n &out_indices_t));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &out_values_t));\n auto out_indices_mat = out_indices_t->matrix();\n auto out_values_flat = out_values_t->vec();\n\n for (i = 0; i < sum_nnz; ++i) {\n const bool from_a = entries_to_copy[i].first;\n const int64 idx = entries_to_copy[i].second;\n out_indices_mat.chip<0>(i) =\n from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx);\n }\n if (sum_nnz > 0) {\n std::copy_n(out_values.begin(), sum_nnz, &out_values_flat(0));\n }\n ctx->set_output(2, *a_shape);\n }", "project": "tensorflow", "hash": 16228492521577769374139271035359656492, "size": 148, "commit_id": "41727ff06111117bdf86b37db198217fd7a143cc", "message": "Validate that a and b are proper sparse tensors\n\nPiperOrigin-RevId: 373248068\nChange-Id: I0a2041a0747901b3f00387a6a3bce9bca6b0b3b1", "target": 0, "dataset": "other", "idx": 274064} {"func": "static int ldapsrv_load_limits(struct ldapsrv_connection *conn)\n{\n\tTALLOC_CTX *tmp_ctx;\n\tconst char *attrs[] = { \"configurationNamingContext\", NULL };\n\tconst char *attrs2[] = { \"lDAPAdminLimits\", NULL };\n\tstruct ldb_message_element *el;\n\tstruct ldb_result *res = NULL;\n\tstruct ldb_dn *basedn;\n\tstruct ldb_dn *conf_dn;\n\tstruct ldb_dn *policy_dn;\n\tunsigned int i;\n\tint ret;\n\n\t/* set defaults limits in case of failure */\n\tconn->limits.initial_timeout = 120;\n\tconn->limits.conn_idle_time = 900;\n\tconn->limits.max_page_size = 1000;\n\tconn->limits.max_notifications = 5;\n\tconn->limits.search_timeout = 120;\n\tconn->limits.expire_time = (struct timeval) {\n\t\t.tv_sec = get_time_t_max(),\n\t};\n\n\n\ttmp_ctx = talloc_new(conn);\n\tif (tmp_ctx == NULL) {\n\t\treturn -1;\n\t}\n\n\tbasedn = ldb_dn_new(tmp_ctx, conn->ldb, NULL);\n\tif (basedn == NULL) {\n\t\tgoto failed;\n\t}\n\n\tret = ldb_search(conn->ldb, tmp_ctx, &res, basedn, LDB_SCOPE_BASE, attrs, NULL);\n\tif (ret != LDB_SUCCESS) {\n\t\tgoto failed;\n\t}\n\n\tif (res->count != 1) {\n\t\tgoto failed;\n\t}\n\n\tconf_dn = ldb_msg_find_attr_as_dn(conn->ldb, tmp_ctx, res->msgs[0], \"configurationNamingContext\");\n\tif (conf_dn == NULL) {\n\t\tgoto failed;\n\t}\n\n\tpolicy_dn = ldb_dn_copy(tmp_ctx, conf_dn);\n\tldb_dn_add_child_fmt(policy_dn, \"CN=Default Query Policy,CN=Query-Policies,CN=Directory Service,CN=Windows NT,CN=Services\");\n\tif (policy_dn == NULL) {\n\t\tgoto failed;\n\t}\n\n\tret = ldb_search(conn->ldb, tmp_ctx, &res, policy_dn, LDB_SCOPE_BASE, attrs2, NULL);\n\tif (ret != LDB_SUCCESS) {\n\t\tgoto failed;\n\t}\n\n\tif (res->count != 1) {\n\t\tgoto failed;\n\t}\n\n\tel = ldb_msg_find_element(res->msgs[0], \"lDAPAdminLimits\");\n\tif (el == NULL) {\n\t\tgoto failed;\n\t}\n\n\tfor (i = 0; i < el->num_values; i++) {\n\t\tchar policy_name[256];\n\t\tint policy_value, s;\n\n\t\ts = sscanf((const char *)el->values[i].data, \"%255[^=]=%d\", policy_name, &policy_value);\n\t\tif (s != 2 || policy_value == 0)\n\t\t\tcontinue;\n\t\tif (strcasecmp(\"InitRecvTimeout\", policy_name) == 0) {\n\t\t\tconn->limits.initial_timeout = policy_value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (strcasecmp(\"MaxConnIdleTime\", policy_name) == 0) {\n\t\t\tconn->limits.conn_idle_time = policy_value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (strcasecmp(\"MaxPageSize\", policy_name) == 0) {\n\t\t\tconn->limits.max_page_size = policy_value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (strcasecmp(\"MaxNotificationPerConn\", policy_name) == 0) {\n\t\t\tconn->limits.max_notifications = policy_value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (strcasecmp(\"MaxQueryDuration\", policy_name) == 0) {\n\t\t\tconn->limits.search_timeout = policy_value;\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\treturn 0;\n\nfailed:\n\tDBG_ERR(\"Failed to load ldap server query policies\\n\");\n\ttalloc_free(tmp_ctx);\n\treturn -1;\n}", "project": "samba", "hash": 179110453965118510639557808253855764974, "size": 104, "commit_id": "f9b2267c6eb8138fc94df7a138ad5d87526f1d79", "message": "CVE-2021-3670 ldap_server: Ensure value of MaxQueryDuration is greater than zero\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=14694\n\nSigned-off-by: Joseph Sutton \nReviewed-by: Douglas Bagnall \n(cherry picked from commit e1ab0c43629686d1d2c0b0b2bcdc90057a792049)", "target": 1, "dataset": "other", "idx": 198425} {"func": "static int ldapsrv_load_limits(struct ldapsrv_connection *conn)\n{\n\tTALLOC_CTX *tmp_ctx;\n\tconst char *attrs[] = { \"configurationNamingContext\", NULL };\n\tconst char *attrs2[] = { \"lDAPAdminLimits\", NULL };\n\tstruct ldb_message_element *el;\n\tstruct ldb_result *res = NULL;\n\tstruct ldb_dn *basedn;\n\tstruct ldb_dn *conf_dn;\n\tstruct ldb_dn *policy_dn;\n\tunsigned int i;\n\tint ret;\n\n\t/* set defaults limits in case of failure */\n\tconn->limits.initial_timeout = 120;\n\tconn->limits.conn_idle_time = 900;\n\tconn->limits.max_page_size = 1000;\n\tconn->limits.max_notifications = 5;\n\tconn->limits.search_timeout = 120;\n\tconn->limits.expire_time = (struct timeval) {\n\t\t.tv_sec = get_time_t_max(),\n\t};\n\n\n\ttmp_ctx = talloc_new(conn);\n\tif (tmp_ctx == NULL) {\n\t\treturn -1;\n\t}\n\n\tbasedn = ldb_dn_new(tmp_ctx, conn->ldb, NULL);\n\tif (basedn == NULL) {\n\t\tgoto failed;\n\t}\n\n\tret = ldb_search(conn->ldb, tmp_ctx, &res, basedn, LDB_SCOPE_BASE, attrs, NULL);\n\tif (ret != LDB_SUCCESS) {\n\t\tgoto failed;\n\t}\n\n\tif (res->count != 1) {\n\t\tgoto failed;\n\t}\n\n\tconf_dn = ldb_msg_find_attr_as_dn(conn->ldb, tmp_ctx, res->msgs[0], \"configurationNamingContext\");\n\tif (conf_dn == NULL) {\n\t\tgoto failed;\n\t}\n\n\tpolicy_dn = ldb_dn_copy(tmp_ctx, conf_dn);\n\tldb_dn_add_child_fmt(policy_dn, \"CN=Default Query Policy,CN=Query-Policies,CN=Directory Service,CN=Windows NT,CN=Services\");\n\tif (policy_dn == NULL) {\n\t\tgoto failed;\n\t}\n\n\tret = ldb_search(conn->ldb, tmp_ctx, &res, policy_dn, LDB_SCOPE_BASE, attrs2, NULL);\n\tif (ret != LDB_SUCCESS) {\n\t\tgoto failed;\n\t}\n\n\tif (res->count != 1) {\n\t\tgoto failed;\n\t}\n\n\tel = ldb_msg_find_element(res->msgs[0], \"lDAPAdminLimits\");\n\tif (el == NULL) {\n\t\tgoto failed;\n\t}\n\n\tfor (i = 0; i < el->num_values; i++) {\n\t\tchar policy_name[256];\n\t\tint policy_value, s;\n\n\t\ts = sscanf((const char *)el->values[i].data, \"%255[^=]=%d\", policy_name, &policy_value);\n\t\tif (s != 2 || policy_value == 0)\n\t\t\tcontinue;\n\t\tif (strcasecmp(\"InitRecvTimeout\", policy_name) == 0) {\n\t\t\tconn->limits.initial_timeout = policy_value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (strcasecmp(\"MaxConnIdleTime\", policy_name) == 0) {\n\t\t\tconn->limits.conn_idle_time = policy_value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (strcasecmp(\"MaxPageSize\", policy_name) == 0) {\n\t\t\tconn->limits.max_page_size = policy_value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (strcasecmp(\"MaxNotificationPerConn\", policy_name) == 0) {\n\t\t\tconn->limits.max_notifications = policy_value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (strcasecmp(\"MaxQueryDuration\", policy_name) == 0) {\n\t\t\tif (policy_value > 0) {\n\t\t\t\tconn->limits.search_timeout = policy_value;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\treturn 0;\n\nfailed:\n\tDBG_ERR(\"Failed to load ldap server query policies\\n\");\n\ttalloc_free(tmp_ctx);\n\treturn -1;\n}", "project": "samba", "hash": 20233092815787754852088965792044905240, "size": 106, "commit_id": "f9b2267c6eb8138fc94df7a138ad5d87526f1d79", "message": "CVE-2021-3670 ldap_server: Ensure value of MaxQueryDuration is greater than zero\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=14694\n\nSigned-off-by: Joseph Sutton \nReviewed-by: Douglas Bagnall \n(cherry picked from commit e1ab0c43629686d1d2c0b0b2bcdc90057a792049)", "target": 0, "dataset": "other", "idx": 274270} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& image = context->input(0);\n OP_REQUIRES(context, image.dims() == 3,\n errors::InvalidArgument(\"image must be 3-dimensional\",\n image.shape().DebugString()));\n OP_REQUIRES(\n context,\n FastBoundsCheck(image.NumElements(), std::numeric_limits::max()),\n errors::InvalidArgument(\"image cannot have >= int32 max elements\"));\n const int32 height = static_cast(image.dim_size(0));\n const int32 width = static_cast(image.dim_size(1));\n const int32 channels = static_cast(image.dim_size(2));\n\n // In some cases, we pass width*channels*2 to png.\n const int32 max_row_width = std::numeric_limits::max() / 2;\n\n OP_REQUIRES(context, FastBoundsCheck(width * channels, max_row_width),\n errors::InvalidArgument(\"image too wide to encode\"));\n\n OP_REQUIRES(context, channels >= 1 && channels <= 4,\n errors::InvalidArgument(\n \"image must have 1, 2, 3, or 4 channels, got \", channels));\n\n // Encode image to png string\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, TensorShape({}), &output));\n if (desired_channel_bits_ == 8) {\n OP_REQUIRES(context,\n png::WriteImageToBuffer(\n image.flat().data(), width, height,\n width * channels, channels, desired_channel_bits_,\n compression_, &output->scalar()(), nullptr),\n errors::Internal(\"PNG encoding failed\"));\n } else {\n OP_REQUIRES(context,\n png::WriteImageToBuffer(\n image.flat().data(), width, height,\n width * channels * 2, channels, desired_channel_bits_,\n compression_, &output->scalar()(), nullptr),\n errors::Internal(\"PNG encoding failed\"));\n }\n }", "project": "tensorflow", "hash": 252338118123250428276547279507438563877, "size": 43, "commit_id": "26eb323554ffccd173e8a79a8c05c15b685ae4d1", "message": "Fix null CHECK issue with `tf.raw_ops.EncodePng`.\n\nPiperOrigin-RevId: 369717714\nChange-Id: I24136cd99c20b8466671f4f93b670ef6f6dd1250", "target": 1, "dataset": "other", "idx": 198430} {"func": " void Compute(OpKernelContext* context) override {\n const Tensor& image = context->input(0);\n OP_REQUIRES(context, image.dims() == 3,\n errors::InvalidArgument(\"image must be 3-dimensional\",\n image.shape().DebugString()));\n OP_REQUIRES(context, image.NumElements() > 0,\n errors::Internal(\"Invalid image provided.\"));\n OP_REQUIRES(\n context,\n FastBoundsCheck(image.NumElements(), std::numeric_limits::max()),\n errors::InvalidArgument(\"image cannot have >= int32 max elements\"));\n const int32 height = static_cast(image.dim_size(0));\n const int32 width = static_cast(image.dim_size(1));\n const int32 channels = static_cast(image.dim_size(2));\n\n // In some cases, we pass width*channels*2 to png.\n const int32 max_row_width = std::numeric_limits::max() / 2;\n\n OP_REQUIRES(context, FastBoundsCheck(width * channels, max_row_width),\n errors::InvalidArgument(\"image too wide to encode\"));\n\n OP_REQUIRES(context, channels >= 1 && channels <= 4,\n errors::InvalidArgument(\n \"image must have 1, 2, 3, or 4 channels, got \", channels));\n\n // Encode image to png string\n Tensor* output = nullptr;\n OP_REQUIRES_OK(context,\n context->allocate_output(0, TensorShape({}), &output));\n if (desired_channel_bits_ == 8) {\n OP_REQUIRES(context,\n png::WriteImageToBuffer(\n image.flat().data(), width, height,\n width * channels, channels, desired_channel_bits_,\n compression_, &output->scalar()(), nullptr),\n errors::Internal(\"PNG encoding failed\"));\n } else {\n OP_REQUIRES(context,\n png::WriteImageToBuffer(\n image.flat().data(), width, height,\n width * channels * 2, channels, desired_channel_bits_,\n compression_, &output->scalar()(), nullptr),\n errors::Internal(\"PNG encoding failed\"));\n }\n }", "project": "tensorflow", "hash": 232608082282450676739866634543277634841, "size": 45, "commit_id": "26eb323554ffccd173e8a79a8c05c15b685ae4d1", "message": "Fix null CHECK issue with `tf.raw_ops.EncodePng`.\n\nPiperOrigin-RevId: 369717714\nChange-Id: I24136cd99c20b8466671f4f93b670ef6f6dd1250", "target": 0, "dataset": "other", "idx": 274583} {"func": "scanner_scan_all (parser_context_t *context_p, /**< context */\n const uint8_t *arg_list_p, /**< function argument list */\n const uint8_t *arg_list_end_p, /**< end of argument list */\n const uint8_t *source_p, /**< valid UTF-8 source code */\n const uint8_t *source_end_p) /**< end of source code */\n{\n scanner_context_t scanner_context;\n\n#if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE)\n if (context_p->is_show_opcodes)\n {\n JERRY_DEBUG_MSG (\"\\n--- Scanning start ---\\n\\n\");\n }\n#endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */\n\n scanner_context.context_status_flags = context_p->status_flags;\n scanner_context.status_flags = SCANNER_CONTEXT_NO_FLAGS;\n#if ENABLED (JERRY_DEBUGGER)\n if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED)\n {\n scanner_context.status_flags |= SCANNER_CONTEXT_DEBUGGER_ENABLED;\n }\n#endif /* ENABLED (JERRY_DEBUGGER) */\n#if ENABLED (JERRY_ES2015)\n scanner_context.binding_type = SCANNER_BINDING_NONE;\n scanner_context.active_binding_list_p = NULL;\n#endif /* ENABLED (JERRY_ES2015) */\n scanner_context.active_literal_pool_p = NULL;\n scanner_context.active_switch_statement.last_case_p = NULL;\n scanner_context.end_arguments_p = NULL;\n#if ENABLED (JERRY_ES2015)\n scanner_context.async_source_p = NULL;\n#endif /* ENABLED (JERRY_ES2015) */\n\n /* This assignment must be here because of Apple compilers. */\n context_p->u.scanner_context_p = &scanner_context;\n\n parser_stack_init (context_p);\n\n PARSER_TRY (context_p->try_buffer)\n {\n context_p->line = 1;\n context_p->column = 1;\n\n if (arg_list_p == NULL)\n {\n context_p->source_p = source_p;\n context_p->source_end_p = source_end_p;\n\n uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION_WITHOUT_ARGUMENTS | SCANNER_LITERAL_POOL_CAN_EVAL;\n\n if (context_p->status_flags & PARSER_IS_STRICT)\n {\n status_flags |= SCANNER_LITERAL_POOL_IS_STRICT;\n }\n\n scanner_literal_pool_t *literal_pool_p = scanner_push_literal_pool (context_p, &scanner_context, status_flags);\n literal_pool_p->source_p = source_p;\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_SCRIPT);\n\n lexer_next_token (context_p);\n scanner_check_directives (context_p, &scanner_context);\n }\n else\n {\n context_p->source_p = arg_list_p;\n context_p->source_end_p = arg_list_end_p;\n\n uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION;\n\n if (context_p->status_flags & PARSER_IS_STRICT)\n {\n status_flags |= SCANNER_LITERAL_POOL_IS_STRICT;\n }\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->status_flags & PARSER_IS_GENERATOR_FUNCTION)\n {\n status_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n scanner_push_literal_pool (context_p, &scanner_context, status_flags);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n parser_stack_push_uint8 (context_p, SCAN_STACK_SCRIPT_FUNCTION);\n\n /* Faking the first token. */\n context_p->token.type = LEXER_LEFT_PAREN;\n }\n\n while (true)\n {\n lexer_token_type_t type = (lexer_token_type_t) context_p->token.type;\n scan_stack_modes_t stack_top = (scan_stack_modes_t) context_p->stack_top_uint8;\n\n switch (scanner_context.mode)\n {\n case SCAN_MODE_PRIMARY_EXPRESSION:\n {\n if (type == LEXER_ADD\n || type == LEXER_SUBTRACT\n || LEXER_IS_UNARY_OP_TOKEN (type))\n {\n break;\n }\n /* FALLTHRU */\n }\n case SCAN_MODE_PRIMARY_EXPRESSION_AFTER_NEW:\n {\n if (scanner_scan_primary_expression (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCAN_MODE_CLASS_DECLARATION:\n {\n if (context_p->token.type == LEXER_KEYW_EXTENDS)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_CLASS_EXTENDS);\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n else if (context_p->token.type != LEXER_LEFT_BRACE)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_context.mode = SCAN_MODE_CLASS_METHOD;\n /* FALLTHRU */\n }\n case SCAN_MODE_CLASS_METHOD:\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR\n || stack_top == SCAN_STACK_EXPLICIT_CLASS_CONSTRUCTOR);\n\n lexer_skip_empty_statements (context_p);\n\n lexer_scan_identifier (context_p);\n\n if (context_p->token.type == LEXER_RIGHT_BRACE)\n {\n scanner_source_start_t source_start;\n\n parser_stack_pop_uint8 (context_p);\n\n if (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR)\n {\n parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));\n }\n\n stack_top = context_p->stack_top_uint8;\n\n JERRY_ASSERT (stack_top == SCAN_STACK_CLASS_STATEMENT || stack_top == SCAN_STACK_CLASS_EXPRESSION);\n\n if (stack_top == SCAN_STACK_CLASS_STATEMENT)\n {\n /* The token is kept to disallow consuming a semicolon after it. */\n scanner_context.mode = SCAN_MODE_STATEMENT_END;\n continue;\n }\n\n scanner_context.mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;\n parser_stack_pop_uint8 (context_p);\n break;\n }\n\n if (context_p->token.type == LEXER_LITERAL\n && LEXER_IS_IDENT_OR_STRING (context_p->token.lit_location.type)\n && lexer_compare_literal_to_string (context_p, \"constructor\", 11))\n {\n if (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR)\n {\n scanner_source_start_t source_start;\n parser_stack_pop_uint8 (context_p);\n parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));\n\n scanner_info_t *info_p = scanner_insert_info (context_p, source_start.source_p, sizeof (scanner_info_t));\n info_p->type = SCANNER_TYPE_CLASS_CONSTRUCTOR;\n parser_stack_push_uint8 (context_p, SCAN_STACK_EXPLICIT_CLASS_CONSTRUCTOR);\n }\n }\n\n if (lexer_token_is_identifier (context_p, \"static\", 6))\n {\n lexer_scan_identifier (context_p);\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n\n uint16_t literal_pool_flags = SCANNER_LITERAL_POOL_FUNCTION;\n\n if (lexer_token_is_identifier (context_p, \"get\", 3)\n || lexer_token_is_identifier (context_p, \"set\", 3))\n {\n lexer_scan_identifier (context_p);\n\n if (context_p->token.type == LEXER_LEFT_PAREN)\n {\n scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);\n continue;\n }\n }\n else if (lexer_token_is_identifier (context_p, \"async\", 5))\n {\n lexer_scan_identifier (context_p);\n\n if (context_p->token.type == LEXER_LEFT_PAREN)\n {\n scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);\n continue;\n }\n\n literal_pool_flags |= SCANNER_LITERAL_POOL_ASYNC;\n\n if (context_p->token.type == LEXER_MULTIPLY)\n {\n lexer_scan_identifier (context_p);\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n }\n else if (context_p->token.type == LEXER_MULTIPLY)\n {\n lexer_scan_identifier (context_p);\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCANNER_FROM_LITERAL_POOL_TO_COMPUTED (literal_pool_flags));\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n if (literal_pool_flags & SCANNER_LITERAL_POOL_GENERATOR)\n {\n context_p->status_flags |= PARSER_IS_GENERATOR_FUNCTION;\n }\n\n scanner_push_literal_pool (context_p, &scanner_context, literal_pool_flags);\n lexer_next_token (context_p);\n continue;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCAN_MODE_POST_PRIMARY_EXPRESSION:\n {\n if (scanner_scan_post_primary_expression (context_p, &scanner_context, type, stack_top))\n {\n break;\n }\n type = (lexer_token_type_t) context_p->token.type;\n /* FALLTHRU */\n }\n case SCAN_MODE_PRIMARY_EXPRESSION_END:\n {\n if (scanner_scan_primary_expression_end (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n break;\n }\n case SCAN_MODE_STATEMENT_OR_TERMINATOR:\n {\n if (type == LEXER_RIGHT_BRACE || type == LEXER_EOS)\n {\n scanner_context.mode = SCAN_MODE_STATEMENT_END;\n continue;\n }\n /* FALLTHRU */\n }\n case SCAN_MODE_STATEMENT:\n {\n if (scanner_scan_statement (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n break;\n }\n case SCAN_MODE_STATEMENT_END:\n {\n if (scanner_scan_statement_end (context_p, &scanner_context, type) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n\n if (context_p->token.type == LEXER_EOS)\n {\n goto scan_completed;\n }\n\n break;\n }\n case SCAN_MODE_VAR_STATEMENT:\n {\n#if ENABLED (JERRY_ES2015)\n if (type == LEXER_LEFT_SQUARE || type == LEXER_LEFT_BRACE)\n {\n uint8_t binding_type = SCANNER_BINDING_VAR;\n\n if (stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_FOR_LET_START)\n {\n binding_type = SCANNER_BINDING_LET;\n }\n else if (stack_top == SCAN_STACK_CONST || stack_top == SCAN_STACK_FOR_CONST_START)\n {\n binding_type = SCANNER_BINDING_CONST;\n }\n\n scanner_push_destructuring_pattern (context_p, &scanner_context, binding_type, false);\n\n if (type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);\n scanner_context.mode = SCAN_MODE_BINDING;\n break;\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);\n scanner_context.mode = SCAN_MODE_PROPERTY_NAME;\n continue;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (type != LEXER_LITERAL\n || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n lexer_lit_location_t *literal_p = scanner_add_literal (context_p, &scanner_context);\n\n#if ENABLED (JERRY_ES2015)\n if (stack_top != SCAN_STACK_VAR && stack_top != SCAN_STACK_FOR_VAR_START)\n {\n scanner_detect_invalid_let (context_p, literal_p);\n\n if (stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_FOR_LET_START)\n {\n literal_p->type |= SCANNER_LITERAL_IS_LET;\n }\n else\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_CONST || stack_top == SCAN_STACK_FOR_CONST_START);\n literal_p->type |= SCANNER_LITERAL_IS_CONST;\n }\n\n lexer_next_token (context_p);\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n }\n else if (context_p->token.type == LEXER_ASSIGN)\n {\n scanner_binding_literal_t binding_literal;\n binding_literal.literal_p = literal_p;\n\n parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));\n parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);\n }\n }\n else\n {\n if (!(literal_p->type & SCANNER_LITERAL_IS_VAR))\n {\n scanner_detect_invalid_var (context_p, &scanner_context, literal_p);\n literal_p->type |= SCANNER_LITERAL_IS_VAR;\n\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n }\n\n lexer_next_token (context_p);\n }\n#else /* !ENABLED (JERRY_ES2015) */\n literal_p->type |= SCANNER_LITERAL_IS_VAR;\n\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n\n lexer_next_token (context_p);\n#endif /* ENABLED (JERRY_ES2015) */\n\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_EXPORT)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n\n switch (context_p->token.type)\n {\n case LEXER_ASSIGN:\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n /* FALLTHRU */\n }\n case LEXER_COMMA:\n {\n lexer_next_token (context_p);\n continue;\n }\n }\n\n if (SCANNER_IS_FOR_START (stack_top))\n {\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n JERRY_ASSERT (!(scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_EXPORT));\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n\n if (context_p->token.type != LEXER_SEMICOLON\n && context_p->token.type != LEXER_KEYW_IN\n && !SCANNER_IDENTIFIER_IS_OF ())\n {\n scanner_raise_error (context_p);\n }\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;\n continue;\n }\n\n#if ENABLED (JERRY_ES2015)\n JERRY_ASSERT (stack_top == SCAN_STACK_VAR || stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_CONST);\n#else /* !ENABLED (JERRY_ES2015) */\n JERRY_ASSERT (stack_top == SCAN_STACK_VAR);\n#endif /* ENABLED (JERRY_ES2015) */\n\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n scanner_context.active_literal_pool_p->status_flags &= (uint16_t) ~SCANNER_LITERAL_POOL_IN_EXPORT;\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n\n scanner_context.mode = SCAN_MODE_STATEMENT_END;\n parser_stack_pop_uint8 (context_p);\n continue;\n }\n case SCAN_MODE_FUNCTION_ARGUMENTS:\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_SCRIPT_FUNCTION\n || stack_top == SCAN_STACK_FUNCTION_STATEMENT\n || stack_top == SCAN_STACK_FUNCTION_EXPRESSION\n || stack_top == SCAN_STACK_FUNCTION_PROPERTY);\n\n scanner_literal_pool_t *literal_pool_p = scanner_context.active_literal_pool_p;\n\n JERRY_ASSERT (literal_pool_p != NULL && (literal_pool_p->status_flags & SCANNER_LITERAL_POOL_FUNCTION));\n\n literal_pool_p->source_p = context_p->source_p;\n\n#if ENABLED (JERRY_ES2015)\n if (JERRY_UNLIKELY (scanner_context.async_source_p != NULL))\n {\n literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ASYNC;\n literal_pool_p->source_p = scanner_context.async_source_p;\n scanner_context.async_source_p = NULL;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (type != LEXER_LEFT_PAREN)\n {\n scanner_raise_error (context_p);\n }\n lexer_next_token (context_p);\n\n#if ENABLED (JERRY_ES2015)\n /* FALLTHRU */\n }\n case SCAN_MODE_CONTINUE_FUNCTION_ARGUMENTS:\n {\n#endif /* ENABLED (JERRY_ES2015) */\n if (context_p->token.type != LEXER_RIGHT_PAREN && context_p->token.type != LEXER_EOS)\n {\n#if ENABLED (JERRY_ES2015)\n lexer_lit_location_t *argument_literal_p;\n#endif /* ENABLED (JERRY_ES2015) */\n\n while (true)\n {\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_THREE_DOTS)\n {\n scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;\n\n lexer_next_token (context_p);\n }\n\n if (context_p->token.type == LEXER_LEFT_SQUARE || context_p->token.type == LEXER_LEFT_BRACE)\n {\n argument_literal_p = NULL;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type != LEXER_LITERAL\n || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n argument_literal_p = scanner_append_argument (context_p, &scanner_context);\n#else /* !ENABLED (JERRY_ES2015) */\n scanner_append_argument (context_p, &scanner_context);\n#endif /* ENABLED (JERRY_ES2015) */\n\n lexer_next_token (context_p);\n\n if (context_p->token.type != LEXER_COMMA)\n {\n break;\n }\n lexer_next_token (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n if (argument_literal_p == NULL)\n {\n scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PARAMETERS);\n scanner_append_hole (context_p, &scanner_context);\n scanner_push_destructuring_pattern (context_p, &scanner_context, SCANNER_BINDING_ARG, false);\n\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);\n scanner_context.mode = SCAN_MODE_BINDING;\n break;\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);\n scanner_context.mode = SCAN_MODE_PROPERTY_NAME;\n continue;\n }\n\n if (context_p->token.type == LEXER_ASSIGN)\n {\n scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PARAMETERS);\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n\n if (argument_literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n JERRY_ASSERT (argument_literal_p->type & SCANNER_LITERAL_EARLY_CREATE);\n break;\n }\n\n scanner_binding_literal_t binding_literal;\n binding_literal.literal_p = argument_literal_p;\n\n parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));\n parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n }\n\n if (context_p->token.type == LEXER_EOS && stack_top == SCAN_STACK_SCRIPT_FUNCTION)\n {\n /* End of argument parsing. */\n scanner_info_t *scanner_info_p = (scanner_info_t *) scanner_malloc (context_p, sizeof (scanner_info_t));\n scanner_info_p->next_p = context_p->next_scanner_info_p;\n scanner_info_p->source_p = NULL;\n scanner_info_p->type = SCANNER_TYPE_END_ARGUMENTS;\n scanner_context.end_arguments_p = scanner_info_p;\n\n context_p->next_scanner_info_p = scanner_info_p;\n context_p->source_p = source_p;\n context_p->source_end_p = source_end_p;\n context_p->line = 1;\n context_p->column = 1;\n\n scanner_filter_arguments (context_p, &scanner_context);\n lexer_next_token (context_p);\n scanner_check_directives (context_p, &scanner_context);\n continue;\n }\n\n if (context_p->token.type != LEXER_RIGHT_PAREN)\n {\n scanner_raise_error (context_p);\n }\n\n lexer_next_token (context_p);\n\n if (context_p->token.type != LEXER_LEFT_BRACE)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_filter_arguments (context_p, &scanner_context);\n lexer_next_token (context_p);\n scanner_check_directives (context_p, &scanner_context);\n continue;\n }\n case SCAN_MODE_PROPERTY_NAME:\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_OBJECT_LITERAL);\n\n if (lexer_scan_identifier (context_p))\n {\n lexer_check_property_modifier (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_COMPUTED_PROPERTY);\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type == LEXER_RIGHT_BRACE)\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;\n continue;\n }\n\n if (context_p->token.type == LEXER_PROPERTY_GETTER\n#if ENABLED (JERRY_ES2015)\n || context_p->token.type == LEXER_KEYW_ASYNC\n || context_p->token.type == LEXER_MULTIPLY\n#endif /* ENABLED (JERRY_ES2015) */\n || context_p->token.type == LEXER_PROPERTY_SETTER)\n {\n uint16_t literal_pool_flags = SCANNER_LITERAL_POOL_FUNCTION;\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_MULTIPLY)\n {\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n else if (context_p->token.type == LEXER_KEYW_ASYNC)\n {\n literal_pool_flags |= SCANNER_LITERAL_POOL_ASYNC;\n\n if (lexer_consume_generator (context_p))\n {\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);\n lexer_scan_identifier (context_p);\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCANNER_FROM_LITERAL_POOL_TO_COMPUTED (literal_pool_flags));\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_push_literal_pool (context_p, &scanner_context, literal_pool_flags);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n break;\n }\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n parser_line_counter_t start_line = context_p->token.line;\n parser_line_counter_t start_column = context_p->token.column;\n bool is_ident = (context_p->token.lit_location.type == LEXER_IDENT_LITERAL);\n#endif /* ENABLED (JERRY_ES2015) */\n\n lexer_next_token (context_p);\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_LEFT_PAREN)\n {\n scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n continue;\n }\n\n if (is_ident\n && (context_p->token.type == LEXER_COMMA\n || context_p->token.type == LEXER_RIGHT_BRACE\n || context_p->token.type == LEXER_ASSIGN))\n {\n context_p->source_p = context_p->token.lit_location.char_p;\n context_p->line = start_line;\n context_p->column = start_column;\n\n lexer_next_token (context_p);\n\n JERRY_ASSERT (context_p->token.type != LEXER_LITERAL\n || context_p->token.lit_location.type == LEXER_IDENT_LITERAL);\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n if (scanner_context.binding_type != SCANNER_BINDING_NONE)\n {\n scanner_context.mode = SCAN_MODE_BINDING;\n continue;\n }\n\n scanner_add_reference (context_p, &scanner_context);\n\n lexer_next_token (context_p);\n\n if (context_p->token.type == LEXER_ASSIGN)\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;\n continue;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type != LEXER_COLON)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n\n#if ENABLED (JERRY_ES2015)\n if (scanner_context.binding_type != SCANNER_BINDING_NONE)\n {\n scanner_context.mode = SCAN_MODE_BINDING;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCAN_MODE_BINDING:\n {\n JERRY_ASSERT (scanner_context.binding_type == SCANNER_BINDING_VAR\n || scanner_context.binding_type == SCANNER_BINDING_LET\n || scanner_context.binding_type == SCANNER_BINDING_CATCH\n || scanner_context.binding_type == SCANNER_BINDING_CONST\n || scanner_context.binding_type == SCANNER_BINDING_ARG\n || scanner_context.binding_type == SCANNER_BINDING_ARROW_ARG);\n\n if (type == LEXER_THREE_DOTS)\n {\n lexer_next_token (context_p);\n type = (lexer_token_type_t) context_p->token.type;\n }\n\n if (type == LEXER_LEFT_SQUARE || type == LEXER_LEFT_BRACE)\n {\n scanner_push_destructuring_pattern (context_p, &scanner_context, scanner_context.binding_type, true);\n\n if (type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);\n break;\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);\n scanner_context.mode = SCAN_MODE_PROPERTY_NAME;\n continue;\n }\n\n if (type != LEXER_LITERAL || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n continue;\n }\n\n lexer_lit_location_t *literal_p = scanner_add_literal (context_p, &scanner_context);\n\n scanner_context.mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;\n\n if (scanner_context.binding_type == SCANNER_BINDING_VAR)\n {\n if (!(literal_p->type & SCANNER_LITERAL_IS_VAR))\n {\n scanner_detect_invalid_var (context_p, &scanner_context, literal_p);\n literal_p->type |= SCANNER_LITERAL_IS_VAR;\n\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n }\n break;\n }\n\n if (scanner_context.binding_type == SCANNER_BINDING_ARROW_ARG)\n {\n literal_p->type |= SCANNER_LITERAL_IS_ARG | SCANNER_LITERAL_IS_ARROW_DESTRUCTURED_ARG;\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n break;\n }\n }\n else\n {\n scanner_detect_invalid_let (context_p, literal_p);\n\n if (scanner_context.binding_type <= SCANNER_BINDING_CATCH)\n {\n JERRY_ASSERT ((scanner_context.binding_type == SCANNER_BINDING_LET)\n || (scanner_context.binding_type == SCANNER_BINDING_CATCH));\n\n literal_p->type |= SCANNER_LITERAL_IS_LET;\n }\n else\n {\n literal_p->type |= SCANNER_LITERAL_IS_CONST;\n\n if (scanner_context.binding_type == SCANNER_BINDING_ARG)\n {\n literal_p->type |= SCANNER_LITERAL_IS_ARG;\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n break;\n }\n }\n }\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n break;\n }\n }\n\n scanner_binding_item_t *binding_item_p;\n binding_item_p = (scanner_binding_item_t *) scanner_malloc (context_p, sizeof (scanner_binding_item_t));\n\n binding_item_p->next_p = scanner_context.active_binding_list_p->items_p;\n binding_item_p->literal_p = literal_p;\n\n scanner_context.active_binding_list_p->items_p = binding_item_p;\n\n lexer_next_token (context_p);\n if (context_p->token.type != LEXER_ASSIGN)\n {\n continue;\n }\n\n scanner_binding_literal_t binding_literal;\n binding_literal.literal_p = literal_p;\n\n parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));\n parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n }\n\n lexer_next_token (context_p);\n }\n\nscan_completed:\n if (context_p->stack_top_uint8 != SCAN_STACK_SCRIPT\n && context_p->stack_top_uint8 != SCAN_STACK_SCRIPT_FUNCTION)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_pop_literal_pool (context_p, &scanner_context);\n\n#if ENABLED (JERRY_ES2015)\n JERRY_ASSERT (scanner_context.active_binding_list_p == NULL);\n#endif /* ENABLED (JERRY_ES2015) */\n JERRY_ASSERT (scanner_context.active_literal_pool_p == NULL);\n\n#ifndef JERRY_NDEBUG\n scanner_context.context_status_flags |= PARSER_SCANNING_SUCCESSFUL;\n#endif /* !JERRY_NDEBUG */\n }\n PARSER_CATCH\n {\n /* Ignore the errors thrown by the lexer. */\n if (context_p->error != PARSER_ERR_OUT_OF_MEMORY)\n {\n context_p->error = PARSER_ERR_NO_ERROR;\n }\n\n#if ENABLED (JERRY_ES2015)\n while (scanner_context.active_binding_list_p != NULL)\n {\n scanner_pop_binding_list (&scanner_context);\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n /* The following code may allocate memory, so it is enclosed in a try/catch. */\n PARSER_TRY (context_p->try_buffer)\n {\n#if ENABLED (JERRY_ES2015)\n if (scanner_context.status_flags & SCANNER_CONTEXT_THROW_ERR_ASYNC_FUNCTION)\n {\n JERRY_ASSERT (scanner_context.async_source_p != NULL);\n\n scanner_info_t *info_p;\n info_p = scanner_insert_info (context_p, scanner_context.async_source_p, sizeof (scanner_info_t));\n info_p->type = SCANNER_TYPE_ERR_ASYNC_FUNCTION;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n while (scanner_context.active_literal_pool_p != NULL)\n {\n scanner_pop_literal_pool (context_p, &scanner_context);\n }\n }\n PARSER_CATCH\n {\n JERRY_ASSERT (context_p->error == PARSER_ERR_NO_ERROR);\n\n while (scanner_context.active_literal_pool_p != NULL)\n {\n scanner_literal_pool_t *literal_pool_p = scanner_context.active_literal_pool_p;\n\n scanner_context.active_literal_pool_p = literal_pool_p->prev_p;\n\n parser_list_free (&literal_pool_p->literal_pool);\n scanner_free (literal_pool_p, sizeof (scanner_literal_pool_t));\n }\n }\n PARSER_TRY_END\n\n#if ENABLED (JERRY_ES2015)\n context_p->status_flags &= (uint32_t) ~PARSER_IS_GENERATOR_FUNCTION;\n#endif /* ENABLED (JERRY_ES2015) */\n }\n PARSER_TRY_END\n\n context_p->status_flags = scanner_context.context_status_flags;\n scanner_reverse_info_list (context_p);\n\n#if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE)\n if (context_p->is_show_opcodes)\n {\n scanner_info_t *info_p = context_p->next_scanner_info_p;\n const uint8_t *source_start_p = (arg_list_p == NULL) ? source_p : arg_list_p;\n\n while (info_p->type != SCANNER_TYPE_END)\n {\n const char *name_p = NULL;\n bool print_location = false;\n\n switch (info_p->type)\n {\n case SCANNER_TYPE_END_ARGUMENTS:\n {\n JERRY_DEBUG_MSG (\" END_ARGUMENTS\\n\");\n source_start_p = source_p;\n break;\n }\n case SCANNER_TYPE_FUNCTION:\n case SCANNER_TYPE_BLOCK:\n {\n const uint8_t *prev_source_p = info_p->source_p - 1;\n const uint8_t *data_p;\n\n if (info_p->type == SCANNER_TYPE_FUNCTION)\n {\n data_p = (const uint8_t *) (info_p + 1);\n\n JERRY_DEBUG_MSG (\" FUNCTION: flags: 0x%x declarations: %d\",\n (int) info_p->u8_arg,\n (int) info_p->u16_arg);\n }\n else\n {\n data_p = (const uint8_t *) (info_p + 1);\n\n JERRY_DEBUG_MSG (\" BLOCK:\");\n }\n\n JERRY_DEBUG_MSG (\" source:%d\\n\", (int) (info_p->source_p - source_start_p));\n\n while (data_p[0] != SCANNER_STREAM_TYPE_END)\n {\n switch (data_p[0] & SCANNER_STREAM_TYPE_MASK)\n {\n case SCANNER_STREAM_TYPE_VAR:\n {\n JERRY_DEBUG_MSG (\" VAR \");\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_STREAM_TYPE_LET:\n {\n JERRY_DEBUG_MSG (\" LET \");\n break;\n }\n case SCANNER_STREAM_TYPE_CONST:\n {\n JERRY_DEBUG_MSG (\" CONST \");\n break;\n }\n case SCANNER_STREAM_TYPE_LOCAL:\n {\n JERRY_DEBUG_MSG (\" LOCAL \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n case SCANNER_STREAM_TYPE_IMPORT:\n {\n JERRY_DEBUG_MSG (\" IMPORT \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n case SCANNER_STREAM_TYPE_ARG:\n {\n JERRY_DEBUG_MSG (\" ARG \");\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_STREAM_TYPE_DESTRUCTURED_ARG:\n {\n JERRY_DEBUG_MSG (\" DESTRUCTURED_ARG \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCANNER_STREAM_TYPE_ARG_FUNC:\n {\n JERRY_DEBUG_MSG (\" ARG_FUNC \");\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_STREAM_TYPE_DESTRUCTURED_ARG_FUNC:\n {\n JERRY_DEBUG_MSG (\" DESTRUCTURED_ARG_FUNC \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCANNER_STREAM_TYPE_FUNC:\n {\n JERRY_DEBUG_MSG (\" FUNC \");\n break;\n }\n default:\n {\n JERRY_ASSERT ((data_p[0] & SCANNER_STREAM_TYPE_MASK) == SCANNER_STREAM_TYPE_HOLE);\n JERRY_DEBUG_MSG (\" HOLE\\n\");\n data_p++;\n continue;\n }\n }\n\n size_t length;\n\n if (!(data_p[0] & SCANNER_STREAM_UINT16_DIFF))\n {\n if (data_p[2] != 0)\n {\n prev_source_p += data_p[2];\n length = 2 + 1;\n }\n else\n {\n memcpy (&prev_source_p, data_p + 2 + 1, sizeof (const uint8_t *));\n length = 2 + 1 + sizeof (const uint8_t *);\n }\n }\n else\n {\n int32_t diff = ((int32_t) data_p[2]) | ((int32_t) data_p[3]) << 8;\n\n if (diff <= UINT8_MAX)\n {\n diff = -diff;\n }\n\n prev_source_p += diff;\n length = 2 + 2;\n }\n\n#if ENABLED (JERRY_ES2015)\n if (data_p[0] & SCANNER_STREAM_EARLY_CREATE)\n {\n JERRY_ASSERT (data_p[0] & SCANNER_STREAM_NO_REG);\n JERRY_DEBUG_MSG (\"*\");\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (data_p[0] & SCANNER_STREAM_NO_REG)\n {\n JERRY_DEBUG_MSG (\"* \");\n }\n\n JERRY_DEBUG_MSG (\"'%.*s'\\n\", data_p[1], (char *) prev_source_p);\n prev_source_p += data_p[1];\n data_p += length;\n }\n break;\n }\n case SCANNER_TYPE_WHILE:\n {\n name_p = \"WHILE\";\n print_location = true;\n break;\n }\n case SCANNER_TYPE_FOR:\n {\n scanner_for_info_t *for_info_p = (scanner_for_info_t *) info_p;\n JERRY_DEBUG_MSG (\" FOR: source:%d expression:%d[%d:%d] end:%d[%d:%d]\\n\",\n (int) (for_info_p->info.source_p - source_start_p),\n (int) (for_info_p->expression_location.source_p - source_start_p),\n (int) for_info_p->expression_location.line,\n (int) for_info_p->expression_location.column,\n (int) (for_info_p->end_location.source_p - source_start_p),\n (int) for_info_p->end_location.line,\n (int) for_info_p->end_location.column);\n break;\n }\n case SCANNER_TYPE_FOR_IN:\n {\n name_p = \"FOR-IN\";\n print_location = true;\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_TYPE_FOR_OF:\n {\n name_p = \"FOR-OF\";\n print_location = true;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCANNER_TYPE_SWITCH:\n {\n JERRY_DEBUG_MSG (\" SWITCH: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n\n scanner_case_info_t *current_case_p = ((scanner_switch_info_t *) info_p)->case_p;\n\n while (current_case_p != NULL)\n {\n JERRY_DEBUG_MSG (\" CASE: location:%d[%d:%d]\\n\",\n (int) (current_case_p->location.source_p - source_start_p),\n (int) current_case_p->location.line,\n (int) current_case_p->location.column);\n\n current_case_p = current_case_p->next_p;\n }\n break;\n }\n case SCANNER_TYPE_CASE:\n {\n name_p = \"CASE\";\n print_location = true;\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_TYPE_INITIALIZER:\n {\n name_p = \"INITIALIZER\";\n print_location = true;\n break;\n }\n case SCANNER_TYPE_CLASS_CONSTRUCTOR:\n {\n JERRY_DEBUG_MSG (\" CLASS-CONSTRUCTOR: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n print_location = false;\n break;\n }\n case SCANNER_TYPE_LET_EXPRESSION:\n {\n JERRY_DEBUG_MSG (\" LET_EXPRESSION: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n break;\n }\n case SCANNER_TYPE_ERR_REDECLARED:\n {\n JERRY_DEBUG_MSG (\" ERR_REDECLARED: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n break;\n }\n case SCANNER_TYPE_ERR_ASYNC_FUNCTION:\n {\n JERRY_DEBUG_MSG (\" ERR_ASYNC_FUNCTION: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n }\n\n if (print_location)\n {\n scanner_location_info_t *location_info_p = (scanner_location_info_t *) info_p;\n JERRY_DEBUG_MSG (\" %s: source:%d location:%d[%d:%d]\\n\",\n name_p,\n (int) (location_info_p->info.source_p - source_start_p),\n (int) (location_info_p->location.source_p - source_start_p),\n (int) location_info_p->location.line,\n (int) location_info_p->location.column);\n }\n\n info_p = info_p->next_p;\n }\n\n JERRY_DEBUG_MSG (\"\\n--- Scanning end ---\\n\\n\");\n }\n#endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */\n\n parser_stack_free (context_p);\n} /* scanner_scan_all */", "project": "jerryscript", "hash": 188299918774090447744906316734921320013, "size": 1234, "commit_id": "69f8e78c2f8d562bd6d8002b5488f1662ac30d24", "message": "Fix error handling in scanner when in case of OOM (#3793)\n\nThis patch fixes #3786 and fixes #3788.\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: Robert Fancsik frobert@inf.u-szeged.hu", "target": 1, "dataset": "other", "idx": 198440} {"func": "scanner_scan_all (parser_context_t *context_p, /**< context */\n const uint8_t *arg_list_p, /**< function argument list */\n const uint8_t *arg_list_end_p, /**< end of argument list */\n const uint8_t *source_p, /**< valid UTF-8 source code */\n const uint8_t *source_end_p) /**< end of source code */\n{\n scanner_context_t scanner_context;\n\n#if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE)\n if (context_p->is_show_opcodes)\n {\n JERRY_DEBUG_MSG (\"\\n--- Scanning start ---\\n\\n\");\n }\n#endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */\n\n scanner_context.context_status_flags = context_p->status_flags;\n scanner_context.status_flags = SCANNER_CONTEXT_NO_FLAGS;\n#if ENABLED (JERRY_DEBUGGER)\n if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED)\n {\n scanner_context.status_flags |= SCANNER_CONTEXT_DEBUGGER_ENABLED;\n }\n#endif /* ENABLED (JERRY_DEBUGGER) */\n#if ENABLED (JERRY_ES2015)\n scanner_context.binding_type = SCANNER_BINDING_NONE;\n scanner_context.active_binding_list_p = NULL;\n#endif /* ENABLED (JERRY_ES2015) */\n scanner_context.active_literal_pool_p = NULL;\n scanner_context.active_switch_statement.last_case_p = NULL;\n scanner_context.end_arguments_p = NULL;\n#if ENABLED (JERRY_ES2015)\n scanner_context.async_source_p = NULL;\n#endif /* ENABLED (JERRY_ES2015) */\n\n /* This assignment must be here because of Apple compilers. */\n context_p->u.scanner_context_p = &scanner_context;\n\n parser_stack_init (context_p);\n\n PARSER_TRY (context_p->try_buffer)\n {\n context_p->line = 1;\n context_p->column = 1;\n\n if (arg_list_p == NULL)\n {\n context_p->source_p = source_p;\n context_p->source_end_p = source_end_p;\n\n uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION_WITHOUT_ARGUMENTS | SCANNER_LITERAL_POOL_CAN_EVAL;\n\n if (context_p->status_flags & PARSER_IS_STRICT)\n {\n status_flags |= SCANNER_LITERAL_POOL_IS_STRICT;\n }\n\n scanner_literal_pool_t *literal_pool_p = scanner_push_literal_pool (context_p, &scanner_context, status_flags);\n literal_pool_p->source_p = source_p;\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_SCRIPT);\n\n lexer_next_token (context_p);\n scanner_check_directives (context_p, &scanner_context);\n }\n else\n {\n context_p->source_p = arg_list_p;\n context_p->source_end_p = arg_list_end_p;\n\n uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION;\n\n if (context_p->status_flags & PARSER_IS_STRICT)\n {\n status_flags |= SCANNER_LITERAL_POOL_IS_STRICT;\n }\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->status_flags & PARSER_IS_GENERATOR_FUNCTION)\n {\n status_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n scanner_push_literal_pool (context_p, &scanner_context, status_flags);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n parser_stack_push_uint8 (context_p, SCAN_STACK_SCRIPT_FUNCTION);\n\n /* Faking the first token. */\n context_p->token.type = LEXER_LEFT_PAREN;\n }\n\n while (true)\n {\n lexer_token_type_t type = (lexer_token_type_t) context_p->token.type;\n scan_stack_modes_t stack_top = (scan_stack_modes_t) context_p->stack_top_uint8;\n\n switch (scanner_context.mode)\n {\n case SCAN_MODE_PRIMARY_EXPRESSION:\n {\n if (type == LEXER_ADD\n || type == LEXER_SUBTRACT\n || LEXER_IS_UNARY_OP_TOKEN (type))\n {\n break;\n }\n /* FALLTHRU */\n }\n case SCAN_MODE_PRIMARY_EXPRESSION_AFTER_NEW:\n {\n if (scanner_scan_primary_expression (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCAN_MODE_CLASS_DECLARATION:\n {\n if (context_p->token.type == LEXER_KEYW_EXTENDS)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_CLASS_EXTENDS);\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n else if (context_p->token.type != LEXER_LEFT_BRACE)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_context.mode = SCAN_MODE_CLASS_METHOD;\n /* FALLTHRU */\n }\n case SCAN_MODE_CLASS_METHOD:\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR\n || stack_top == SCAN_STACK_EXPLICIT_CLASS_CONSTRUCTOR);\n\n lexer_skip_empty_statements (context_p);\n\n lexer_scan_identifier (context_p);\n\n if (context_p->token.type == LEXER_RIGHT_BRACE)\n {\n scanner_source_start_t source_start;\n\n parser_stack_pop_uint8 (context_p);\n\n if (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR)\n {\n parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));\n }\n\n stack_top = context_p->stack_top_uint8;\n\n JERRY_ASSERT (stack_top == SCAN_STACK_CLASS_STATEMENT || stack_top == SCAN_STACK_CLASS_EXPRESSION);\n\n if (stack_top == SCAN_STACK_CLASS_STATEMENT)\n {\n /* The token is kept to disallow consuming a semicolon after it. */\n scanner_context.mode = SCAN_MODE_STATEMENT_END;\n continue;\n }\n\n scanner_context.mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;\n parser_stack_pop_uint8 (context_p);\n break;\n }\n\n if (context_p->token.type == LEXER_LITERAL\n && LEXER_IS_IDENT_OR_STRING (context_p->token.lit_location.type)\n && lexer_compare_literal_to_string (context_p, \"constructor\", 11))\n {\n if (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR)\n {\n scanner_source_start_t source_start;\n parser_stack_pop_uint8 (context_p);\n parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));\n\n scanner_info_t *info_p = scanner_insert_info (context_p, source_start.source_p, sizeof (scanner_info_t));\n info_p->type = SCANNER_TYPE_CLASS_CONSTRUCTOR;\n parser_stack_push_uint8 (context_p, SCAN_STACK_EXPLICIT_CLASS_CONSTRUCTOR);\n }\n }\n\n if (lexer_token_is_identifier (context_p, \"static\", 6))\n {\n lexer_scan_identifier (context_p);\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n\n uint16_t literal_pool_flags = SCANNER_LITERAL_POOL_FUNCTION;\n\n if (lexer_token_is_identifier (context_p, \"get\", 3)\n || lexer_token_is_identifier (context_p, \"set\", 3))\n {\n lexer_scan_identifier (context_p);\n\n if (context_p->token.type == LEXER_LEFT_PAREN)\n {\n scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);\n continue;\n }\n }\n else if (lexer_token_is_identifier (context_p, \"async\", 5))\n {\n lexer_scan_identifier (context_p);\n\n if (context_p->token.type == LEXER_LEFT_PAREN)\n {\n scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);\n continue;\n }\n\n literal_pool_flags |= SCANNER_LITERAL_POOL_ASYNC;\n\n if (context_p->token.type == LEXER_MULTIPLY)\n {\n lexer_scan_identifier (context_p);\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n }\n else if (context_p->token.type == LEXER_MULTIPLY)\n {\n lexer_scan_identifier (context_p);\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCANNER_FROM_LITERAL_POOL_TO_COMPUTED (literal_pool_flags));\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n if (literal_pool_flags & SCANNER_LITERAL_POOL_GENERATOR)\n {\n context_p->status_flags |= PARSER_IS_GENERATOR_FUNCTION;\n }\n\n scanner_push_literal_pool (context_p, &scanner_context, literal_pool_flags);\n lexer_next_token (context_p);\n continue;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCAN_MODE_POST_PRIMARY_EXPRESSION:\n {\n if (scanner_scan_post_primary_expression (context_p, &scanner_context, type, stack_top))\n {\n break;\n }\n type = (lexer_token_type_t) context_p->token.type;\n /* FALLTHRU */\n }\n case SCAN_MODE_PRIMARY_EXPRESSION_END:\n {\n if (scanner_scan_primary_expression_end (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n break;\n }\n case SCAN_MODE_STATEMENT_OR_TERMINATOR:\n {\n if (type == LEXER_RIGHT_BRACE || type == LEXER_EOS)\n {\n scanner_context.mode = SCAN_MODE_STATEMENT_END;\n continue;\n }\n /* FALLTHRU */\n }\n case SCAN_MODE_STATEMENT:\n {\n if (scanner_scan_statement (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n break;\n }\n case SCAN_MODE_STATEMENT_END:\n {\n if (scanner_scan_statement_end (context_p, &scanner_context, type) != SCAN_NEXT_TOKEN)\n {\n continue;\n }\n\n if (context_p->token.type == LEXER_EOS)\n {\n goto scan_completed;\n }\n\n break;\n }\n case SCAN_MODE_VAR_STATEMENT:\n {\n#if ENABLED (JERRY_ES2015)\n if (type == LEXER_LEFT_SQUARE || type == LEXER_LEFT_BRACE)\n {\n uint8_t binding_type = SCANNER_BINDING_VAR;\n\n if (stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_FOR_LET_START)\n {\n binding_type = SCANNER_BINDING_LET;\n }\n else if (stack_top == SCAN_STACK_CONST || stack_top == SCAN_STACK_FOR_CONST_START)\n {\n binding_type = SCANNER_BINDING_CONST;\n }\n\n scanner_push_destructuring_pattern (context_p, &scanner_context, binding_type, false);\n\n if (type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);\n scanner_context.mode = SCAN_MODE_BINDING;\n break;\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);\n scanner_context.mode = SCAN_MODE_PROPERTY_NAME;\n continue;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (type != LEXER_LITERAL\n || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n lexer_lit_location_t *literal_p = scanner_add_literal (context_p, &scanner_context);\n\n#if ENABLED (JERRY_ES2015)\n if (stack_top != SCAN_STACK_VAR && stack_top != SCAN_STACK_FOR_VAR_START)\n {\n scanner_detect_invalid_let (context_p, literal_p);\n\n if (stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_FOR_LET_START)\n {\n literal_p->type |= SCANNER_LITERAL_IS_LET;\n }\n else\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_CONST || stack_top == SCAN_STACK_FOR_CONST_START);\n literal_p->type |= SCANNER_LITERAL_IS_CONST;\n }\n\n lexer_next_token (context_p);\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n }\n else if (context_p->token.type == LEXER_ASSIGN)\n {\n scanner_binding_literal_t binding_literal;\n binding_literal.literal_p = literal_p;\n\n parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));\n parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);\n }\n }\n else\n {\n if (!(literal_p->type & SCANNER_LITERAL_IS_VAR))\n {\n scanner_detect_invalid_var (context_p, &scanner_context, literal_p);\n literal_p->type |= SCANNER_LITERAL_IS_VAR;\n\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n }\n\n lexer_next_token (context_p);\n }\n#else /* !ENABLED (JERRY_ES2015) */\n literal_p->type |= SCANNER_LITERAL_IS_VAR;\n\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n\n lexer_next_token (context_p);\n#endif /* ENABLED (JERRY_ES2015) */\n\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_EXPORT)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n\n switch (context_p->token.type)\n {\n case LEXER_ASSIGN:\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n /* FALLTHRU */\n }\n case LEXER_COMMA:\n {\n lexer_next_token (context_p);\n continue;\n }\n }\n\n if (SCANNER_IS_FOR_START (stack_top))\n {\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n JERRY_ASSERT (!(scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_EXPORT));\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n\n if (context_p->token.type != LEXER_SEMICOLON\n && context_p->token.type != LEXER_KEYW_IN\n && !SCANNER_IDENTIFIER_IS_OF ())\n {\n scanner_raise_error (context_p);\n }\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;\n continue;\n }\n\n#if ENABLED (JERRY_ES2015)\n JERRY_ASSERT (stack_top == SCAN_STACK_VAR || stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_CONST);\n#else /* !ENABLED (JERRY_ES2015) */\n JERRY_ASSERT (stack_top == SCAN_STACK_VAR);\n#endif /* ENABLED (JERRY_ES2015) */\n\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n scanner_context.active_literal_pool_p->status_flags &= (uint16_t) ~SCANNER_LITERAL_POOL_IN_EXPORT;\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n\n scanner_context.mode = SCAN_MODE_STATEMENT_END;\n parser_stack_pop_uint8 (context_p);\n continue;\n }\n case SCAN_MODE_FUNCTION_ARGUMENTS:\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_SCRIPT_FUNCTION\n || stack_top == SCAN_STACK_FUNCTION_STATEMENT\n || stack_top == SCAN_STACK_FUNCTION_EXPRESSION\n || stack_top == SCAN_STACK_FUNCTION_PROPERTY);\n\n scanner_literal_pool_t *literal_pool_p = scanner_context.active_literal_pool_p;\n\n JERRY_ASSERT (literal_pool_p != NULL && (literal_pool_p->status_flags & SCANNER_LITERAL_POOL_FUNCTION));\n\n literal_pool_p->source_p = context_p->source_p;\n\n#if ENABLED (JERRY_ES2015)\n if (JERRY_UNLIKELY (scanner_context.async_source_p != NULL))\n {\n literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ASYNC;\n literal_pool_p->source_p = scanner_context.async_source_p;\n scanner_context.async_source_p = NULL;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (type != LEXER_LEFT_PAREN)\n {\n scanner_raise_error (context_p);\n }\n lexer_next_token (context_p);\n\n#if ENABLED (JERRY_ES2015)\n /* FALLTHRU */\n }\n case SCAN_MODE_CONTINUE_FUNCTION_ARGUMENTS:\n {\n#endif /* ENABLED (JERRY_ES2015) */\n if (context_p->token.type != LEXER_RIGHT_PAREN && context_p->token.type != LEXER_EOS)\n {\n#if ENABLED (JERRY_ES2015)\n lexer_lit_location_t *argument_literal_p;\n#endif /* ENABLED (JERRY_ES2015) */\n\n while (true)\n {\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_THREE_DOTS)\n {\n scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;\n\n lexer_next_token (context_p);\n }\n\n if (context_p->token.type == LEXER_LEFT_SQUARE || context_p->token.type == LEXER_LEFT_BRACE)\n {\n argument_literal_p = NULL;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type != LEXER_LITERAL\n || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n argument_literal_p = scanner_append_argument (context_p, &scanner_context);\n#else /* !ENABLED (JERRY_ES2015) */\n scanner_append_argument (context_p, &scanner_context);\n#endif /* ENABLED (JERRY_ES2015) */\n\n lexer_next_token (context_p);\n\n if (context_p->token.type != LEXER_COMMA)\n {\n break;\n }\n lexer_next_token (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n if (argument_literal_p == NULL)\n {\n scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PARAMETERS);\n scanner_append_hole (context_p, &scanner_context);\n scanner_push_destructuring_pattern (context_p, &scanner_context, SCANNER_BINDING_ARG, false);\n\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);\n scanner_context.mode = SCAN_MODE_BINDING;\n break;\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);\n scanner_context.mode = SCAN_MODE_PROPERTY_NAME;\n continue;\n }\n\n if (context_p->token.type == LEXER_ASSIGN)\n {\n scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PARAMETERS);\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n\n if (argument_literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n JERRY_ASSERT (argument_literal_p->type & SCANNER_LITERAL_EARLY_CREATE);\n break;\n }\n\n scanner_binding_literal_t binding_literal;\n binding_literal.literal_p = argument_literal_p;\n\n parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));\n parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n }\n\n if (context_p->token.type == LEXER_EOS && stack_top == SCAN_STACK_SCRIPT_FUNCTION)\n {\n /* End of argument parsing. */\n scanner_info_t *scanner_info_p = (scanner_info_t *) scanner_malloc (context_p, sizeof (scanner_info_t));\n scanner_info_p->next_p = context_p->next_scanner_info_p;\n scanner_info_p->source_p = NULL;\n scanner_info_p->type = SCANNER_TYPE_END_ARGUMENTS;\n scanner_context.end_arguments_p = scanner_info_p;\n\n context_p->next_scanner_info_p = scanner_info_p;\n context_p->source_p = source_p;\n context_p->source_end_p = source_end_p;\n context_p->line = 1;\n context_p->column = 1;\n\n scanner_filter_arguments (context_p, &scanner_context);\n lexer_next_token (context_p);\n scanner_check_directives (context_p, &scanner_context);\n continue;\n }\n\n if (context_p->token.type != LEXER_RIGHT_PAREN)\n {\n scanner_raise_error (context_p);\n }\n\n lexer_next_token (context_p);\n\n if (context_p->token.type != LEXER_LEFT_BRACE)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_filter_arguments (context_p, &scanner_context);\n lexer_next_token (context_p);\n scanner_check_directives (context_p, &scanner_context);\n continue;\n }\n case SCAN_MODE_PROPERTY_NAME:\n {\n JERRY_ASSERT (stack_top == SCAN_STACK_OBJECT_LITERAL);\n\n if (lexer_scan_identifier (context_p))\n {\n lexer_check_property_modifier (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_COMPUTED_PROPERTY);\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type == LEXER_RIGHT_BRACE)\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;\n continue;\n }\n\n if (context_p->token.type == LEXER_PROPERTY_GETTER\n#if ENABLED (JERRY_ES2015)\n || context_p->token.type == LEXER_KEYW_ASYNC\n || context_p->token.type == LEXER_MULTIPLY\n#endif /* ENABLED (JERRY_ES2015) */\n || context_p->token.type == LEXER_PROPERTY_SETTER)\n {\n uint16_t literal_pool_flags = SCANNER_LITERAL_POOL_FUNCTION;\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_MULTIPLY)\n {\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n else if (context_p->token.type == LEXER_KEYW_ASYNC)\n {\n literal_pool_flags |= SCANNER_LITERAL_POOL_ASYNC;\n\n if (lexer_consume_generator (context_p))\n {\n literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;\n }\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);\n lexer_scan_identifier (context_p);\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCANNER_FROM_LITERAL_POOL_TO_COMPUTED (literal_pool_flags));\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_push_literal_pool (context_p, &scanner_context, literal_pool_flags);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n break;\n }\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n#if ENABLED (JERRY_ES2015)\n parser_line_counter_t start_line = context_p->token.line;\n parser_line_counter_t start_column = context_p->token.column;\n bool is_ident = (context_p->token.lit_location.type == LEXER_IDENT_LITERAL);\n#endif /* ENABLED (JERRY_ES2015) */\n\n lexer_next_token (context_p);\n\n#if ENABLED (JERRY_ES2015)\n if (context_p->token.type == LEXER_LEFT_PAREN)\n {\n scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);\n scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;\n continue;\n }\n\n if (is_ident\n && (context_p->token.type == LEXER_COMMA\n || context_p->token.type == LEXER_RIGHT_BRACE\n || context_p->token.type == LEXER_ASSIGN))\n {\n context_p->source_p = context_p->token.lit_location.char_p;\n context_p->line = start_line;\n context_p->column = start_column;\n\n lexer_next_token (context_p);\n\n JERRY_ASSERT (context_p->token.type != LEXER_LITERAL\n || context_p->token.lit_location.type == LEXER_IDENT_LITERAL);\n\n if (context_p->token.type != LEXER_LITERAL)\n {\n scanner_raise_error (context_p);\n }\n\n if (scanner_context.binding_type != SCANNER_BINDING_NONE)\n {\n scanner_context.mode = SCAN_MODE_BINDING;\n continue;\n }\n\n scanner_add_reference (context_p, &scanner_context);\n\n lexer_next_token (context_p);\n\n if (context_p->token.type == LEXER_ASSIGN)\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;\n continue;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (context_p->token.type != LEXER_COLON)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n\n#if ENABLED (JERRY_ES2015)\n if (scanner_context.binding_type != SCANNER_BINDING_NONE)\n {\n scanner_context.mode = SCAN_MODE_BINDING;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCAN_MODE_BINDING:\n {\n JERRY_ASSERT (scanner_context.binding_type == SCANNER_BINDING_VAR\n || scanner_context.binding_type == SCANNER_BINDING_LET\n || scanner_context.binding_type == SCANNER_BINDING_CATCH\n || scanner_context.binding_type == SCANNER_BINDING_CONST\n || scanner_context.binding_type == SCANNER_BINDING_ARG\n || scanner_context.binding_type == SCANNER_BINDING_ARROW_ARG);\n\n if (type == LEXER_THREE_DOTS)\n {\n lexer_next_token (context_p);\n type = (lexer_token_type_t) context_p->token.type;\n }\n\n if (type == LEXER_LEFT_SQUARE || type == LEXER_LEFT_BRACE)\n {\n scanner_push_destructuring_pattern (context_p, &scanner_context, scanner_context.binding_type, true);\n\n if (type == LEXER_LEFT_SQUARE)\n {\n parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);\n break;\n }\n\n parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);\n scanner_context.mode = SCAN_MODE_PROPERTY_NAME;\n continue;\n }\n\n if (type != LEXER_LITERAL || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)\n {\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n continue;\n }\n\n lexer_lit_location_t *literal_p = scanner_add_literal (context_p, &scanner_context);\n\n scanner_context.mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;\n\n if (scanner_context.binding_type == SCANNER_BINDING_VAR)\n {\n if (!(literal_p->type & SCANNER_LITERAL_IS_VAR))\n {\n scanner_detect_invalid_var (context_p, &scanner_context, literal_p);\n literal_p->type |= SCANNER_LITERAL_IS_VAR;\n\n if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)\n {\n literal_p->type |= SCANNER_LITERAL_NO_REG;\n }\n }\n break;\n }\n\n if (scanner_context.binding_type == SCANNER_BINDING_ARROW_ARG)\n {\n literal_p->type |= SCANNER_LITERAL_IS_ARG | SCANNER_LITERAL_IS_ARROW_DESTRUCTURED_ARG;\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n break;\n }\n }\n else\n {\n scanner_detect_invalid_let (context_p, literal_p);\n\n if (scanner_context.binding_type <= SCANNER_BINDING_CATCH)\n {\n JERRY_ASSERT ((scanner_context.binding_type == SCANNER_BINDING_LET)\n || (scanner_context.binding_type == SCANNER_BINDING_CATCH));\n\n literal_p->type |= SCANNER_LITERAL_IS_LET;\n }\n else\n {\n literal_p->type |= SCANNER_LITERAL_IS_CONST;\n\n if (scanner_context.binding_type == SCANNER_BINDING_ARG)\n {\n literal_p->type |= SCANNER_LITERAL_IS_ARG;\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n break;\n }\n }\n }\n\n if (literal_p->type & SCANNER_LITERAL_IS_USED)\n {\n literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;\n break;\n }\n }\n\n scanner_binding_item_t *binding_item_p;\n binding_item_p = (scanner_binding_item_t *) scanner_malloc (context_p, sizeof (scanner_binding_item_t));\n\n binding_item_p->next_p = scanner_context.active_binding_list_p->items_p;\n binding_item_p->literal_p = literal_p;\n\n scanner_context.active_binding_list_p->items_p = binding_item_p;\n\n lexer_next_token (context_p);\n if (context_p->token.type != LEXER_ASSIGN)\n {\n continue;\n }\n\n scanner_binding_literal_t binding_literal;\n binding_literal.literal_p = literal_p;\n\n parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));\n parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);\n\n scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n }\n\n lexer_next_token (context_p);\n }\n\nscan_completed:\n if (context_p->stack_top_uint8 != SCAN_STACK_SCRIPT\n && context_p->stack_top_uint8 != SCAN_STACK_SCRIPT_FUNCTION)\n {\n scanner_raise_error (context_p);\n }\n\n scanner_pop_literal_pool (context_p, &scanner_context);\n\n#if ENABLED (JERRY_ES2015)\n JERRY_ASSERT (scanner_context.active_binding_list_p == NULL);\n#endif /* ENABLED (JERRY_ES2015) */\n JERRY_ASSERT (scanner_context.active_literal_pool_p == NULL);\n\n#ifndef JERRY_NDEBUG\n scanner_context.context_status_flags |= PARSER_SCANNING_SUCCESSFUL;\n#endif /* !JERRY_NDEBUG */\n }\n PARSER_CATCH\n {\n#if ENABLED (JERRY_ES2015)\n while (scanner_context.active_binding_list_p != NULL)\n {\n scanner_pop_binding_list (&scanner_context);\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (JERRY_UNLIKELY (context_p->error != PARSER_ERR_OUT_OF_MEMORY))\n {\n /* Ignore the errors thrown by the lexer. */\n context_p->error = PARSER_ERR_NO_ERROR;\n\n /* The following code may allocate memory, so it is enclosed in a try/catch. */\n PARSER_TRY (context_p->try_buffer)\n {\n #if ENABLED (JERRY_ES2015)\n if (scanner_context.status_flags & SCANNER_CONTEXT_THROW_ERR_ASYNC_FUNCTION)\n {\n JERRY_ASSERT (scanner_context.async_source_p != NULL);\n\n scanner_info_t *info_p;\n info_p = scanner_insert_info (context_p, scanner_context.async_source_p, sizeof (scanner_info_t));\n info_p->type = SCANNER_TYPE_ERR_ASYNC_FUNCTION;\n }\n #endif /* ENABLED (JERRY_ES2015) */\n\n while (scanner_context.active_literal_pool_p != NULL)\n {\n scanner_pop_literal_pool (context_p, &scanner_context);\n }\n }\n PARSER_CATCH\n {\n JERRY_ASSERT (context_p->error == PARSER_ERR_OUT_OF_MEMORY);\n }\n PARSER_TRY_END\n }\n\n JERRY_ASSERT (context_p->error == PARSER_ERR_NO_ERROR || context_p->error == PARSER_ERR_OUT_OF_MEMORY);\n\n if (context_p->error == PARSER_ERR_OUT_OF_MEMORY)\n {\n while (scanner_context.active_literal_pool_p != NULL)\n {\n scanner_literal_pool_t *literal_pool_p = scanner_context.active_literal_pool_p;\n\n scanner_context.active_literal_pool_p = literal_pool_p->prev_p;\n\n parser_list_free (&literal_pool_p->literal_pool);\n scanner_free (literal_pool_p, sizeof (scanner_literal_pool_t));\n }\n\n parser_stack_free (context_p);\n return;\n }\n }\n PARSER_TRY_END\n\n context_p->status_flags = scanner_context.context_status_flags;\n scanner_reverse_info_list (context_p);\n\n#if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE)\n if (context_p->is_show_opcodes)\n {\n scanner_info_t *info_p = context_p->next_scanner_info_p;\n const uint8_t *source_start_p = (arg_list_p == NULL) ? source_p : arg_list_p;\n\n while (info_p->type != SCANNER_TYPE_END)\n {\n const char *name_p = NULL;\n bool print_location = false;\n\n switch (info_p->type)\n {\n case SCANNER_TYPE_END_ARGUMENTS:\n {\n JERRY_DEBUG_MSG (\" END_ARGUMENTS\\n\");\n source_start_p = source_p;\n break;\n }\n case SCANNER_TYPE_FUNCTION:\n case SCANNER_TYPE_BLOCK:\n {\n const uint8_t *prev_source_p = info_p->source_p - 1;\n const uint8_t *data_p;\n\n if (info_p->type == SCANNER_TYPE_FUNCTION)\n {\n data_p = (const uint8_t *) (info_p + 1);\n\n JERRY_DEBUG_MSG (\" FUNCTION: flags: 0x%x declarations: %d\",\n (int) info_p->u8_arg,\n (int) info_p->u16_arg);\n }\n else\n {\n data_p = (const uint8_t *) (info_p + 1);\n\n JERRY_DEBUG_MSG (\" BLOCK:\");\n }\n\n JERRY_DEBUG_MSG (\" source:%d\\n\", (int) (info_p->source_p - source_start_p));\n\n while (data_p[0] != SCANNER_STREAM_TYPE_END)\n {\n switch (data_p[0] & SCANNER_STREAM_TYPE_MASK)\n {\n case SCANNER_STREAM_TYPE_VAR:\n {\n JERRY_DEBUG_MSG (\" VAR \");\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_STREAM_TYPE_LET:\n {\n JERRY_DEBUG_MSG (\" LET \");\n break;\n }\n case SCANNER_STREAM_TYPE_CONST:\n {\n JERRY_DEBUG_MSG (\" CONST \");\n break;\n }\n case SCANNER_STREAM_TYPE_LOCAL:\n {\n JERRY_DEBUG_MSG (\" LOCAL \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)\n case SCANNER_STREAM_TYPE_IMPORT:\n {\n JERRY_DEBUG_MSG (\" IMPORT \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */\n case SCANNER_STREAM_TYPE_ARG:\n {\n JERRY_DEBUG_MSG (\" ARG \");\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_STREAM_TYPE_DESTRUCTURED_ARG:\n {\n JERRY_DEBUG_MSG (\" DESTRUCTURED_ARG \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCANNER_STREAM_TYPE_ARG_FUNC:\n {\n JERRY_DEBUG_MSG (\" ARG_FUNC \");\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_STREAM_TYPE_DESTRUCTURED_ARG_FUNC:\n {\n JERRY_DEBUG_MSG (\" DESTRUCTURED_ARG_FUNC \");\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCANNER_STREAM_TYPE_FUNC:\n {\n JERRY_DEBUG_MSG (\" FUNC \");\n break;\n }\n default:\n {\n JERRY_ASSERT ((data_p[0] & SCANNER_STREAM_TYPE_MASK) == SCANNER_STREAM_TYPE_HOLE);\n JERRY_DEBUG_MSG (\" HOLE\\n\");\n data_p++;\n continue;\n }\n }\n\n size_t length;\n\n if (!(data_p[0] & SCANNER_STREAM_UINT16_DIFF))\n {\n if (data_p[2] != 0)\n {\n prev_source_p += data_p[2];\n length = 2 + 1;\n }\n else\n {\n memcpy (&prev_source_p, data_p + 2 + 1, sizeof (const uint8_t *));\n length = 2 + 1 + sizeof (const uint8_t *);\n }\n }\n else\n {\n int32_t diff = ((int32_t) data_p[2]) | ((int32_t) data_p[3]) << 8;\n\n if (diff <= UINT8_MAX)\n {\n diff = -diff;\n }\n\n prev_source_p += diff;\n length = 2 + 2;\n }\n\n#if ENABLED (JERRY_ES2015)\n if (data_p[0] & SCANNER_STREAM_EARLY_CREATE)\n {\n JERRY_ASSERT (data_p[0] & SCANNER_STREAM_NO_REG);\n JERRY_DEBUG_MSG (\"*\");\n }\n#endif /* ENABLED (JERRY_ES2015) */\n\n if (data_p[0] & SCANNER_STREAM_NO_REG)\n {\n JERRY_DEBUG_MSG (\"* \");\n }\n\n JERRY_DEBUG_MSG (\"'%.*s'\\n\", data_p[1], (char *) prev_source_p);\n prev_source_p += data_p[1];\n data_p += length;\n }\n break;\n }\n case SCANNER_TYPE_WHILE:\n {\n name_p = \"WHILE\";\n print_location = true;\n break;\n }\n case SCANNER_TYPE_FOR:\n {\n scanner_for_info_t *for_info_p = (scanner_for_info_t *) info_p;\n JERRY_DEBUG_MSG (\" FOR: source:%d expression:%d[%d:%d] end:%d[%d:%d]\\n\",\n (int) (for_info_p->info.source_p - source_start_p),\n (int) (for_info_p->expression_location.source_p - source_start_p),\n (int) for_info_p->expression_location.line,\n (int) for_info_p->expression_location.column,\n (int) (for_info_p->end_location.source_p - source_start_p),\n (int) for_info_p->end_location.line,\n (int) for_info_p->end_location.column);\n break;\n }\n case SCANNER_TYPE_FOR_IN:\n {\n name_p = \"FOR-IN\";\n print_location = true;\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_TYPE_FOR_OF:\n {\n name_p = \"FOR-OF\";\n print_location = true;\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n case SCANNER_TYPE_SWITCH:\n {\n JERRY_DEBUG_MSG (\" SWITCH: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n\n scanner_case_info_t *current_case_p = ((scanner_switch_info_t *) info_p)->case_p;\n\n while (current_case_p != NULL)\n {\n JERRY_DEBUG_MSG (\" CASE: location:%d[%d:%d]\\n\",\n (int) (current_case_p->location.source_p - source_start_p),\n (int) current_case_p->location.line,\n (int) current_case_p->location.column);\n\n current_case_p = current_case_p->next_p;\n }\n break;\n }\n case SCANNER_TYPE_CASE:\n {\n name_p = \"CASE\";\n print_location = true;\n break;\n }\n#if ENABLED (JERRY_ES2015)\n case SCANNER_TYPE_INITIALIZER:\n {\n name_p = \"INITIALIZER\";\n print_location = true;\n break;\n }\n case SCANNER_TYPE_CLASS_CONSTRUCTOR:\n {\n JERRY_DEBUG_MSG (\" CLASS-CONSTRUCTOR: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n print_location = false;\n break;\n }\n case SCANNER_TYPE_LET_EXPRESSION:\n {\n JERRY_DEBUG_MSG (\" LET_EXPRESSION: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n break;\n }\n case SCANNER_TYPE_ERR_REDECLARED:\n {\n JERRY_DEBUG_MSG (\" ERR_REDECLARED: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n break;\n }\n case SCANNER_TYPE_ERR_ASYNC_FUNCTION:\n {\n JERRY_DEBUG_MSG (\" ERR_ASYNC_FUNCTION: source:%d\\n\",\n (int) (info_p->source_p - source_start_p));\n break;\n }\n#endif /* ENABLED (JERRY_ES2015) */\n }\n\n if (print_location)\n {\n scanner_location_info_t *location_info_p = (scanner_location_info_t *) info_p;\n JERRY_DEBUG_MSG (\" %s: source:%d location:%d[%d:%d]\\n\",\n name_p,\n (int) (location_info_p->info.source_p - source_start_p),\n (int) (location_info_p->location.source_p - source_start_p),\n (int) location_info_p->location.line,\n (int) location_info_p->location.column);\n }\n\n info_p = info_p->next_p;\n }\n\n JERRY_DEBUG_MSG (\"\\n--- Scanning end ---\\n\\n\");\n }\n#endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */\n\n parser_stack_free (context_p);\n} /* scanner_scan_all */", "project": "jerryscript", "hash": 279987808649331350784855300505332773163, "size": 1238, "commit_id": "69f8e78c2f8d562bd6d8002b5488f1662ac30d24", "message": "Fix error handling in scanner when in case of OOM (#3793)\n\nThis patch fixes #3786 and fixes #3788.\r\n\r\nJerryScript-DCO-1.0-Signed-off-by: Robert Fancsik frobert@inf.u-szeged.hu", "target": 0, "dataset": "other", "idx": 274775} {"func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n\n auto data_type = output->type;\n TF_LITE_ENSURE(context,\n data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||\n data_type == kTfLiteInt8 || data_type == kTfLiteInt32 ||\n data_type == kTfLiteInt64);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n const int block_size = params->block_size;\n const int input_height = input->dims->data[1];\n const int input_width = input->dims->data[2];\n int output_height = input_height / block_size;\n int output_width = input_width / block_size;\n\n TF_LITE_ENSURE_EQ(context, input_height, output_height * block_size);\n TF_LITE_ENSURE_EQ(context, input_width, output_width * block_size);\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);\n output_size->data[0] = input->dims->data[0];\n output_size->data[1] = output_height;\n output_size->data[2] = output_width;\n output_size->data[3] = input->dims->data[3] * block_size * block_size;\n\n return context->ResizeTensor(context, output, output_size);\n}", "project": "tensorflow", "hash": 31179933714560962811339968929323691110, "size": 39, "commit_id": "0d45ea1ca641b21b73bcf9c00e0179cda284e7e7", "message": "Prevent one more div by 0 in TFLite\n\nPiperOrigin-RevId: 370800114\nChange-Id: I6b956aeb8c458cc6f514408d2e89ffacfe249e57", "target": 1, "dataset": "other", "idx": 198448} {"func": "TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n\n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n\n auto data_type = output->type;\n TF_LITE_ENSURE(context,\n data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||\n data_type == kTfLiteInt8 || data_type == kTfLiteInt32 ||\n data_type == kTfLiteInt64);\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n\n const int block_size = params->block_size;\n TF_LITE_ENSURE(context, block_size > 0);\n const int input_height = input->dims->data[1];\n const int input_width = input->dims->data[2];\n int output_height = input_height / block_size;\n int output_width = input_width / block_size;\n\n TF_LITE_ENSURE_EQ(context, input_height, output_height * block_size);\n TF_LITE_ENSURE_EQ(context, input_width, output_width * block_size);\n\n TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);\n output_size->data[0] = input->dims->data[0];\n output_size->data[1] = output_height;\n output_size->data[2] = output_width;\n output_size->data[3] = input->dims->data[3] * block_size * block_size;\n\n return context->ResizeTensor(context, output, output_size);\n}", "project": "tensorflow", "hash": 53852501749742148609964241513124776788, "size": 40, "commit_id": "0d45ea1ca641b21b73bcf9c00e0179cda284e7e7", "message": "Prevent one more div by 0 in TFLite\n\nPiperOrigin-RevId: 370800114\nChange-Id: I6b956aeb8c458cc6f514408d2e89ffacfe249e57", "target": 0, "dataset": "other", "idx": 274812} {"func": "void gf_isom_cenc_get_default_info_internal(GF_TrackBox *trak, u32 sampleDescriptionIndex, u32 *container_type, Bool *default_IsEncrypted, u8 *crypt_byte_block, u8 *skip_byte_block, const u8 **key_info, u32 *key_info_size)\n{\n\tGF_ProtectionSchemeInfoBox *sinf;\n\n\n\t//setup all default as not encrypted\n\tif (default_IsEncrypted) *default_IsEncrypted = GF_FALSE;\n\tif (crypt_byte_block) *crypt_byte_block = 0;\n\tif (skip_byte_block) *skip_byte_block = 0;\n\tif (container_type) *container_type = 0;\n\tif (key_info) *key_info = NULL;\n\tif (key_info_size) *key_info_size = 0;\n\n\tsinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CENC_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CBC_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CENS_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CBCS_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_PIFF_SCHEME, NULL);\n\n\tif (!sinf) {\n\t\tu32 i, nb_stsd = gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes);\n\t\tfor (i=0; iMedia->information->sampleTable->SampleDescription->child_boxes, i);\n\t\t\ta_sinf = (GF_ProtectionSchemeInfoBox *) gf_isom_box_find_child(sentry->child_boxes, GF_ISOM_BOX_TYPE_SINF);\n\t\t\tif (!a_sinf) continue;\n\t\t\t//signal default (not encrypted)\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (sinf && sinf->info && sinf->info->tenc) {\n\t\tif (default_IsEncrypted) *default_IsEncrypted = sinf->info->tenc->isProtected;\n\t\tif (crypt_byte_block) *crypt_byte_block = sinf->info->tenc->crypt_byte_block;\n\t\tif (skip_byte_block) *skip_byte_block = sinf->info->tenc->skip_byte_block;\n\t\tif (key_info) *key_info = sinf->info->tenc->key_info;\n\t\tif (key_info_size) {\n\t\t\t*key_info_size = 20;\n\t\t\tif (!sinf->info->tenc->key_info[3])\n\t\t\t\t*key_info_size += 1 + sinf->info->tenc->key_info[20];\n\t\t}\n\n\t\t//set default value, overwritten below\n\t\tif (container_type) *container_type = GF_ISOM_BOX_TYPE_SENC;\n\t} else if (sinf && sinf->info && sinf->info->piff_tenc) {\n\t\tif (default_IsEncrypted) *default_IsEncrypted = GF_TRUE;\n\t\tif (key_info) *key_info = sinf->info->piff_tenc->key_info;\n\t\tif (key_info_size) *key_info_size = 19;\n\t\t//set default value, overwritten below\n\t\tif (container_type) *container_type = GF_ISOM_BOX_UUID_PSEC;\n\t} else {\n\t\tu32 i, count = 0;\n\t\tGF_CENCSampleEncryptionGroupEntry *seig_entry = NULL;\n\n\t\tif (!trak->moov->mov->is_smooth)\n\t\t\tcount = gf_list_count(trak->Media->information->sampleTable->sampleGroupsDescription);\n\n\t\tfor (i=0; iMedia->information->sampleTable->sampleGroupsDescription, i);\n\t\t\tif (sgdesc->grouping_type!=GF_ISOM_SAMPLE_GROUP_SEIG) continue;\n\t\t\tif (sgdesc->default_description_index)\n\t\t\t\tseig_entry = gf_list_get(sgdesc->group_descriptions, sgdesc->default_description_index-1);\n\t\t\telse\n\t\t\t\tseig_entry = gf_list_get(sgdesc->group_descriptions, 0);\n\t\t\tif (!seig_entry->key_info[0])\n\t\t\t\tseig_entry = NULL;\n\t\t\tbreak;\n\t\t}\n\t\tif (seig_entry) {\n\t\t\tif (default_IsEncrypted) *default_IsEncrypted = seig_entry->IsProtected;\n\t\t\tif (crypt_byte_block) *crypt_byte_block = seig_entry->crypt_byte_block;\n\t\t\tif (skip_byte_block) *skip_byte_block = seig_entry->skip_byte_block;\n\t\t\tif (key_info) *key_info = seig_entry->key_info;\n\t\t\tif (key_info_size) *key_info_size = seig_entry->key_info_size;\n\t\t\tif (container_type) *container_type = GF_ISOM_BOX_TYPE_SENC;\n\t\t} else {\n\t\t\tif (! trak->moov->mov->is_smooth ) {\n\t\t\t\ttrak->moov->mov->is_smooth = GF_TRUE;\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] senc box without tenc, assuming MS smooth+piff\\n\"));\n\t\t\t}\n\t\t\tif (default_IsEncrypted) *default_IsEncrypted = GF_TRUE;\n\t\t\t//set default value, overwritten below\n\t\t\tif (container_type) *container_type = GF_ISOM_BOX_UUID_PSEC;\n\t\t}\n\t}\n\n\tif (container_type && trak->sample_encryption) {\n\t\tif (trak->sample_encryption->type == GF_ISOM_BOX_TYPE_SENC) *container_type = GF_ISOM_BOX_TYPE_SENC;\n\t\telse if (trak->sample_encryption->type == GF_ISOM_BOX_TYPE_UUID) *container_type = ((GF_UUIDBox*)trak->sample_encryption)->internal_4cc;\n\t}\n}", "project": "gpac", "hash": 294092012517353484945000599386797471926, "size": 93, "commit_id": "3b84ffcbacf144ce35650df958432f472b6483f8", "message": "fixed #1735", "target": 1, "dataset": "other", "idx": 198469} {"func": "void gf_isom_cenc_get_default_info_internal(GF_TrackBox *trak, u32 sampleDescriptionIndex, u32 *container_type, Bool *default_IsEncrypted, u8 *crypt_byte_block, u8 *skip_byte_block, const u8 **key_info, u32 *key_info_size)\n{\n\tGF_ProtectionSchemeInfoBox *sinf;\n\n\n\t//setup all default as not encrypted\n\tif (default_IsEncrypted) *default_IsEncrypted = GF_FALSE;\n\tif (crypt_byte_block) *crypt_byte_block = 0;\n\tif (skip_byte_block) *skip_byte_block = 0;\n\tif (container_type) *container_type = 0;\n\tif (key_info) *key_info = NULL;\n\tif (key_info_size) *key_info_size = 0;\n\n\tsinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CENC_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CBC_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CENS_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CBCS_SCHEME, NULL);\n\tif (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_PIFF_SCHEME, NULL);\n\n\tif (!sinf) {\n\t\tu32 i, nb_stsd = gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes);\n\t\tfor (i=0; iMedia->information->sampleTable->SampleDescription->child_boxes, i);\n\t\t\ta_sinf = (GF_ProtectionSchemeInfoBox *) gf_isom_box_find_child(sentry->child_boxes, GF_ISOM_BOX_TYPE_SINF);\n\t\t\tif (!a_sinf) continue;\n\t\t\t//signal default (not encrypted)\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (sinf && sinf->info && sinf->info->tenc) {\n\t\tif (default_IsEncrypted) *default_IsEncrypted = sinf->info->tenc->isProtected;\n\t\tif (crypt_byte_block) *crypt_byte_block = sinf->info->tenc->crypt_byte_block;\n\t\tif (skip_byte_block) *skip_byte_block = sinf->info->tenc->skip_byte_block;\n\t\tif (key_info) *key_info = sinf->info->tenc->key_info;\n\t\tif (key_info_size) {\n\t\t\t*key_info_size = 20;\n\t\t\tif (!sinf->info->tenc->key_info[3])\n\t\t\t\t*key_info_size += 1 + sinf->info->tenc->key_info[20];\n\t\t}\n\n\t\t//set default value, overwritten below\n\t\tif (container_type) *container_type = GF_ISOM_BOX_TYPE_SENC;\n\t} else if (sinf && sinf->info && sinf->info->piff_tenc) {\n\t\tif (default_IsEncrypted) *default_IsEncrypted = GF_TRUE;\n\t\tif (key_info) *key_info = sinf->info->piff_tenc->key_info;\n\t\tif (key_info_size) *key_info_size = 19;\n\t\t//set default value, overwritten below\n\t\tif (container_type) *container_type = GF_ISOM_BOX_UUID_PSEC;\n\t} else {\n\t\tu32 i, count = 0;\n\t\tGF_CENCSampleEncryptionGroupEntry *seig_entry = NULL;\n\n\t\tif (!trak->moov->mov->is_smooth)\n\t\t\tcount = gf_list_count(trak->Media->information->sampleTable->sampleGroupsDescription);\n\n\t\tfor (i=0; iMedia->information->sampleTable->sampleGroupsDescription, i);\n\t\t\tif (sgdesc->grouping_type!=GF_ISOM_SAMPLE_GROUP_SEIG) continue;\n\t\t\tif (sgdesc->default_description_index)\n\t\t\t\tseig_entry = gf_list_get(sgdesc->group_descriptions, sgdesc->default_description_index-1);\n\t\t\telse\n\t\t\t\tseig_entry = gf_list_get(sgdesc->group_descriptions, 0);\n\t\t\tif (seig_entry && !seig_entry->key_info[0])\n\t\t\t\tseig_entry = NULL;\n\t\t\tbreak;\n\t\t}\n\t\tif (seig_entry) {\n\t\t\tif (default_IsEncrypted) *default_IsEncrypted = seig_entry->IsProtected;\n\t\t\tif (crypt_byte_block) *crypt_byte_block = seig_entry->crypt_byte_block;\n\t\t\tif (skip_byte_block) *skip_byte_block = seig_entry->skip_byte_block;\n\t\t\tif (key_info) *key_info = seig_entry->key_info;\n\t\t\tif (key_info_size) *key_info_size = seig_entry->key_info_size;\n\t\t\tif (container_type) *container_type = GF_ISOM_BOX_TYPE_SENC;\n\t\t} else {\n\t\t\tif (! trak->moov->mov->is_smooth ) {\n\t\t\t\ttrak->moov->mov->is_smooth = GF_TRUE;\n\t\t\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] senc box without tenc, assuming MS smooth+piff\\n\"));\n\t\t\t}\n\t\t\tif (default_IsEncrypted) *default_IsEncrypted = GF_TRUE;\n\t\t\t//set default value, overwritten below\n\t\t\tif (container_type) *container_type = GF_ISOM_BOX_UUID_PSEC;\n\t\t}\n\t}\n\n\tif (container_type && trak->sample_encryption) {\n\t\tif (trak->sample_encryption->type == GF_ISOM_BOX_TYPE_SENC) *container_type = GF_ISOM_BOX_TYPE_SENC;\n\t\telse if (trak->sample_encryption->type == GF_ISOM_BOX_TYPE_UUID) *container_type = ((GF_UUIDBox*)trak->sample_encryption)->internal_4cc;\n\t}\n}", "project": "gpac", "hash": 297446364103780389560620090307720640177, "size": 93, "commit_id": "3b84ffcbacf144ce35650df958432f472b6483f8", "message": "fixed #1735", "target": 0, "dataset": "other", "idx": 275434} {"func": "inline Status SparseTensor::Split(const SparseTensor& input_tensor,\n const int split_dim, const int num_split,\n std::vector* result) {\n std::vector output_indices;\n std::vector output_values;\n std::vector output_shapes;\n output_indices.reserve(num_split);\n output_values.reserve(num_split);\n output_shapes.reserve(num_split);\n\n std::vector::Matrix> output_indices_t;\n std::vector::Vec> output_values_t;\n output_indices_t.reserve(num_split);\n output_values_t.reserve(num_split);\n auto input_values_t = input_tensor.values().vec();\n auto input_indices_t = input_tensor.indices().matrix();\n\n std::vector num_values(num_split, 0);\n const int num_dim = input_tensor.shape().size();\n const int split_dim_size = input_tensor.shape()[split_dim];\n const int split_size = split_dim_size / num_split;\n\n if (!(num_split > 0 && num_split <= split_dim_size)) {\n return errors::InvalidArgument(\"num_split must be in the interval (0, \",\n split_dim_size, \"]\");\n }\n if (!(split_dim >= 0 && split_dim < num_dim)) {\n return errors::InvalidArgument(\"num_dim must be in the interval [0, \",\n num_dim, \")\");\n }\n\n const int residual = split_dim_size % num_split;\n for (int i = 0; i < input_tensor.indices().dim_size(0); ++i) {\n const int dim = input_tensor.indices().matrix()(i, split_dim);\n int slice_index = GetSliceIndex(dim, split_size, residual);\n num_values[slice_index]++;\n }\n\n for (int i = 0; i < num_split; ++i) {\n // TODO(ataei): Pass an allocator to avoid allocating large memory buffer.\n output_indices.emplace_back(DT_INT64,\n TensorShape({num_values[i], num_dim}));\n output_values.emplace_back(DataTypeToEnum::v(),\n TensorShape({num_values[i]}));\n output_shapes.emplace_back(input_tensor.shape());\n output_indices_t.emplace_back(output_indices[i].matrix());\n output_values_t.emplace_back(output_values[i].vec());\n const int size = GetSliceShape(i, split_size, residual);\n output_shapes[i].set_dim(split_dim, size);\n }\n\n std::vector values_inserted_in_slice(num_split, 0);\n for (int i = 0; i < input_tensor.indices().dim_size(0); ++i) {\n const int dim = input_indices_t(i, split_dim);\n const int slice_index = GetSliceIndex(dim, split_size, residual);\n const int slice_dim = values_inserted_in_slice[slice_index]++;\n output_values_t[slice_index](slice_dim) = input_values_t(i);\n for (int j = 0; j < num_dim; ++j) {\n const int64 original_dim = input_indices_t(i, j);\n output_indices_t[slice_index](slice_dim, j) =\n (j == split_dim)\n ? GetDimensionInSlice(original_dim, split_size, residual)\n : original_dim;\n }\n }\n\n result->clear();\n result->reserve(num_split);\n for (int i = 0; i < num_split; ++i) {\n SparseTensor tensor;\n Status create_status =\n Create(output_indices[i], output_values[i], output_shapes[i], &tensor);\n if (!create_status.ok()) {\n return create_status;\n }\n result->push_back(std::move(tensor));\n }\n return Status::OK();\n}", "project": "tensorflow", "hash": 146709249587504964012296817765190543788, "size": 79, "commit_id": "8ba6fa29cd8bf9cef9b718dc31c78c73081f5b31", "message": "Fix heap-buffer-overflow issue with `tf.raw_ops.SparseSplit`.\n\nPiperOrigin-RevId: 371242872\nChange-Id: I482bb3d12602c7c3cc9446f97fb9f584bb98e9a4", "target": 1, "dataset": "other", "idx": 198557} {"func": "inline Status SparseTensor::Split(const SparseTensor& input_tensor,\n const int split_dim, const int num_split,\n std::vector* result) {\n std::vector output_indices;\n std::vector output_values;\n std::vector output_shapes;\n output_indices.reserve(num_split);\n output_values.reserve(num_split);\n output_shapes.reserve(num_split);\n\n std::vector::Matrix> output_indices_t;\n std::vector::Vec> output_values_t;\n output_indices_t.reserve(num_split);\n output_values_t.reserve(num_split);\n auto input_values_t = input_tensor.values().vec();\n auto input_indices_t = input_tensor.indices().matrix();\n\n std::vector num_values(num_split, 0);\n const int num_dim = input_tensor.shape().size();\n const int split_dim_size = input_tensor.shape()[split_dim];\n const int split_size = split_dim_size / num_split;\n\n if (!(num_split > 0 && num_split <= split_dim_size)) {\n return errors::InvalidArgument(\"num_split must be in the interval (0, \",\n split_dim_size, \"]\");\n }\n if (!(split_dim >= 0 && split_dim < num_dim)) {\n return errors::InvalidArgument(\"num_dim must be in the interval [0, \",\n num_dim, \")\");\n }\n\n const int residual = split_dim_size % num_split;\n for (int i = 0; i < input_tensor.indices().dim_size(0); ++i) {\n const int dim = input_tensor.indices().matrix()(i, split_dim);\n int slice_index = GetSliceIndex(dim, split_size, residual);\n if (slice_index >= num_values.size()) {\n return errors::InvalidArgument(\"Slice index \", slice_index,\n \" is larger than num_split.\");\n }\n num_values[slice_index]++;\n }\n\n for (int i = 0; i < num_split; ++i) {\n // TODO(ataei): Pass an allocator to avoid allocating large memory buffer.\n output_indices.emplace_back(DT_INT64,\n TensorShape({num_values[i], num_dim}));\n output_values.emplace_back(DataTypeToEnum::v(),\n TensorShape({num_values[i]}));\n output_shapes.emplace_back(input_tensor.shape());\n output_indices_t.emplace_back(output_indices[i].matrix());\n output_values_t.emplace_back(output_values[i].vec());\n const int size = GetSliceShape(i, split_size, residual);\n output_shapes[i].set_dim(split_dim, size);\n }\n\n std::vector values_inserted_in_slice(num_split, 0);\n for (int i = 0; i < input_tensor.indices().dim_size(0); ++i) {\n const int dim = input_indices_t(i, split_dim);\n const int slice_index = GetSliceIndex(dim, split_size, residual);\n const int slice_dim = values_inserted_in_slice[slice_index]++;\n output_values_t[slice_index](slice_dim) = input_values_t(i);\n for (int j = 0; j < num_dim; ++j) {\n const int64 original_dim = input_indices_t(i, j);\n output_indices_t[slice_index](slice_dim, j) =\n (j == split_dim)\n ? GetDimensionInSlice(original_dim, split_size, residual)\n : original_dim;\n }\n }\n\n result->clear();\n result->reserve(num_split);\n for (int i = 0; i < num_split; ++i) {\n SparseTensor tensor;\n Status create_status =\n Create(output_indices[i], output_values[i], output_shapes[i], &tensor);\n if (!create_status.ok()) {\n return create_status;\n }\n result->push_back(std::move(tensor));\n }\n return Status::OK();\n}", "project": "tensorflow", "hash": 10706522302590550572564966482861572860, "size": 83, "commit_id": "8ba6fa29cd8bf9cef9b718dc31c78c73081f5b31", "message": "Fix heap-buffer-overflow issue with `tf.raw_ops.SparseSplit`.\n\nPiperOrigin-RevId: 371242872\nChange-Id: I482bb3d12602c7c3cc9446f97fb9f584bb98e9a4", "target": 0, "dataset": "other", "idx": 277030} {"func": "file_continue(i_ctx_t *i_ctx_p)\n{\n os_ptr op = osp;\n es_ptr pscratch = esp - 2;\n file_enum *pfen = r_ptr(esp - 1, file_enum);\n int devlen = esp[-3].value.intval;\n gx_io_device *iodev = r_ptr(esp - 4, gx_io_device);\n uint len = r_size(pscratch);\n uint code;\n\n if (len < devlen)\n return_error(gs_error_rangecheck); /* not even room for device len */\n memcpy((char *)pscratch->value.bytes, iodev->dname, devlen);\n code = iodev->procs.enumerate_next(pfen, (char *)pscratch->value.bytes + devlen,\n len - devlen);\n if (code == ~(uint) 0) { /* all done */\n esp -= 5; /* pop proc, pfen, devlen, iodev , mark */\n return o_pop_estack;\n } else if (code > len) /* overran string */\n return_error(gs_error_rangecheck);\n else {\n push(1);\n ref_assign(op, pscratch);\n r_set_size(op, code + devlen);\n push_op_estack(file_continue); /* come again */\n *++esp = pscratch[2]; /* proc */\n return o_push_estack;\n }\n}", "project": "ghostpdl", "hash": 138719953418437027565060145640300598234, "size": 29, "commit_id": "ab109aaeb3ddba59518b036fb288402a65cf7ce8", "message": "Bug 694724: Have filenameforall and getenv honor SAFER", "target": 1, "dataset": "other", "idx": 198559} {"func": "file_continue(i_ctx_t *i_ctx_p)\n{\n os_ptr op = osp;\n es_ptr pscratch = esp - 2;\n file_enum *pfen = r_ptr(esp - 1, file_enum);\n int devlen = esp[-3].value.intval;\n gx_io_device *iodev = r_ptr(esp - 4, gx_io_device);\n uint len = r_size(pscratch);\n uint code;\n\n if (len < devlen)\n return_error(gs_error_rangecheck); /* not even room for device len */\n\n do {\n memcpy((char *)pscratch->value.bytes, iodev->dname, devlen);\n code = iodev->procs.enumerate_next(pfen, (char *)pscratch->value.bytes + devlen,\n len - devlen);\n if (code == ~(uint) 0) { /* all done */\n esp -= 5; /* pop proc, pfen, devlen, iodev , mark */\n return o_pop_estack;\n } else if (code > len) /* overran string */\n return_error(gs_error_rangecheck);\n else if (iodev != iodev_default(imemory)\n || (check_file_permissions_reduced(i_ctx_p, (char *)pscratch->value.bytes, code + devlen, \"PermitFileReading\")) == 0) {\n push(1);\n ref_assign(op, pscratch);\n r_set_size(op, code + devlen);\n push_op_estack(file_continue); /* come again */\n *++esp = pscratch[2]; /* proc */\n return o_push_estack;\n }\n } while(1);\n}", "project": "ghostpdl", "hash": 160037816602598820891675771187589764736, "size": 33, "commit_id": "ab109aaeb3ddba59518b036fb288402a65cf7ce8", "message": "Bug 694724: Have filenameforall and getenv honor SAFER", "target": 0, "dataset": "other", "idx": 277036} {"func": "calculateNumTiles (int *numTiles,\n\t\t int numLevels,\n\t\t int min, int max,\n\t\t int size,\n\t\t LevelRoundingMode rmode)\n{\n for (int i = 0; i < numLevels; i++)\n {\n int l = levelSize (min, max, i, rmode);\n if (l > std::numeric_limits::max() - size + 1)\n throw IEX_NAMESPACE::ArgExc (\"Invalid size.\");\n\n numTiles[i] = (l + size - 1) / size;\n }\n}", "project": "openexr", "hash": 245031744365829335891668455873877538315, "size": 15, "commit_id": "2a18ed424a854598c2a20b5dd7e782b436a1e753", "message": "Avoid overflow in calculateNumTiles when size=MAX_INT (#825)\n\n* Avoid overflow in calculateNumTiles when size=MAX_INT\r\n\r\nSigned-off-by: Cary Phillips \r\n\r\n* Compute level size with 64 bits to avoid overflow\r\n\r\nSigned-off-by: Cary Phillips ", "target": 1, "dataset": "other", "idx": 198573} {"func": "calculateNumTiles (int *numTiles,\n\t\t int numLevels,\n\t\t int min, int max,\n\t\t int size,\n\t\t LevelRoundingMode rmode)\n{\n for (int i = 0; i < numLevels; i++)\n {\n // use 64 bits to avoid int overflow if size is large.\n Int64 l = levelSize (min, max, i, rmode);\n numTiles[i] = (l + size - 1) / size;\n }\n}", "project": "openexr", "hash": 70611141410577235686014934945173630473, "size": 13, "commit_id": "2a18ed424a854598c2a20b5dd7e782b436a1e753", "message": "Avoid overflow in calculateNumTiles when size=MAX_INT (#825)\n\n* Avoid overflow in calculateNumTiles when size=MAX_INT\r\n\r\nSigned-off-by: Cary Phillips \r\n\r\n* Compute level size with 64 bits to avoid overflow\r\n\r\nSigned-off-by: Cary Phillips ", "target": 0, "dataset": "other", "idx": 277662} {"func": "ins_comp_get_next_word_or_line(\n\tbuf_T\t*ins_buf,\t\t// buffer being scanned\n\tpos_T\t*cur_match_pos,\t\t// current match position\n\tint\t*match_len,\n\tint\t*cont_s_ipos)\t\t// next ^X<> will set initial_pos\n{\n char_u\t*ptr;\n int\t\tlen;\n\n *match_len = 0;\n ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +\n\tcur_match_pos->col;\n if (ctrl_x_mode_line_or_eval())\n {\n\tif (compl_status_adding())\n\t{\n\t if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)\n\t\treturn NULL;\n\t ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);\n\t if (!p_paste)\n\t\tptr = skipwhite(ptr);\n\t}\n\tlen = (int)STRLEN(ptr);\n }\n else\n {\n\tchar_u\t*tmp_ptr = ptr;\n\n\tif (compl_status_adding())\n\t{\n\t tmp_ptr += compl_length;\n\t // Skip if already inside a word.\n\t if (vim_iswordp(tmp_ptr))\n\t\treturn NULL;\n\t // Find start of next word.\n\t tmp_ptr = find_word_start(tmp_ptr);\n\t}\n\t// Find end of this word.\n\ttmp_ptr = find_word_end(tmp_ptr);\n\tlen = (int)(tmp_ptr - ptr);\n\n\tif (compl_status_adding() && len == compl_length)\n\t{\n\t if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)\n\t {\n\t\t// Try next line, if any. the new word will be\n\t\t// \"join\" as if the normal command \"J\" was used.\n\t\t// IOSIZE is always greater than\n\t\t// compl_length, so the next STRNCPY always\n\t\t// works -- Acevedo\n\t\tSTRNCPY(IObuff, ptr, len);\n\t\tptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);\n\t\ttmp_ptr = ptr = skipwhite(ptr);\n\t\t// Find start of next word.\n\t\ttmp_ptr = find_word_start(tmp_ptr);\n\t\t// Find end of next word.\n\t\ttmp_ptr = find_word_end(tmp_ptr);\n\t\tif (tmp_ptr > ptr)\n\t\t{\n\t\t if (*ptr != ')' && IObuff[len - 1] != TAB)\n\t\t {\n\t\t\tif (IObuff[len - 1] != ' ')\n\t\t\t IObuff[len++] = ' ';\n\t\t\t// IObuf =~ \"\\k.* \", thus len >= 2\n\t\t\tif (p_js\n\t\t\t\t&& (IObuff[len - 2] == '.'\n\t\t\t\t || (vim_strchr(p_cpo, CPO_JOINSP)\n\t\t\t\t\t== NULL\n\t\t\t\t\t&& (IObuff[len - 2] == '?'\n\t\t\t\t\t || IObuff[len - 2] == '!'))))\n\t\t\t IObuff[len++] = ' ';\n\t\t }\n\t\t // copy as much as possible of the new word\n\t\t if (tmp_ptr - ptr >= IOSIZE - len)\n\t\t\ttmp_ptr = ptr + IOSIZE - len - 1;\n\t\t STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);\n\t\t len += (int)(tmp_ptr - ptr);\n\t\t *cont_s_ipos = TRUE;\n\t\t}\n\t\tIObuff[len] = NUL;\n\t\tptr = IObuff;\n\t }\n\t if (len == compl_length)\n\t\treturn NULL;\n\t}\n }\n\n *match_len = len;\n return ptr;\n}", "project": "vim", "hash": 205333609836782956561185481131919699922, "size": 90, "commit_id": "a6f9e300161f4cb54713da22f65b261595e8e614", "message": "patch 9.0.0102: reading past end of line with insert mode completion\n\nProblem: Reading past end of line with insert mode completion.\nSolution: Check text length.", "target": 1, "dataset": "other", "idx": 198585} {"func": "ins_comp_get_next_word_or_line(\n\tbuf_T\t*ins_buf,\t\t// buffer being scanned\n\tpos_T\t*cur_match_pos,\t\t// current match position\n\tint\t*match_len,\n\tint\t*cont_s_ipos)\t\t// next ^X<> will set initial_pos\n{\n char_u\t*ptr;\n int\t\tlen;\n\n *match_len = 0;\n ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +\n\tcur_match_pos->col;\n if (ctrl_x_mode_line_or_eval())\n {\n\tif (compl_status_adding())\n\t{\n\t if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)\n\t\treturn NULL;\n\t ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);\n\t if (!p_paste)\n\t\tptr = skipwhite(ptr);\n\t}\n\tlen = (int)STRLEN(ptr);\n }\n else\n {\n\tchar_u\t*tmp_ptr = ptr;\n\n\tif (compl_status_adding() && compl_length <= (int)STRLEN(tmp_ptr))\n\t{\n\t tmp_ptr += compl_length;\n\t // Skip if already inside a word.\n\t if (vim_iswordp(tmp_ptr))\n\t\treturn NULL;\n\t // Find start of next word.\n\t tmp_ptr = find_word_start(tmp_ptr);\n\t}\n\t// Find end of this word.\n\ttmp_ptr = find_word_end(tmp_ptr);\n\tlen = (int)(tmp_ptr - ptr);\n\n\tif (compl_status_adding() && len == compl_length)\n\t{\n\t if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)\n\t {\n\t\t// Try next line, if any. the new word will be\n\t\t// \"join\" as if the normal command \"J\" was used.\n\t\t// IOSIZE is always greater than\n\t\t// compl_length, so the next STRNCPY always\n\t\t// works -- Acevedo\n\t\tSTRNCPY(IObuff, ptr, len);\n\t\tptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);\n\t\ttmp_ptr = ptr = skipwhite(ptr);\n\t\t// Find start of next word.\n\t\ttmp_ptr = find_word_start(tmp_ptr);\n\t\t// Find end of next word.\n\t\ttmp_ptr = find_word_end(tmp_ptr);\n\t\tif (tmp_ptr > ptr)\n\t\t{\n\t\t if (*ptr != ')' && IObuff[len - 1] != TAB)\n\t\t {\n\t\t\tif (IObuff[len - 1] != ' ')\n\t\t\t IObuff[len++] = ' ';\n\t\t\t// IObuf =~ \"\\k.* \", thus len >= 2\n\t\t\tif (p_js\n\t\t\t\t&& (IObuff[len - 2] == '.'\n\t\t\t\t || (vim_strchr(p_cpo, CPO_JOINSP)\n\t\t\t\t\t== NULL\n\t\t\t\t\t&& (IObuff[len - 2] == '?'\n\t\t\t\t\t || IObuff[len - 2] == '!'))))\n\t\t\t IObuff[len++] = ' ';\n\t\t }\n\t\t // copy as much as possible of the new word\n\t\t if (tmp_ptr - ptr >= IOSIZE - len)\n\t\t\ttmp_ptr = ptr + IOSIZE - len - 1;\n\t\t STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);\n\t\t len += (int)(tmp_ptr - ptr);\n\t\t *cont_s_ipos = TRUE;\n\t\t}\n\t\tIObuff[len] = NUL;\n\t\tptr = IObuff;\n\t }\n\t if (len == compl_length)\n\t\treturn NULL;\n\t}\n }\n\n *match_len = len;\n return ptr;\n}", "project": "vim", "hash": 219722132728553087998374150001249172766, "size": 90, "commit_id": "a6f9e300161f4cb54713da22f65b261595e8e614", "message": "patch 9.0.0102: reading past end of line with insert mode completion\n\nProblem: Reading past end of line with insert mode completion.\nSolution: Check text length.", "target": 0, "dataset": "other", "idx": 277954} {"func": "nosy_ioctl(struct file *file, unsigned int cmd, unsigned long arg)\n{\n\tstruct client *client = file->private_data;\n\tspinlock_t *client_list_lock = &client->lynx->client_list_lock;\n\tstruct nosy_stats stats;\n\n\tswitch (cmd) {\n\tcase NOSY_IOC_GET_STATS:\n\t\tspin_lock_irq(client_list_lock);\n\t\tstats.total_packet_count = client->buffer.total_packet_count;\n\t\tstats.lost_packet_count = client->buffer.lost_packet_count;\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\tif (copy_to_user((void __user *) arg, &stats, sizeof stats))\n\t\t\treturn -EFAULT;\n\t\telse\n\t\t\treturn 0;\n\n\tcase NOSY_IOC_START:\n\t\tspin_lock_irq(client_list_lock);\n\t\tlist_add_tail(&client->link, &client->lynx->client_list);\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\treturn 0;\n\n\tcase NOSY_IOC_STOP:\n\t\tspin_lock_irq(client_list_lock);\n\t\tlist_del_init(&client->link);\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\treturn 0;\n\n\tcase NOSY_IOC_FILTER:\n\t\tspin_lock_irq(client_list_lock);\n\t\tclient->tcode_mask = arg;\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\treturn 0;\n\n\tdefault:\n\t\treturn -EINVAL;\n\t\t/* Flush buffer, configure filter. */\n\t}\n}", "project": "linux", "hash": 195769529492278534124032952899358865154, "size": 44, "commit_id": "829933ef05a951c8ff140e814656d73e74915faf", "message": "firewire: nosy: Fix a use-after-free bug in nosy_ioctl()\n\nFor each device, the nosy driver allocates a pcilynx structure.\nA use-after-free might happen in the following scenario:\n\n 1. Open nosy device for the first time and call ioctl with command\n NOSY_IOC_START, then a new client A will be malloced and added to\n doubly linked list.\n 2. Open nosy device for the second time and call ioctl with command\n NOSY_IOC_START, then a new client B will be malloced and added to\n doubly linked list.\n 3. Call ioctl with command NOSY_IOC_START for client A, then client A\n will be readded to the doubly linked list. Now the doubly linked\n list is messed up.\n 4. Close the first nosy device and nosy_release will be called. In\n nosy_release, client A will be unlinked and freed.\n 5. Close the second nosy device, and client A will be referenced,\n resulting in UAF.\n\nThe root cause of this bug is that the element in the doubly linked list\nis reentered into the list.\n\nFix this bug by adding a check before inserting a client. If a client\nis already in the linked list, don't insert it.\n\nThe following KASAN report reveals it:\n\n BUG: KASAN: use-after-free in nosy_release+0x1ea/0x210\n Write of size 8 at addr ffff888102ad7360 by task poc\n CPU: 3 PID: 337 Comm: poc Not tainted 5.12.0-rc5+ #6\n Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS rel-1.12.0-59-gc9ba5276e321-prebuilt.qemu.org 04/01/2014\n Call Trace:\n nosy_release+0x1ea/0x210\n __fput+0x1e2/0x840\n task_work_run+0xe8/0x180\n exit_to_user_mode_prepare+0x114/0x120\n syscall_exit_to_user_mode+0x1d/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n Allocated by task 337:\n nosy_open+0x154/0x4d0\n misc_open+0x2ec/0x410\n chrdev_open+0x20d/0x5a0\n do_dentry_open+0x40f/0xe80\n path_openat+0x1cf9/0x37b0\n do_filp_open+0x16d/0x390\n do_sys_openat2+0x11d/0x360\n __x64_sys_open+0xfd/0x1a0\n do_syscall_64+0x33/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n Freed by task 337:\n kfree+0x8f/0x210\n nosy_release+0x158/0x210\n __fput+0x1e2/0x840\n task_work_run+0xe8/0x180\n exit_to_user_mode_prepare+0x114/0x120\n syscall_exit_to_user_mode+0x1d/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n The buggy address belongs to the object at ffff888102ad7300 which belongs to the cache kmalloc-128 of size 128\n The buggy address is located 96 bytes inside of 128-byte region [ffff888102ad7300, ffff888102ad7380)\n\n[ Modified to use 'list_empty()' inside proper lock - Linus ]\n\nLink: https://lore.kernel.org/lkml/1617433116-5930-1-git-send-email-zheyuma97@gmail.com/\nReported-and-tested-by: \u9a6c\u54f2\u5b87 (Zheyu Ma) \nSigned-off-by: Zheyu Ma \nCc: Greg Kroah-Hartman \nCc: Stefan Richter \nSigned-off-by: Linus Torvalds ", "target": 1, "dataset": "other", "idx": 198639} {"func": "nosy_ioctl(struct file *file, unsigned int cmd, unsigned long arg)\n{\n\tstruct client *client = file->private_data;\n\tspinlock_t *client_list_lock = &client->lynx->client_list_lock;\n\tstruct nosy_stats stats;\n\tint ret;\n\n\tswitch (cmd) {\n\tcase NOSY_IOC_GET_STATS:\n\t\tspin_lock_irq(client_list_lock);\n\t\tstats.total_packet_count = client->buffer.total_packet_count;\n\t\tstats.lost_packet_count = client->buffer.lost_packet_count;\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\tif (copy_to_user((void __user *) arg, &stats, sizeof stats))\n\t\t\treturn -EFAULT;\n\t\telse\n\t\t\treturn 0;\n\n\tcase NOSY_IOC_START:\n\t\tret = -EBUSY;\n\t\tspin_lock_irq(client_list_lock);\n\t\tif (list_empty(&client->link)) {\n\t\t\tlist_add_tail(&client->link, &client->lynx->client_list);\n\t\t\tret = 0;\n\t\t}\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\treturn ret;\n\n\tcase NOSY_IOC_STOP:\n\t\tspin_lock_irq(client_list_lock);\n\t\tlist_del_init(&client->link);\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\treturn 0;\n\n\tcase NOSY_IOC_FILTER:\n\t\tspin_lock_irq(client_list_lock);\n\t\tclient->tcode_mask = arg;\n\t\tspin_unlock_irq(client_list_lock);\n\n\t\treturn 0;\n\n\tdefault:\n\t\treturn -EINVAL;\n\t\t/* Flush buffer, configure filter. */\n\t}\n}", "project": "linux", "hash": 228155701602816497915464580422124821519, "size": 49, "commit_id": "829933ef05a951c8ff140e814656d73e74915faf", "message": "firewire: nosy: Fix a use-after-free bug in nosy_ioctl()\n\nFor each device, the nosy driver allocates a pcilynx structure.\nA use-after-free might happen in the following scenario:\n\n 1. Open nosy device for the first time and call ioctl with command\n NOSY_IOC_START, then a new client A will be malloced and added to\n doubly linked list.\n 2. Open nosy device for the second time and call ioctl with command\n NOSY_IOC_START, then a new client B will be malloced and added to\n doubly linked list.\n 3. Call ioctl with command NOSY_IOC_START for client A, then client A\n will be readded to the doubly linked list. Now the doubly linked\n list is messed up.\n 4. Close the first nosy device and nosy_release will be called. In\n nosy_release, client A will be unlinked and freed.\n 5. Close the second nosy device, and client A will be referenced,\n resulting in UAF.\n\nThe root cause of this bug is that the element in the doubly linked list\nis reentered into the list.\n\nFix this bug by adding a check before inserting a client. If a client\nis already in the linked list, don't insert it.\n\nThe following KASAN report reveals it:\n\n BUG: KASAN: use-after-free in nosy_release+0x1ea/0x210\n Write of size 8 at addr ffff888102ad7360 by task poc\n CPU: 3 PID: 337 Comm: poc Not tainted 5.12.0-rc5+ #6\n Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS rel-1.12.0-59-gc9ba5276e321-prebuilt.qemu.org 04/01/2014\n Call Trace:\n nosy_release+0x1ea/0x210\n __fput+0x1e2/0x840\n task_work_run+0xe8/0x180\n exit_to_user_mode_prepare+0x114/0x120\n syscall_exit_to_user_mode+0x1d/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n Allocated by task 337:\n nosy_open+0x154/0x4d0\n misc_open+0x2ec/0x410\n chrdev_open+0x20d/0x5a0\n do_dentry_open+0x40f/0xe80\n path_openat+0x1cf9/0x37b0\n do_filp_open+0x16d/0x390\n do_sys_openat2+0x11d/0x360\n __x64_sys_open+0xfd/0x1a0\n do_syscall_64+0x33/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n Freed by task 337:\n kfree+0x8f/0x210\n nosy_release+0x158/0x210\n __fput+0x1e2/0x840\n task_work_run+0xe8/0x180\n exit_to_user_mode_prepare+0x114/0x120\n syscall_exit_to_user_mode+0x1d/0x40\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\n The buggy address belongs to the object at ffff888102ad7300 which belongs to the cache kmalloc-128 of size 128\n The buggy address is located 96 bytes inside of 128-byte region [ffff888102ad7300, ffff888102ad7380)\n\n[ Modified to use 'list_empty()' inside proper lock - Linus ]\n\nLink: https://lore.kernel.org/lkml/1617433116-5930-1-git-send-email-zheyuma97@gmail.com/\nReported-and-tested-by: \u9a6c\u54f2\u5b87 (Zheyu Ma) \nSigned-off-by: Zheyu Ma \nCc: Greg Kroah-Hartman \nCc: Stefan Richter \nSigned-off-by: Linus Torvalds ", "target": 0, "dataset": "other", "idx": 279632} {"func": "static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,\n const size_t number_parameters,const double *parameters,\n ExceptionInfo *exception)\n{\n MagickRealType\n result;\n\n ssize_t\n i;\n\n (void) exception;\n result=0.0;\n switch (function)\n {\n case PolynomialFunction:\n {\n /*\n * Polynomial\n * Parameters: polynomial constants, highest to lowest order\n * For example: c0*x^3 + c1*x^2 + c2*x + c3\n */\n result=0.0;\n for (i=0; i < (ssize_t) number_parameters; i++)\n result=result*QuantumScale*pixel + parameters[i];\n result*=QuantumRange;\n break;\n }\n case SinusoidFunction:\n {\n /* Sinusoid Function\n * Parameters: Freq, Phase, Ampl, bias\n */\n double freq,phase,ampl,bias;\n freq = ( number_parameters >= 1 ) ? parameters[0] : 1.0;\n phase = ( number_parameters >= 2 ) ? parameters[1] : 0.0;\n ampl = ( number_parameters >= 3 ) ? parameters[2] : 0.5;\n bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5;\n result=(MagickRealType) (QuantumRange*(ampl*sin((double) (2.0*MagickPI*\n (freq*QuantumScale*pixel + phase/360.0) )) + bias ) );\n break;\n }\n case ArcsinFunction:\n {\n /* Arcsin Function (peged at range limits for invalid results)\n * Parameters: Width, Center, Range, Bias\n */\n double width,range,center,bias;\n width = ( number_parameters >= 1 ) ? parameters[0] : 1.0;\n center = ( number_parameters >= 2 ) ? parameters[1] : 0.5;\n range = ( number_parameters >= 3 ) ? parameters[2] : 1.0;\n bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5;\n result = 2.0/width*(QuantumScale*pixel - center);\n if ( result <= -1.0 )\n result = bias - range/2.0;\n else if ( result >= 1.0 )\n result = bias + range/2.0;\n else\n result=(MagickRealType) (range/MagickPI*asin((double) result)+bias);\n result *= QuantumRange;\n break;\n }\n case ArctanFunction:\n {\n /* Arctan Function\n * Parameters: Slope, Center, Range, Bias\n */\n double slope,range,center,bias;\n slope = ( number_parameters >= 1 ) ? parameters[0] : 1.0;\n center = ( number_parameters >= 2 ) ? parameters[1] : 0.5;\n range = ( number_parameters >= 3 ) ? parameters[2] : 1.0;\n bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5;\n result=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center));\n result=(MagickRealType) (QuantumRange*(range/MagickPI*atan((double)\n result) + bias ) );\n break;\n }\n case UndefinedFunction:\n break;\n }\n return(ClampToQuantum(result));\n}", "project": "ImageMagick6", "hash": 304799564303649187232279385135928444641, "size": 81, "commit_id": "072d7b10dbe74d1cf4ec0d008990c1a28c076f9e", "message": "https://github.com/ImageMagick/ImageMagick/issues/3332", "target": 1, "dataset": "other", "idx": 198640} {"func": "static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,\n const size_t number_parameters,const double *parameters,\n ExceptionInfo *exception)\n{\n MagickRealType\n result;\n\n ssize_t\n i;\n\n (void) exception;\n result=0.0;\n switch (function)\n {\n case PolynomialFunction:\n {\n /*\n * Polynomial\n * Parameters: polynomial constants, highest to lowest order\n * For example: c0*x^3 + c1*x^2 + c2*x + c3\n */\n result=0.0;\n for (i=0; i < (ssize_t) number_parameters; i++)\n result=result*QuantumScale*pixel + parameters[i];\n result*=QuantumRange;\n break;\n }\n case SinusoidFunction:\n {\n /* Sinusoid Function\n * Parameters: Freq, Phase, Ampl, bias\n */\n double freq,phase,ampl,bias;\n freq = ( number_parameters >= 1 ) ? parameters[0] : 1.0;\n phase = ( number_parameters >= 2 ) ? parameters[1] : 0.0;\n ampl = ( number_parameters >= 3 ) ? parameters[2] : 0.5;\n bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5;\n result=(MagickRealType) (QuantumRange*(ampl*sin((double) (2.0*MagickPI*\n (freq*QuantumScale*pixel + phase/360.0) )) + bias ) );\n break;\n }\n case ArcsinFunction:\n {\n double\n bias,\n center,\n range,\n width;\n\n /* Arcsin Function (peged at range limits for invalid results)\n * Parameters: Width, Center, Range, Bias\n */\n width=(number_parameters >= 1) ? parameters[0] : 1.0;\n center=(number_parameters >= 2) ? parameters[1] : 0.5;\n range=(number_parameters >= 3) ? parameters[2] : 1.0;\n bias=(number_parameters >= 4) ? parameters[3] : 0.5;\n result=2.0*PerceptibleReciprocal(width)*(QuantumScale*pixel-center);\n if (result <= -1.0)\n result=bias-range/2.0;\n else\n if (result >= 1.0)\n result=bias+range/2.0;\n else\n result=(MagickRealType) (range/MagickPI*asin((double) result)+bias);\n result*=QuantumRange;\n break;\n }\n case ArctanFunction:\n {\n /* Arctan Function\n * Parameters: Slope, Center, Range, Bias\n */\n double slope,range,center,bias;\n slope = ( number_parameters >= 1 ) ? parameters[0] : 1.0;\n center = ( number_parameters >= 2 ) ? parameters[1] : 0.5;\n range = ( number_parameters >= 3 ) ? parameters[2] : 1.0;\n bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5;\n result=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center));\n result=(MagickRealType) (QuantumRange*(range/MagickPI*atan((double)\n result) + bias ) );\n break;\n }\n case UndefinedFunction:\n break;\n }\n return(ClampToQuantum(result));\n}", "project": "ImageMagick6", "hash": 315303757418884079516642944898609784871, "size": 87, "commit_id": "072d7b10dbe74d1cf4ec0d008990c1a28c076f9e", "message": "https://github.com/ImageMagick/ImageMagick/issues/3332", "target": 0, "dataset": "other", "idx": 279663} {"func": "NTSTATUS change_notify_create(struct files_struct *fsp,\n\t\t\t uint32_t max_buffer_size,\n\t\t\t uint32_t filter,\n\t\t\t bool recursive)\n{\n\tsize_t len = fsp_fullbasepath(fsp, NULL, 0);\n\tchar fullpath[len+1];\n\tNTSTATUS status = NT_STATUS_NOT_IMPLEMENTED;\n\n\tif (fsp->notify != NULL) {\n\t\tDEBUG(1, (\"change_notify_create: fsp->notify != NULL, \"\n\t\t\t \"fname = %s\\n\", fsp->fsp_name->base_name));\n\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t}\n\n\tif (!(fsp->notify = talloc_zero(NULL, struct notify_change_buf))) {\n\t\tDEBUG(0, (\"talloc failed\\n\"));\n\t\treturn NT_STATUS_NO_MEMORY;\n\t}\n\tfsp->notify->filter = filter;\n\tfsp->notify->subdir_filter = recursive ? filter : 0;\n\tfsp->notify->max_buffer_size = max_buffer_size;\n\n\tfsp_fullbasepath(fsp, fullpath, sizeof(fullpath));\n\n\t/*\n\t * Avoid /. at the end of the path name. notify can't deal with it.\n\t */\n\tif (len > 1 && fullpath[len-1] == '.' && fullpath[len-2] == '/') {\n\t\tfullpath[len-2] = '\\0';\n\t}\n\n\tif ((fsp->notify->filter != 0) ||\n\t (fsp->notify->subdir_filter != 0)) {\n\t\tstatus = notify_add(fsp->conn->sconn->notify_ctx,\n\t\t\t\t fullpath, fsp->notify->filter,\n\t\t\t\t fsp->notify->subdir_filter, fsp);\n\t}\n\n\treturn status;\n}", "project": "samba", "hash": 309795918628451459392198770553612485822, "size": 41, "commit_id": "c300a85848350635e7ddd8129b31c4d439dc0f8a", "message": "s3: smbd: Ensure change notifies can't get set unless the directory handle is open for SEC_DIR_LIST.\n\nRemove knownfail entry.\n\nCVE-2020-14318\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=14434\n\nSigned-off-by: Jeremy Allison ", "target": 1, "dataset": "other", "idx": 198641} {"func": "NTSTATUS change_notify_create(struct files_struct *fsp,\n\t\t\t uint32_t max_buffer_size,\n\t\t\t uint32_t filter,\n\t\t\t bool recursive)\n{\n\tsize_t len = fsp_fullbasepath(fsp, NULL, 0);\n\tchar fullpath[len+1];\n\tNTSTATUS status = NT_STATUS_NOT_IMPLEMENTED;\n\n\t/*\n\t * Setting a changenotify needs READ/LIST access\n\t * on the directory handle.\n\t */\n\tif (!(fsp->access_mask & SEC_DIR_LIST)) {\n\t\treturn NT_STATUS_ACCESS_DENIED;\n\t}\n\n\tif (fsp->notify != NULL) {\n\t\tDEBUG(1, (\"change_notify_create: fsp->notify != NULL, \"\n\t\t\t \"fname = %s\\n\", fsp->fsp_name->base_name));\n\t\treturn NT_STATUS_INVALID_PARAMETER;\n\t}\n\n\tif (!(fsp->notify = talloc_zero(NULL, struct notify_change_buf))) {\n\t\tDEBUG(0, (\"talloc failed\\n\"));\n\t\treturn NT_STATUS_NO_MEMORY;\n\t}\n\tfsp->notify->filter = filter;\n\tfsp->notify->subdir_filter = recursive ? filter : 0;\n\tfsp->notify->max_buffer_size = max_buffer_size;\n\n\tfsp_fullbasepath(fsp, fullpath, sizeof(fullpath));\n\n\t/*\n\t * Avoid /. at the end of the path name. notify can't deal with it.\n\t */\n\tif (len > 1 && fullpath[len-1] == '.' && fullpath[len-2] == '/') {\n\t\tfullpath[len-2] = '\\0';\n\t}\n\n\tif ((fsp->notify->filter != 0) ||\n\t (fsp->notify->subdir_filter != 0)) {\n\t\tstatus = notify_add(fsp->conn->sconn->notify_ctx,\n\t\t\t\t fullpath, fsp->notify->filter,\n\t\t\t\t fsp->notify->subdir_filter, fsp);\n\t}\n\n\treturn status;\n}", "project": "samba", "hash": 105712949554026737390193230545599570192, "size": 49, "commit_id": "c300a85848350635e7ddd8129b31c4d439dc0f8a", "message": "s3: smbd: Ensure change notifies can't get set unless the directory handle is open for SEC_DIR_LIST.\n\nRemove knownfail entry.\n\nCVE-2020-14318\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=14434\n\nSigned-off-by: Jeremy Allison ", "target": 0, "dataset": "other", "idx": 279699} {"func": "bool ItemStackMetadata::setString(const std::string &name, const std::string &var)\n{\n\tbool result = Metadata::setString(name, var);\n\tif (name == TOOLCAP_KEY)\n\t\tupdateToolCapabilities();\n\treturn result;\n}", "project": "minetest", "hash": 260790760425028914771767596212402179523, "size": 7, "commit_id": "b5956bde259faa240a81060ff4e598e25ad52dae", "message": "Sanitize ItemStack meta text", "target": 1, "dataset": "other", "idx": 198663} {"func": "bool ItemStackMetadata::setString(const std::string &name, const std::string &var)\n{\n\tstd::string clean_name = name;\n\tstd::string clean_var = var;\n\tsanitize_string(clean_name);\n\tsanitize_string(clean_var);\n\n\tbool result = Metadata::setString(clean_name, clean_var);\n\tif (clean_name == TOOLCAP_KEY)\n\t\tupdateToolCapabilities();\n\treturn result;\n}", "project": "minetest", "hash": 29693985862186695302198532605370901986, "size": 12, "commit_id": "b5956bde259faa240a81060ff4e598e25ad52dae", "message": "Sanitize ItemStack meta text", "target": 0, "dataset": "other", "idx": 279961} {"func": "int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,\n\t\t\t void **p)\n{\n\tstruct kmem_cache_cpu *c;\n\tint i;\n\n\t/* memcg and kmem_cache debug support */\n\ts = slab_pre_alloc_hook(s, flags);\n\tif (unlikely(!s))\n\t\treturn false;\n\t/*\n\t * Drain objects in the per cpu slab, while disabling local\n\t * IRQs, which protects against PREEMPT and interrupts\n\t * handlers invoking normal fastpath.\n\t */\n\tlocal_irq_disable();\n\tc = this_cpu_ptr(s->cpu_slab);\n\n\tfor (i = 0; i < size; i++) {\n\t\tvoid *object = c->freelist;\n\n\t\tif (unlikely(!object)) {\n\t\t\t/*\n\t\t\t * Invoking slow path likely have side-effect\n\t\t\t * of re-populating per CPU c->freelist\n\t\t\t */\n\t\t\tp[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,\n\t\t\t\t\t _RET_IP_, c);\n\t\t\tif (unlikely(!p[i]))\n\t\t\t\tgoto error;\n\n\t\t\tc = this_cpu_ptr(s->cpu_slab);\n\t\t\tmaybe_wipe_obj_freeptr(s, p[i]);\n\n\t\t\tcontinue; /* goto for-loop */\n\t\t}\n\t\tc->freelist = get_freepointer(s, object);\n\t\tp[i] = object;\n\t\tmaybe_wipe_obj_freeptr(s, p[i]);\n\t}\n\tc->tid = next_tid(c->tid);\n\tlocal_irq_enable();\n\n\t/* Clear memory outside IRQ disabled fastpath loop */\n\tif (unlikely(slab_want_init_on_alloc(flags, s))) {\n\t\tint j;\n\n\t\tfor (j = 0; j < i; j++)\n\t\t\tmemset(p[j], 0, s->object_size);\n\t}\n\n\t/* memcg and kmem_cache debug support */\n\tslab_post_alloc_hook(s, flags, size, p);\n\treturn i;\nerror:\n\tlocal_irq_enable();\n\tslab_post_alloc_hook(s, flags, i, p);\n\t__kmem_cache_free_bulk(s, i, p);\n\treturn 0;\n}", "project": "linux", "hash": 124517195750956527135706940064747760759, "size": 60, "commit_id": "fd4d9c7d0c71866ec0c2825189ebd2ce35bd95b8", "message": "mm: slub: add missing TID bump in kmem_cache_alloc_bulk()\n\nWhen kmem_cache_alloc_bulk() attempts to allocate N objects from a percpu\nfreelist of length M, and N > M > 0, it will first remove the M elements\nfrom the percpu freelist, then call ___slab_alloc() to allocate the next\nelement and repopulate the percpu freelist. ___slab_alloc() can re-enable\nIRQs via allocate_slab(), so the TID must be bumped before ___slab_alloc()\nto properly commit the freelist head change.\n\nFix it by unconditionally bumping c->tid when entering the slowpath.\n\nCc: stable@vger.kernel.org\nFixes: ebe909e0fdb3 (\"slub: improve bulk alloc strategy\")\nSigned-off-by: Jann Horn \nSigned-off-by: Linus Torvalds ", "target": 1, "dataset": "other", "idx": 198668} {"func": "int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,\n\t\t\t void **p)\n{\n\tstruct kmem_cache_cpu *c;\n\tint i;\n\n\t/* memcg and kmem_cache debug support */\n\ts = slab_pre_alloc_hook(s, flags);\n\tif (unlikely(!s))\n\t\treturn false;\n\t/*\n\t * Drain objects in the per cpu slab, while disabling local\n\t * IRQs, which protects against PREEMPT and interrupts\n\t * handlers invoking normal fastpath.\n\t */\n\tlocal_irq_disable();\n\tc = this_cpu_ptr(s->cpu_slab);\n\n\tfor (i = 0; i < size; i++) {\n\t\tvoid *object = c->freelist;\n\n\t\tif (unlikely(!object)) {\n\t\t\t/*\n\t\t\t * We may have removed an object from c->freelist using\n\t\t\t * the fastpath in the previous iteration; in that case,\n\t\t\t * c->tid has not been bumped yet.\n\t\t\t * Since ___slab_alloc() may reenable interrupts while\n\t\t\t * allocating memory, we should bump c->tid now.\n\t\t\t */\n\t\t\tc->tid = next_tid(c->tid);\n\n\t\t\t/*\n\t\t\t * Invoking slow path likely have side-effect\n\t\t\t * of re-populating per CPU c->freelist\n\t\t\t */\n\t\t\tp[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,\n\t\t\t\t\t _RET_IP_, c);\n\t\t\tif (unlikely(!p[i]))\n\t\t\t\tgoto error;\n\n\t\t\tc = this_cpu_ptr(s->cpu_slab);\n\t\t\tmaybe_wipe_obj_freeptr(s, p[i]);\n\n\t\t\tcontinue; /* goto for-loop */\n\t\t}\n\t\tc->freelist = get_freepointer(s, object);\n\t\tp[i] = object;\n\t\tmaybe_wipe_obj_freeptr(s, p[i]);\n\t}\n\tc->tid = next_tid(c->tid);\n\tlocal_irq_enable();\n\n\t/* Clear memory outside IRQ disabled fastpath loop */\n\tif (unlikely(slab_want_init_on_alloc(flags, s))) {\n\t\tint j;\n\n\t\tfor (j = 0; j < i; j++)\n\t\t\tmemset(p[j], 0, s->object_size);\n\t}\n\n\t/* memcg and kmem_cache debug support */\n\tslab_post_alloc_hook(s, flags, size, p);\n\treturn i;\nerror:\n\tlocal_irq_enable();\n\tslab_post_alloc_hook(s, flags, i, p);\n\t__kmem_cache_free_bulk(s, i, p);\n\treturn 0;\n}", "project": "linux", "hash": 286573245831184637475846363298679212083, "size": 69, "commit_id": "fd4d9c7d0c71866ec0c2825189ebd2ce35bd95b8", "message": "mm: slub: add missing TID bump in kmem_cache_alloc_bulk()\n\nWhen kmem_cache_alloc_bulk() attempts to allocate N objects from a percpu\nfreelist of length M, and N > M > 0, it will first remove the M elements\nfrom the percpu freelist, then call ___slab_alloc() to allocate the next\nelement and repopulate the percpu freelist. ___slab_alloc() can re-enable\nIRQs via allocate_slab(), so the TID must be bumped before ___slab_alloc()\nto properly commit the freelist head change.\n\nFix it by unconditionally bumping c->tid when entering the slowpath.\n\nCc: stable@vger.kernel.org\nFixes: ebe909e0fdb3 (\"slub: improve bulk alloc strategy\")\nSigned-off-by: Jann Horn \nSigned-off-by: Linus Torvalds ", "target": 0, "dataset": "other", "idx": 280052} {"func": "decode_NXAST_RAW_ENCAP(const struct nx_action_encap *nae,\n enum ofp_version ofp_version OVS_UNUSED,\n struct ofpbuf *out)\n{\n struct ofpact_encap *encap;\n const struct ofp_ed_prop_header *ofp_prop;\n size_t props_len;\n uint16_t n_props = 0;\n int err;\n\n encap = ofpact_put_ENCAP(out);\n encap->ofpact.raw = NXAST_RAW_ENCAP;\n switch (ntohl(nae->new_pkt_type)) {\n case PT_ETH:\n case PT_NSH:\n /* Add supported encap header types here. */\n break;\n default:\n return OFPERR_NXBAC_BAD_HEADER_TYPE;\n }\n encap->new_pkt_type = nae->new_pkt_type;\n encap->hdr_size = ntohs(nae->hdr_size);\n\n ofp_prop = nae->props;\n props_len = ntohs(nae->len) - offsetof(struct nx_action_encap, props);\n n_props = 0;\n while (props_len > 0) {\n err = decode_ed_prop(&ofp_prop, out, &props_len);\n if (err) {\n return err;\n }\n n_props++;\n }\n encap->n_props = n_props;\n out->header = &encap->ofpact;\n ofpact_finish_ENCAP(out, &encap);\n\n return 0;\n}", "project": "ovs", "hash": 58951518954942858611729288502768220883, "size": 39, "commit_id": "65c61b0c23a0d474696d7b1cea522a5016a8aeb3", "message": "ofp-actions: Fix use-after-free while decoding RAW_ENCAP.\n\nWhile decoding RAW_ENCAP action, decode_ed_prop() might re-allocate\nofpbuf if there is no enough space left. However, function\n'decode_NXAST_RAW_ENCAP' continues to use old pointer to 'encap'\nstructure leading to write-after-free and incorrect decoding.\n\n ==3549105==ERROR: AddressSanitizer: heap-use-after-free on address\n 0x60600000011a at pc 0x0000005f6cc6 bp 0x7ffc3a2d4410 sp 0x7ffc3a2d4408\n WRITE of size 2 at 0x60600000011a thread T0\n #0 0x5f6cc5 in decode_NXAST_RAW_ENCAP lib/ofp-actions.c:4461:20\n #1 0x5f0551 in ofpact_decode ./lib/ofp-actions.inc2:4777:16\n #2 0x5ed17c in ofpacts_decode lib/ofp-actions.c:7752:21\n #3 0x5eba9a in ofpacts_pull_openflow_actions__ lib/ofp-actions.c:7791:13\n #4 0x5eb9fc in ofpacts_pull_openflow_actions lib/ofp-actions.c:7835:12\n #5 0x64bb8b in ofputil_decode_packet_out lib/ofp-packet.c:1113:17\n #6 0x65b6f4 in ofp_print_packet_out lib/ofp-print.c:148:13\n #7 0x659e3f in ofp_to_string__ lib/ofp-print.c:1029:16\n #8 0x659b24 in ofp_to_string lib/ofp-print.c:1244:21\n #9 0x65a28c in ofp_print lib/ofp-print.c:1288:28\n #10 0x540d11 in ofctl_ofp_parse utilities/ovs-ofctl.c:2814:9\n #11 0x564228 in ovs_cmdl_run_command__ lib/command-line.c:247:17\n #12 0x56408a in ovs_cmdl_run_command lib/command-line.c:278:5\n #13 0x5391ae in main utilities/ovs-ofctl.c:179:9\n #14 0x7f6911ce9081 in __libc_start_main (/lib64/libc.so.6+0x27081)\n #15 0x461fed in _start (utilities/ovs-ofctl+0x461fed)\n\nFix that by getting a new pointer before using.\n\nCredit to OSS-Fuzz.\n\nFuzzer regression test will fail only with AddressSanitizer enabled.\n\nReported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=27851\nFixes: f839892a206a (\"OF support and translation of generic encap and decap\")\nAcked-by: William Tu \nSigned-off-by: Ilya Maximets ", "target": 1, "dataset": "other", "idx": 198672} {"func": "decode_NXAST_RAW_ENCAP(const struct nx_action_encap *nae,\n enum ofp_version ofp_version OVS_UNUSED,\n struct ofpbuf *out)\n{\n struct ofpact_encap *encap;\n const struct ofp_ed_prop_header *ofp_prop;\n const size_t encap_ofs = out->size;\n size_t props_len;\n uint16_t n_props = 0;\n int err;\n\n encap = ofpact_put_ENCAP(out);\n encap->ofpact.raw = NXAST_RAW_ENCAP;\n switch (ntohl(nae->new_pkt_type)) {\n case PT_ETH:\n case PT_NSH:\n /* Add supported encap header types here. */\n break;\n default:\n return OFPERR_NXBAC_BAD_HEADER_TYPE;\n }\n encap->new_pkt_type = nae->new_pkt_type;\n encap->hdr_size = ntohs(nae->hdr_size);\n\n ofp_prop = nae->props;\n props_len = ntohs(nae->len) - offsetof(struct nx_action_encap, props);\n n_props = 0;\n while (props_len > 0) {\n err = decode_ed_prop(&ofp_prop, out, &props_len);\n if (err) {\n return err;\n }\n n_props++;\n }\n encap = ofpbuf_at_assert(out, encap_ofs, sizeof *encap);\n encap->n_props = n_props;\n out->header = &encap->ofpact;\n ofpact_finish_ENCAP(out, &encap);\n\n return 0;\n}", "project": "ovs", "hash": 102959166777006843366923731847257991889, "size": 41, "commit_id": "65c61b0c23a0d474696d7b1cea522a5016a8aeb3", "message": "ofp-actions: Fix use-after-free while decoding RAW_ENCAP.\n\nWhile decoding RAW_ENCAP action, decode_ed_prop() might re-allocate\nofpbuf if there is no enough space left. However, function\n'decode_NXAST_RAW_ENCAP' continues to use old pointer to 'encap'\nstructure leading to write-after-free and incorrect decoding.\n\n ==3549105==ERROR: AddressSanitizer: heap-use-after-free on address\n 0x60600000011a at pc 0x0000005f6cc6 bp 0x7ffc3a2d4410 sp 0x7ffc3a2d4408\n WRITE of size 2 at 0x60600000011a thread T0\n #0 0x5f6cc5 in decode_NXAST_RAW_ENCAP lib/ofp-actions.c:4461:20\n #1 0x5f0551 in ofpact_decode ./lib/ofp-actions.inc2:4777:16\n #2 0x5ed17c in ofpacts_decode lib/ofp-actions.c:7752:21\n #3 0x5eba9a in ofpacts_pull_openflow_actions__ lib/ofp-actions.c:7791:13\n #4 0x5eb9fc in ofpacts_pull_openflow_actions lib/ofp-actions.c:7835:12\n #5 0x64bb8b in ofputil_decode_packet_out lib/ofp-packet.c:1113:17\n #6 0x65b6f4 in ofp_print_packet_out lib/ofp-print.c:148:13\n #7 0x659e3f in ofp_to_string__ lib/ofp-print.c:1029:16\n #8 0x659b24 in ofp_to_string lib/ofp-print.c:1244:21\n #9 0x65a28c in ofp_print lib/ofp-print.c:1288:28\n #10 0x540d11 in ofctl_ofp_parse utilities/ovs-ofctl.c:2814:9\n #11 0x564228 in ovs_cmdl_run_command__ lib/command-line.c:247:17\n #12 0x56408a in ovs_cmdl_run_command lib/command-line.c:278:5\n #13 0x5391ae in main utilities/ovs-ofctl.c:179:9\n #14 0x7f6911ce9081 in __libc_start_main (/lib64/libc.so.6+0x27081)\n #15 0x461fed in _start (utilities/ovs-ofctl+0x461fed)\n\nFix that by getting a new pointer before using.\n\nCredit to OSS-Fuzz.\n\nFuzzer regression test will fail only with AddressSanitizer enabled.\n\nReported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=27851\nFixes: f839892a206a (\"OF support and translation of generic encap and decap\")\nAcked-by: William Tu \nSigned-off-by: Ilya Maximets ", "target": 0, "dataset": "other", "idx": 280721} {"func": "static u32 *gen9_init_indirectctx_bb(struct intel_engine_cs *engine, u32 *batch)\n{\n\tstatic const struct lri lri[] = {\n\t\t/* WaDisableGatherAtSetShaderCommonSlice:skl,bxt,kbl,glk */\n\t\t{\n\t\t\tCOMMON_SLICE_CHICKEN2,\n\t\t\t__MASKED_FIELD(GEN9_DISABLE_GATHER_AT_SET_SHADER_COMMON_SLICE,\n\t\t\t\t 0),\n\t\t},\n\n\t\t/* BSpec: 11391 */\n\t\t{\n\t\t\tFF_SLICE_CHICKEN,\n\t\t\t__MASKED_FIELD(FF_SLICE_CHICKEN_CL_PROVOKING_VERTEX_FIX,\n\t\t\t\t FF_SLICE_CHICKEN_CL_PROVOKING_VERTEX_FIX),\n\t\t},\n\n\t\t/* BSpec: 11299 */\n\t\t{\n\t\t\t_3D_CHICKEN3,\n\t\t\t__MASKED_FIELD(_3D_CHICKEN_SF_PROVOKING_VERTEX_FIX,\n\t\t\t\t _3D_CHICKEN_SF_PROVOKING_VERTEX_FIX),\n\t\t}\n\t};\n\n\t*batch++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;\n\n\t/* WaFlushCoherentL3CacheLinesAtContextSwitch:skl,bxt,glk */\n\tbatch = gen8_emit_flush_coherentl3_wa(engine, batch);\n\n\tbatch = emit_lri(batch, lri, ARRAY_SIZE(lri));\n\n\t/* WaMediaPoolStateCmdInWABB:bxt,glk */\n\tif (HAS_POOLED_EU(engine->i915)) {\n\t\t/*\n\t\t * EU pool configuration is setup along with golden context\n\t\t * during context initialization. This value depends on\n\t\t * device type (2x6 or 3x6) and needs to be updated based\n\t\t * on which subslice is disabled especially for 2x6\n\t\t * devices, however it is safe to load default\n\t\t * configuration of 3x6 device instead of masking off\n\t\t * corresponding bits because HW ignores bits of a disabled\n\t\t * subslice and drops down to appropriate config. Please\n\t\t * see render_state_setup() in i915_gem_render_state.c for\n\t\t * possible configurations, to avoid duplication they are\n\t\t * not shown here again.\n\t\t */\n\t\t*batch++ = GEN9_MEDIA_POOL_STATE;\n\t\t*batch++ = GEN9_MEDIA_POOL_ENABLE;\n\t\t*batch++ = 0x00777000;\n\t\t*batch++ = 0;\n\t\t*batch++ = 0;\n\t\t*batch++ = 0;\n\t}\n\n\t*batch++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;\n\n\t/* Pad to end of cacheline */\n\twhile ((unsigned long)batch % CACHELINE_BYTES)\n\t\t*batch++ = MI_NOOP;\n\n\treturn batch;\n}", "project": "linux", "hash": 201520787713853255332939412295673036655, "size": 63, "commit_id": "bc8a76a152c5f9ef3b48104154a65a68a8b76946", "message": "drm/i915/gen9: Clear residual context state on context switch\n\nIntel ID: PSIRT-TA-201910-001\nCVEID: CVE-2019-14615\n\nIntel GPU Hardware prior to Gen11 does not clear EU state\nduring a context switch. This can result in information\nleakage between contexts.\n\nFor Gen8 and Gen9, hardware provides a mechanism for\nfast cleardown of the EU state, by issuing a PIPE_CONTROL\nwith bit 27 set. We can use this in a context batch buffer\nto explicitly cleardown the state on every context switch.\n\nAs this workaround is already in place for gen8, we can borrow\nthe code verbatim for Gen9.\n\nSigned-off-by: Mika Kuoppala \nSigned-off-by: Akeem G Abodunrin \nCc: Kumar Valsan Prathap \nCc: Chris Wilson \nCc: Balestrieri Francesco \nCc: Bloomfield Jon \nCc: Dutt Sudeep ", "target": 1, "dataset": "other", "idx": 198697} {"func": "static u32 *gen9_init_indirectctx_bb(struct intel_engine_cs *engine, u32 *batch)\n{\n\tstatic const struct lri lri[] = {\n\t\t/* WaDisableGatherAtSetShaderCommonSlice:skl,bxt,kbl,glk */\n\t\t{\n\t\t\tCOMMON_SLICE_CHICKEN2,\n\t\t\t__MASKED_FIELD(GEN9_DISABLE_GATHER_AT_SET_SHADER_COMMON_SLICE,\n\t\t\t\t 0),\n\t\t},\n\n\t\t/* BSpec: 11391 */\n\t\t{\n\t\t\tFF_SLICE_CHICKEN,\n\t\t\t__MASKED_FIELD(FF_SLICE_CHICKEN_CL_PROVOKING_VERTEX_FIX,\n\t\t\t\t FF_SLICE_CHICKEN_CL_PROVOKING_VERTEX_FIX),\n\t\t},\n\n\t\t/* BSpec: 11299 */\n\t\t{\n\t\t\t_3D_CHICKEN3,\n\t\t\t__MASKED_FIELD(_3D_CHICKEN_SF_PROVOKING_VERTEX_FIX,\n\t\t\t\t _3D_CHICKEN_SF_PROVOKING_VERTEX_FIX),\n\t\t}\n\t};\n\n\t*batch++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;\n\n\t/* WaFlushCoherentL3CacheLinesAtContextSwitch:skl,bxt,glk */\n\tbatch = gen8_emit_flush_coherentl3_wa(engine, batch);\n\n\t/* WaClearSlmSpaceAtContextSwitch:skl,bxt,kbl,glk,cfl */\n\tbatch = gen8_emit_pipe_control(batch,\n\t\t\t\t PIPE_CONTROL_FLUSH_L3 |\n\t\t\t\t PIPE_CONTROL_STORE_DATA_INDEX |\n\t\t\t\t PIPE_CONTROL_CS_STALL |\n\t\t\t\t PIPE_CONTROL_QW_WRITE,\n\t\t\t\t LRC_PPHWSP_SCRATCH_ADDR);\n\n\tbatch = emit_lri(batch, lri, ARRAY_SIZE(lri));\n\n\t/* WaMediaPoolStateCmdInWABB:bxt,glk */\n\tif (HAS_POOLED_EU(engine->i915)) {\n\t\t/*\n\t\t * EU pool configuration is setup along with golden context\n\t\t * during context initialization. This value depends on\n\t\t * device type (2x6 or 3x6) and needs to be updated based\n\t\t * on which subslice is disabled especially for 2x6\n\t\t * devices, however it is safe to load default\n\t\t * configuration of 3x6 device instead of masking off\n\t\t * corresponding bits because HW ignores bits of a disabled\n\t\t * subslice and drops down to appropriate config. Please\n\t\t * see render_state_setup() in i915_gem_render_state.c for\n\t\t * possible configurations, to avoid duplication they are\n\t\t * not shown here again.\n\t\t */\n\t\t*batch++ = GEN9_MEDIA_POOL_STATE;\n\t\t*batch++ = GEN9_MEDIA_POOL_ENABLE;\n\t\t*batch++ = 0x00777000;\n\t\t*batch++ = 0;\n\t\t*batch++ = 0;\n\t\t*batch++ = 0;\n\t}\n\n\t*batch++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;\n\n\t/* Pad to end of cacheline */\n\twhile ((unsigned long)batch % CACHELINE_BYTES)\n\t\t*batch++ = MI_NOOP;\n\n\treturn batch;\n}", "project": "linux", "hash": 287263079175771631246087515336497738963, "size": 71, "commit_id": "bc8a76a152c5f9ef3b48104154a65a68a8b76946", "message": "drm/i915/gen9: Clear residual context state on context switch\n\nIntel ID: PSIRT-TA-201910-001\nCVEID: CVE-2019-14615\n\nIntel GPU Hardware prior to Gen11 does not clear EU state\nduring a context switch. This can result in information\nleakage between contexts.\n\nFor Gen8 and Gen9, hardware provides a mechanism for\nfast cleardown of the EU state, by issuing a PIPE_CONTROL\nwith bit 27 set. We can use this in a context batch buffer\nto explicitly cleardown the state on every context switch.\n\nAs this workaround is already in place for gen8, we can borrow\nthe code verbatim for Gen9.\n\nSigned-off-by: Mika Kuoppala \nSigned-off-by: Akeem G Abodunrin \nCc: Kumar Valsan Prathap \nCc: Chris Wilson \nCc: Balestrieri Francesco \nCc: Bloomfield Jon \nCc: Dutt Sudeep ", "target": 0, "dataset": "other", "idx": 281552} {"func": "static void unzzip_cat_file(ZZIP_DIR* disk, char* name, FILE* out)\n{\n ZZIP_FILE* file = zzip_file_open (disk, name, 0);\n if (file) \n {\n\tchar buffer[1024]; int len;\n\twhile ((len = zzip_file_read (file, buffer, 1024))) \n\t{\n\t fwrite (buffer, 1, len, out);\n\t}\n\t\n\tzzip_file_close (file);\n }\n}", "project": "zziplib", "hash": 213540364375667917653366276803369040606, "size": 14, "commit_id": "ac9ae39ef419e9f0f83da1e583314d8c7cda34a6", "message": "#68 ssize_t return value of zzip_file_read is a signed value being possibly -1", "target": 1, "dataset": "other", "idx": 198733} {"func": "static void unzzip_cat_file(ZZIP_DIR* disk, char* name, FILE* out)\n{\n ZZIP_FILE* file = zzip_file_open (disk, name, 0);\n if (file) \n {\n\tchar buffer[1024]; int len;\n\twhile (0 < (len = zzip_file_read (file, buffer, 1024))) \n\t{\n\t fwrite (buffer, 1, len, out);\n\t}\n\t\n\tzzip_file_close (file);\n }\n}", "project": "zziplib", "hash": 253924670115102704045568268367383544838, "size": 14, "commit_id": "ac9ae39ef419e9f0f83da1e583314d8c7cda34a6", "message": "#68 ssize_t return value of zzip_file_read is a signed value being possibly -1", "target": 0, "dataset": "other", "idx": 282823} {"func": "static int dissect_dvb_s2_bb(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n{\n proto_item *ti;\n proto_tree *dvb_s2_bb_tree;\n\n guint8 input8, matype1;\n guint8 sync_flag = 0;\n guint16 input16, bb_data_len = 0, user_packet_length;\n\n int sub_dissected = 0, flag_is_ms = 0, new_off = 0;\n\n static int * const bb_header_bitfields[] = {\n &hf_dvb_s2_bb_matype1_gs,\n &hf_dvb_s2_bb_matype1_mis,\n &hf_dvb_s2_bb_matype1_acm,\n &hf_dvb_s2_bb_matype1_issyi,\n &hf_dvb_s2_bb_matype1_npd,\n &hf_dvb_s2_bb_matype1_low_ro,\n NULL\n };\n\n col_append_str(pinfo->cinfo, COL_PROTOCOL, \"BB \");\n col_append_str(pinfo->cinfo, COL_INFO, \"Baseband \");\n\n /* create display subtree for the protocol */\n ti = proto_tree_add_item(tree, proto_dvb_s2_bb, tvb, 0, DVB_S2_BB_HEADER_LEN, ENC_NA);\n dvb_s2_bb_tree = proto_item_add_subtree(ti, ett_dvb_s2_bb);\n\n matype1 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE1);\n new_off += 1;\n\n if (BIT_IS_CLEAR(matype1, DVB_S2_BB_MIS_POS))\n flag_is_ms = 1;\n\n proto_tree_add_bitmask_with_flags(dvb_s2_bb_tree, tvb, DVB_S2_BB_OFFS_MATYPE1, hf_dvb_s2_bb_matype1,\n ett_dvb_s2_bb_matype1, bb_header_bitfields, ENC_BIG_ENDIAN, BMT_NO_FLAGS);\n\n input8 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE1);\n\n if ((pinfo->fd->num == 1) && (_use_low_rolloff_value != 0)) {\n _use_low_rolloff_value = 0;\n }\n if (((input8 & 0x03) == 3) && !_use_low_rolloff_value) {\n _use_low_rolloff_value = 1;\n }\n if (_use_low_rolloff_value) {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_low_ro, tvb,\n DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n } else {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_high_ro, tvb,\n DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n }\n\n input8 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE2);\n new_off += 1;\n if (flag_is_ms) {\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb,\n DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"Input Stream Identifier (ISI): %d\",\n input8);\n } else {\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb,\n DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"reserved\");\n }\n\n user_packet_length = input16 = tvb_get_ntohs(tvb, DVB_S2_BB_OFFS_UPL);\n new_off += 2;\n\n proto_tree_add_uint_format(dvb_s2_bb_tree, hf_dvb_s2_bb_upl, tvb,\n DVB_S2_BB_OFFS_UPL, 2, input16, \"User Packet Length: %d bits (%d bytes)\",\n (guint16) input16, (guint16) input16 / 8);\n\n bb_data_len = input16 = tvb_get_ntohs(tvb, DVB_S2_BB_OFFS_DFL);\n bb_data_len /= 8;\n new_off += 2;\n\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_dfl, tvb,\n DVB_S2_BB_OFFS_DFL, 2, input16, \"%d bits (%d bytes)\", input16, input16 / 8);\n\n new_off += 1;\n sync_flag = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_SYNC);\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_sync, tvb, DVB_S2_BB_OFFS_SYNC, 1, ENC_BIG_ENDIAN);\n\n new_off += 2;\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_syncd, tvb, DVB_S2_BB_OFFS_SYNCD, 2, ENC_BIG_ENDIAN);\n\n new_off += 1;\n proto_tree_add_checksum(dvb_s2_bb_tree, tvb, DVB_S2_BB_OFFS_CRC, hf_dvb_s2_bb_crc, hf_dvb_s2_bb_crc_status, &ei_dvb_s2_bb_crc, pinfo,\n compute_crc8(tvb, DVB_S2_BB_HEADER_LEN - 1, 0), ENC_NA, PROTO_CHECKSUM_VERIFY);\n\n switch (matype1 & DVB_S2_BB_TSGS_MASK) {\n case DVB_S2_BB_TSGS_GENERIC_CONTINUOUS:\n /* Check GSE constraints on the BB header per 9.2.1 of ETSI TS 102 771 */\n if (BIT_IS_SET(matype1, DVB_S2_BB_ISSYI_POS)) {\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_issy_invalid);\n }\n if (BIT_IS_SET(matype1, DVB_S2_BB_NPD_POS)) {\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_npd_invalid);\n }\n if (user_packet_length != 0x0000) {\n expert_add_info_format(pinfo, ti, &ei_dvb_s2_bb_upl_invalid,\n \"UPL is 0x%04x. It must be 0x0000 for GSE packets.\", user_packet_length);\n }\n\n\n if (dvb_s2_df_dissection) {\n while (bb_data_len) {\n if (sync_flag == DVB_S2_BB_SYNC_EIP_CRC32 && bb_data_len == DVB_S2_BB_EIP_CRC32_LEN) {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_eip_crc32, tvb, new_off, bb_data_len, ENC_NA);\n bb_data_len = 0;\n new_off += DVB_S2_BB_EIP_CRC32_LEN;\n } else {\n /* start DVB-GSE dissector */\n sub_dissected = dissect_dvb_s2_gse(tvb_new_subset_length(tvb, new_off, bb_data_len), pinfo, tree, NULL);\n new_off += sub_dissected;\n\n if ((sub_dissected <= bb_data_len) && (sub_dissected >= DVB_S2_GSE_MINSIZE)) {\n bb_data_len -= sub_dissected;\n if (bb_data_len < DVB_S2_GSE_MINSIZE)\n bb_data_len = 0;\n }\n }\n }\n } else {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_df, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n }\n break;\n\n case DVB_S2_BB_TSGS_GENERIC_PACKETIZED:\n proto_tree_add_item(tree, hf_dvb_s2_bb_packetized, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n break;\n\n case DVB_S2_BB_TSGS_TRANSPORT_STREAM:\n proto_tree_add_item(tree, hf_dvb_s2_bb_transport, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n break;\n\n default:\n proto_tree_add_item(tree, hf_dvb_s2_bb_reserved, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_reserved);\n break;\n }\n\n return new_off;\n}", "project": "wireshark", "hash": 210796043791253976716955079241114200072, "size": 147, "commit_id": "0137c24d60934f131b25506a88c9464e4dc827de", "message": "DVB-S2-BB: Prevent infinite loop\n\nCommit 4bf4ee88f0544727e7f89f3f288c6afd2f650a4c removed an else\nstatement that broke out of the BBFrame processing loop. Without\nit, infinite loops might be possible if the GSE frames have bit errors\nin the length field.", "target": 1, "dataset": "other", "idx": 198763} {"func": "static int dissect_dvb_s2_bb(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n{\n proto_item *ti;\n proto_tree *dvb_s2_bb_tree;\n\n guint8 input8, matype1;\n guint8 sync_flag = 0;\n guint16 input16, bb_data_len = 0, user_packet_length;\n\n int sub_dissected = 0, flag_is_ms = 0, new_off = 0;\n\n static int * const bb_header_bitfields[] = {\n &hf_dvb_s2_bb_matype1_gs,\n &hf_dvb_s2_bb_matype1_mis,\n &hf_dvb_s2_bb_matype1_acm,\n &hf_dvb_s2_bb_matype1_issyi,\n &hf_dvb_s2_bb_matype1_npd,\n &hf_dvb_s2_bb_matype1_low_ro,\n NULL\n };\n\n col_append_str(pinfo->cinfo, COL_PROTOCOL, \"BB \");\n col_append_str(pinfo->cinfo, COL_INFO, \"Baseband \");\n\n /* create display subtree for the protocol */\n ti = proto_tree_add_item(tree, proto_dvb_s2_bb, tvb, 0, DVB_S2_BB_HEADER_LEN, ENC_NA);\n dvb_s2_bb_tree = proto_item_add_subtree(ti, ett_dvb_s2_bb);\n\n matype1 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE1);\n new_off += 1;\n\n if (BIT_IS_CLEAR(matype1, DVB_S2_BB_MIS_POS))\n flag_is_ms = 1;\n\n proto_tree_add_bitmask_with_flags(dvb_s2_bb_tree, tvb, DVB_S2_BB_OFFS_MATYPE1, hf_dvb_s2_bb_matype1,\n ett_dvb_s2_bb_matype1, bb_header_bitfields, ENC_BIG_ENDIAN, BMT_NO_FLAGS);\n\n input8 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE1);\n\n if ((pinfo->fd->num == 1) && (_use_low_rolloff_value != 0)) {\n _use_low_rolloff_value = 0;\n }\n if (((input8 & 0x03) == 3) && !_use_low_rolloff_value) {\n _use_low_rolloff_value = 1;\n }\n if (_use_low_rolloff_value) {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_low_ro, tvb,\n DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n } else {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_high_ro, tvb,\n DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN);\n }\n\n input8 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE2);\n new_off += 1;\n if (flag_is_ms) {\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb,\n DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"Input Stream Identifier (ISI): %d\",\n input8);\n } else {\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb,\n DVB_S2_BB_OFFS_MATYPE2, 1, input8, \"reserved\");\n }\n\n user_packet_length = input16 = tvb_get_ntohs(tvb, DVB_S2_BB_OFFS_UPL);\n new_off += 2;\n\n proto_tree_add_uint_format(dvb_s2_bb_tree, hf_dvb_s2_bb_upl, tvb,\n DVB_S2_BB_OFFS_UPL, 2, input16, \"User Packet Length: %d bits (%d bytes)\",\n (guint16) input16, (guint16) input16 / 8);\n\n bb_data_len = input16 = tvb_get_ntohs(tvb, DVB_S2_BB_OFFS_DFL);\n bb_data_len /= 8;\n new_off += 2;\n\n proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_dfl, tvb,\n DVB_S2_BB_OFFS_DFL, 2, input16, \"%d bits (%d bytes)\", input16, input16 / 8);\n\n new_off += 1;\n sync_flag = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_SYNC);\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_sync, tvb, DVB_S2_BB_OFFS_SYNC, 1, ENC_BIG_ENDIAN);\n\n new_off += 2;\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_syncd, tvb, DVB_S2_BB_OFFS_SYNCD, 2, ENC_BIG_ENDIAN);\n\n new_off += 1;\n proto_tree_add_checksum(dvb_s2_bb_tree, tvb, DVB_S2_BB_OFFS_CRC, hf_dvb_s2_bb_crc, hf_dvb_s2_bb_crc_status, &ei_dvb_s2_bb_crc, pinfo,\n compute_crc8(tvb, DVB_S2_BB_HEADER_LEN - 1, 0), ENC_NA, PROTO_CHECKSUM_VERIFY);\n\n switch (matype1 & DVB_S2_BB_TSGS_MASK) {\n case DVB_S2_BB_TSGS_GENERIC_CONTINUOUS:\n /* Check GSE constraints on the BB header per 9.2.1 of ETSI TS 102 771 */\n if (BIT_IS_SET(matype1, DVB_S2_BB_ISSYI_POS)) {\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_issy_invalid);\n }\n if (BIT_IS_SET(matype1, DVB_S2_BB_NPD_POS)) {\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_npd_invalid);\n }\n if (user_packet_length != 0x0000) {\n expert_add_info_format(pinfo, ti, &ei_dvb_s2_bb_upl_invalid,\n \"UPL is 0x%04x. It must be 0x0000 for GSE packets.\", user_packet_length);\n }\n\n\n if (dvb_s2_df_dissection) {\n while (bb_data_len) {\n if (sync_flag == DVB_S2_BB_SYNC_EIP_CRC32 && bb_data_len == DVB_S2_BB_EIP_CRC32_LEN) {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_eip_crc32, tvb, new_off, bb_data_len, ENC_NA);\n bb_data_len = 0;\n new_off += DVB_S2_BB_EIP_CRC32_LEN;\n } else {\n /* start DVB-GSE dissector */\n sub_dissected = dissect_dvb_s2_gse(tvb_new_subset_length(tvb, new_off, bb_data_len), pinfo, tree, NULL);\n new_off += sub_dissected;\n\n if ((sub_dissected <= bb_data_len) && (sub_dissected >= DVB_S2_GSE_MINSIZE)) {\n bb_data_len -= sub_dissected;\n if (bb_data_len < DVB_S2_GSE_MINSIZE)\n bb_data_len = 0;\n } else {\n bb_data_len = 0;\n }\n }\n }\n } else {\n proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_df, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n }\n break;\n\n case DVB_S2_BB_TSGS_GENERIC_PACKETIZED:\n proto_tree_add_item(tree, hf_dvb_s2_bb_packetized, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n break;\n\n case DVB_S2_BB_TSGS_TRANSPORT_STREAM:\n proto_tree_add_item(tree, hf_dvb_s2_bb_transport, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n break;\n\n default:\n proto_tree_add_item(tree, hf_dvb_s2_bb_reserved, tvb, new_off, bb_data_len, ENC_NA);\n new_off += bb_data_len;\n expert_add_info(pinfo, ti, &ei_dvb_s2_bb_reserved);\n break;\n }\n\n return new_off;\n}", "project": "wireshark", "hash": 330364968381030963517562341505385463003, "size": 149, "commit_id": "0137c24d60934f131b25506a88c9464e4dc827de", "message": "DVB-S2-BB: Prevent infinite loop\n\nCommit 4bf4ee88f0544727e7f89f3f288c6afd2f650a4c removed an else\nstatement that broke out of the BBFrame processing loop. Without\nit, infinite loops might be possible if the GSE frames have bit errors\nin the length field.", "target": 0, "dataset": "other", "idx": 283344} {"func": "static void set_error_response(h2_stream *stream, int http_status)\n{\n if (!h2_stream_is_ready(stream)) {\n stream->rtmp->http_status = http_status;\n }\n}", "project": "httpd", "hash": 172068702792085315081162612263931698574, "size": 6, "commit_id": "f990e5ecad40b100a8a5c7c1033c46044a9cb244", "message": "mod_htt2: fix incomplete sync with latest changes in github, adjust version number.\n\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1889119 13f79535-47bb-0310-9956-ffa450edef68", "target": 1, "dataset": "other", "idx": 198837} {"func": "static void set_error_response(h2_stream *stream, int http_status)\n{\n if (!h2_stream_is_ready(stream) && stream->rtmp) {\n stream->rtmp->http_status = http_status;\n }\n}", "project": "httpd", "hash": 163842922705465616802565387268745890925, "size": 6, "commit_id": "f990e5ecad40b100a8a5c7c1033c46044a9cb244", "message": "mod_htt2: fix incomplete sync with latest changes in github, adjust version number.\n\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1889119 13f79535-47bb-0310-9956-ffa450edef68", "target": 0, "dataset": "other", "idx": 284266} {"func": "parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,\n\t reg_syntax_t syntax, Idx nest, reg_errcode_t *err)\n{\n re_dfa_t *dfa = preg->buffer;\n bin_tree_t *tree, *branch = NULL;\n tree = parse_branch (regexp, preg, token, syntax, nest, err);\n if (BE (*err != REG_NOERROR && tree == NULL, 0))\n return NULL;\n\n while (token->type == OP_ALT)\n {\n fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE);\n if (token->type != OP_ALT && token->type != END_OF_RE\n\t && (nest == 0 || token->type != OP_CLOSE_SUBEXP))\n\t{\n\t branch = parse_branch (regexp, preg, token, syntax, nest, err);\n\t if (BE (*err != REG_NOERROR && branch == NULL, 0))\n\t {\n\t if (tree != NULL)\n\t\tpostorder (tree, free_tree, NULL);\n\t return NULL;\n\t }\n\t}\n else\n\tbranch = NULL;\n tree = create_tree (dfa, tree, branch, OP_ALT);\n if (BE (tree == NULL, 0))\n\t{\n\t *err = REG_ESPACE;\n\t return NULL;\n\t}\n }\n return tree;\n}", "project": "gnulib", "hash": 273676495705910113330018924005947558068, "size": 34, "commit_id": "5513b40999149090987a0341c018d05d3eea1272", "message": "Diagnose ERE '()|\\1'\n\nProblem reported by Hanno B\u00f6ck in: http://bugs.gnu.org/21513\n* lib/regcomp.c (parse_reg_exp): While parsing alternatives, keep\ntrack of the set of previously-completed subexpressions available\nbefore the first alternative, and restore this set just before\nparsing each subsequent alternative. This lets us diagnose the\ninvalid back-reference in the ERE '()|\\1'.", "target": 1, "dataset": "other", "idx": 198942} {"func": "parse_reg_exp (re_string_t *regexp, regex_t *preg, re_token_t *token,\n\t reg_syntax_t syntax, Idx nest, reg_errcode_t *err)\n{\n re_dfa_t *dfa = preg->buffer;\n bin_tree_t *tree, *branch = NULL;\n bitset_word_t initial_bkref_map = dfa->completed_bkref_map;\n tree = parse_branch (regexp, preg, token, syntax, nest, err);\n if (BE (*err != REG_NOERROR && tree == NULL, 0))\n return NULL;\n\n while (token->type == OP_ALT)\n {\n fetch_token (token, regexp, syntax | RE_CARET_ANCHORS_HERE);\n if (token->type != OP_ALT && token->type != END_OF_RE\n\t && (nest == 0 || token->type != OP_CLOSE_SUBEXP))\n\t{\n\t bitset_word_t accumulated_bkref_map = dfa->completed_bkref_map;\n\t dfa->completed_bkref_map = initial_bkref_map;\n\t branch = parse_branch (regexp, preg, token, syntax, nest, err);\n\t if (BE (*err != REG_NOERROR && branch == NULL, 0))\n\t {\n\t if (tree != NULL)\n\t\tpostorder (tree, free_tree, NULL);\n\t return NULL;\n\t }\n\t dfa->completed_bkref_map |= accumulated_bkref_map;\n\t}\n else\n\tbranch = NULL;\n tree = create_tree (dfa, tree, branch, OP_ALT);\n if (BE (tree == NULL, 0))\n\t{\n\t *err = REG_ESPACE;\n\t return NULL;\n\t}\n }\n return tree;\n}", "project": "gnulib", "hash": 313711019416566665334745674532461859910, "size": 38, "commit_id": "5513b40999149090987a0341c018d05d3eea1272", "message": "Diagnose ERE '()|\\1'\n\nProblem reported by Hanno B\u00f6ck in: http://bugs.gnu.org/21513\n* lib/regcomp.c (parse_reg_exp): While parsing alternatives, keep\ntrack of the set of previously-completed subexpressions available\nbefore the first alternative, and restore this set just before\nparsing each subsequent alternative. This lets us diagnose the\ninvalid back-reference in the ERE '()|\\1'.", "target": 0, "dataset": "other", "idx": 285543} {"func": "xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)\n{\n\txmlParserCtxtPtr ctxt = NULL;\n\txmlDocPtr ret;\n\tzend_bool old_allow_url_fopen;\n\n/*\n\txmlInitParser();\n*/\n\n\told_allow_url_fopen = PG(allow_url_fopen);\n\tPG(allow_url_fopen) = 1;\n\tctxt = xmlCreateFileParserCtxt(filename);\n\tPG(allow_url_fopen) = old_allow_url_fopen;\n\tif (ctxt) {\n\t\tzend_bool old;\n\n\t\tctxt->keepBlanks = 0;\n\t\tctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;\n\t\tctxt->sax->comment = soap_Comment;\n\t\tctxt->sax->warning = NULL;\n\t\tctxt->sax->error = NULL;\n\t\t/*ctxt->sax->fatalError = NULL;*/\n\t\told = php_libxml_disable_entity_loader(1);\n\t\txmlParseDocument(ctxt);\n\t\tphp_libxml_disable_entity_loader(old);\n\t\tif (ctxt->wellFormed) {\n\t\t\tret = ctxt->myDoc;\n\t\t\tif (ret->URL == NULL && ctxt->directory != NULL) {\n\t\t\t\tret->URL = xmlCharStrdup(ctxt->directory);\n\t\t\t}\n\t\t} else {\n\t\t\tret = NULL;\n\t\t\txmlFreeDoc(ctxt->myDoc);\n\t\t\tctxt->myDoc = NULL;\n\t\t}\n\t\txmlFreeParserCtxt(ctxt);\n\t} else {\n\t\tret = NULL;\n\t}\n\n/*\n\txmlCleanupParser();\n*/\n\n\tif (ret) {\n\t\tcleanup_xml_node((xmlNodePtr)ret);\n\t}\n\treturn ret;\n}", "project": "php-src", "hash": 149172573949708914156035129804477784284, "size": 50, "commit_id": "fcd4b5335a6df4e0676ee32e2267ca71d70fe623", "message": "Fix TSRM (after afc1debb)", "target": 1, "dataset": "other", "idx": 198943} {"func": "xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)\n{\n\txmlParserCtxtPtr ctxt = NULL;\n\txmlDocPtr ret;\n\tzend_bool old_allow_url_fopen;\n\n/*\n\txmlInitParser();\n*/\n\n\told_allow_url_fopen = PG(allow_url_fopen);\n\tPG(allow_url_fopen) = 1;\n\tctxt = xmlCreateFileParserCtxt(filename);\n\tPG(allow_url_fopen) = old_allow_url_fopen;\n\tif (ctxt) {\n\t\tzend_bool old;\n\n\t\tctxt->keepBlanks = 0;\n\t\tctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;\n\t\tctxt->sax->comment = soap_Comment;\n\t\tctxt->sax->warning = NULL;\n\t\tctxt->sax->error = NULL;\n\t\t/*ctxt->sax->fatalError = NULL;*/\n\t\told = php_libxml_disable_entity_loader(1 TSRMLS_CC);\n\t\txmlParseDocument(ctxt);\n\t\tphp_libxml_disable_entity_loader(old TSRMLS_CC);\n\t\tif (ctxt->wellFormed) {\n\t\t\tret = ctxt->myDoc;\n\t\t\tif (ret->URL == NULL && ctxt->directory != NULL) {\n\t\t\t\tret->URL = xmlCharStrdup(ctxt->directory);\n\t\t\t}\n\t\t} else {\n\t\t\tret = NULL;\n\t\t\txmlFreeDoc(ctxt->myDoc);\n\t\t\tctxt->myDoc = NULL;\n\t\t}\n\t\txmlFreeParserCtxt(ctxt);\n\t} else {\n\t\tret = NULL;\n\t}\n\n/*\n\txmlCleanupParser();\n*/\n\n\tif (ret) {\n\t\tcleanup_xml_node((xmlNodePtr)ret);\n\t}\n\treturn ret;\n}", "project": "php-src", "hash": 81104495453836081457129860350581051957, "size": 50, "commit_id": "fcd4b5335a6df4e0676ee32e2267ca71d70fe623", "message": "Fix TSRM (after afc1debb)", "target": 0, "dataset": "other", "idx": 285598} {"func": "xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)\n{\n\txmlParserCtxtPtr ctxt = NULL;\n\txmlDocPtr ret;\n\n/*\n\txmlInitParser();\n*/\n\tctxt = xmlCreateMemoryParserCtxt(buf, buf_size);\n\tif (ctxt) {\n\t\tzend_bool old;\n\n\t\tctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;\n\t\tctxt->sax->comment = soap_Comment;\n\t\tctxt->sax->warning = NULL;\n\t\tctxt->sax->error = NULL;\n\t\t/*ctxt->sax->fatalError = NULL;*/\n#if LIBXML_VERSION >= 20703\n\t\tctxt->options |= XML_PARSE_HUGE;\n#endif\n\t\told = php_libxml_disable_entity_loader(1);\n\t\txmlParseDocument(ctxt);\n\t\tphp_libxml_disable_entity_loader(old);\n\t\tif (ctxt->wellFormed) {\n\t\t\tret = ctxt->myDoc;\n\t\t\tif (ret->URL == NULL && ctxt->directory != NULL) {\n\t\t\t\tret->URL = xmlCharStrdup(ctxt->directory);\n\t\t\t}\n\t\t} else {\n\t\t\tret = NULL;\n\t\t\txmlFreeDoc(ctxt->myDoc);\n\t\t\tctxt->myDoc = NULL;\n\t\t}\n\t\txmlFreeParserCtxt(ctxt);\n\t} else {\n\t\tret = NULL;\n\t}\n\n/*\n\txmlCleanupParser();\n*/\n\n/*\n\tif (ret) {\n\t\tcleanup_xml_node((xmlNodePtr)ret);\n\t}\n*/\n\treturn ret;\n}", "project": "php-src", "hash": 134084765210679426355834754154630655990, "size": 49, "commit_id": "fcd4b5335a6df4e0676ee32e2267ca71d70fe623", "message": "Fix TSRM (after afc1debb)", "target": 1, "dataset": "other", "idx": 198944} {"func": "xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)\n{\n\txmlParserCtxtPtr ctxt = NULL;\n\txmlDocPtr ret;\n\n\tTSRMLS_FETCH();\n\n/*\n\txmlInitParser();\n*/\n\tctxt = xmlCreateMemoryParserCtxt(buf, buf_size);\n\tif (ctxt) {\n\t\tzend_bool old;\n\n\t\tctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;\n\t\tctxt->sax->comment = soap_Comment;\n\t\tctxt->sax->warning = NULL;\n\t\tctxt->sax->error = NULL;\n\t\t/*ctxt->sax->fatalError = NULL;*/\n#if LIBXML_VERSION >= 20703\n\t\tctxt->options |= XML_PARSE_HUGE;\n#endif\n\t\told = php_libxml_disable_entity_loader(1 TSRMLS_CC);\n\t\txmlParseDocument(ctxt);\n\t\tphp_libxml_disable_entity_loader(old TSRMLS_CC);\n\t\tif (ctxt->wellFormed) {\n\t\t\tret = ctxt->myDoc;\n\t\t\tif (ret->URL == NULL && ctxt->directory != NULL) {\n\t\t\t\tret->URL = xmlCharStrdup(ctxt->directory);\n\t\t\t}\n\t\t} else {\n\t\t\tret = NULL;\n\t\t\txmlFreeDoc(ctxt->myDoc);\n\t\t\tctxt->myDoc = NULL;\n\t\t}\n\t\txmlFreeParserCtxt(ctxt);\n\t} else {\n\t\tret = NULL;\n\t}\n\n/*\n\txmlCleanupParser();\n*/\n\n/*\n\tif (ret) {\n\t\tcleanup_xml_node((xmlNodePtr)ret);\n\t}\n*/\n\treturn ret;\n}", "project": "php-src", "hash": 101208883108715639540706738822841294770, "size": 51, "commit_id": "fcd4b5335a6df4e0676ee32e2267ca71d70fe623", "message": "Fix TSRM (after afc1debb)", "target": 0, "dataset": "other", "idx": 285589} {"func": "size_t intsetBlobLen(intset *is) {\n return sizeof(intset)+intrev32ifbe(is->length)*intrev32ifbe(is->encoding);\n}", "project": "redis", "hash": 61618186628749728684651827175100336534, "size": 3, "commit_id": "789f10156009b404950ad717642a9496ed887083", "message": "Fix integer overflow in intset (CVE-2021-29478)\n\nAn integer overflow bug in Redis 6.2 could be exploited to corrupt the heap and\npotentially result with remote code execution.\n\nThe vulnerability involves changing the default set-max-intset-entries\nconfiguration value, creating a large set key that consists of integer values\nand using the COPY command to duplicate it.\n\nThe integer overflow bug exists in all versions of Redis starting with 2.6,\nwhere it could result with a corrupted RDB or DUMP payload, but not exploited\nthrough COPY (which did not exist before 6.2).\n\n(cherry picked from commit 29900d4e6bccdf3691bedf0ea9a5d84863fa3592)", "target": 1, "dataset": "other", "idx": 199227} {"func": "size_t intsetBlobLen(intset *is) {\n return sizeof(intset)+(size_t)intrev32ifbe(is->length)*intrev32ifbe(is->encoding);\n}", "project": "redis", "hash": 270360219559243121696705431487155837807, "size": 3, "commit_id": "789f10156009b404950ad717642a9496ed887083", "message": "Fix integer overflow in intset (CVE-2021-29478)\n\nAn integer overflow bug in Redis 6.2 could be exploited to corrupt the heap and\npotentially result with remote code execution.\n\nThe vulnerability involves changing the default set-max-intset-entries\nconfiguration value, creating a large set key that consists of integer values\nand using the COPY command to duplicate it.\n\nThe integer overflow bug exists in all versions of Redis starting with 2.6,\nwhere it could result with a corrupted RDB or DUMP payload, but not exploited\nthrough COPY (which did not exist before 6.2).\n\n(cherry picked from commit 29900d4e6bccdf3691bedf0ea9a5d84863fa3592)", "target": 0, "dataset": "other", "idx": 290629} {"func": "static int php_openssl_validate_iv(char **piv, size_t *piv_len, size_t iv_required_len,\n\t\tzend_bool *free_iv, EVP_CIPHER_CTX *cipher_ctx, struct php_openssl_cipher_mode *mode) /* {{{ */\n{\n\tchar *iv_new;\n\n\t/* Best case scenario, user behaved */\n\tif (*piv_len == iv_required_len) {\n\t\treturn SUCCESS;\n\t}\n\n\tif (mode->is_aead) {\n\t\tif (EVP_CIPHER_CTX_ctrl(cipher_ctx, mode->aead_ivlen_flag, *piv_len, NULL) != 1) {\n\t\t\tphp_error_docref(NULL, E_WARNING, \"Setting of IV length for AEAD mode failed\");\n\t\t\treturn FAILURE;\n\t\t}\n\t\treturn SUCCESS;\n\t}\n\n\tiv_new = ecalloc(1, iv_required_len + 1);\n\n\tif (*piv_len == 0) {\n\t\t/* BC behavior */\n\t\t*piv_len = iv_required_len;\n\t\t*piv = iv_new;\n\t\t*free_iv = 1;\n\t\treturn SUCCESS;\n\n\t}\n\n\tif (*piv_len < iv_required_len) {\n\t\tphp_error_docref(NULL, E_WARNING,\n\t\t\t\t\"IV passed is only %zd bytes long, cipher expects an IV of precisely %zd bytes, padding with \\\\0\",\n\t\t\t\t*piv_len, iv_required_len);\n\t\tmemcpy(iv_new, *piv, *piv_len);\n\t\t*piv_len = iv_required_len;\n\t\t*piv = iv_new;\n\t\t*free_iv = 1;\n\t\treturn SUCCESS;\n\t}\n\n\tphp_error_docref(NULL, E_WARNING,\n\t\t\t\"IV passed is %zd bytes long which is longer than the %zd expected by selected cipher, truncating\",\n\t\t\t*piv_len, iv_required_len);\n\tmemcpy(iv_new, *piv, iv_required_len);\n\t*piv_len = iv_required_len;\n\t*piv = iv_new;\n\t*free_iv = 1;\n\treturn SUCCESS;\n\n}", "project": "php-src", "hash": 232840072465422852413169490519972262918, "size": 50, "commit_id": "0216630ea2815a5789a24279a1211ac398d4de79", "message": "Fix bug #79601 (Wrong ciphertext/tag in AES-CCM encryption for a 12 bytes IV)", "target": 1, "dataset": "other", "idx": 199700} {"func": "static int php_openssl_validate_iv(char **piv, size_t *piv_len, size_t iv_required_len,\n\t\tzend_bool *free_iv, EVP_CIPHER_CTX *cipher_ctx, struct php_openssl_cipher_mode *mode) /* {{{ */\n{\n\tchar *iv_new;\n\n\tif (mode->is_aead) {\n\t\tif (EVP_CIPHER_CTX_ctrl(cipher_ctx, mode->aead_ivlen_flag, *piv_len, NULL) != 1) {\n\t\t\tphp_error_docref(NULL, E_WARNING, \"Setting of IV length for AEAD mode failed\");\n\t\t\treturn FAILURE;\n\t\t}\n\t\treturn SUCCESS;\n\t}\n\n\t/* Best case scenario, user behaved */\n\tif (*piv_len == iv_required_len) {\n\t\treturn SUCCESS;\n\t}\n\n\tiv_new = ecalloc(1, iv_required_len + 1);\n\n\tif (*piv_len == 0) {\n\t\t/* BC behavior */\n\t\t*piv_len = iv_required_len;\n\t\t*piv = iv_new;\n\t\t*free_iv = 1;\n\t\treturn SUCCESS;\n\n\t}\n\n\tif (*piv_len < iv_required_len) {\n\t\tphp_error_docref(NULL, E_WARNING,\n\t\t\t\t\"IV passed is only %zd bytes long, cipher expects an IV of precisely %zd bytes, padding with \\\\0\",\n\t\t\t\t*piv_len, iv_required_len);\n\t\tmemcpy(iv_new, *piv, *piv_len);\n\t\t*piv_len = iv_required_len;\n\t\t*piv = iv_new;\n\t\t*free_iv = 1;\n\t\treturn SUCCESS;\n\t}\n\n\tphp_error_docref(NULL, E_WARNING,\n\t\t\t\"IV passed is %zd bytes long which is longer than the %zd expected by selected cipher, truncating\",\n\t\t\t*piv_len, iv_required_len);\n\tmemcpy(iv_new, *piv, iv_required_len);\n\t*piv_len = iv_required_len;\n\t*piv = iv_new;\n\t*free_iv = 1;\n\treturn SUCCESS;\n\n}", "project": "php-src", "hash": 248839184558979669461751117706652524696, "size": 50, "commit_id": "0216630ea2815a5789a24279a1211ac398d4de79", "message": "Fix bug #79601 (Wrong ciphertext/tag in AES-CCM encryption for a 12 bytes IV)", "target": 0, "dataset": "other", "idx": 291448} {"func": "static __latent_entropy struct task_struct *copy_process(\n\t\t\t\t\tstruct pid *pid,\n\t\t\t\t\tint trace,\n\t\t\t\t\tint node,\n\t\t\t\t\tstruct kernel_clone_args *args)\n{\n\tint pidfd = -1, retval;\n\tstruct task_struct *p;\n\tstruct multiprocess_signals delayed;\n\tstruct file *pidfile = NULL;\n\tu64 clone_flags = args->flags;\n\tstruct nsproxy *nsp = current->nsproxy;\n\n\t/*\n\t * Don't allow sharing the root directory with processes in a different\n\t * namespace\n\t */\n\tif ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))\n\t\treturn ERR_PTR(-EINVAL);\n\n\tif ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * Thread groups must share signals as well, and detached threads\n\t * can only be started up within the thread group.\n\t */\n\tif ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * Shared signal handlers imply shared VM. By way of the above,\n\t * thread groups also imply shared VM. Blocking this case allows\n\t * for various simplifications in other code.\n\t */\n\tif ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * Siblings of global init remain as zombies on exit since they are\n\t * not reaped by their parent (swapper). To solve this and to avoid\n\t * multi-rooted process trees, prevent global and container-inits\n\t * from creating siblings.\n\t */\n\tif ((clone_flags & CLONE_PARENT) &&\n\t\t\t\tcurrent->signal->flags & SIGNAL_UNKILLABLE)\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * If the new process will be in a different pid or user namespace\n\t * do not allow it to share a thread group with the forking task.\n\t */\n\tif (clone_flags & CLONE_THREAD) {\n\t\tif ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||\n\t\t (task_active_pid_ns(current) != nsp->pid_ns_for_children))\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\t/*\n\t * If the new process will be in a different time namespace\n\t * do not allow it to share VM or a thread group with the forking task.\n\t */\n\tif (clone_flags & (CLONE_THREAD | CLONE_VM)) {\n\t\tif (nsp->time_ns != nsp->time_ns_for_children)\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\tif (clone_flags & CLONE_PIDFD) {\n\t\t/*\n\t\t * - CLONE_DETACHED is blocked so that we can potentially\n\t\t * reuse it later for CLONE_PIDFD.\n\t\t * - CLONE_THREAD is blocked until someone really needs it.\n\t\t */\n\t\tif (clone_flags & (CLONE_DETACHED | CLONE_THREAD))\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\t/*\n\t * Force any signals received before this point to be delivered\n\t * before the fork happens. Collect up signals sent to multiple\n\t * processes that happen during the fork and delay them so that\n\t * they appear to happen after the fork.\n\t */\n\tsigemptyset(&delayed.signal);\n\tINIT_HLIST_NODE(&delayed.node);\n\n\tspin_lock_irq(¤t->sighand->siglock);\n\tif (!(clone_flags & CLONE_THREAD))\n\t\thlist_add_head(&delayed.node, ¤t->signal->multiprocess);\n\trecalc_sigpending();\n\tspin_unlock_irq(¤t->sighand->siglock);\n\tretval = -ERESTARTNOINTR;\n\tif (signal_pending(current))\n\t\tgoto fork_out;\n\n\tretval = -ENOMEM;\n\tp = dup_task_struct(current, node);\n\tif (!p)\n\t\tgoto fork_out;\n\n\t/*\n\t * This _must_ happen before we call free_task(), i.e. before we jump\n\t * to any of the bad_fork_* labels. This is to avoid freeing\n\t * p->set_child_tid which is (ab)used as a kthread's data pointer for\n\t * kernel threads (PF_KTHREAD).\n\t */\n\tp->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;\n\t/*\n\t * Clear TID on mm_release()?\n\t */\n\tp->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;\n\n\tftrace_graph_init_task(p);\n\n\trt_mutex_init_task(p);\n\n\tlockdep_assert_irqs_enabled();\n#ifdef CONFIG_PROVE_LOCKING\n\tDEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);\n#endif\n\tretval = -EAGAIN;\n\tif (atomic_read(&p->real_cred->user->processes) >=\n\t\t\ttask_rlimit(p, RLIMIT_NPROC)) {\n\t\tif (p->real_cred->user != INIT_USER &&\n\t\t !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))\n\t\t\tgoto bad_fork_free;\n\t}\n\tcurrent->flags &= ~PF_NPROC_EXCEEDED;\n\n\tretval = copy_creds(p, clone_flags);\n\tif (retval < 0)\n\t\tgoto bad_fork_free;\n\n\t/*\n\t * If multiple threads are within copy_process(), then this check\n\t * triggers too late. This doesn't hurt, the check is only there\n\t * to stop root fork bombs.\n\t */\n\tretval = -EAGAIN;\n\tif (data_race(nr_threads >= max_threads))\n\t\tgoto bad_fork_cleanup_count;\n\n\tdelayacct_tsk_init(p);\t/* Must remain after dup_task_struct() */\n\tp->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);\n\tp->flags |= PF_FORKNOEXEC;\n\tINIT_LIST_HEAD(&p->children);\n\tINIT_LIST_HEAD(&p->sibling);\n\trcu_copy_process(p);\n\tp->vfork_done = NULL;\n\tspin_lock_init(&p->alloc_lock);\n\n\tinit_sigpending(&p->pending);\n\n\tp->utime = p->stime = p->gtime = 0;\n#ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME\n\tp->utimescaled = p->stimescaled = 0;\n#endif\n\tprev_cputime_init(&p->prev_cputime);\n\n#ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN\n\tseqcount_init(&p->vtime.seqcount);\n\tp->vtime.starttime = 0;\n\tp->vtime.state = VTIME_INACTIVE;\n#endif\n\n#ifdef CONFIG_IO_URING\n\tp->io_uring = NULL;\n#endif\n\n#if defined(SPLIT_RSS_COUNTING)\n\tmemset(&p->rss_stat, 0, sizeof(p->rss_stat));\n#endif\n\n\tp->default_timer_slack_ns = current->timer_slack_ns;\n\n#ifdef CONFIG_PSI\n\tp->psi_flags = 0;\n#endif\n\n\ttask_io_accounting_init(&p->ioac);\n\tacct_clear_integrals(p);\n\n\tposix_cputimers_init(&p->posix_cputimers);\n\n\tp->io_context = NULL;\n\taudit_set_context(p, NULL);\n\tcgroup_fork(p);\n#ifdef CONFIG_NUMA\n\tp->mempolicy = mpol_dup(p->mempolicy);\n\tif (IS_ERR(p->mempolicy)) {\n\t\tretval = PTR_ERR(p->mempolicy);\n\t\tp->mempolicy = NULL;\n\t\tgoto bad_fork_cleanup_threadgroup_lock;\n\t}\n#endif\n#ifdef CONFIG_CPUSETS\n\tp->cpuset_mem_spread_rotor = NUMA_NO_NODE;\n\tp->cpuset_slab_spread_rotor = NUMA_NO_NODE;\n\tseqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);\n#endif\n#ifdef CONFIG_TRACE_IRQFLAGS\n\tmemset(&p->irqtrace, 0, sizeof(p->irqtrace));\n\tp->irqtrace.hardirq_disable_ip\t= _THIS_IP_;\n\tp->irqtrace.softirq_enable_ip\t= _THIS_IP_;\n\tp->softirqs_enabled\t\t= 1;\n\tp->softirq_context\t\t= 0;\n#endif\n\n\tp->pagefault_disabled = 0;\n\n#ifdef CONFIG_LOCKDEP\n\tlockdep_init_task(p);\n#endif\n\n#ifdef CONFIG_DEBUG_MUTEXES\n\tp->blocked_on = NULL; /* not blocked yet */\n#endif\n#ifdef CONFIG_BCACHE\n\tp->sequential_io\t= 0;\n\tp->sequential_io_avg\t= 0;\n#endif\n\n\t/* Perform scheduler related setup. Assign this task to a CPU. */\n\tretval = sched_fork(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_policy;\n\n\tretval = perf_event_init_task(p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_policy;\n\tretval = audit_alloc(p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_perf;\n\t/* copy all the process information */\n\tshm_init_task(p);\n\tretval = security_task_alloc(p, clone_flags);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_audit;\n\tretval = copy_semundo(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_security;\n\tretval = copy_files(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_semundo;\n\tretval = copy_fs(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_files;\n\tretval = copy_sighand(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_fs;\n\tretval = copy_signal(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_sighand;\n\tretval = copy_mm(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_signal;\n\tretval = copy_namespaces(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_mm;\n\tretval = copy_io(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_namespaces;\n\tretval = copy_thread(clone_flags, args->stack, args->stack_size, p, args->tls);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_io;\n\n\tstackleak_task_init(p);\n\n\tif (pid != &init_struct_pid) {\n\t\tpid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,\n\t\t\t\targs->set_tid_size);\n\t\tif (IS_ERR(pid)) {\n\t\t\tretval = PTR_ERR(pid);\n\t\t\tgoto bad_fork_cleanup_thread;\n\t\t}\n\t}\n\n\t/*\n\t * This has to happen after we've potentially unshared the file\n\t * descriptor table (so that the pidfd doesn't leak into the child\n\t * if the fd table isn't shared).\n\t */\n\tif (clone_flags & CLONE_PIDFD) {\n\t\tretval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);\n\t\tif (retval < 0)\n\t\t\tgoto bad_fork_free_pid;\n\n\t\tpidfd = retval;\n\n\t\tpidfile = anon_inode_getfile(\"[pidfd]\", &pidfd_fops, pid,\n\t\t\t\t\t O_RDWR | O_CLOEXEC);\n\t\tif (IS_ERR(pidfile)) {\n\t\t\tput_unused_fd(pidfd);\n\t\t\tretval = PTR_ERR(pidfile);\n\t\t\tgoto bad_fork_free_pid;\n\t\t}\n\t\tget_pid(pid);\t/* held by pidfile now */\n\n\t\tretval = put_user(pidfd, args->pidfd);\n\t\tif (retval)\n\t\t\tgoto bad_fork_put_pidfd;\n\t}\n\n#ifdef CONFIG_BLOCK\n\tp->plug = NULL;\n#endif\n\tfutex_init_task(p);\n\n\t/*\n\t * sigaltstack should be cleared when sharing the same VM\n\t */\n\tif ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)\n\t\tsas_ss_reset(p);\n\n\t/*\n\t * Syscall tracing and stepping should be turned off in the\n\t * child regardless of CLONE_PTRACE.\n\t */\n\tuser_disable_single_step(p);\n\tclear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);\n#ifdef TIF_SYSCALL_EMU\n\tclear_tsk_thread_flag(p, TIF_SYSCALL_EMU);\n#endif\n\tclear_tsk_latency_tracing(p);\n\n\t/* ok, now we should be set up.. */\n\tp->pid = pid_nr(pid);\n\tif (clone_flags & CLONE_THREAD) {\n\t\tp->exit_signal = -1;\n\t\tp->group_leader = current->group_leader;\n\t\tp->tgid = current->tgid;\n\t} else {\n\t\tif (clone_flags & CLONE_PARENT)\n\t\t\tp->exit_signal = current->group_leader->exit_signal;\n\t\telse\n\t\t\tp->exit_signal = args->exit_signal;\n\t\tp->group_leader = p;\n\t\tp->tgid = p->pid;\n\t}\n\n\tp->nr_dirtied = 0;\n\tp->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);\n\tp->dirty_paused_when = 0;\n\n\tp->pdeath_signal = 0;\n\tINIT_LIST_HEAD(&p->thread_group);\n\tp->task_works = NULL;\n\n\t/*\n\t * Ensure that the cgroup subsystem policies allow the new process to be\n\t * forked. It should be noted that the new process's css_set can be changed\n\t * between here and cgroup_post_fork() if an organisation operation is in\n\t * progress.\n\t */\n\tretval = cgroup_can_fork(p, args);\n\tif (retval)\n\t\tgoto bad_fork_put_pidfd;\n\n\t/*\n\t * From this point on we must avoid any synchronous user-space\n\t * communication until we take the tasklist-lock. In particular, we do\n\t * not want user-space to be able to predict the process start-time by\n\t * stalling fork(2) after we recorded the start_time but before it is\n\t * visible to the system.\n\t */\n\n\tp->start_time = ktime_get_ns();\n\tp->start_boottime = ktime_get_boottime_ns();\n\n\t/*\n\t * Make it visible to the rest of the system, but dont wake it up yet.\n\t * Need tasklist lock for parent etc handling!\n\t */\n\twrite_lock_irq(&tasklist_lock);\n\n\t/* CLONE_PARENT re-uses the old parent */\n\tif (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {\n\t\tp->real_parent = current->real_parent;\n\t\tp->parent_exec_id = current->parent_exec_id;\n\t} else {\n\t\tp->real_parent = current;\n\t\tp->parent_exec_id = current->self_exec_id;\n\t}\n\n\tklp_copy_process(p);\n\n\tspin_lock(¤t->sighand->siglock);\n\n\t/*\n\t * Copy seccomp details explicitly here, in case they were changed\n\t * before holding sighand lock.\n\t */\n\tcopy_seccomp(p);\n\n\trseq_fork(p, clone_flags);\n\n\t/* Don't start children in a dying pid namespace */\n\tif (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {\n\t\tretval = -ENOMEM;\n\t\tgoto bad_fork_cancel_cgroup;\n\t}\n\n\t/* Let kill terminate clone/fork in the middle */\n\tif (fatal_signal_pending(current)) {\n\t\tretval = -EINTR;\n\t\tgoto bad_fork_cancel_cgroup;\n\t}\n\n\t/* past the last point of failure */\n\tif (pidfile)\n\t\tfd_install(pidfd, pidfile);\n\n\tinit_task_pid_links(p);\n\tif (likely(p->pid)) {\n\t\tptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);\n\n\t\tinit_task_pid(p, PIDTYPE_PID, pid);\n\t\tif (thread_group_leader(p)) {\n\t\t\tinit_task_pid(p, PIDTYPE_TGID, pid);\n\t\t\tinit_task_pid(p, PIDTYPE_PGID, task_pgrp(current));\n\t\t\tinit_task_pid(p, PIDTYPE_SID, task_session(current));\n\n\t\t\tif (is_child_reaper(pid)) {\n\t\t\t\tns_of_pid(pid)->child_reaper = p;\n\t\t\t\tp->signal->flags |= SIGNAL_UNKILLABLE;\n\t\t\t}\n\t\t\tp->signal->shared_pending.signal = delayed.signal;\n\t\t\tp->signal->tty = tty_kref_get(current->signal->tty);\n\t\t\t/*\n\t\t\t * Inherit has_child_subreaper flag under the same\n\t\t\t * tasklist_lock with adding child to the process tree\n\t\t\t * for propagate_has_child_subreaper optimization.\n\t\t\t */\n\t\t\tp->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||\n\t\t\t\t\t\t\t p->real_parent->signal->is_child_subreaper;\n\t\t\tlist_add_tail(&p->sibling, &p->real_parent->children);\n\t\t\tlist_add_tail_rcu(&p->tasks, &init_task.tasks);\n\t\t\tattach_pid(p, PIDTYPE_TGID);\n\t\t\tattach_pid(p, PIDTYPE_PGID);\n\t\t\tattach_pid(p, PIDTYPE_SID);\n\t\t\t__this_cpu_inc(process_counts);\n\t\t} else {\n\t\t\tcurrent->signal->nr_threads++;\n\t\t\tatomic_inc(¤t->signal->live);\n\t\t\trefcount_inc(¤t->signal->sigcnt);\n\t\t\ttask_join_group_stop(p);\n\t\t\tlist_add_tail_rcu(&p->thread_group,\n\t\t\t\t\t &p->group_leader->thread_group);\n\t\t\tlist_add_tail_rcu(&p->thread_node,\n\t\t\t\t\t &p->signal->thread_head);\n\t\t}\n\t\tattach_pid(p, PIDTYPE_PID);\n\t\tnr_threads++;\n\t}\n\ttotal_forks++;\n\thlist_del_init(&delayed.node);\n\tspin_unlock(¤t->sighand->siglock);\n\tsyscall_tracepoint_update(p);\n\twrite_unlock_irq(&tasklist_lock);\n\n\tproc_fork_connector(p);\n\tsched_post_fork(p);\n\tcgroup_post_fork(p, args);\n\tperf_event_fork(p);\n\n\ttrace_task_newtask(p, clone_flags);\n\tuprobe_copy_process(p, clone_flags);\n\n\tcopy_oom_score_adj(clone_flags, p);\n\n\treturn p;\n\nbad_fork_cancel_cgroup:\n\tspin_unlock(¤t->sighand->siglock);\n\twrite_unlock_irq(&tasklist_lock);\n\tcgroup_cancel_fork(p, args);\nbad_fork_put_pidfd:\n\tif (clone_flags & CLONE_PIDFD) {\n\t\tfput(pidfile);\n\t\tput_unused_fd(pidfd);\n\t}\nbad_fork_free_pid:\n\tif (pid != &init_struct_pid)\n\t\tfree_pid(pid);\nbad_fork_cleanup_thread:\n\texit_thread(p);\nbad_fork_cleanup_io:\n\tif (p->io_context)\n\t\texit_io_context(p);\nbad_fork_cleanup_namespaces:\n\texit_task_namespaces(p);\nbad_fork_cleanup_mm:\n\tif (p->mm) {\n\t\tmm_clear_owner(p->mm, p);\n\t\tmmput(p->mm);\n\t}\nbad_fork_cleanup_signal:\n\tif (!(clone_flags & CLONE_THREAD))\n\t\tfree_signal_struct(p->signal);\nbad_fork_cleanup_sighand:\n\t__cleanup_sighand(p->sighand);\nbad_fork_cleanup_fs:\n\texit_fs(p); /* blocking */\nbad_fork_cleanup_files:\n\texit_files(p); /* blocking */\nbad_fork_cleanup_semundo:\n\texit_sem(p);\nbad_fork_cleanup_security:\n\tsecurity_task_free(p);\nbad_fork_cleanup_audit:\n\taudit_free(p);\nbad_fork_cleanup_perf:\n\tperf_event_free_task(p);\nbad_fork_cleanup_policy:\n\tlockdep_free_task(p);\n#ifdef CONFIG_NUMA\n\tmpol_put(p->mempolicy);\nbad_fork_cleanup_threadgroup_lock:\n#endif\n\tdelayacct_tsk_free(p);\nbad_fork_cleanup_count:\n\tatomic_dec(&p->cred->user->processes);\n\texit_creds(p);\nbad_fork_free:\n\tp->state = TASK_DEAD;\n\tput_task_stack(p);\n\tdelayed_free_task(p);\nfork_out:\n\tspin_lock_irq(¤t->sighand->siglock);\n\thlist_del_init(&delayed.node);\n\tspin_unlock_irq(¤t->sighand->siglock);\n\treturn ERR_PTR(retval);\n}", "project": "linux", "hash": 173143261973963860691601241949264591134, "size": 533, "commit_id": "b4e00444cab4c3f3fec876dc0cccc8cbb0d1a948", "message": "fork: fix copy_process(CLONE_PARENT) race with the exiting ->real_parent\n\ncurrent->group_leader->exit_signal may change during copy_process() if\ncurrent->real_parent exits.\n\nMove the assignment inside tasklist_lock to avoid the race.\n\nSigned-off-by: Eddy Wu \nAcked-by: Oleg Nesterov \nSigned-off-by: Linus Torvalds ", "target": 1, "dataset": "other", "idx": 199840} {"func": "static __latent_entropy struct task_struct *copy_process(\n\t\t\t\t\tstruct pid *pid,\n\t\t\t\t\tint trace,\n\t\t\t\t\tint node,\n\t\t\t\t\tstruct kernel_clone_args *args)\n{\n\tint pidfd = -1, retval;\n\tstruct task_struct *p;\n\tstruct multiprocess_signals delayed;\n\tstruct file *pidfile = NULL;\n\tu64 clone_flags = args->flags;\n\tstruct nsproxy *nsp = current->nsproxy;\n\n\t/*\n\t * Don't allow sharing the root directory with processes in a different\n\t * namespace\n\t */\n\tif ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))\n\t\treturn ERR_PTR(-EINVAL);\n\n\tif ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * Thread groups must share signals as well, and detached threads\n\t * can only be started up within the thread group.\n\t */\n\tif ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * Shared signal handlers imply shared VM. By way of the above,\n\t * thread groups also imply shared VM. Blocking this case allows\n\t * for various simplifications in other code.\n\t */\n\tif ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * Siblings of global init remain as zombies on exit since they are\n\t * not reaped by their parent (swapper). To solve this and to avoid\n\t * multi-rooted process trees, prevent global and container-inits\n\t * from creating siblings.\n\t */\n\tif ((clone_flags & CLONE_PARENT) &&\n\t\t\t\tcurrent->signal->flags & SIGNAL_UNKILLABLE)\n\t\treturn ERR_PTR(-EINVAL);\n\n\t/*\n\t * If the new process will be in a different pid or user namespace\n\t * do not allow it to share a thread group with the forking task.\n\t */\n\tif (clone_flags & CLONE_THREAD) {\n\t\tif ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||\n\t\t (task_active_pid_ns(current) != nsp->pid_ns_for_children))\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\t/*\n\t * If the new process will be in a different time namespace\n\t * do not allow it to share VM or a thread group with the forking task.\n\t */\n\tif (clone_flags & (CLONE_THREAD | CLONE_VM)) {\n\t\tif (nsp->time_ns != nsp->time_ns_for_children)\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\tif (clone_flags & CLONE_PIDFD) {\n\t\t/*\n\t\t * - CLONE_DETACHED is blocked so that we can potentially\n\t\t * reuse it later for CLONE_PIDFD.\n\t\t * - CLONE_THREAD is blocked until someone really needs it.\n\t\t */\n\t\tif (clone_flags & (CLONE_DETACHED | CLONE_THREAD))\n\t\t\treturn ERR_PTR(-EINVAL);\n\t}\n\n\t/*\n\t * Force any signals received before this point to be delivered\n\t * before the fork happens. Collect up signals sent to multiple\n\t * processes that happen during the fork and delay them so that\n\t * they appear to happen after the fork.\n\t */\n\tsigemptyset(&delayed.signal);\n\tINIT_HLIST_NODE(&delayed.node);\n\n\tspin_lock_irq(¤t->sighand->siglock);\n\tif (!(clone_flags & CLONE_THREAD))\n\t\thlist_add_head(&delayed.node, ¤t->signal->multiprocess);\n\trecalc_sigpending();\n\tspin_unlock_irq(¤t->sighand->siglock);\n\tretval = -ERESTARTNOINTR;\n\tif (signal_pending(current))\n\t\tgoto fork_out;\n\n\tretval = -ENOMEM;\n\tp = dup_task_struct(current, node);\n\tif (!p)\n\t\tgoto fork_out;\n\n\t/*\n\t * This _must_ happen before we call free_task(), i.e. before we jump\n\t * to any of the bad_fork_* labels. This is to avoid freeing\n\t * p->set_child_tid which is (ab)used as a kthread's data pointer for\n\t * kernel threads (PF_KTHREAD).\n\t */\n\tp->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;\n\t/*\n\t * Clear TID on mm_release()?\n\t */\n\tp->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;\n\n\tftrace_graph_init_task(p);\n\n\trt_mutex_init_task(p);\n\n\tlockdep_assert_irqs_enabled();\n#ifdef CONFIG_PROVE_LOCKING\n\tDEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);\n#endif\n\tretval = -EAGAIN;\n\tif (atomic_read(&p->real_cred->user->processes) >=\n\t\t\ttask_rlimit(p, RLIMIT_NPROC)) {\n\t\tif (p->real_cred->user != INIT_USER &&\n\t\t !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))\n\t\t\tgoto bad_fork_free;\n\t}\n\tcurrent->flags &= ~PF_NPROC_EXCEEDED;\n\n\tretval = copy_creds(p, clone_flags);\n\tif (retval < 0)\n\t\tgoto bad_fork_free;\n\n\t/*\n\t * If multiple threads are within copy_process(), then this check\n\t * triggers too late. This doesn't hurt, the check is only there\n\t * to stop root fork bombs.\n\t */\n\tretval = -EAGAIN;\n\tif (data_race(nr_threads >= max_threads))\n\t\tgoto bad_fork_cleanup_count;\n\n\tdelayacct_tsk_init(p);\t/* Must remain after dup_task_struct() */\n\tp->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);\n\tp->flags |= PF_FORKNOEXEC;\n\tINIT_LIST_HEAD(&p->children);\n\tINIT_LIST_HEAD(&p->sibling);\n\trcu_copy_process(p);\n\tp->vfork_done = NULL;\n\tspin_lock_init(&p->alloc_lock);\n\n\tinit_sigpending(&p->pending);\n\n\tp->utime = p->stime = p->gtime = 0;\n#ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME\n\tp->utimescaled = p->stimescaled = 0;\n#endif\n\tprev_cputime_init(&p->prev_cputime);\n\n#ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN\n\tseqcount_init(&p->vtime.seqcount);\n\tp->vtime.starttime = 0;\n\tp->vtime.state = VTIME_INACTIVE;\n#endif\n\n#ifdef CONFIG_IO_URING\n\tp->io_uring = NULL;\n#endif\n\n#if defined(SPLIT_RSS_COUNTING)\n\tmemset(&p->rss_stat, 0, sizeof(p->rss_stat));\n#endif\n\n\tp->default_timer_slack_ns = current->timer_slack_ns;\n\n#ifdef CONFIG_PSI\n\tp->psi_flags = 0;\n#endif\n\n\ttask_io_accounting_init(&p->ioac);\n\tacct_clear_integrals(p);\n\n\tposix_cputimers_init(&p->posix_cputimers);\n\n\tp->io_context = NULL;\n\taudit_set_context(p, NULL);\n\tcgroup_fork(p);\n#ifdef CONFIG_NUMA\n\tp->mempolicy = mpol_dup(p->mempolicy);\n\tif (IS_ERR(p->mempolicy)) {\n\t\tretval = PTR_ERR(p->mempolicy);\n\t\tp->mempolicy = NULL;\n\t\tgoto bad_fork_cleanup_threadgroup_lock;\n\t}\n#endif\n#ifdef CONFIG_CPUSETS\n\tp->cpuset_mem_spread_rotor = NUMA_NO_NODE;\n\tp->cpuset_slab_spread_rotor = NUMA_NO_NODE;\n\tseqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);\n#endif\n#ifdef CONFIG_TRACE_IRQFLAGS\n\tmemset(&p->irqtrace, 0, sizeof(p->irqtrace));\n\tp->irqtrace.hardirq_disable_ip\t= _THIS_IP_;\n\tp->irqtrace.softirq_enable_ip\t= _THIS_IP_;\n\tp->softirqs_enabled\t\t= 1;\n\tp->softirq_context\t\t= 0;\n#endif\n\n\tp->pagefault_disabled = 0;\n\n#ifdef CONFIG_LOCKDEP\n\tlockdep_init_task(p);\n#endif\n\n#ifdef CONFIG_DEBUG_MUTEXES\n\tp->blocked_on = NULL; /* not blocked yet */\n#endif\n#ifdef CONFIG_BCACHE\n\tp->sequential_io\t= 0;\n\tp->sequential_io_avg\t= 0;\n#endif\n\n\t/* Perform scheduler related setup. Assign this task to a CPU. */\n\tretval = sched_fork(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_policy;\n\n\tretval = perf_event_init_task(p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_policy;\n\tretval = audit_alloc(p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_perf;\n\t/* copy all the process information */\n\tshm_init_task(p);\n\tretval = security_task_alloc(p, clone_flags);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_audit;\n\tretval = copy_semundo(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_security;\n\tretval = copy_files(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_semundo;\n\tretval = copy_fs(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_files;\n\tretval = copy_sighand(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_fs;\n\tretval = copy_signal(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_sighand;\n\tretval = copy_mm(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_signal;\n\tretval = copy_namespaces(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_mm;\n\tretval = copy_io(clone_flags, p);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_namespaces;\n\tretval = copy_thread(clone_flags, args->stack, args->stack_size, p, args->tls);\n\tif (retval)\n\t\tgoto bad_fork_cleanup_io;\n\n\tstackleak_task_init(p);\n\n\tif (pid != &init_struct_pid) {\n\t\tpid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,\n\t\t\t\targs->set_tid_size);\n\t\tif (IS_ERR(pid)) {\n\t\t\tretval = PTR_ERR(pid);\n\t\t\tgoto bad_fork_cleanup_thread;\n\t\t}\n\t}\n\n\t/*\n\t * This has to happen after we've potentially unshared the file\n\t * descriptor table (so that the pidfd doesn't leak into the child\n\t * if the fd table isn't shared).\n\t */\n\tif (clone_flags & CLONE_PIDFD) {\n\t\tretval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);\n\t\tif (retval < 0)\n\t\t\tgoto bad_fork_free_pid;\n\n\t\tpidfd = retval;\n\n\t\tpidfile = anon_inode_getfile(\"[pidfd]\", &pidfd_fops, pid,\n\t\t\t\t\t O_RDWR | O_CLOEXEC);\n\t\tif (IS_ERR(pidfile)) {\n\t\t\tput_unused_fd(pidfd);\n\t\t\tretval = PTR_ERR(pidfile);\n\t\t\tgoto bad_fork_free_pid;\n\t\t}\n\t\tget_pid(pid);\t/* held by pidfile now */\n\n\t\tretval = put_user(pidfd, args->pidfd);\n\t\tif (retval)\n\t\t\tgoto bad_fork_put_pidfd;\n\t}\n\n#ifdef CONFIG_BLOCK\n\tp->plug = NULL;\n#endif\n\tfutex_init_task(p);\n\n\t/*\n\t * sigaltstack should be cleared when sharing the same VM\n\t */\n\tif ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)\n\t\tsas_ss_reset(p);\n\n\t/*\n\t * Syscall tracing and stepping should be turned off in the\n\t * child regardless of CLONE_PTRACE.\n\t */\n\tuser_disable_single_step(p);\n\tclear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);\n#ifdef TIF_SYSCALL_EMU\n\tclear_tsk_thread_flag(p, TIF_SYSCALL_EMU);\n#endif\n\tclear_tsk_latency_tracing(p);\n\n\t/* ok, now we should be set up.. */\n\tp->pid = pid_nr(pid);\n\tif (clone_flags & CLONE_THREAD) {\n\t\tp->group_leader = current->group_leader;\n\t\tp->tgid = current->tgid;\n\t} else {\n\t\tp->group_leader = p;\n\t\tp->tgid = p->pid;\n\t}\n\n\tp->nr_dirtied = 0;\n\tp->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);\n\tp->dirty_paused_when = 0;\n\n\tp->pdeath_signal = 0;\n\tINIT_LIST_HEAD(&p->thread_group);\n\tp->task_works = NULL;\n\n\t/*\n\t * Ensure that the cgroup subsystem policies allow the new process to be\n\t * forked. It should be noted that the new process's css_set can be changed\n\t * between here and cgroup_post_fork() if an organisation operation is in\n\t * progress.\n\t */\n\tretval = cgroup_can_fork(p, args);\n\tif (retval)\n\t\tgoto bad_fork_put_pidfd;\n\n\t/*\n\t * From this point on we must avoid any synchronous user-space\n\t * communication until we take the tasklist-lock. In particular, we do\n\t * not want user-space to be able to predict the process start-time by\n\t * stalling fork(2) after we recorded the start_time but before it is\n\t * visible to the system.\n\t */\n\n\tp->start_time = ktime_get_ns();\n\tp->start_boottime = ktime_get_boottime_ns();\n\n\t/*\n\t * Make it visible to the rest of the system, but dont wake it up yet.\n\t * Need tasklist lock for parent etc handling!\n\t */\n\twrite_lock_irq(&tasklist_lock);\n\n\t/* CLONE_PARENT re-uses the old parent */\n\tif (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {\n\t\tp->real_parent = current->real_parent;\n\t\tp->parent_exec_id = current->parent_exec_id;\n\t\tif (clone_flags & CLONE_THREAD)\n\t\t\tp->exit_signal = -1;\n\t\telse\n\t\t\tp->exit_signal = current->group_leader->exit_signal;\n\t} else {\n\t\tp->real_parent = current;\n\t\tp->parent_exec_id = current->self_exec_id;\n\t\tp->exit_signal = args->exit_signal;\n\t}\n\n\tklp_copy_process(p);\n\n\tspin_lock(¤t->sighand->siglock);\n\n\t/*\n\t * Copy seccomp details explicitly here, in case they were changed\n\t * before holding sighand lock.\n\t */\n\tcopy_seccomp(p);\n\n\trseq_fork(p, clone_flags);\n\n\t/* Don't start children in a dying pid namespace */\n\tif (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {\n\t\tretval = -ENOMEM;\n\t\tgoto bad_fork_cancel_cgroup;\n\t}\n\n\t/* Let kill terminate clone/fork in the middle */\n\tif (fatal_signal_pending(current)) {\n\t\tretval = -EINTR;\n\t\tgoto bad_fork_cancel_cgroup;\n\t}\n\n\t/* past the last point of failure */\n\tif (pidfile)\n\t\tfd_install(pidfd, pidfile);\n\n\tinit_task_pid_links(p);\n\tif (likely(p->pid)) {\n\t\tptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);\n\n\t\tinit_task_pid(p, PIDTYPE_PID, pid);\n\t\tif (thread_group_leader(p)) {\n\t\t\tinit_task_pid(p, PIDTYPE_TGID, pid);\n\t\t\tinit_task_pid(p, PIDTYPE_PGID, task_pgrp(current));\n\t\t\tinit_task_pid(p, PIDTYPE_SID, task_session(current));\n\n\t\t\tif (is_child_reaper(pid)) {\n\t\t\t\tns_of_pid(pid)->child_reaper = p;\n\t\t\t\tp->signal->flags |= SIGNAL_UNKILLABLE;\n\t\t\t}\n\t\t\tp->signal->shared_pending.signal = delayed.signal;\n\t\t\tp->signal->tty = tty_kref_get(current->signal->tty);\n\t\t\t/*\n\t\t\t * Inherit has_child_subreaper flag under the same\n\t\t\t * tasklist_lock with adding child to the process tree\n\t\t\t * for propagate_has_child_subreaper optimization.\n\t\t\t */\n\t\t\tp->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||\n\t\t\t\t\t\t\t p->real_parent->signal->is_child_subreaper;\n\t\t\tlist_add_tail(&p->sibling, &p->real_parent->children);\n\t\t\tlist_add_tail_rcu(&p->tasks, &init_task.tasks);\n\t\t\tattach_pid(p, PIDTYPE_TGID);\n\t\t\tattach_pid(p, PIDTYPE_PGID);\n\t\t\tattach_pid(p, PIDTYPE_SID);\n\t\t\t__this_cpu_inc(process_counts);\n\t\t} else {\n\t\t\tcurrent->signal->nr_threads++;\n\t\t\tatomic_inc(¤t->signal->live);\n\t\t\trefcount_inc(¤t->signal->sigcnt);\n\t\t\ttask_join_group_stop(p);\n\t\t\tlist_add_tail_rcu(&p->thread_group,\n\t\t\t\t\t &p->group_leader->thread_group);\n\t\t\tlist_add_tail_rcu(&p->thread_node,\n\t\t\t\t\t &p->signal->thread_head);\n\t\t}\n\t\tattach_pid(p, PIDTYPE_PID);\n\t\tnr_threads++;\n\t}\n\ttotal_forks++;\n\thlist_del_init(&delayed.node);\n\tspin_unlock(¤t->sighand->siglock);\n\tsyscall_tracepoint_update(p);\n\twrite_unlock_irq(&tasklist_lock);\n\n\tproc_fork_connector(p);\n\tsched_post_fork(p);\n\tcgroup_post_fork(p, args);\n\tperf_event_fork(p);\n\n\ttrace_task_newtask(p, clone_flags);\n\tuprobe_copy_process(p, clone_flags);\n\n\tcopy_oom_score_adj(clone_flags, p);\n\n\treturn p;\n\nbad_fork_cancel_cgroup:\n\tspin_unlock(¤t->sighand->siglock);\n\twrite_unlock_irq(&tasklist_lock);\n\tcgroup_cancel_fork(p, args);\nbad_fork_put_pidfd:\n\tif (clone_flags & CLONE_PIDFD) {\n\t\tfput(pidfile);\n\t\tput_unused_fd(pidfd);\n\t}\nbad_fork_free_pid:\n\tif (pid != &init_struct_pid)\n\t\tfree_pid(pid);\nbad_fork_cleanup_thread:\n\texit_thread(p);\nbad_fork_cleanup_io:\n\tif (p->io_context)\n\t\texit_io_context(p);\nbad_fork_cleanup_namespaces:\n\texit_task_namespaces(p);\nbad_fork_cleanup_mm:\n\tif (p->mm) {\n\t\tmm_clear_owner(p->mm, p);\n\t\tmmput(p->mm);\n\t}\nbad_fork_cleanup_signal:\n\tif (!(clone_flags & CLONE_THREAD))\n\t\tfree_signal_struct(p->signal);\nbad_fork_cleanup_sighand:\n\t__cleanup_sighand(p->sighand);\nbad_fork_cleanup_fs:\n\texit_fs(p); /* blocking */\nbad_fork_cleanup_files:\n\texit_files(p); /* blocking */\nbad_fork_cleanup_semundo:\n\texit_sem(p);\nbad_fork_cleanup_security:\n\tsecurity_task_free(p);\nbad_fork_cleanup_audit:\n\taudit_free(p);\nbad_fork_cleanup_perf:\n\tperf_event_free_task(p);\nbad_fork_cleanup_policy:\n\tlockdep_free_task(p);\n#ifdef CONFIG_NUMA\n\tmpol_put(p->mempolicy);\nbad_fork_cleanup_threadgroup_lock:\n#endif\n\tdelayacct_tsk_free(p);\nbad_fork_cleanup_count:\n\tatomic_dec(&p->cred->user->processes);\n\texit_creds(p);\nbad_fork_free:\n\tp->state = TASK_DEAD;\n\tput_task_stack(p);\n\tdelayed_free_task(p);\nfork_out:\n\tspin_lock_irq(¤t->sighand->siglock);\n\thlist_del_init(&delayed.node);\n\tspin_unlock_irq(¤t->sighand->siglock);\n\treturn ERR_PTR(retval);\n}", "project": "linux", "hash": 308794257608074143275963692734333829208, "size": 533, "commit_id": "b4e00444cab4c3f3fec876dc0cccc8cbb0d1a948", "message": "fork: fix copy_process(CLONE_PARENT) race with the exiting ->real_parent\n\ncurrent->group_leader->exit_signal may change during copy_process() if\ncurrent->real_parent exits.\n\nMove the assignment inside tasklist_lock to avoid the race.\n\nSigned-off-by: Eddy Wu \nAcked-by: Oleg Nesterov \nSigned-off-by: Linus Torvalds ", "target": 0, "dataset": "other", "idx": 293695} {"func": "UINT rdpgfx_read_rect16(wStream* s, RECTANGLE_16* rect16)\n{\n\tif (Stream_GetRemainingLength(s) < 8)\n\t{\n\t\tWLog_ERR(TAG, \"not enough data!\");\n\t\treturn ERROR_INVALID_DATA;\n\t}\n\n\tStream_Read_UINT16(s, rect16->left); /* left (2 bytes) */\n\tStream_Read_UINT16(s, rect16->top); /* top (2 bytes) */\n\tStream_Read_UINT16(s, rect16->right); /* right (2 bytes) */\n\tStream_Read_UINT16(s, rect16->bottom); /* bottom (2 bytes) */\n\treturn CHANNEL_RC_OK;\n}", "project": "FreeRDP", "hash": 138858215555612283726888611189591944586, "size": 14, "commit_id": "40393700642ad38437982e8a3afc34ff33ccf28e", "message": "Fixed input sanitation in rdpgfx_recv_solid_fill_pdu\n\nThe input rectangle must be checked for plausibility.\n\nThanks to Sunglin and HuanGMz of the Knownsec 404 security team and pangzi of pwnzen", "target": 1, "dataset": "other", "idx": 199860} {"func": "UINT rdpgfx_read_rect16(wStream* s, RECTANGLE_16* rect16)\n{\n\tif (Stream_GetRemainingLength(s) < 8)\n\t{\n\t\tWLog_ERR(TAG, \"not enough data!\");\n\t\treturn ERROR_INVALID_DATA;\n\t}\n\n\tStream_Read_UINT16(s, rect16->left); /* left (2 bytes) */\n\tStream_Read_UINT16(s, rect16->top); /* top (2 bytes) */\n\tStream_Read_UINT16(s, rect16->right); /* right (2 bytes) */\n\tStream_Read_UINT16(s, rect16->bottom); /* bottom (2 bytes) */\n\tif (rect16->left >= rect16->right)\n\t\treturn ERROR_INVALID_DATA;\n\tif (rect16->top >= rect16->bottom)\n\t\treturn ERROR_INVALID_DATA;\n\treturn CHANNEL_RC_OK;\n}", "project": "FreeRDP", "hash": 165617928321411316983723181749205350057, "size": 18, "commit_id": "40393700642ad38437982e8a3afc34ff33ccf28e", "message": "Fixed input sanitation in rdpgfx_recv_solid_fill_pdu\n\nThe input rectangle must be checked for plausibility.\n\nThanks to Sunglin and HuanGMz of the Knownsec 404 security team and pangzi of pwnzen", "target": 0, "dataset": "other", "idx": 294212} {"func": "BOOL update_recv(rdpUpdate* update, wStream* s)\n{\n\tBOOL rc = FALSE;\n\tUINT16 updateType;\n\trdpContext* context = update->context;\n\n\tif (Stream_GetRemainingLength(s) < 2)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_GetRemainingLength(s) < 2\");\n\t\treturn FALSE;\n\t}\n\n\tStream_Read_UINT16(s, updateType); /* updateType (2 bytes) */\n\tWLog_Print(update->log, WLOG_TRACE, \"%s Update Data PDU\", UPDATE_TYPE_STRINGS[updateType]);\n\n\tif (!update_begin_paint(update))\n\t\tgoto fail;\n\n\tswitch (updateType)\n\t{\n\t\tcase UPDATE_TYPE_ORDERS:\n\t\t\trc = update_recv_orders(update, s);\n\t\t\tbreak;\n\n\t\tcase UPDATE_TYPE_BITMAP:\n\t\t{\n\t\t\tBITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s);\n\n\t\t\tif (!bitmap_update)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed\");\n\t\t\t\tgoto fail;\n\t\t\t}\n\n\t\t\trc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update);\n\t\t\tfree_bitmap_update(update->context, bitmap_update);\n\t\t}\n\t\tbreak;\n\n\t\tcase UPDATE_TYPE_PALETTE:\n\t\t{\n\t\t\tPALETTE_UPDATE* palette_update = update_read_palette(update, s);\n\n\t\t\tif (!palette_update)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"UPDATE_TYPE_PALETTE - update_read_palette() failed\");\n\t\t\t\tgoto fail;\n\t\t\t}\n\n\t\t\trc = IFCALLRESULT(FALSE, update->Palette, context, palette_update);\n\t\t\tfree_palette_update(context, palette_update);\n\t\t}\n\t\tbreak;\n\n\t\tcase UPDATE_TYPE_SYNCHRONIZE:\n\t\t\tif (!update_read_synchronize(update, s))\n\t\t\t\tgoto fail;\n\t\t\trc = IFCALLRESULT(TRUE, update->Synchronize, context);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\nfail:\n\n\tif (!update_end_paint(update))\n\t\trc = FALSE;\n\n\tif (!rc)\n\t{\n\t\tWLog_ERR(TAG, \"UPDATE_TYPE %s [%\" PRIu16 \"] failed\", update_type_to_string(updateType),\n\t\t updateType);\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "project": "FreeRDP", "hash": 241599745468172248070055396754810927395, "size": 78, "commit_id": "0332cad015fdf7fac7e5c6863484f18a554e0fcf", "message": "Fixed oob read in update_recv\n\nproperly use update_type_to_string to print update type.\nThanks to hac425 CVE-2020-11019", "target": 1, "dataset": "other", "idx": 199894} {"func": "BOOL update_recv(rdpUpdate* update, wStream* s)\n{\n\tBOOL rc = FALSE;\n\tUINT16 updateType;\n\trdpContext* context = update->context;\n\n\tif (Stream_GetRemainingLength(s) < 2)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_GetRemainingLength(s) < 2\");\n\t\treturn FALSE;\n\t}\n\n\tStream_Read_UINT16(s, updateType); /* updateType (2 bytes) */\n\tWLog_Print(update->log, WLOG_TRACE, \"%s Update Data PDU\", update_type_to_string(updateType));\n\n\tif (!update_begin_paint(update))\n\t\tgoto fail;\n\n\tswitch (updateType)\n\t{\n\t\tcase UPDATE_TYPE_ORDERS:\n\t\t\trc = update_recv_orders(update, s);\n\t\t\tbreak;\n\n\t\tcase UPDATE_TYPE_BITMAP:\n\t\t{\n\t\t\tBITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s);\n\n\t\t\tif (!bitmap_update)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed\");\n\t\t\t\tgoto fail;\n\t\t\t}\n\n\t\t\trc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update);\n\t\t\tfree_bitmap_update(update->context, bitmap_update);\n\t\t}\n\t\tbreak;\n\n\t\tcase UPDATE_TYPE_PALETTE:\n\t\t{\n\t\t\tPALETTE_UPDATE* palette_update = update_read_palette(update, s);\n\n\t\t\tif (!palette_update)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"UPDATE_TYPE_PALETTE - update_read_palette() failed\");\n\t\t\t\tgoto fail;\n\t\t\t}\n\n\t\t\trc = IFCALLRESULT(FALSE, update->Palette, context, palette_update);\n\t\t\tfree_palette_update(context, palette_update);\n\t\t}\n\t\tbreak;\n\n\t\tcase UPDATE_TYPE_SYNCHRONIZE:\n\t\t\tif (!update_read_synchronize(update, s))\n\t\t\t\tgoto fail;\n\t\t\trc = IFCALLRESULT(TRUE, update->Synchronize, context);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\nfail:\n\n\tif (!update_end_paint(update))\n\t\trc = FALSE;\n\n\tif (!rc)\n\t{\n\t\tWLog_ERR(TAG, \"UPDATE_TYPE %s [%\" PRIu16 \"] failed\", update_type_to_string(updateType),\n\t\t updateType);\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "project": "FreeRDP", "hash": 210712111577567156501672184535618537131, "size": 78, "commit_id": "0332cad015fdf7fac7e5c6863484f18a554e0fcf", "message": "Fixed oob read in update_recv\n\nproperly use update_type_to_string to print update type.\nThanks to hac425 CVE-2020-11019", "target": 0, "dataset": "other", "idx": 295081} {"func": "static int may_create_in_sticky(struct dentry * const dir,\n\t\t\t\tstruct inode * const inode)\n{\n\tif ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||\n\t (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||\n\t likely(!(dir->d_inode->i_mode & S_ISVTX)) ||\n\t uid_eq(inode->i_uid, dir->d_inode->i_uid) ||\n\t uid_eq(current_fsuid(), inode->i_uid))\n\t\treturn 0;\n\n\tif (likely(dir->d_inode->i_mode & 0002) ||\n\t (dir->d_inode->i_mode & 0020 &&\n\t ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||\n\t (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {\n\t\tconst char *operation = S_ISFIFO(inode->i_mode) ?\n\t\t\t\t\t\"sticky_create_fifo\" :\n\t\t\t\t\t\"sticky_create_regular\";\n\t\taudit_log_path_denied(AUDIT_ANOM_CREAT, operation);\n\t\treturn -EACCES;\n\t}\n\treturn 0;\n}", "project": "linux", "hash": 20871760417441141942075932160806615554, "size": 22, "commit_id": "d0cb50185ae942b03c4327be322055d622dc79f6", "message": "do_last(): fetch directory ->i_mode and ->i_uid before it's too late\n\nmay_create_in_sticky() call is done when we already have dropped the\nreference to dir.\n\nFixes: 30aba6656f61e (namei: allow restricted O_CREAT of FIFOs and regular files)\nSigned-off-by: Al Viro ", "target": 1, "dataset": "other", "idx": 199916} {"func": "static int may_create_in_sticky(umode_t dir_mode, kuid_t dir_uid,\n\t\t\t\tstruct inode * const inode)\n{\n\tif ((!sysctl_protected_fifos && S_ISFIFO(inode->i_mode)) ||\n\t (!sysctl_protected_regular && S_ISREG(inode->i_mode)) ||\n\t likely(!(dir_mode & S_ISVTX)) ||\n\t uid_eq(inode->i_uid, dir_uid) ||\n\t uid_eq(current_fsuid(), inode->i_uid))\n\t\treturn 0;\n\n\tif (likely(dir_mode & 0002) ||\n\t (dir_mode & 0020 &&\n\t ((sysctl_protected_fifos >= 2 && S_ISFIFO(inode->i_mode)) ||\n\t (sysctl_protected_regular >= 2 && S_ISREG(inode->i_mode))))) {\n\t\tconst char *operation = S_ISFIFO(inode->i_mode) ?\n\t\t\t\t\t\"sticky_create_fifo\" :\n\t\t\t\t\t\"sticky_create_regular\";\n\t\taudit_log_path_denied(AUDIT_ANOM_CREAT, operation);\n\t\treturn -EACCES;\n\t}\n\treturn 0;\n}", "project": "linux", "hash": 265796941351907819719857276883338893990, "size": 22, "commit_id": "d0cb50185ae942b03c4327be322055d622dc79f6", "message": "do_last(): fetch directory ->i_mode and ->i_uid before it's too late\n\nmay_create_in_sticky() call is done when we already have dropped the\nreference to dir.\n\nFixes: 30aba6656f61e (namei: allow restricted O_CREAT of FIFOs and regular files)\nSigned-off-by: Al Viro ", "target": 0, "dataset": "other", "idx": 295331} {"func": "CallResult Interpreter::interpretFunction(\n Runtime *runtime,\n InterpreterState &state) {\n // The interepter is re-entrant and also saves/restores its IP via the runtime\n // whenever a call out is made (see the CAPTURE_IP_* macros). As such, failure\n // to preserve the IP across calls to interpeterFunction() disrupt interpreter\n // calls further up the C++ callstack. The RAII utility class below makes sure\n // we always do this correctly.\n //\n // TODO: The IPs stored in the C++ callstack via this holder will generally be\n // the same as in the JS stack frames via the Saved IP field. We can probably\n // get rid of one of these redundant stores. Doing this isn't completely\n // trivial as there are currently cases where we re-enter the interpreter\n // without calling Runtime::saveCallerIPInStackFrame(), and there are features\n // (I think mostly the debugger + stack traces) which implicitly rely on\n // this behavior. At least their tests break if this behavior is not\n // preserved.\n struct IPSaver {\n IPSaver(Runtime *runtime)\n : ip_(runtime->getCurrentIP()), runtime_(runtime) {}\n\n ~IPSaver() {\n runtime_->setCurrentIP(ip_);\n }\n\n private:\n const Inst *ip_;\n Runtime *runtime_;\n };\n IPSaver ipSaver(runtime);\n\n#ifndef HERMES_ENABLE_DEBUGGER\n static_assert(!SingleStep, \"can't use single-step mode without the debugger\");\n#endif\n // Make sure that the cache can use an optimization by avoiding a branch to\n // access the property storage.\n static_assert(\n HiddenClass::kDictionaryThreshold <=\n SegmentedArray::kValueToSegmentThreshold,\n \"Cannot avoid branches in cache check if the dictionary \"\n \"crossover point is larger than the inline storage\");\n\n CodeBlock *curCodeBlock = state.codeBlock;\n const Inst *ip = nullptr;\n // Holds runtime->currentFrame_.ptr()-1 which is the first local\n // register. This eliminates the indirect load from Runtime and the -1 offset.\n PinnedHermesValue *frameRegs;\n // Strictness of current function.\n bool strictMode;\n // Default flags when accessing properties.\n PropOpFlags defaultPropOpFlags;\n\n// These CAPTURE_IP* macros should wrap around any major calls out of the\n// interpeter loop. They stash and retrieve the IP via the current Runtime\n// allowing the IP to be externally observed and even altered to change the flow\n// of execution. Explicitly saving AND restoring the IP from the Runtime in this\n// way means the C++ compiler will keep IP in a register within the rest of the\n// interpeter loop.\n//\n// When assertions are enabled we take the extra step of \"invalidating\" the IP\n// between captures so we can detect if it's erroneously accessed.\n//\n// In some cases we explicitly don't want to invalidate the IP and instead want\n// it to stay set. For this we use the *NO_INVALIDATE variants. This comes up\n// when we're performing a call operation which may re-enter the interpeter\n// loop, and so need the IP available for the saveCallerIPInStackFrame() call\n// when we next enter.\n#define CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr) \\\n runtime->setCurrentIP(ip); \\\n dst = expr; \\\n ip = runtime->getCurrentIP();\n\n#ifdef NDEBUG\n\n#define CAPTURE_IP(expr) \\\n runtime->setCurrentIP(ip); \\\n (void)expr; \\\n ip = runtime->getCurrentIP();\n\n#define CAPTURE_IP_ASSIGN(dst, expr) CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr)\n\n#else // !NDEBUG\n\n#define CAPTURE_IP(expr) \\\n runtime->setCurrentIP(ip); \\\n (void)expr; \\\n ip = runtime->getCurrentIP(); \\\n runtime->invalidateCurrentIP();\n\n#define CAPTURE_IP_ASSIGN(dst, expr) \\\n runtime->setCurrentIP(ip); \\\n dst = expr; \\\n ip = runtime->getCurrentIP(); \\\n runtime->invalidateCurrentIP();\n\n#endif // NDEBUG\n\n LLVM_DEBUG(dbgs() << \"interpretFunction() called\\n\");\n\n ScopedNativeDepthTracker depthTracker{runtime};\n if (LLVM_UNLIKELY(depthTracker.overflowed())) {\n return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);\n }\n\n if (!SingleStep) {\n if (auto jitPtr = runtime->jitContext_.compile(runtime, curCodeBlock)) {\n return (*jitPtr)(runtime);\n }\n }\n\n GCScope gcScope(runtime);\n // Avoid allocating a handle dynamically by reusing this one.\n MutableHandle<> tmpHandle(runtime);\n CallResult res{ExecutionStatus::EXCEPTION};\n CallResult> resPH{ExecutionStatus::EXCEPTION};\n CallResult> resArgs{ExecutionStatus::EXCEPTION};\n CallResult boolRes{ExecutionStatus::EXCEPTION};\n\n // Mark the gcScope so we can clear all allocated handles.\n // Remember how many handles the scope has so we can clear them in the loop.\n static constexpr unsigned KEEP_HANDLES = 1;\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"scope has unexpected number of handles\");\n\n INIT_OPCODE_PROFILER;\n\n#if !defined(HERMESVM_PROFILER_EXTERN)\ntailCall:\n#endif\n PROFILER_ENTER_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_DEBUGGER\n runtime->getDebugger().willEnterCodeBlock(curCodeBlock);\n#endif\n\n runtime->getCodeCoverageProfiler().markExecuted(runtime, curCodeBlock);\n\n // Update function executionCount_ count\n curCodeBlock->incrementExecutionCount();\n\n if (!SingleStep) {\n auto newFrame = runtime->setCurrentFrameToTopOfStack();\n runtime->saveCallerIPInStackFrame();\n#ifndef NDEBUG\n runtime->invalidateCurrentIP();\n#endif\n\n // Point frameRegs to the first register in the new frame. Note that at this\n // moment technically it points above the top of the stack, but we are never\n // going to access it.\n frameRegs = &newFrame.getFirstLocalRef();\n\n#ifndef NDEBUG\n LLVM_DEBUG(\n dbgs() << \"function entry: stackLevel=\" << runtime->getStackLevel()\n << \", argCount=\" << runtime->getCurrentFrame().getArgCount()\n << \", frameSize=\" << curCodeBlock->getFrameSize() << \"\\n\");\n\n LLVM_DEBUG(\n dbgs() << \" callee \"\n << DumpHermesValue(\n runtime->getCurrentFrame().getCalleeClosureOrCBRef())\n << \"\\n\");\n LLVM_DEBUG(\n dbgs() << \" this \"\n << DumpHermesValue(runtime->getCurrentFrame().getThisArgRef())\n << \"\\n\");\n for (uint32_t i = 0; i != runtime->getCurrentFrame()->getArgCount(); ++i) {\n LLVM_DEBUG(\n dbgs() << \" \" << llvh::format_decimal(i, 4) << \" \"\n << DumpHermesValue(runtime->getCurrentFrame().getArgRef(i))\n << \"\\n\");\n }\n#endif\n\n // Allocate the registers for the new frame.\n if (LLVM_UNLIKELY(!runtime->checkAndAllocStack(\n curCodeBlock->getFrameSize() +\n StackFrameLayout::CalleeExtraRegistersAtStart,\n HermesValue::encodeUndefinedValue())))\n goto stackOverflow;\n\n ip = (Inst const *)curCodeBlock->begin();\n\n // Check for invalid invocation.\n if (LLVM_UNLIKELY(curCodeBlock->getHeaderFlags().isCallProhibited(\n newFrame.isConstructorCall()))) {\n if (!newFrame.isConstructorCall()) {\n CAPTURE_IP(\n runtime->raiseTypeError(\"Class constructor invoked without new\"));\n } else {\n CAPTURE_IP(runtime->raiseTypeError(\"Function is not a constructor\"));\n }\n goto handleExceptionInParent;\n }\n } else {\n // Point frameRegs to the first register in the frame.\n frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();\n ip = (Inst const *)(curCodeBlock->begin() + state.offset);\n }\n\n assert((const uint8_t *)ip < curCodeBlock->end() && \"CodeBlock is empty\");\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n\n#define BEFORE_OP_CODE \\\n { \\\n UPDATE_OPCODE_TIME_SPENT; \\\n HERMES_SLOW_ASSERT( \\\n curCodeBlock->contains(ip) && \"curCodeBlock must contain ip\"); \\\n HERMES_SLOW_ASSERT((printDebugInfo(curCodeBlock, frameRegs, ip), true)); \\\n HERMES_SLOW_ASSERT( \\\n gcScope.getHandleCountDbg() == KEEP_HANDLES && \\\n \"unaccounted handles were created\"); \\\n HERMES_SLOW_ASSERT(tmpHandle->isUndefined() && \"tmpHandle not cleared\"); \\\n RECORD_OPCODE_START_TIME; \\\n INC_OPCODE_COUNT; \\\n }\n\n#ifdef HERMESVM_INDIRECT_THREADING\n static void *opcodeDispatch[] = {\n#define DEFINE_OPCODE(name) &&case_##name,\n#include \"hermes/BCGen/HBC/BytecodeList.def\"\n &&case__last};\n\n#define CASE(name) case_##name:\n#define DISPATCH \\\n BEFORE_OP_CODE; \\\n if (SingleStep) { \\\n state.codeBlock = curCodeBlock; \\\n state.offset = CUROFFSET; \\\n return HermesValue::encodeUndefinedValue(); \\\n } \\\n goto *opcodeDispatch[(unsigned)ip->opCode]\n\n#else // HERMESVM_INDIRECT_THREADING\n\n#define CASE(name) case OpCode::name:\n#define DISPATCH \\\n if (SingleStep) { \\\n state.codeBlock = curCodeBlock; \\\n state.offset = CUROFFSET; \\\n return HermesValue::encodeUndefinedValue(); \\\n } \\\n continue\n\n#endif // HERMESVM_INDIRECT_THREADING\n\n#define RUN_DEBUGGER_ASYNC_BREAK(flags) \\\n do { \\\n CAPTURE_IP_ASSIGN( \\\n auto dRes, \\\n runDebuggerUpdatingState( \\\n (uint8_t)(flags) & \\\n (uint8_t)Runtime::AsyncBreakReasonBits::DebuggerExplicit \\\n ? Debugger::RunReason::AsyncBreakExplicit \\\n : Debugger::RunReason::AsyncBreakImplicit, \\\n runtime, \\\n curCodeBlock, \\\n ip, \\\n frameRegs)); \\\n if (dRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n } while (0)\n\n for (;;) {\n BEFORE_OP_CODE;\n\n#ifdef HERMESVM_INDIRECT_THREADING\n goto *opcodeDispatch[(unsigned)ip->opCode];\n#else\n switch (ip->opCode)\n#endif\n {\n const Inst *nextIP;\n uint32_t idVal;\n bool tryProp;\n uint32_t callArgCount;\n // This is HermesValue::getRaw(), since HermesValue cannot be assigned\n // to. It is meant to be used only for very short durations, in the\n // dispatch of call instructions, when there is definitely no possibility\n // of a GC.\n HermesValue::RawType callNewTarget;\n\n/// Handle an opcode \\p name with an out-of-line implementation in a function\n/// ExecutionStatus caseName(\n/// Runtime *,\n/// PinnedHermesValue *frameRegs,\n/// Inst *ip)\n#define CASE_OUTOFLINE(name) \\\n CASE(name) { \\\n CAPTURE_IP_ASSIGN(auto res, case##name(runtime, frameRegs, ip)); \\\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { \\\n goto exception; \\\n } \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a binary arithmetic instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction. The fast path case will have a\n/// \"n\" appended to the name.\n/// \\param oper the C++ operator to use to actually perform the arithmetic\n/// operation.\n#define BINOP(name, oper) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n CASE(name##N) { \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n oper(O2REG(name).getNumber(), O3REG(name).getNumber())); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n } \\\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n double left = res->getDouble(); \\\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n O1REG(name) = \\\n HermesValue::encodeDoubleValue(oper(left, res->getDouble())); \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a shift instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the shift\n/// operation.\n/// \\param lConv the conversion function for the LHS of the expression.\n/// \\param lType the type of the LHS operand.\n/// \\param returnType the type of the return value.\n#define SHIFTOP(name, oper, lConv, lType, returnType) \\\n CASE(name) { \\\n if (LLVM_LIKELY( \\\n O2REG(name).isNumber() && \\\n O3REG(name).isNumber())) { /* Fast-path. */ \\\n auto lnum = static_cast( \\\n hermes::truncateToInt32(O2REG(name).getNumber())); \\\n auto rnum = static_cast( \\\n hermes::truncateToInt32(O3REG(name).getNumber())) & \\\n 0x1f; \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast(lnum oper rnum)); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN(res, lConv(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n auto lnum = static_cast(res->getNumber()); \\\n CAPTURE_IP_ASSIGN(res, toUInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n auto rnum = static_cast(res->getNumber()) & 0x1f; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast(lnum oper rnum)); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a binary bitwise instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the bitwise\n/// operation.\n#define BITWISEBINOP(name, oper) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n hermes::truncateToInt32(O2REG(name).getNumber()) \\\n oper hermes::truncateToInt32(O3REG(name).getNumber())); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n int32_t left = res->getNumberAs(); \\\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n O1REG(name) = \\\n HermesValue::encodeNumberValue(left oper res->getNumberAs()); \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a comparison instruction.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the fast arithmetic\n/// comparison.\n/// \\param operFuncName function to call for the slow-path comparison.\n#define CONDOP(name, oper, operFuncName) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n O1REG(name) = HermesValue::encodeBoolValue( \\\n O2REG(name).getNumber() oper O3REG(name).getNumber()); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN( \\\n boolRes, \\\n operFuncName( \\\n runtime, Handle<>(&O2REG(name)), Handle<>(&O3REG(name)))); \\\n if (boolRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n O1REG(name) = HermesValue::encodeBoolValue(boolRes.getValue()); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a comparison conditional jump with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction. The fast path case will have a\n/// \"N\" appended to the name.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param oper the C++ operator to use to actually perform the fast arithmetic\n/// comparison.\n/// \\param operFuncName function to call for the slow-path comparison.\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_IMPL(name, suffix, oper, operFuncName, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n if (LLVM_LIKELY( \\\n O2REG(name##suffix).isNumber() && \\\n O3REG(name##suffix).isNumber())) { \\\n /* Fast-path. */ \\\n CASE(name##N##suffix) { \\\n if (O2REG(name##N##suffix) \\\n .getNumber() oper O3REG(name##N##suffix) \\\n .getNumber()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n } \\\n } \\\n CAPTURE_IP_ASSIGN( \\\n boolRes, \\\n operFuncName( \\\n runtime, \\\n Handle<>(&O2REG(name##suffix)), \\\n Handle<>(&O3REG(name##suffix)))); \\\n if (boolRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n if (boolRes.getValue()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement a strict equality conditional jump\n/// \\param name the name of the instruction.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_STRICT_EQ_IMPL(name, suffix, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n if (strictEqualityTest(O2REG(name##suffix), O3REG(name##suffix))) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement an equality conditional jump\n/// \\param name the name of the instruction.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_EQ_IMPL(name, suffix, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n CAPTURE_IP_ASSIGN( \\\n res, \\\n abstractEqualityTest_RJS( \\\n runtime, \\\n Handle<>(&O2REG(name##suffix)), \\\n Handle<>(&O3REG(name##suffix)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n if (res->getBool()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement the long and short forms of a conditional jump, and its negation.\n#define JCOND(name, oper, operFuncName) \\\n JCOND_IMPL( \\\n J##name, \\\n , \\\n oper, \\\n operFuncName, \\\n IPADD(ip->iJ##name.op1), \\\n NEXTINST(J##name)); \\\n JCOND_IMPL( \\\n J##name, \\\n Long, \\\n oper, \\\n operFuncName, \\\n IPADD(ip->iJ##name##Long.op1), \\\n NEXTINST(J##name##Long)); \\\n JCOND_IMPL( \\\n JNot##name, \\\n , \\\n oper, \\\n operFuncName, \\\n NEXTINST(JNot##name), \\\n IPADD(ip->iJNot##name.op1)); \\\n JCOND_IMPL( \\\n JNot##name, \\\n Long, \\\n oper, \\\n operFuncName, \\\n NEXTINST(JNot##name##Long), \\\n IPADD(ip->iJNot##name##Long.op1));\n\n/// Load a constant.\n/// \\param value is the value to store in the output register.\n#define LOAD_CONST(name, value) \\\n CASE(name) { \\\n O1REG(name) = value; \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n#define LOAD_CONST_CAPTURE_IP(name, value) \\\n CASE(name) { \\\n CAPTURE_IP_ASSIGN(O1REG(name), value); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n CASE(Mov) {\n O1REG(Mov) = O2REG(Mov);\n ip = NEXTINST(Mov);\n DISPATCH;\n }\n\n CASE(MovLong) {\n O1REG(MovLong) = O2REG(MovLong);\n ip = NEXTINST(MovLong);\n DISPATCH;\n }\n\n CASE(LoadParam) {\n if (LLVM_LIKELY(ip->iLoadParam.op2 <= FRAME.getArgCount())) {\n // index 0 must load 'this'. Index 1 the first argument, etc.\n O1REG(LoadParam) = FRAME.getArgRef((int32_t)ip->iLoadParam.op2 - 1);\n ip = NEXTINST(LoadParam);\n DISPATCH;\n }\n O1REG(LoadParam) = HermesValue::encodeUndefinedValue();\n ip = NEXTINST(LoadParam);\n DISPATCH;\n }\n\n CASE(LoadParamLong) {\n if (LLVM_LIKELY(ip->iLoadParamLong.op2 <= FRAME.getArgCount())) {\n // index 0 must load 'this'. Index 1 the first argument, etc.\n O1REG(LoadParamLong) =\n FRAME.getArgRef((int32_t)ip->iLoadParamLong.op2 - 1);\n ip = NEXTINST(LoadParamLong);\n DISPATCH;\n }\n O1REG(LoadParamLong) = HermesValue::encodeUndefinedValue();\n ip = NEXTINST(LoadParamLong);\n DISPATCH;\n }\n\n CASE(CoerceThisNS) {\n if (LLVM_LIKELY(O2REG(CoerceThisNS).isObject())) {\n O1REG(CoerceThisNS) = O2REG(CoerceThisNS);\n } else if (\n O2REG(CoerceThisNS).isNull() || O2REG(CoerceThisNS).isUndefined()) {\n O1REG(CoerceThisNS) = runtime->global_;\n } else {\n tmpHandle = O2REG(CoerceThisNS);\n nextIP = NEXTINST(CoerceThisNS);\n goto coerceThisSlowPath;\n }\n ip = NEXTINST(CoerceThisNS);\n DISPATCH;\n }\n CASE(LoadThisNS) {\n if (LLVM_LIKELY(FRAME.getThisArgRef().isObject())) {\n O1REG(LoadThisNS) = FRAME.getThisArgRef();\n } else if (\n FRAME.getThisArgRef().isNull() ||\n FRAME.getThisArgRef().isUndefined()) {\n O1REG(LoadThisNS) = runtime->global_;\n } else {\n tmpHandle = FRAME.getThisArgRef();\n nextIP = NEXTINST(LoadThisNS);\n goto coerceThisSlowPath;\n }\n ip = NEXTINST(LoadThisNS);\n DISPATCH;\n }\n coerceThisSlowPath : {\n CAPTURE_IP_ASSIGN(res, toObject(runtime, tmpHandle));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CoerceThisNS) = res.getValue();\n tmpHandle.clear();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(ConstructLong) {\n callArgCount = (uint32_t)ip->iConstructLong.op3;\n nextIP = NEXTINST(ConstructLong);\n callNewTarget = O2REG(ConstructLong).getRaw();\n goto doCall;\n }\n CASE(CallLong) {\n callArgCount = (uint32_t)ip->iCallLong.op3;\n nextIP = NEXTINST(CallLong);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n // Note in Call1 through Call4, the first argument is 'this' which has\n // argument index -1.\n // Also note that we are writing to callNewTarget last, to avoid the\n // possibility of it being aliased by the arg writes.\n CASE(Call1) {\n callArgCount = 1;\n nextIP = NEXTINST(Call1);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call1);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call2) {\n callArgCount = 2;\n nextIP = NEXTINST(Call2);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call2);\n fr.getArgRefUnsafe(0) = O4REG(Call2);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call3) {\n callArgCount = 3;\n nextIP = NEXTINST(Call3);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call3);\n fr.getArgRefUnsafe(0) = O4REG(Call3);\n fr.getArgRefUnsafe(1) = O5REG(Call3);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call4) {\n callArgCount = 4;\n nextIP = NEXTINST(Call4);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call4);\n fr.getArgRefUnsafe(0) = O4REG(Call4);\n fr.getArgRefUnsafe(1) = O5REG(Call4);\n fr.getArgRefUnsafe(2) = O6REG(Call4);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Construct) {\n callArgCount = (uint32_t)ip->iConstruct.op3;\n nextIP = NEXTINST(Construct);\n callNewTarget = O2REG(Construct).getRaw();\n goto doCall;\n }\n CASE(Call) {\n callArgCount = (uint32_t)ip->iCall.op3;\n nextIP = NEXTINST(Call);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n // Fall through.\n }\n\n doCall : {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n // Subtract 1 from callArgCount as 'this' is considered an argument in the\n // instruction, but not in the frame.\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n callArgCount - 1,\n O2REG(Call),\n HermesValue::fromRaw(callNewTarget)));\n (void)newFrame;\n\n SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n if (auto *func = dyn_vmcast(O2REG(Call))) {\n assert(!SingleStep && \"can't single-step a call\");\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->pushCallStack(curCodeBlock, ip);\n#endif\n\n CodeBlock *calleeBlock = func->getCodeBlock();\n calleeBlock->lazyCompile(runtime);\n#if defined(HERMESVM_PROFILER_EXTERN)\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n res, runtime->interpretFunction(calleeBlock));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(Call) = *res;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n#else\n if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {\n res = (*jitPtr)(runtime);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(Call) = *res;\n SLOW_DEBUG(\n dbgs() << \"JIT return value r\" << (unsigned)ip->iCall.op1 << \"=\"\n << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n curCodeBlock = calleeBlock;\n goto tailCall;\n#endif\n }\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n resPH, Interpreter::handleCallSlowPath(runtime, &O2REG(Call)));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(Call) = std::move(resPH->get());\n SLOW_DEBUG(\n dbgs() << \"native return value r\" << (unsigned)ip->iCall.op1 << \"=\"\n << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(CallDirect)\n CASE(CallDirectLongIndex) {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n CAPTURE_IP_ASSIGN(\n CodeBlock * calleeBlock,\n ip->opCode == OpCode::CallDirect\n ? curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(\n ip->iCallDirect.op3)\n : curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(\n ip->iCallDirectLongIndex.op3));\n\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n (uint32_t)ip->iCallDirect.op2 - 1,\n HermesValue::encodeNativePointer(calleeBlock),\n HermesValue::encodeUndefinedValue()));\n (void)newFrame;\n\n LLVM_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n assert(!SingleStep && \"can't single-step a call\");\n\n calleeBlock->lazyCompile(runtime);\n#if defined(HERMESVM_PROFILER_EXTERN)\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n res, runtime->interpretFunction(calleeBlock));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CallDirect) = *res;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)\n : NEXTINST(CallDirectLongIndex);\n DISPATCH;\n#else\n if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {\n res = (*jitPtr)(runtime);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(CallDirect) = *res;\n LLVM_DEBUG(\n dbgs() << \"JIT return value r\" << (unsigned)ip->iCallDirect.op1\n << \"=\" << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)\n : NEXTINST(CallDirectLongIndex);\n DISPATCH;\n }\n curCodeBlock = calleeBlock;\n goto tailCall;\n#endif\n }\n\n CASE(CallBuiltin) {\n NativeFunction *nf =\n runtime->getBuiltinNativeFunction(ip->iCallBuiltin.op2);\n\n CAPTURE_IP_ASSIGN(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n (uint32_t)ip->iCallBuiltin.op3 - 1,\n nf,\n false));\n // \"thisArg\" is implicitly assumed to \"undefined\".\n newFrame.getThisArgRef() = HermesValue::encodeUndefinedValue();\n\n SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n CAPTURE_IP_ASSIGN(resPH, NativeFunction::_nativeCall(nf, runtime));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(CallBuiltin) = std::move(resPH->get());\n SLOW_DEBUG(\n dbgs() << \"native return value r\" << (unsigned)ip->iCallBuiltin.op1\n << \"=\" << DumpHermesValue(O1REG(CallBuiltin)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CallBuiltin);\n DISPATCH;\n }\n\n CASE(CompleteGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n innerFn->setState(GeneratorInnerFunction::State::Completed);\n ip = NEXTINST(CompleteGenerator);\n DISPATCH;\n }\n\n CASE(SaveGenerator) {\n nextIP = IPADD(ip->iSaveGenerator.op1);\n goto doSaveGen;\n }\n CASE(SaveGeneratorLong) {\n nextIP = IPADD(ip->iSaveGeneratorLong.op1);\n goto doSaveGen;\n }\n\n doSaveGen : {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n\n innerFn->saveStack(runtime);\n innerFn->setNextIP(nextIP);\n innerFn->setState(GeneratorInnerFunction::State::SuspendedYield);\n ip = NEXTINST(SaveGenerator);\n DISPATCH;\n }\n\n CASE(StartGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n if (innerFn->getState() ==\n GeneratorInnerFunction::State::SuspendedStart) {\n nextIP = NEXTINST(StartGenerator);\n } else {\n nextIP = innerFn->getNextIP();\n innerFn->restoreStack(runtime);\n }\n innerFn->setState(GeneratorInnerFunction::State::Executing);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(ResumeGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n O1REG(ResumeGenerator) = innerFn->getResult();\n O2REG(ResumeGenerator) = HermesValue::encodeBoolValue(\n innerFn->getAction() == GeneratorInnerFunction::Action::Return);\n innerFn->clearResult(runtime);\n if (innerFn->getAction() == GeneratorInnerFunction::Action::Throw) {\n runtime->setThrownValue(O1REG(ResumeGenerator));\n goto exception;\n }\n ip = NEXTINST(ResumeGenerator);\n DISPATCH;\n }\n\n CASE(Ret) {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n PROFILER_EXIT_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->popCallStack();\n#endif\n\n // Store the return value.\n res = O1REG(Ret);\n\n ip = FRAME.getSavedIP();\n curCodeBlock = FRAME.getSavedCodeBlock();\n\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n SLOW_DEBUG(\n dbgs() << \"function exit: restored stackLevel=\"\n << runtime->getStackLevel() << \"\\n\");\n\n // Are we returning to native code?\n if (!curCodeBlock) {\n SLOW_DEBUG(dbgs() << \"function exit: returning to native code\\n\");\n return res;\n }\n\n// Return because of recursive calling structure\n#if defined(HERMESVM_PROFILER_EXTERN)\n return res;\n#endif\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n O1REG(Call) = res.getValue();\n ip = nextInstCall(ip);\n DISPATCH;\n }\n\n CASE(Catch) {\n assert(!runtime->thrownValue_.isEmpty() && \"Invalid thrown value\");\n assert(\n !isUncatchableError(runtime->thrownValue_) &&\n \"Uncatchable thrown value was caught\");\n O1REG(Catch) = runtime->thrownValue_;\n runtime->clearThrownValue();\n#ifdef HERMES_ENABLE_DEBUGGER\n // Signal to the debugger that we're done unwinding an exception,\n // and we can resume normal debugging flow.\n runtime->debugger_.finishedUnwindingException();\n#endif\n ip = NEXTINST(Catch);\n DISPATCH;\n }\n\n CASE(Throw) {\n runtime->thrownValue_ = O1REG(Throw);\n SLOW_DEBUG(\n dbgs() << \"Exception thrown: \"\n << DumpHermesValue(runtime->thrownValue_) << \"\\n\");\n goto exception;\n }\n\n CASE(ThrowIfUndefinedInst) {\n if (LLVM_UNLIKELY(O1REG(ThrowIfUndefinedInst).isUndefined())) {\n SLOW_DEBUG(\n dbgs() << \"Throwing ReferenceError for undefined variable\");\n CAPTURE_IP(runtime->raiseReferenceError(\n \"accessing an uninitialized variable\"));\n goto exception;\n }\n ip = NEXTINST(ThrowIfUndefinedInst);\n DISPATCH;\n }\n\n CASE(Debugger) {\n SLOW_DEBUG(dbgs() << \"debugger statement executed\\n\");\n#ifdef HERMES_ENABLE_DEBUGGER\n {\n if (!runtime->debugger_.isDebugging()) {\n // Only run the debugger if we're not already debugging.\n // Don't want to call it again and mess with its state.\n CAPTURE_IP_ASSIGN(\n auto res,\n runDebuggerUpdatingState(\n Debugger::RunReason::Opcode,\n runtime,\n curCodeBlock,\n ip,\n frameRegs));\n if (res == ExecutionStatus::EXCEPTION) {\n // If one of the internal steps threw,\n // then handle that here by jumping to where we're supposed to go.\n // If we're in mid-step, the breakpoint at the catch point\n // will have been set by the debugger.\n // We don't want to execute this instruction because it's already\n // thrown.\n goto exception;\n }\n }\n auto breakpointOpt = runtime->debugger_.getBreakpointLocation(ip);\n if (breakpointOpt.hasValue()) {\n // We're on a breakpoint but we're supposed to continue.\n curCodeBlock->uninstallBreakpointAtOffset(\n CUROFFSET, breakpointOpt->opCode);\n if (ip->opCode == OpCode::Debugger) {\n // Breakpointed a debugger instruction, so move past it\n // since we've already called the debugger on this instruction.\n ip = NEXTINST(Debugger);\n } else {\n InterpreterState newState{curCodeBlock, (uint32_t)CUROFFSET};\n CAPTURE_IP_ASSIGN(\n ExecutionStatus status, runtime->stepFunction(newState));\n curCodeBlock->installBreakpointAtOffset(CUROFFSET);\n if (status == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n curCodeBlock = newState.codeBlock;\n ip = newState.codeBlock->getOffsetPtr(newState.offset);\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n // Single-stepping should handle call stack management for us.\n frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();\n }\n } else if (ip->opCode == OpCode::Debugger) {\n // No breakpoint here and we've already run the debugger,\n // just continue on.\n // If the current instruction is no longer a debugger instruction,\n // we're just going to keep executing from the current IP.\n ip = NEXTINST(Debugger);\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n DISPATCH;\n#else\n ip = NEXTINST(Debugger);\n DISPATCH;\n#endif\n }\n\n CASE(AsyncBreakCheck) {\n if (LLVM_UNLIKELY(runtime->hasAsyncBreak())) {\n#ifdef HERMES_ENABLE_DEBUGGER\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n }\n#endif\n if (runtime->testAndClearTimeoutAsyncBreakRequest()) {\n CAPTURE_IP_ASSIGN(auto nRes, runtime->notifyTimeout());\n if (nRes == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n\n ip = NEXTINST(AsyncBreakCheck);\n DISPATCH;\n }\n\n CASE(ProfilePoint) {\n#ifdef HERMESVM_PROFILER_BB\n auto pointIndex = ip->iProfilePoint.op1;\n SLOW_DEBUG(llvh::dbgs() << \"ProfilePoint: \" << pointIndex << \"\\n\");\n CAPTURE_IP(runtime->getBasicBlockExecutionInfo().executeBlock(\n curCodeBlock, pointIndex));\n#endif\n ip = NEXTINST(ProfilePoint);\n DISPATCH;\n }\n\n CASE(Unreachable) {\n llvm_unreachable(\"Hermes bug: unreachable instruction\");\n }\n\n CASE(CreateClosure) {\n idVal = ip->iCreateClosure.op3;\n nextIP = NEXTINST(CreateClosure);\n goto createClosure;\n }\n CASE(CreateClosureLongIndex) {\n idVal = ip->iCreateClosureLongIndex.op3;\n nextIP = NEXTINST(CreateClosureLongIndex);\n goto createClosure;\n }\n createClosure : {\n auto *runtimeModule = curCodeBlock->getRuntimeModule();\n CAPTURE_IP_ASSIGN(\n O1REG(CreateClosure),\n JSFunction::create(\n runtime,\n runtimeModule->getDomain(runtime),\n Handle::vmcast(&runtime->functionPrototype),\n Handle::vmcast(&O2REG(CreateClosure)),\n runtimeModule->getCodeBlockMayAllocate(idVal))\n .getHermesValue());\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(CreateGeneratorClosure) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGeneratorClosure(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateClosure.op3,\n Handle::vmcast(&O2REG(CreateGeneratorClosure))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorClosure) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorClosure);\n DISPATCH;\n }\n CASE(CreateGeneratorClosureLongIndex) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGeneratorClosure(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateClosureLongIndex.op3,\n Handle::vmcast(\n &O2REG(CreateGeneratorClosureLongIndex))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorClosureLongIndex) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorClosureLongIndex);\n DISPATCH;\n }\n\n CASE(CreateGenerator) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGenerator_RJS(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateGenerator.op3,\n Handle::vmcast(&O2REG(CreateGenerator)),\n FRAME.getNativeArgs()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGenerator) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGenerator);\n DISPATCH;\n }\n CASE(CreateGeneratorLongIndex) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGenerator_RJS(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateGeneratorLongIndex.op3,\n Handle::vmcast(&O2REG(CreateGeneratorLongIndex)),\n FRAME.getNativeArgs()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorLongIndex) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorLongIndex);\n DISPATCH;\n }\n\n CASE(GetEnvironment) {\n // The currently executing function must exist, so get the environment.\n Environment *curEnv =\n FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime);\n for (unsigned level = ip->iGetEnvironment.op2; level; --level) {\n assert(curEnv && \"invalid environment relative level\");\n curEnv = curEnv->getParentEnvironment(runtime);\n }\n O1REG(GetEnvironment) = HermesValue::encodeObjectValue(curEnv);\n ip = NEXTINST(GetEnvironment);\n DISPATCH;\n }\n\n CASE(CreateEnvironment) {\n tmpHandle = HermesValue::encodeObjectValue(\n FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime));\n\n CAPTURE_IP_ASSIGN(\n res,\n Environment::create(\n runtime,\n tmpHandle->getPointer() ? Handle::vmcast(tmpHandle)\n : Handle::vmcast_or_null(\n &runtime->nullPointer_),\n curCodeBlock->getEnvironmentSize()));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(CreateEnvironment) = *res;\n#ifdef HERMES_ENABLE_DEBUGGER\n FRAME.getDebugEnvironmentRef() = *res;\n#endif\n tmpHandle = HermesValue::encodeUndefinedValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateEnvironment);\n DISPATCH;\n }\n\n CASE(StoreToEnvironment) {\n vmcast(O1REG(StoreToEnvironment))\n ->slot(ip->iStoreToEnvironment.op2)\n .set(O3REG(StoreToEnvironment), &runtime->getHeap());\n ip = NEXTINST(StoreToEnvironment);\n DISPATCH;\n }\n CASE(StoreToEnvironmentL) {\n vmcast(O1REG(StoreToEnvironmentL))\n ->slot(ip->iStoreToEnvironmentL.op2)\n .set(O3REG(StoreToEnvironmentL), &runtime->getHeap());\n ip = NEXTINST(StoreToEnvironmentL);\n DISPATCH;\n }\n\n CASE(StoreNPToEnvironment) {\n vmcast(O1REG(StoreNPToEnvironment))\n ->slot(ip->iStoreNPToEnvironment.op2)\n .setNonPtr(O3REG(StoreNPToEnvironment), &runtime->getHeap());\n ip = NEXTINST(StoreNPToEnvironment);\n DISPATCH;\n }\n CASE(StoreNPToEnvironmentL) {\n vmcast(O1REG(StoreNPToEnvironmentL))\n ->slot(ip->iStoreNPToEnvironmentL.op2)\n .setNonPtr(O3REG(StoreNPToEnvironmentL), &runtime->getHeap());\n ip = NEXTINST(StoreNPToEnvironmentL);\n DISPATCH;\n }\n\n CASE(LoadFromEnvironment) {\n O1REG(LoadFromEnvironment) =\n vmcast(O2REG(LoadFromEnvironment))\n ->slot(ip->iLoadFromEnvironment.op3);\n ip = NEXTINST(LoadFromEnvironment);\n DISPATCH;\n }\n\n CASE(LoadFromEnvironmentL) {\n O1REG(LoadFromEnvironmentL) =\n vmcast(O2REG(LoadFromEnvironmentL))\n ->slot(ip->iLoadFromEnvironmentL.op3);\n ip = NEXTINST(LoadFromEnvironmentL);\n DISPATCH;\n }\n\n CASE(GetGlobalObject) {\n O1REG(GetGlobalObject) = runtime->global_;\n ip = NEXTINST(GetGlobalObject);\n DISPATCH;\n }\n\n CASE(GetNewTarget) {\n O1REG(GetNewTarget) = FRAME.getNewTargetRef();\n ip = NEXTINST(GetNewTarget);\n DISPATCH;\n }\n\n CASE(DeclareGlobalVar) {\n DefinePropertyFlags dpf =\n DefinePropertyFlags::getDefaultNewPropertyFlags();\n dpf.configurable = 0;\n // Do not overwrite existing globals with undefined.\n dpf.setValue = 0;\n\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::defineOwnProperty(\n runtime->getGlobal(),\n runtime,\n ID(ip->iDeclareGlobalVar.op1),\n dpf,\n Runtime::getUndefinedValue(),\n PropOpFlags().plusThrowOnError()));\n if (res == ExecutionStatus::EXCEPTION) {\n assert(\n !runtime->getGlobal()->isProxyObject() &&\n \"global can't be a proxy object\");\n // If the property already exists, this should be a noop.\n // Instead of incurring the cost to check every time, do it\n // only if an exception is thrown, and swallow the exception\n // if it exists, since we didn't want to make the call,\n // anyway. This most likely means the property is\n // non-configurable.\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::getOwnNamedDescriptor(\n runtime->getGlobal(),\n runtime,\n ID(ip->iDeclareGlobalVar.op1),\n desc));\n if (!res) {\n goto exception;\n } else {\n runtime->clearThrownValue();\n }\n // fall through\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(DeclareGlobalVar);\n DISPATCH;\n }\n\n CASE(TryGetByIdLong) {\n tryProp = true;\n idVal = ip->iTryGetByIdLong.op4;\n nextIP = NEXTINST(TryGetByIdLong);\n goto getById;\n }\n CASE(GetByIdLong) {\n tryProp = false;\n idVal = ip->iGetByIdLong.op4;\n nextIP = NEXTINST(GetByIdLong);\n goto getById;\n }\n CASE(GetByIdShort) {\n tryProp = false;\n idVal = ip->iGetByIdShort.op4;\n nextIP = NEXTINST(GetByIdShort);\n goto getById;\n }\n CASE(TryGetById) {\n tryProp = true;\n idVal = ip->iTryGetById.op4;\n nextIP = NEXTINST(TryGetById);\n goto getById;\n }\n CASE(GetById) {\n tryProp = false;\n idVal = ip->iGetById.op4;\n nextIP = NEXTINST(GetById);\n }\n getById : {\n ++NumGetById;\n // NOTE: it is safe to use OnREG(GetById) here because all instructions\n // have the same layout: opcode, registers, non-register operands, i.e.\n // they only differ in the width of the last \"identifier\" field.\n CallResult propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetById).isObject())) {\n auto *obj = vmcast(O2REG(GetById));\n auto cacheIdx = ip->iGetById.op3;\n auto *cacheEntry = curCodeBlock->getReadCacheEntry(cacheIdx);\n\n#ifdef HERMESVM_PROFILER_BB\n {\n HERMES_SLOW_ASSERT(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"unaccounted handles were created\");\n auto objHandle = runtime->makeHandle(obj);\n auto cacheHCPtr = vmcast_or_null(static_cast(\n cacheEntry->clazz.get(runtime, &runtime->getHeap())));\n CAPTURE_IP(runtime->recordHiddenClass(\n curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));\n // obj may be moved by GC due to recordHiddenClass\n obj = objHandle.get();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n#endif\n auto clazzGCPtr = obj->getClassGCPtr();\n#ifndef NDEBUG\n if (clazzGCPtr.get(runtime)->isDictionary())\n ++NumGetByIdDict;\n#else\n (void)NumGetByIdDict;\n#endif\n\n // If we have a cache hit, reuse the cached offset and immediately\n // return the property.\n if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {\n ++NumGetByIdCacheHits;\n CAPTURE_IP_ASSIGN(\n O1REG(GetById),\n JSObject::getNamedSlotValue(\n obj, runtime, cacheEntry->slot));\n ip = nextIP;\n DISPATCH;\n }\n auto id = ID(idVal);\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n OptValue fastPathResult,\n JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));\n if (LLVM_LIKELY(\n fastPathResult.hasValue() && fastPathResult.getValue()) &&\n !desc.flags.accessor) {\n ++NumGetByIdFastPaths;\n\n // cacheIdx == 0 indicates no caching so don't update the cache in\n // those cases.\n auto *clazz = clazzGCPtr.getNonNull(runtime);\n if (LLVM_LIKELY(!clazz->isDictionaryNoCache()) &&\n LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {\n#ifdef HERMES_SLOW_DEBUG\n if (cacheEntry->clazz &&\n cacheEntry->clazz != clazzGCPtr.getStorageType())\n ++NumGetByIdCacheEvicts;\n#else\n (void)NumGetByIdCacheEvicts;\n#endif\n // Cache the class, id and property slot.\n cacheEntry->clazz = clazzGCPtr.getStorageType();\n cacheEntry->slot = desc.slot;\n }\n\n CAPTURE_IP_ASSIGN(\n O1REG(GetById), JSObject::getNamedSlotValue(obj, runtime, desc));\n ip = nextIP;\n DISPATCH;\n }\n\n // The cache may also be populated via the prototype of the object.\n // This value is only reliable if the fast path was a definite\n // not-found.\n if (fastPathResult.hasValue() && !fastPathResult.getValue() &&\n !obj->isProxyObject()) {\n CAPTURE_IP_ASSIGN(JSObject * parent, obj->getParent(runtime));\n // TODO: This isLazy check is because a lazy object is reported as\n // having no properties and therefore cannot contain the property.\n // This check does not belong here, it should be merged into\n // tryGetOwnNamedDescriptorFast().\n if (parent &&\n cacheEntry->clazz == parent->getClassGCPtr().getStorageType() &&\n LLVM_LIKELY(!obj->isLazy())) {\n ++NumGetByIdProtoHits;\n CAPTURE_IP_ASSIGN(\n O1REG(GetById),\n JSObject::getNamedSlotValue(parent, runtime, cacheEntry->slot));\n ip = nextIP;\n DISPATCH;\n }\n }\n\n#ifdef HERMES_SLOW_DEBUG\n CAPTURE_IP_ASSIGN(\n JSObject * propObj,\n JSObject::getNamedDescriptor(\n Handle::vmcast(&O2REG(GetById)), runtime, id, desc));\n if (propObj) {\n if (desc.flags.accessor)\n ++NumGetByIdAccessor;\n else if (propObj != vmcast(O2REG(GetById)))\n ++NumGetByIdProto;\n } else {\n ++NumGetByIdNotFound;\n }\n#else\n (void)NumGetByIdAccessor;\n (void)NumGetByIdProto;\n (void)NumGetByIdNotFound;\n#endif\n#ifdef HERMES_SLOW_DEBUG\n auto *savedClass = cacheIdx != hbc::PROPERTY_CACHING_DISABLED\n ? cacheEntry->clazz.get(runtime, &runtime->getHeap())\n : nullptr;\n#endif\n ++NumGetByIdSlow;\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getNamed_RJS(\n Handle::vmcast(&O2REG(GetById)),\n runtime,\n id,\n !tryProp ? defaultPropOpFlags\n : defaultPropOpFlags.plusMustExist(),\n cacheIdx != hbc::PROPERTY_CACHING_DISABLED ? cacheEntry\n : nullptr));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n#ifdef HERMES_SLOW_DEBUG\n if (cacheIdx != hbc::PROPERTY_CACHING_DISABLED && savedClass &&\n cacheEntry->clazz.get(runtime, &runtime->getHeap()) != savedClass) {\n ++NumGetByIdCacheEvicts;\n }\n#endif\n } else {\n ++NumGetByIdTransient;\n assert(!tryProp && \"TryGetById can only be used on the global object\");\n /* Slow path. */\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::getByIdTransient_RJS(\n runtime, Handle<>(&O2REG(GetById)), ID(idVal)));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n O1REG(GetById) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(TryPutByIdLong) {\n tryProp = true;\n idVal = ip->iTryPutByIdLong.op4;\n nextIP = NEXTINST(TryPutByIdLong);\n goto putById;\n }\n CASE(PutByIdLong) {\n tryProp = false;\n idVal = ip->iPutByIdLong.op4;\n nextIP = NEXTINST(PutByIdLong);\n goto putById;\n }\n CASE(TryPutById) {\n tryProp = true;\n idVal = ip->iTryPutById.op4;\n nextIP = NEXTINST(TryPutById);\n goto putById;\n }\n CASE(PutById) {\n tryProp = false;\n idVal = ip->iPutById.op4;\n nextIP = NEXTINST(PutById);\n }\n putById : {\n ++NumPutById;\n if (LLVM_LIKELY(O1REG(PutById).isObject())) {\n auto *obj = vmcast(O1REG(PutById));\n auto cacheIdx = ip->iPutById.op3;\n auto *cacheEntry = curCodeBlock->getWriteCacheEntry(cacheIdx);\n\n#ifdef HERMESVM_PROFILER_BB\n {\n HERMES_SLOW_ASSERT(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"unaccounted handles were created\");\n auto objHandle = runtime->makeHandle(obj);\n auto cacheHCPtr = vmcast_or_null(static_cast(\n cacheEntry->clazz.get(runtime, &runtime->getHeap())));\n CAPTURE_IP(runtime->recordHiddenClass(\n curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));\n // obj may be moved by GC due to recordHiddenClass\n obj = objHandle.get();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n#endif\n auto clazzGCPtr = obj->getClassGCPtr();\n // If we have a cache hit, reuse the cached offset and immediately\n // return the property.\n if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {\n ++NumPutByIdCacheHits;\n CAPTURE_IP(JSObject::setNamedSlotValue(\n obj, runtime, cacheEntry->slot, O2REG(PutById)));\n ip = nextIP;\n DISPATCH;\n }\n auto id = ID(idVal);\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n OptValue hasOwnProp,\n JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));\n if (LLVM_LIKELY(hasOwnProp.hasValue() && hasOwnProp.getValue()) &&\n !desc.flags.accessor && desc.flags.writable &&\n !desc.flags.internalSetter) {\n ++NumPutByIdFastPaths;\n\n // cacheIdx == 0 indicates no caching so don't update the cache in\n // those cases.\n auto *clazz = clazzGCPtr.getNonNull(runtime);\n if (LLVM_LIKELY(!clazz->isDictionary()) &&\n LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {\n#ifdef HERMES_SLOW_DEBUG\n if (cacheEntry->clazz &&\n cacheEntry->clazz != clazzGCPtr.getStorageType())\n ++NumPutByIdCacheEvicts;\n#else\n (void)NumPutByIdCacheEvicts;\n#endif\n // Cache the class and property slot.\n cacheEntry->clazz = clazzGCPtr.getStorageType();\n cacheEntry->slot = desc.slot;\n }\n\n CAPTURE_IP(JSObject::setNamedSlotValue(\n obj, runtime, desc.slot, O2REG(PutById)));\n ip = nextIP;\n DISPATCH;\n }\n\n CAPTURE_IP_ASSIGN(\n auto putRes,\n JSObject::putNamed_RJS(\n Handle::vmcast(&O1REG(PutById)),\n runtime,\n id,\n Handle<>(&O2REG(PutById)),\n !tryProp ? defaultPropOpFlags\n : defaultPropOpFlags.plusMustExist()));\n if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n ++NumPutByIdTransient;\n assert(!tryProp && \"TryPutById can only be used on the global object\");\n CAPTURE_IP_ASSIGN(\n auto retStatus,\n Interpreter::putByIdTransient_RJS(\n runtime,\n Handle<>(&O1REG(PutById)),\n ID(idVal),\n Handle<>(&O2REG(PutById)),\n strictMode));\n if (retStatus == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(GetByVal) {\n CallResult propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getComputed_RJS(\n Handle::vmcast(&O2REG(GetByVal)),\n runtime,\n Handle<>(&O3REG(GetByVal))));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::getByValTransient_RJS(\n runtime,\n Handle<>(&O2REG(GetByVal)),\n Handle<>(&O3REG(GetByVal))));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetByVal) = resPH->get();\n ip = NEXTINST(GetByVal);\n DISPATCH;\n }\n\n CASE(PutByVal) {\n if (LLVM_LIKELY(O1REG(PutByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto putRes,\n JSObject::putComputed_RJS(\n Handle::vmcast(&O1REG(PutByVal)),\n runtime,\n Handle<>(&O2REG(PutByVal)),\n Handle<>(&O3REG(PutByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(\n auto retStatus,\n Interpreter::putByValTransient_RJS(\n runtime,\n Handle<>(&O1REG(PutByVal)),\n Handle<>(&O2REG(PutByVal)),\n Handle<>(&O3REG(PutByVal)),\n strictMode));\n if (LLVM_UNLIKELY(retStatus == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(PutByVal);\n DISPATCH;\n }\n\n CASE(PutOwnByIndexL) {\n nextIP = NEXTINST(PutOwnByIndexL);\n idVal = ip->iPutOwnByIndexL.op3;\n goto putOwnByIndex;\n }\n CASE(PutOwnByIndex) {\n nextIP = NEXTINST(PutOwnByIndex);\n idVal = ip->iPutOwnByIndex.op3;\n }\n putOwnByIndex : {\n tmpHandle = HermesValue::encodeDoubleValue(idVal);\n CAPTURE_IP(JSObject::defineOwnComputedPrimitive(\n Handle::vmcast(&O1REG(PutOwnByIndex)),\n runtime,\n tmpHandle,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n Handle<>(&O2REG(PutOwnByIndex))));\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(GetPNameList) {\n CAPTURE_IP_ASSIGN(\n auto pRes, handleGetPNameList(runtime, frameRegs, ip));\n if (LLVM_UNLIKELY(pRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(GetPNameList);\n DISPATCH;\n }\n\n CASE(GetNextPName) {\n {\n assert(\n vmisa(O2REG(GetNextPName)) &&\n \"GetNextPName's second op must be BigStorage\");\n auto obj = Handle::vmcast(&O3REG(GetNextPName));\n auto arr = Handle::vmcast(&O2REG(GetNextPName));\n uint32_t idx = O4REG(GetNextPName).getNumber();\n uint32_t size = O5REG(GetNextPName).getNumber();\n MutableHandle propObj{runtime};\n // Loop until we find a property which is present.\n while (idx < size) {\n tmpHandle = arr->at(idx);\n ComputedPropertyDescriptor desc;\n CAPTURE_IP(JSObject::getComputedPrimitiveDescriptor(\n obj, runtime, tmpHandle, propObj, desc));\n if (LLVM_LIKELY(propObj))\n break;\n ++idx;\n }\n if (idx < size) {\n // We must return the property as a string\n if (tmpHandle->isNumber()) {\n CAPTURE_IP_ASSIGN(auto status, toString_RJS(runtime, tmpHandle));\n assert(\n status == ExecutionStatus::RETURNED &&\n \"toString on number cannot fail\");\n tmpHandle = status->getHermesValue();\n }\n O1REG(GetNextPName) = tmpHandle.get();\n O4REG(GetNextPName) = HermesValue::encodeNumberValue(idx + 1);\n } else {\n O1REG(GetNextPName) = HermesValue::encodeUndefinedValue();\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(GetNextPName);\n DISPATCH;\n }\n\n CASE(ToNumber) {\n if (LLVM_LIKELY(O2REG(ToNumber).isNumber())) {\n O1REG(ToNumber) = O2REG(ToNumber);\n ip = NEXTINST(ToNumber);\n } else {\n CAPTURE_IP_ASSIGN(\n res, toNumber_RJS(runtime, Handle<>(&O2REG(ToNumber))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(ToNumber) = res.getValue();\n ip = NEXTINST(ToNumber);\n }\n DISPATCH;\n }\n\n CASE(ToInt32) {\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(ToInt32))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(ToInt32) = res.getValue();\n ip = NEXTINST(ToInt32);\n DISPATCH;\n }\n\n CASE(AddEmptyString) {\n if (LLVM_LIKELY(O2REG(AddEmptyString).isString())) {\n O1REG(AddEmptyString) = O2REG(AddEmptyString);\n ip = NEXTINST(AddEmptyString);\n } else {\n CAPTURE_IP_ASSIGN(\n res,\n toPrimitive_RJS(\n runtime,\n Handle<>(&O2REG(AddEmptyString)),\n PreferredType::NONE));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(auto strRes, toString_RJS(runtime, tmpHandle));\n if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION))\n goto exception;\n tmpHandle.clear();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(AddEmptyString) = strRes->getHermesValue();\n ip = NEXTINST(AddEmptyString);\n }\n DISPATCH;\n }\n\n CASE(Jmp) {\n ip = IPADD(ip->iJmp.op1);\n DISPATCH;\n }\n CASE(JmpLong) {\n ip = IPADD(ip->iJmpLong.op1);\n DISPATCH;\n }\n CASE(JmpTrue) {\n if (toBoolean(O2REG(JmpTrue)))\n ip = IPADD(ip->iJmpTrue.op1);\n else\n ip = NEXTINST(JmpTrue);\n DISPATCH;\n }\n CASE(JmpTrueLong) {\n if (toBoolean(O2REG(JmpTrueLong)))\n ip = IPADD(ip->iJmpTrueLong.op1);\n else\n ip = NEXTINST(JmpTrueLong);\n DISPATCH;\n }\n CASE(JmpFalse) {\n if (!toBoolean(O2REG(JmpFalse)))\n ip = IPADD(ip->iJmpFalse.op1);\n else\n ip = NEXTINST(JmpFalse);\n DISPATCH;\n }\n CASE(JmpFalseLong) {\n if (!toBoolean(O2REG(JmpFalseLong)))\n ip = IPADD(ip->iJmpFalseLong.op1);\n else\n ip = NEXTINST(JmpFalseLong);\n DISPATCH;\n }\n CASE(JmpUndefined) {\n if (O2REG(JmpUndefined).isUndefined())\n ip = IPADD(ip->iJmpUndefined.op1);\n else\n ip = NEXTINST(JmpUndefined);\n DISPATCH;\n }\n CASE(JmpUndefinedLong) {\n if (O2REG(JmpUndefinedLong).isUndefined())\n ip = IPADD(ip->iJmpUndefinedLong.op1);\n else\n ip = NEXTINST(JmpUndefinedLong);\n DISPATCH;\n }\n CASE(Add) {\n if (LLVM_LIKELY(\n O2REG(Add).isNumber() &&\n O3REG(Add).isNumber())) { /* Fast-path. */\n CASE(AddN) {\n O1REG(Add) = HermesValue::encodeDoubleValue(\n O2REG(Add).getNumber() + O3REG(Add).getNumber());\n ip = NEXTINST(Add);\n DISPATCH;\n }\n }\n CAPTURE_IP_ASSIGN(\n res,\n addOp_RJS(runtime, Handle<>(&O2REG(Add)), Handle<>(&O3REG(Add))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Add) = res.getValue();\n ip = NEXTINST(Add);\n DISPATCH;\n }\n\n CASE(BitNot) {\n if (LLVM_LIKELY(O2REG(BitNot).isNumber())) { /* Fast-path. */\n O1REG(BitNot) = HermesValue::encodeDoubleValue(\n ~hermes::truncateToInt32(O2REG(BitNot).getNumber()));\n ip = NEXTINST(BitNot);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(BitNot))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(BitNot) = HermesValue::encodeDoubleValue(\n ~static_cast(res->getNumber()));\n ip = NEXTINST(BitNot);\n DISPATCH;\n }\n\n CASE(GetArgumentsLength) {\n // If the arguments object hasn't been created yet.\n if (O2REG(GetArgumentsLength).isUndefined()) {\n O1REG(GetArgumentsLength) =\n HermesValue::encodeNumberValue(FRAME.getArgCount());\n ip = NEXTINST(GetArgumentsLength);\n DISPATCH;\n }\n // The arguments object has been created, so this is a regular property\n // get.\n assert(\n O2REG(GetArgumentsLength).isObject() &&\n \"arguments lazy register is not an object\");\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getNamed_RJS(\n Handle::vmcast(&O2REG(GetArgumentsLength)),\n runtime,\n Predefined::getSymbolID(Predefined::length)));\n if (resPH == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetArgumentsLength) = resPH->get();\n ip = NEXTINST(GetArgumentsLength);\n DISPATCH;\n }\n\n CASE(GetArgumentsPropByVal) {\n // If the arguments object hasn't been created yet and we have a\n // valid integer index, we use the fast path.\n if (O3REG(GetArgumentsPropByVal).isUndefined()) {\n // If this is an integer index.\n if (auto index = toArrayIndexFastPath(O2REG(GetArgumentsPropByVal))) {\n // Is this an existing argument?\n if (*index < FRAME.getArgCount()) {\n O1REG(GetArgumentsPropByVal) = FRAME.getArgRef(*index);\n ip = NEXTINST(GetArgumentsPropByVal);\n DISPATCH;\n }\n }\n }\n // Slow path.\n CAPTURE_IP_ASSIGN(\n auto res,\n getArgumentsPropByValSlowPath_RJS(\n runtime,\n &O3REG(GetArgumentsPropByVal),\n &O2REG(GetArgumentsPropByVal),\n FRAME.getCalleeClosureHandleUnsafe(),\n strictMode));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetArgumentsPropByVal) = res->getHermesValue();\n ip = NEXTINST(GetArgumentsPropByVal);\n DISPATCH;\n }\n\n CASE(ReifyArguments) {\n // If the arguments object was already created, do nothing.\n if (!O1REG(ReifyArguments).isUndefined()) {\n assert(\n O1REG(ReifyArguments).isObject() &&\n \"arguments lazy register is not an object\");\n ip = NEXTINST(ReifyArguments);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(\n resArgs,\n reifyArgumentsSlowPath(\n runtime, FRAME.getCalleeClosureHandleUnsafe(), strictMode));\n if (LLVM_UNLIKELY(resArgs == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(ReifyArguments) = resArgs->getHermesValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(ReifyArguments);\n DISPATCH;\n }\n\n CASE(NewObject) {\n // Create a new object using the built-in constructor. Note that the\n // built-in constructor is empty, so we don't actually need to call\n // it.\n CAPTURE_IP_ASSIGN(\n O1REG(NewObject), JSObject::create(runtime).getHermesValue());\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"Should not create handles.\");\n ip = NEXTINST(NewObject);\n DISPATCH;\n }\n CASE(NewObjectWithParent) {\n CAPTURE_IP_ASSIGN(\n O1REG(NewObjectWithParent),\n JSObject::create(\n runtime,\n O2REG(NewObjectWithParent).isObject()\n ? Handle::vmcast(&O2REG(NewObjectWithParent))\n : O2REG(NewObjectWithParent).isNull()\n ? Runtime::makeNullHandle()\n : Handle::vmcast(&runtime->objectPrototype))\n .getHermesValue());\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"Should not create handles.\");\n ip = NEXTINST(NewObjectWithParent);\n DISPATCH;\n }\n\n CASE(NewObjectWithBuffer) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createObjectFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewObjectWithBuffer.op3,\n ip->iNewObjectWithBuffer.op4,\n ip->iNewObjectWithBuffer.op5));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewObjectWithBuffer) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewObjectWithBuffer);\n DISPATCH;\n }\n\n CASE(NewObjectWithBufferLong) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createObjectFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewObjectWithBufferLong.op3,\n ip->iNewObjectWithBufferLong.op4,\n ip->iNewObjectWithBufferLong.op5));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewObjectWithBufferLong) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewObjectWithBufferLong);\n DISPATCH;\n }\n\n CASE(NewArray) {\n // Create a new array using the built-in constructor. Note that the\n // built-in constructor is empty, so we don't actually need to call\n // it.\n CAPTURE_IP_ASSIGN(\n auto createRes,\n JSArray::create(runtime, ip->iNewArray.op2, ip->iNewArray.op2));\n if (createRes == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(NewArray) = createRes->getHermesValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewArray);\n DISPATCH;\n }\n\n CASE(NewArrayWithBuffer) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createArrayFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewArrayWithBuffer.op2,\n ip->iNewArrayWithBuffer.op3,\n ip->iNewArrayWithBuffer.op4));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewArrayWithBuffer) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(NewArrayWithBuffer);\n DISPATCH;\n }\n\n CASE(NewArrayWithBufferLong) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createArrayFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewArrayWithBufferLong.op2,\n ip->iNewArrayWithBufferLong.op3,\n ip->iNewArrayWithBufferLong.op4));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewArrayWithBufferLong) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(NewArrayWithBufferLong);\n DISPATCH;\n }\n\n CASE(CreateThis) {\n // Registers: output, prototype, closure.\n if (LLVM_UNLIKELY(!vmisa(O3REG(CreateThis)))) {\n CAPTURE_IP(runtime->raiseTypeError(\"constructor is not callable\"));\n goto exception;\n }\n CAPTURE_IP_ASSIGN(\n auto res,\n Callable::newObject(\n Handle::vmcast(&O3REG(CreateThis)),\n runtime,\n Handle::vmcast(\n O2REG(CreateThis).isObject() ? &O2REG(CreateThis)\n : &runtime->objectPrototype)));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(CreateThis) = res->getHermesValue();\n ip = NEXTINST(CreateThis);\n DISPATCH;\n }\n\n CASE(SelectObject) {\n // Registers: output, thisObject, constructorReturnValue.\n O1REG(SelectObject) = O3REG(SelectObject).isObject()\n ? O3REG(SelectObject)\n : O2REG(SelectObject);\n ip = NEXTINST(SelectObject);\n DISPATCH;\n }\n\n CASE(Eq)\n CASE(Neq) {\n CAPTURE_IP_ASSIGN(\n res,\n abstractEqualityTest_RJS(\n runtime, Handle<>(&O2REG(Eq)), Handle<>(&O3REG(Eq))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Eq) = ip->opCode == OpCode::Eq\n ? res.getValue()\n : HermesValue::encodeBoolValue(!res->getBool());\n ip = NEXTINST(Eq);\n DISPATCH;\n }\n CASE(StrictEq) {\n O1REG(StrictEq) = HermesValue::encodeBoolValue(\n strictEqualityTest(O2REG(StrictEq), O3REG(StrictEq)));\n ip = NEXTINST(StrictEq);\n DISPATCH;\n }\n CASE(StrictNeq) {\n O1REG(StrictNeq) = HermesValue::encodeBoolValue(\n !strictEqualityTest(O2REG(StrictNeq), O3REG(StrictNeq)));\n ip = NEXTINST(StrictNeq);\n DISPATCH;\n }\n CASE(Not) {\n O1REG(Not) = HermesValue::encodeBoolValue(!toBoolean(O2REG(Not)));\n ip = NEXTINST(Not);\n DISPATCH;\n }\n CASE(Negate) {\n if (LLVM_LIKELY(O2REG(Negate).isNumber())) {\n O1REG(Negate) =\n HermesValue::encodeDoubleValue(-O2REG(Negate).getNumber());\n } else {\n CAPTURE_IP_ASSIGN(\n res, toNumber_RJS(runtime, Handle<>(&O2REG(Negate))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Negate) = HermesValue::encodeDoubleValue(-res->getNumber());\n }\n ip = NEXTINST(Negate);\n DISPATCH;\n }\n CASE(TypeOf) {\n CAPTURE_IP_ASSIGN(\n O1REG(TypeOf), typeOf(runtime, Handle<>(&O2REG(TypeOf))));\n ip = NEXTINST(TypeOf);\n DISPATCH;\n }\n CASE(Mod) {\n // We use fmod here for simplicity. Theoretically fmod behaves slightly\n // differently than the ECMAScript Spec. fmod applies round-towards-zero\n // for the remainder when it's not representable by a double; while the\n // spec requires round-to-nearest. As an example, 5 % 0.7 will give\n // 0.10000000000000031 using fmod, but using the rounding style\n // described\n // by the spec, the output should really be 0.10000000000000053.\n // Such difference can be ignored in practice.\n if (LLVM_LIKELY(O2REG(Mod).isNumber() && O3REG(Mod).isNumber())) {\n /* Fast-path. */\n O1REG(Mod) = HermesValue::encodeDoubleValue(\n std::fmod(O2REG(Mod).getNumber(), O3REG(Mod).getNumber()));\n ip = NEXTINST(Mod);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(Mod))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n double left = res->getDouble();\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(Mod))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n O1REG(Mod) =\n HermesValue::encodeDoubleValue(std::fmod(left, res->getDouble()));\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(Mod);\n DISPATCH;\n }\n CASE(InstanceOf) {\n CAPTURE_IP_ASSIGN(\n auto result,\n instanceOfOperator_RJS(\n runtime,\n Handle<>(&O2REG(InstanceOf)),\n Handle<>(&O3REG(InstanceOf))));\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(InstanceOf) = HermesValue::encodeBoolValue(*result);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(InstanceOf);\n DISPATCH;\n }\n CASE(IsIn) {\n {\n if (LLVM_UNLIKELY(!O3REG(IsIn).isObject())) {\n CAPTURE_IP(runtime->raiseTypeError(\n \"right operand of 'in' is not an object\"));\n goto exception;\n }\n CAPTURE_IP_ASSIGN(\n auto cr,\n JSObject::hasComputed(\n Handle::vmcast(&O3REG(IsIn)),\n runtime,\n Handle<>(&O2REG(IsIn))));\n if (cr == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(IsIn) = HermesValue::encodeBoolValue(*cr);\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(IsIn);\n DISPATCH;\n }\n\n CASE(PutNewOwnByIdShort) {\n nextIP = NEXTINST(PutNewOwnByIdShort);\n idVal = ip->iPutNewOwnByIdShort.op3;\n goto putOwnById;\n }\n CASE(PutNewOwnNEByIdLong)\n CASE(PutNewOwnByIdLong) {\n nextIP = NEXTINST(PutNewOwnByIdLong);\n idVal = ip->iPutNewOwnByIdLong.op3;\n goto putOwnById;\n }\n CASE(PutNewOwnNEById)\n CASE(PutNewOwnById) {\n nextIP = NEXTINST(PutNewOwnById);\n idVal = ip->iPutNewOwnById.op3;\n }\n putOwnById : {\n assert(\n O1REG(PutNewOwnById).isObject() &&\n \"Object argument of PutNewOwnById must be an object\");\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::defineNewOwnProperty(\n Handle::vmcast(&O1REG(PutNewOwnById)),\n runtime,\n ID(idVal),\n ip->opCode <= OpCode::PutNewOwnByIdLong\n ? PropertyFlags::defaultNewNamedPropertyFlags()\n : PropertyFlags::nonEnumerablePropertyFlags(),\n Handle<>(&O2REG(PutNewOwnById))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(DelByIdLong) {\n idVal = ip->iDelByIdLong.op3;\n nextIP = NEXTINST(DelByIdLong);\n goto DelById;\n }\n\n CASE(DelById) {\n idVal = ip->iDelById.op3;\n nextIP = NEXTINST(DelById);\n }\n DelById : {\n if (LLVM_LIKELY(O2REG(DelById).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteNamed(\n Handle::vmcast(&O2REG(DelById)),\n runtime,\n ID(idVal),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelById))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n // If an exception is thrown, likely we are trying to convert\n // undefined/null to an object. Passing over the name of the property\n // so that we could emit more meaningful error messages.\n CAPTURE_IP(amendPropAccessErrorMsgWithPropName(\n runtime, Handle<>(&O2REG(DelById)), \"delete\", ID(idVal)));\n goto exception;\n }\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteNamed(\n Handle::vmcast(tmpHandle),\n runtime,\n ID(idVal),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());\n tmpHandle.clear();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(DelByVal) {\n if (LLVM_LIKELY(O2REG(DelByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteComputed(\n Handle::vmcast(&O2REG(DelByVal)),\n runtime,\n Handle<>(&O3REG(DelByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelByVal))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteComputed(\n Handle::vmcast(tmpHandle),\n runtime,\n Handle<>(&O3REG(DelByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(DelByVal);\n DISPATCH;\n }\n CASE(CreateRegExp) {\n {\n // Create the RegExp object.\n CAPTURE_IP_ASSIGN(auto re, JSRegExp::create(runtime));\n // Initialize the regexp.\n CAPTURE_IP_ASSIGN(\n auto pattern,\n runtime->makeHandle(curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iCreateRegExp.op2)));\n CAPTURE_IP_ASSIGN(\n auto flags,\n runtime->makeHandle(curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iCreateRegExp.op3)));\n CAPTURE_IP_ASSIGN(\n auto bytecode,\n curCodeBlock->getRuntimeModule()->getRegExpBytecodeFromRegExpID(\n ip->iCreateRegExp.op4));\n CAPTURE_IP_ASSIGN(\n auto initRes,\n JSRegExp::initialize(re, runtime, pattern, flags, bytecode));\n if (LLVM_UNLIKELY(initRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n // Done, return the new object.\n O1REG(CreateRegExp) = re.getHermesValue();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateRegExp);\n DISPATCH;\n }\n\n CASE(SwitchImm) {\n if (LLVM_LIKELY(O1REG(SwitchImm).isNumber())) {\n double numVal = O1REG(SwitchImm).getNumber();\n uint32_t uintVal = (uint32_t)numVal;\n if (LLVM_LIKELY(numVal == uintVal) && // Only integers.\n LLVM_LIKELY(uintVal >= ip->iSwitchImm.op4) && // Bounds checking.\n LLVM_LIKELY(uintVal <= ip->iSwitchImm.op5)) // Bounds checking.\n {\n // Calculate the offset into the bytecode where the jump table for\n // this SwitchImm starts.\n const uint8_t *tablestart = (const uint8_t *)llvh::alignAddr(\n (const uint8_t *)ip + ip->iSwitchImm.op2, sizeof(uint32_t));\n\n // Read the offset from the table.\n // Must be signed to account for backwards branching.\n const int32_t *loc =\n (const int32_t *)tablestart + uintVal - ip->iSwitchImm.op4;\n\n ip = IPADD(*loc);\n DISPATCH;\n }\n }\n // Wrong type or out of range, jump to default.\n ip = IPADD(ip->iSwitchImm.op3);\n DISPATCH;\n }\n LOAD_CONST(\n LoadConstUInt8,\n HermesValue::encodeDoubleValue(ip->iLoadConstUInt8.op2));\n LOAD_CONST(\n LoadConstInt, HermesValue::encodeDoubleValue(ip->iLoadConstInt.op2));\n LOAD_CONST(\n LoadConstDouble,\n HermesValue::encodeDoubleValue(ip->iLoadConstDouble.op2));\n LOAD_CONST_CAPTURE_IP(\n LoadConstString,\n HermesValue::encodeStringValue(\n curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iLoadConstString.op2)));\n LOAD_CONST_CAPTURE_IP(\n LoadConstStringLongIndex,\n HermesValue::encodeStringValue(\n curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iLoadConstStringLongIndex.op2)));\n LOAD_CONST(LoadConstUndefined, HermesValue::encodeUndefinedValue());\n LOAD_CONST(LoadConstNull, HermesValue::encodeNullValue());\n LOAD_CONST(LoadConstTrue, HermesValue::encodeBoolValue(true));\n LOAD_CONST(LoadConstFalse, HermesValue::encodeBoolValue(false));\n LOAD_CONST(LoadConstZero, HermesValue::encodeDoubleValue(0));\n BINOP(Sub, doSub);\n BINOP(Mul, doMult);\n BINOP(Div, doDiv);\n BITWISEBINOP(BitAnd, &);\n BITWISEBINOP(BitOr, |);\n BITWISEBINOP(BitXor, ^);\n // For LShift, we need to use toUInt32 first because lshift on negative\n // numbers is undefined behavior in theory.\n SHIFTOP(LShift, <<, toUInt32_RJS, uint32_t, int32_t);\n SHIFTOP(RShift, >>, toInt32_RJS, int32_t, int32_t);\n SHIFTOP(URshift, >>, toUInt32_RJS, uint32_t, uint32_t);\n CONDOP(Less, <, lessOp_RJS);\n CONDOP(LessEq, <=, lessEqualOp_RJS);\n CONDOP(Greater, >, greaterOp_RJS);\n CONDOP(GreaterEq, >=, greaterEqualOp_RJS);\n JCOND(Less, <, lessOp_RJS);\n JCOND(LessEqual, <=, lessEqualOp_RJS);\n JCOND(Greater, >, greaterOp_RJS);\n JCOND(GreaterEqual, >=, greaterEqualOp_RJS);\n\n JCOND_STRICT_EQ_IMPL(\n JStrictEqual, , IPADD(ip->iJStrictEqual.op1), NEXTINST(JStrictEqual));\n JCOND_STRICT_EQ_IMPL(\n JStrictEqual,\n Long,\n IPADD(ip->iJStrictEqualLong.op1),\n NEXTINST(JStrictEqualLong));\n JCOND_STRICT_EQ_IMPL(\n JStrictNotEqual,\n ,\n NEXTINST(JStrictNotEqual),\n IPADD(ip->iJStrictNotEqual.op1));\n JCOND_STRICT_EQ_IMPL(\n JStrictNotEqual,\n Long,\n NEXTINST(JStrictNotEqualLong),\n IPADD(ip->iJStrictNotEqualLong.op1));\n\n JCOND_EQ_IMPL(JEqual, , IPADD(ip->iJEqual.op1), NEXTINST(JEqual));\n JCOND_EQ_IMPL(\n JEqual, Long, IPADD(ip->iJEqualLong.op1), NEXTINST(JEqualLong));\n JCOND_EQ_IMPL(\n JNotEqual, , NEXTINST(JNotEqual), IPADD(ip->iJNotEqual.op1));\n JCOND_EQ_IMPL(\n JNotEqual,\n Long,\n NEXTINST(JNotEqualLong),\n IPADD(ip->iJNotEqualLong.op1));\n\n CASE_OUTOFLINE(PutOwnByVal);\n CASE_OUTOFLINE(PutOwnGetterSetterByVal);\n CASE_OUTOFLINE(DirectEval);\n\n CASE_OUTOFLINE(IteratorBegin);\n CASE_OUTOFLINE(IteratorNext);\n CASE(IteratorClose) {\n if (LLVM_UNLIKELY(O1REG(IteratorClose).isObject())) {\n // The iterator must be closed if it's still an object.\n // That means it was never an index and is not done iterating (a state\n // which is indicated by `undefined`).\n CAPTURE_IP_ASSIGN(\n auto res,\n iteratorClose(\n runtime,\n Handle::vmcast(&O1REG(IteratorClose)),\n Runtime::getEmptyValue()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n if (ip->iIteratorClose.op2 &&\n !isUncatchableError(runtime->thrownValue_)) {\n // Ignore inner exception.\n runtime->clearThrownValue();\n } else {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n ip = NEXTINST(IteratorClose);\n DISPATCH;\n }\n\n CASE(_last) {\n llvm_unreachable(\"Invalid opcode _last\");\n }\n }\n\n llvm_unreachable(\"unreachable\");\n\n // We arrive here if we couldn't allocate the registers for the current frame.\n stackOverflow:\n CAPTURE_IP(runtime->raiseStackOverflow(\n Runtime::StackOverflowKind::JSRegisterStack));\n\n // We arrive here when we raised an exception in a callee, but we don't want\n // the callee to be able to handle it.\n handleExceptionInParent:\n // Restore the caller code block and IP.\n curCodeBlock = FRAME.getSavedCodeBlock();\n ip = FRAME.getSavedIP();\n\n // Pop to the previous frame where technically the error happened.\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n // If we are coming from native code, return.\n if (!curCodeBlock)\n return ExecutionStatus::EXCEPTION;\n\n// Return because of recursive calling structure\n#ifdef HERMESVM_PROFILER_EXTERN\n return ExecutionStatus::EXCEPTION;\n#endif\n // Handle the exception.\n exception:\n UPDATE_OPCODE_TIME_SPENT;\n assert(\n !runtime->thrownValue_.isEmpty() &&\n \"thrownValue unavailable at exception\");\n\n bool catchable = true;\n // If this is an Error object that was thrown internally, it didn't have\n // access to the current codeblock and IP, so collect the stack trace here.\n if (auto *jsError = dyn_vmcast(runtime->thrownValue_)) {\n catchable = jsError->catchable();\n if (!jsError->getStackTrace()) {\n // Temporarily clear the thrown value for following operations.\n CAPTURE_IP_ASSIGN(\n auto errorHandle,\n runtime->makeHandle(vmcast(runtime->thrownValue_)));\n runtime->clearThrownValue();\n\n CAPTURE_IP(JSError::recordStackTrace(\n errorHandle, runtime, false, curCodeBlock, ip));\n\n // Restore the thrown value.\n runtime->setThrownValue(errorHandle.getHermesValue());\n }\n }\n\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n\n#ifdef HERMES_ENABLE_DEBUGGER\n if (SingleStep) {\n // If we're single stepping, don't bother with any more checks,\n // and simply signal that we should continue execution with an exception.\n state.codeBlock = curCodeBlock;\n state.offset = CUROFFSET;\n return ExecutionStatus::EXCEPTION;\n }\n\n using PauseOnThrowMode = facebook::hermes::debugger::PauseOnThrowMode;\n auto mode = runtime->debugger_.getPauseOnThrowMode();\n if (mode != PauseOnThrowMode::None) {\n if (!runtime->debugger_.isDebugging()) {\n // Determine whether the PauseOnThrowMode requires us to stop here.\n bool caught =\n runtime->debugger_\n .findCatchTarget(InterpreterState(curCodeBlock, CUROFFSET))\n .hasValue();\n bool shouldStop = mode == PauseOnThrowMode::All ||\n (mode == PauseOnThrowMode::Uncaught && !caught);\n if (shouldStop) {\n // When runDebugger is invoked after an exception,\n // stepping should never happen internally.\n // Any step is a step to an exception handler, which we do\n // directly here in the interpreter.\n // Thus, the result state should be the same as the input state.\n InterpreterState tmpState{curCodeBlock, (uint32_t)CUROFFSET};\n CAPTURE_IP_ASSIGN(\n ExecutionStatus resultStatus,\n runtime->debugger_.runDebugger(\n Debugger::RunReason::Exception, tmpState));\n (void)resultStatus;\n assert(\n tmpState == InterpreterState(curCodeBlock, CUROFFSET) &&\n \"not allowed to step internally in a pauseOnThrow\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n }\n }\n#endif\n\n int32_t handlerOffset = 0;\n\n // If the exception is not catchable, skip found catch blocks.\n while (((handlerOffset = curCodeBlock->findCatchTargetOffset(CUROFFSET)) ==\n -1) ||\n !catchable) {\n PROFILER_EXIT_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->popCallStack();\n#endif\n\n // Restore the code block and IP.\n curCodeBlock = FRAME.getSavedCodeBlock();\n ip = FRAME.getSavedIP();\n\n // Pop a stack frame.\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n SLOW_DEBUG(\n dbgs() << \"function exit with exception: restored stackLevel=\"\n << runtime->getStackLevel() << \"\\n\");\n\n // Are we returning to native code?\n if (!curCodeBlock) {\n SLOW_DEBUG(\n dbgs()\n << \"function exit with exception: returning to native code\\n\");\n return ExecutionStatus::EXCEPTION;\n }\n\n assert(\n isCallType(ip->opCode) &&\n \"return address is not Call-type instruction\");\n\n// Return because of recursive calling structure\n#ifdef HERMESVM_PROFILER_EXTERN\n return ExecutionStatus::EXCEPTION;\n#endif\n }\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n\n ip = IPADD(handlerOffset - CUROFFSET);\n }\n}", "project": "hermes", "hash": 239731606711042238751809560389055742004, "size": 2753, "commit_id": "b2021df620824627f5a8c96615edbd1eb7fdddfc", "message": "Fix CVE-2020-1914 by using NEXTINST for SaveGeneratorLong\n\nSummary:\nIf `SaveGeneratorLong` was emitted, it would accidentally jump to the\nwrong next instruction, based on how long SaveGenerator was.\n\nMake a callout function to handle the common case, and handle the dispatch\nwithin each case of the interpreter loop.\n\nFixes CVE-2020-1914\n\nReviewed By: neildhar\n\nDifferential Revision: D24024242\n\nfbshipit-source-id: 3bcb88daa740f0d50e91771a49eb212551ce8bd8", "target": 1, "dataset": "other", "idx": 199924} {"func": "CallResult Interpreter::interpretFunction(\n Runtime *runtime,\n InterpreterState &state) {\n // The interepter is re-entrant and also saves/restores its IP via the runtime\n // whenever a call out is made (see the CAPTURE_IP_* macros). As such, failure\n // to preserve the IP across calls to interpeterFunction() disrupt interpreter\n // calls further up the C++ callstack. The RAII utility class below makes sure\n // we always do this correctly.\n //\n // TODO: The IPs stored in the C++ callstack via this holder will generally be\n // the same as in the JS stack frames via the Saved IP field. We can probably\n // get rid of one of these redundant stores. Doing this isn't completely\n // trivial as there are currently cases where we re-enter the interpreter\n // without calling Runtime::saveCallerIPInStackFrame(), and there are features\n // (I think mostly the debugger + stack traces) which implicitly rely on\n // this behavior. At least their tests break if this behavior is not\n // preserved.\n struct IPSaver {\n IPSaver(Runtime *runtime)\n : ip_(runtime->getCurrentIP()), runtime_(runtime) {}\n\n ~IPSaver() {\n runtime_->setCurrentIP(ip_);\n }\n\n private:\n const Inst *ip_;\n Runtime *runtime_;\n };\n IPSaver ipSaver(runtime);\n\n#ifndef HERMES_ENABLE_DEBUGGER\n static_assert(!SingleStep, \"can't use single-step mode without the debugger\");\n#endif\n // Make sure that the cache can use an optimization by avoiding a branch to\n // access the property storage.\n static_assert(\n HiddenClass::kDictionaryThreshold <=\n SegmentedArray::kValueToSegmentThreshold,\n \"Cannot avoid branches in cache check if the dictionary \"\n \"crossover point is larger than the inline storage\");\n\n CodeBlock *curCodeBlock = state.codeBlock;\n const Inst *ip = nullptr;\n // Holds runtime->currentFrame_.ptr()-1 which is the first local\n // register. This eliminates the indirect load from Runtime and the -1 offset.\n PinnedHermesValue *frameRegs;\n // Strictness of current function.\n bool strictMode;\n // Default flags when accessing properties.\n PropOpFlags defaultPropOpFlags;\n\n// These CAPTURE_IP* macros should wrap around any major calls out of the\n// interpeter loop. They stash and retrieve the IP via the current Runtime\n// allowing the IP to be externally observed and even altered to change the flow\n// of execution. Explicitly saving AND restoring the IP from the Runtime in this\n// way means the C++ compiler will keep IP in a register within the rest of the\n// interpeter loop.\n//\n// When assertions are enabled we take the extra step of \"invalidating\" the IP\n// between captures so we can detect if it's erroneously accessed.\n//\n// In some cases we explicitly don't want to invalidate the IP and instead want\n// it to stay set. For this we use the *NO_INVALIDATE variants. This comes up\n// when we're performing a call operation which may re-enter the interpeter\n// loop, and so need the IP available for the saveCallerIPInStackFrame() call\n// when we next enter.\n#define CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr) \\\n runtime->setCurrentIP(ip); \\\n dst = expr; \\\n ip = runtime->getCurrentIP();\n\n#ifdef NDEBUG\n\n#define CAPTURE_IP(expr) \\\n runtime->setCurrentIP(ip); \\\n (void)expr; \\\n ip = runtime->getCurrentIP();\n\n#define CAPTURE_IP_ASSIGN(dst, expr) CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr)\n\n#else // !NDEBUG\n\n#define CAPTURE_IP(expr) \\\n runtime->setCurrentIP(ip); \\\n (void)expr; \\\n ip = runtime->getCurrentIP(); \\\n runtime->invalidateCurrentIP();\n\n#define CAPTURE_IP_ASSIGN(dst, expr) \\\n runtime->setCurrentIP(ip); \\\n dst = expr; \\\n ip = runtime->getCurrentIP(); \\\n runtime->invalidateCurrentIP();\n\n#endif // NDEBUG\n\n/// \\def DONT_CAPTURE_IP(expr)\n/// \\param expr A call expression to a function external to the interpreter. The\n/// expression should not make any allocations and the IP should be set\n/// immediately following this macro.\n#define DONT_CAPTURE_IP(expr) \\\n do { \\\n NoAllocScope noAlloc(runtime); \\\n (void)expr; \\\n } while (false)\n\n LLVM_DEBUG(dbgs() << \"interpretFunction() called\\n\");\n\n ScopedNativeDepthTracker depthTracker{runtime};\n if (LLVM_UNLIKELY(depthTracker.overflowed())) {\n return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);\n }\n\n if (!SingleStep) {\n if (auto jitPtr = runtime->jitContext_.compile(runtime, curCodeBlock)) {\n return (*jitPtr)(runtime);\n }\n }\n\n GCScope gcScope(runtime);\n // Avoid allocating a handle dynamically by reusing this one.\n MutableHandle<> tmpHandle(runtime);\n CallResult res{ExecutionStatus::EXCEPTION};\n CallResult> resPH{ExecutionStatus::EXCEPTION};\n CallResult> resArgs{ExecutionStatus::EXCEPTION};\n CallResult boolRes{ExecutionStatus::EXCEPTION};\n\n // Mark the gcScope so we can clear all allocated handles.\n // Remember how many handles the scope has so we can clear them in the loop.\n static constexpr unsigned KEEP_HANDLES = 1;\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"scope has unexpected number of handles\");\n\n INIT_OPCODE_PROFILER;\n\n#if !defined(HERMESVM_PROFILER_EXTERN)\ntailCall:\n#endif\n PROFILER_ENTER_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_DEBUGGER\n runtime->getDebugger().willEnterCodeBlock(curCodeBlock);\n#endif\n\n runtime->getCodeCoverageProfiler().markExecuted(runtime, curCodeBlock);\n\n // Update function executionCount_ count\n curCodeBlock->incrementExecutionCount();\n\n if (!SingleStep) {\n auto newFrame = runtime->setCurrentFrameToTopOfStack();\n runtime->saveCallerIPInStackFrame();\n#ifndef NDEBUG\n runtime->invalidateCurrentIP();\n#endif\n\n // Point frameRegs to the first register in the new frame. Note that at this\n // moment technically it points above the top of the stack, but we are never\n // going to access it.\n frameRegs = &newFrame.getFirstLocalRef();\n\n#ifndef NDEBUG\n LLVM_DEBUG(\n dbgs() << \"function entry: stackLevel=\" << runtime->getStackLevel()\n << \", argCount=\" << runtime->getCurrentFrame().getArgCount()\n << \", frameSize=\" << curCodeBlock->getFrameSize() << \"\\n\");\n\n LLVM_DEBUG(\n dbgs() << \" callee \"\n << DumpHermesValue(\n runtime->getCurrentFrame().getCalleeClosureOrCBRef())\n << \"\\n\");\n LLVM_DEBUG(\n dbgs() << \" this \"\n << DumpHermesValue(runtime->getCurrentFrame().getThisArgRef())\n << \"\\n\");\n for (uint32_t i = 0; i != runtime->getCurrentFrame()->getArgCount(); ++i) {\n LLVM_DEBUG(\n dbgs() << \" \" << llvh::format_decimal(i, 4) << \" \"\n << DumpHermesValue(runtime->getCurrentFrame().getArgRef(i))\n << \"\\n\");\n }\n#endif\n\n // Allocate the registers for the new frame.\n if (LLVM_UNLIKELY(!runtime->checkAndAllocStack(\n curCodeBlock->getFrameSize() +\n StackFrameLayout::CalleeExtraRegistersAtStart,\n HermesValue::encodeUndefinedValue())))\n goto stackOverflow;\n\n ip = (Inst const *)curCodeBlock->begin();\n\n // Check for invalid invocation.\n if (LLVM_UNLIKELY(curCodeBlock->getHeaderFlags().isCallProhibited(\n newFrame.isConstructorCall()))) {\n if (!newFrame.isConstructorCall()) {\n CAPTURE_IP(\n runtime->raiseTypeError(\"Class constructor invoked without new\"));\n } else {\n CAPTURE_IP(runtime->raiseTypeError(\"Function is not a constructor\"));\n }\n goto handleExceptionInParent;\n }\n } else {\n // Point frameRegs to the first register in the frame.\n frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();\n ip = (Inst const *)(curCodeBlock->begin() + state.offset);\n }\n\n assert((const uint8_t *)ip < curCodeBlock->end() && \"CodeBlock is empty\");\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n\n#define BEFORE_OP_CODE \\\n { \\\n UPDATE_OPCODE_TIME_SPENT; \\\n HERMES_SLOW_ASSERT( \\\n curCodeBlock->contains(ip) && \"curCodeBlock must contain ip\"); \\\n HERMES_SLOW_ASSERT((printDebugInfo(curCodeBlock, frameRegs, ip), true)); \\\n HERMES_SLOW_ASSERT( \\\n gcScope.getHandleCountDbg() == KEEP_HANDLES && \\\n \"unaccounted handles were created\"); \\\n HERMES_SLOW_ASSERT(tmpHandle->isUndefined() && \"tmpHandle not cleared\"); \\\n RECORD_OPCODE_START_TIME; \\\n INC_OPCODE_COUNT; \\\n }\n\n#ifdef HERMESVM_INDIRECT_THREADING\n static void *opcodeDispatch[] = {\n#define DEFINE_OPCODE(name) &&case_##name,\n#include \"hermes/BCGen/HBC/BytecodeList.def\"\n &&case__last};\n\n#define CASE(name) case_##name:\n#define DISPATCH \\\n BEFORE_OP_CODE; \\\n if (SingleStep) { \\\n state.codeBlock = curCodeBlock; \\\n state.offset = CUROFFSET; \\\n return HermesValue::encodeUndefinedValue(); \\\n } \\\n goto *opcodeDispatch[(unsigned)ip->opCode]\n\n#else // HERMESVM_INDIRECT_THREADING\n\n#define CASE(name) case OpCode::name:\n#define DISPATCH \\\n if (SingleStep) { \\\n state.codeBlock = curCodeBlock; \\\n state.offset = CUROFFSET; \\\n return HermesValue::encodeUndefinedValue(); \\\n } \\\n continue\n\n#endif // HERMESVM_INDIRECT_THREADING\n\n#define RUN_DEBUGGER_ASYNC_BREAK(flags) \\\n do { \\\n CAPTURE_IP_ASSIGN( \\\n auto dRes, \\\n runDebuggerUpdatingState( \\\n (uint8_t)(flags) & \\\n (uint8_t)Runtime::AsyncBreakReasonBits::DebuggerExplicit \\\n ? Debugger::RunReason::AsyncBreakExplicit \\\n : Debugger::RunReason::AsyncBreakImplicit, \\\n runtime, \\\n curCodeBlock, \\\n ip, \\\n frameRegs)); \\\n if (dRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n } while (0)\n\n for (;;) {\n BEFORE_OP_CODE;\n\n#ifdef HERMESVM_INDIRECT_THREADING\n goto *opcodeDispatch[(unsigned)ip->opCode];\n#else\n switch (ip->opCode)\n#endif\n {\n const Inst *nextIP;\n uint32_t idVal;\n bool tryProp;\n uint32_t callArgCount;\n // This is HermesValue::getRaw(), since HermesValue cannot be assigned\n // to. It is meant to be used only for very short durations, in the\n // dispatch of call instructions, when there is definitely no possibility\n // of a GC.\n HermesValue::RawType callNewTarget;\n\n/// Handle an opcode \\p name with an out-of-line implementation in a function\n/// ExecutionStatus caseName(\n/// Runtime *,\n/// PinnedHermesValue *frameRegs,\n/// Inst *ip)\n#define CASE_OUTOFLINE(name) \\\n CASE(name) { \\\n CAPTURE_IP_ASSIGN(auto res, case##name(runtime, frameRegs, ip)); \\\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { \\\n goto exception; \\\n } \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a binary arithmetic instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction. The fast path case will have a\n/// \"n\" appended to the name.\n/// \\param oper the C++ operator to use to actually perform the arithmetic\n/// operation.\n#define BINOP(name, oper) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n CASE(name##N) { \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n oper(O2REG(name).getNumber(), O3REG(name).getNumber())); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n } \\\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n double left = res->getDouble(); \\\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n O1REG(name) = \\\n HermesValue::encodeDoubleValue(oper(left, res->getDouble())); \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a shift instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the shift\n/// operation.\n/// \\param lConv the conversion function for the LHS of the expression.\n/// \\param lType the type of the LHS operand.\n/// \\param returnType the type of the return value.\n#define SHIFTOP(name, oper, lConv, lType, returnType) \\\n CASE(name) { \\\n if (LLVM_LIKELY( \\\n O2REG(name).isNumber() && \\\n O3REG(name).isNumber())) { /* Fast-path. */ \\\n auto lnum = static_cast( \\\n hermes::truncateToInt32(O2REG(name).getNumber())); \\\n auto rnum = static_cast( \\\n hermes::truncateToInt32(O3REG(name).getNumber())) & \\\n 0x1f; \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast(lnum oper rnum)); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN(res, lConv(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n auto lnum = static_cast(res->getNumber()); \\\n CAPTURE_IP_ASSIGN(res, toUInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n auto rnum = static_cast(res->getNumber()) & 0x1f; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n static_cast(lnum oper rnum)); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a binary bitwise instruction with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the bitwise\n/// operation.\n#define BITWISEBINOP(name, oper) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n O1REG(name) = HermesValue::encodeDoubleValue( \\\n hermes::truncateToInt32(O2REG(name).getNumber()) \\\n oper hermes::truncateToInt32(O3REG(name).getNumber())); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n int32_t left = res->getNumberAs(); \\\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O3REG(name)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n O1REG(name) = \\\n HermesValue::encodeNumberValue(left oper res->getNumberAs()); \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a comparison instruction.\n/// \\param name the name of the instruction.\n/// \\param oper the C++ operator to use to actually perform the fast arithmetic\n/// comparison.\n/// \\param operFuncName function to call for the slow-path comparison.\n#define CONDOP(name, oper, operFuncName) \\\n CASE(name) { \\\n if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \\\n /* Fast-path. */ \\\n O1REG(name) = HermesValue::encodeBoolValue( \\\n O2REG(name).getNumber() oper O3REG(name).getNumber()); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n } \\\n CAPTURE_IP_ASSIGN( \\\n boolRes, \\\n operFuncName( \\\n runtime, Handle<>(&O2REG(name)), Handle<>(&O3REG(name)))); \\\n if (boolRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n O1REG(name) = HermesValue::encodeBoolValue(boolRes.getValue()); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n/// Implement a comparison conditional jump with a fast path where both\n/// operands are numbers.\n/// \\param name the name of the instruction. The fast path case will have a\n/// \"N\" appended to the name.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param oper the C++ operator to use to actually perform the fast arithmetic\n/// comparison.\n/// \\param operFuncName function to call for the slow-path comparison.\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_IMPL(name, suffix, oper, operFuncName, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n if (LLVM_LIKELY( \\\n O2REG(name##suffix).isNumber() && \\\n O3REG(name##suffix).isNumber())) { \\\n /* Fast-path. */ \\\n CASE(name##N##suffix) { \\\n if (O2REG(name##N##suffix) \\\n .getNumber() oper O3REG(name##N##suffix) \\\n .getNumber()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n } \\\n } \\\n CAPTURE_IP_ASSIGN( \\\n boolRes, \\\n operFuncName( \\\n runtime, \\\n Handle<>(&O2REG(name##suffix)), \\\n Handle<>(&O3REG(name##suffix)))); \\\n if (boolRes == ExecutionStatus::EXCEPTION) \\\n goto exception; \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n if (boolRes.getValue()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement a strict equality conditional jump\n/// \\param name the name of the instruction.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_STRICT_EQ_IMPL(name, suffix, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n if (strictEqualityTest(O2REG(name##suffix), O3REG(name##suffix))) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement an equality conditional jump\n/// \\param name the name of the instruction.\n/// \\param suffix Optional suffix to be added to the end (e.g. Long)\n/// \\param trueDest ip value if the conditional evaluates to true\n/// \\param falseDest ip value if the conditional evaluates to false\n#define JCOND_EQ_IMPL(name, suffix, trueDest, falseDest) \\\n CASE(name##suffix) { \\\n CAPTURE_IP_ASSIGN( \\\n res, \\\n abstractEqualityTest_RJS( \\\n runtime, \\\n Handle<>(&O2REG(name##suffix)), \\\n Handle<>(&O3REG(name##suffix)))); \\\n if (res == ExecutionStatus::EXCEPTION) { \\\n goto exception; \\\n } \\\n gcScope.flushToSmallCount(KEEP_HANDLES); \\\n if (res->getBool()) { \\\n ip = trueDest; \\\n DISPATCH; \\\n } \\\n ip = falseDest; \\\n DISPATCH; \\\n }\n\n/// Implement the long and short forms of a conditional jump, and its negation.\n#define JCOND(name, oper, operFuncName) \\\n JCOND_IMPL( \\\n J##name, \\\n , \\\n oper, \\\n operFuncName, \\\n IPADD(ip->iJ##name.op1), \\\n NEXTINST(J##name)); \\\n JCOND_IMPL( \\\n J##name, \\\n Long, \\\n oper, \\\n operFuncName, \\\n IPADD(ip->iJ##name##Long.op1), \\\n NEXTINST(J##name##Long)); \\\n JCOND_IMPL( \\\n JNot##name, \\\n , \\\n oper, \\\n operFuncName, \\\n NEXTINST(JNot##name), \\\n IPADD(ip->iJNot##name.op1)); \\\n JCOND_IMPL( \\\n JNot##name, \\\n Long, \\\n oper, \\\n operFuncName, \\\n NEXTINST(JNot##name##Long), \\\n IPADD(ip->iJNot##name##Long.op1));\n\n/// Load a constant.\n/// \\param value is the value to store in the output register.\n#define LOAD_CONST(name, value) \\\n CASE(name) { \\\n O1REG(name) = value; \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n#define LOAD_CONST_CAPTURE_IP(name, value) \\\n CASE(name) { \\\n CAPTURE_IP_ASSIGN(O1REG(name), value); \\\n ip = NEXTINST(name); \\\n DISPATCH; \\\n }\n\n CASE(Mov) {\n O1REG(Mov) = O2REG(Mov);\n ip = NEXTINST(Mov);\n DISPATCH;\n }\n\n CASE(MovLong) {\n O1REG(MovLong) = O2REG(MovLong);\n ip = NEXTINST(MovLong);\n DISPATCH;\n }\n\n CASE(LoadParam) {\n if (LLVM_LIKELY(ip->iLoadParam.op2 <= FRAME.getArgCount())) {\n // index 0 must load 'this'. Index 1 the first argument, etc.\n O1REG(LoadParam) = FRAME.getArgRef((int32_t)ip->iLoadParam.op2 - 1);\n ip = NEXTINST(LoadParam);\n DISPATCH;\n }\n O1REG(LoadParam) = HermesValue::encodeUndefinedValue();\n ip = NEXTINST(LoadParam);\n DISPATCH;\n }\n\n CASE(LoadParamLong) {\n if (LLVM_LIKELY(ip->iLoadParamLong.op2 <= FRAME.getArgCount())) {\n // index 0 must load 'this'. Index 1 the first argument, etc.\n O1REG(LoadParamLong) =\n FRAME.getArgRef((int32_t)ip->iLoadParamLong.op2 - 1);\n ip = NEXTINST(LoadParamLong);\n DISPATCH;\n }\n O1REG(LoadParamLong) = HermesValue::encodeUndefinedValue();\n ip = NEXTINST(LoadParamLong);\n DISPATCH;\n }\n\n CASE(CoerceThisNS) {\n if (LLVM_LIKELY(O2REG(CoerceThisNS).isObject())) {\n O1REG(CoerceThisNS) = O2REG(CoerceThisNS);\n } else if (\n O2REG(CoerceThisNS).isNull() || O2REG(CoerceThisNS).isUndefined()) {\n O1REG(CoerceThisNS) = runtime->global_;\n } else {\n tmpHandle = O2REG(CoerceThisNS);\n nextIP = NEXTINST(CoerceThisNS);\n goto coerceThisSlowPath;\n }\n ip = NEXTINST(CoerceThisNS);\n DISPATCH;\n }\n CASE(LoadThisNS) {\n if (LLVM_LIKELY(FRAME.getThisArgRef().isObject())) {\n O1REG(LoadThisNS) = FRAME.getThisArgRef();\n } else if (\n FRAME.getThisArgRef().isNull() ||\n FRAME.getThisArgRef().isUndefined()) {\n O1REG(LoadThisNS) = runtime->global_;\n } else {\n tmpHandle = FRAME.getThisArgRef();\n nextIP = NEXTINST(LoadThisNS);\n goto coerceThisSlowPath;\n }\n ip = NEXTINST(LoadThisNS);\n DISPATCH;\n }\n coerceThisSlowPath : {\n CAPTURE_IP_ASSIGN(res, toObject(runtime, tmpHandle));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CoerceThisNS) = res.getValue();\n tmpHandle.clear();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(ConstructLong) {\n callArgCount = (uint32_t)ip->iConstructLong.op3;\n nextIP = NEXTINST(ConstructLong);\n callNewTarget = O2REG(ConstructLong).getRaw();\n goto doCall;\n }\n CASE(CallLong) {\n callArgCount = (uint32_t)ip->iCallLong.op3;\n nextIP = NEXTINST(CallLong);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n // Note in Call1 through Call4, the first argument is 'this' which has\n // argument index -1.\n // Also note that we are writing to callNewTarget last, to avoid the\n // possibility of it being aliased by the arg writes.\n CASE(Call1) {\n callArgCount = 1;\n nextIP = NEXTINST(Call1);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call1);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call2) {\n callArgCount = 2;\n nextIP = NEXTINST(Call2);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call2);\n fr.getArgRefUnsafe(0) = O4REG(Call2);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call3) {\n callArgCount = 3;\n nextIP = NEXTINST(Call3);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call3);\n fr.getArgRefUnsafe(0) = O4REG(Call3);\n fr.getArgRefUnsafe(1) = O5REG(Call3);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Call4) {\n callArgCount = 4;\n nextIP = NEXTINST(Call4);\n StackFramePtr fr{runtime->stackPointer_};\n fr.getArgRefUnsafe(-1) = O3REG(Call4);\n fr.getArgRefUnsafe(0) = O4REG(Call4);\n fr.getArgRefUnsafe(1) = O5REG(Call4);\n fr.getArgRefUnsafe(2) = O6REG(Call4);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n goto doCall;\n }\n\n CASE(Construct) {\n callArgCount = (uint32_t)ip->iConstruct.op3;\n nextIP = NEXTINST(Construct);\n callNewTarget = O2REG(Construct).getRaw();\n goto doCall;\n }\n CASE(Call) {\n callArgCount = (uint32_t)ip->iCall.op3;\n nextIP = NEXTINST(Call);\n callNewTarget = HermesValue::encodeUndefinedValue().getRaw();\n // Fall through.\n }\n\n doCall : {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n // Subtract 1 from callArgCount as 'this' is considered an argument in the\n // instruction, but not in the frame.\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n callArgCount - 1,\n O2REG(Call),\n HermesValue::fromRaw(callNewTarget)));\n (void)newFrame;\n\n SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n if (auto *func = dyn_vmcast(O2REG(Call))) {\n assert(!SingleStep && \"can't single-step a call\");\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->pushCallStack(curCodeBlock, ip);\n#endif\n\n CodeBlock *calleeBlock = func->getCodeBlock();\n calleeBlock->lazyCompile(runtime);\n#if defined(HERMESVM_PROFILER_EXTERN)\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n res, runtime->interpretFunction(calleeBlock));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(Call) = *res;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n#else\n if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {\n res = (*jitPtr)(runtime);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(Call) = *res;\n SLOW_DEBUG(\n dbgs() << \"JIT return value r\" << (unsigned)ip->iCall.op1 << \"=\"\n << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n curCodeBlock = calleeBlock;\n goto tailCall;\n#endif\n }\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n resPH, Interpreter::handleCallSlowPath(runtime, &O2REG(Call)));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(Call) = std::move(resPH->get());\n SLOW_DEBUG(\n dbgs() << \"native return value r\" << (unsigned)ip->iCall.op1 << \"=\"\n << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(CallDirect)\n CASE(CallDirectLongIndex) {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n CAPTURE_IP_ASSIGN(\n CodeBlock * calleeBlock,\n ip->opCode == OpCode::CallDirect\n ? curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(\n ip->iCallDirect.op3)\n : curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(\n ip->iCallDirectLongIndex.op3));\n\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n (uint32_t)ip->iCallDirect.op2 - 1,\n HermesValue::encodeNativePointer(calleeBlock),\n HermesValue::encodeUndefinedValue()));\n (void)newFrame;\n\n LLVM_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n assert(!SingleStep && \"can't single-step a call\");\n\n calleeBlock->lazyCompile(runtime);\n#if defined(HERMESVM_PROFILER_EXTERN)\n CAPTURE_IP_ASSIGN_NO_INVALIDATE(\n res, runtime->interpretFunction(calleeBlock));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CallDirect) = *res;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)\n : NEXTINST(CallDirectLongIndex);\n DISPATCH;\n#else\n if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {\n res = (*jitPtr)(runtime);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(CallDirect) = *res;\n LLVM_DEBUG(\n dbgs() << \"JIT return value r\" << (unsigned)ip->iCallDirect.op1\n << \"=\" << DumpHermesValue(O1REG(Call)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)\n : NEXTINST(CallDirectLongIndex);\n DISPATCH;\n }\n curCodeBlock = calleeBlock;\n goto tailCall;\n#endif\n }\n\n CASE(CallBuiltin) {\n NativeFunction *nf =\n runtime->getBuiltinNativeFunction(ip->iCallBuiltin.op2);\n\n CAPTURE_IP_ASSIGN(\n auto newFrame,\n StackFramePtr::initFrame(\n runtime->stackPointer_,\n FRAME,\n ip,\n curCodeBlock,\n (uint32_t)ip->iCallBuiltin.op3 - 1,\n nf,\n false));\n // \"thisArg\" is implicitly assumed to \"undefined\".\n newFrame.getThisArgRef() = HermesValue::encodeUndefinedValue();\n\n SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));\n\n CAPTURE_IP_ASSIGN(resPH, NativeFunction::_nativeCall(nf, runtime));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION))\n goto exception;\n O1REG(CallBuiltin) = std::move(resPH->get());\n SLOW_DEBUG(\n dbgs() << \"native return value r\" << (unsigned)ip->iCallBuiltin.op1\n << \"=\" << DumpHermesValue(O1REG(CallBuiltin)) << \"\\n\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CallBuiltin);\n DISPATCH;\n }\n\n CASE(CompleteGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n innerFn->setState(GeneratorInnerFunction::State::Completed);\n ip = NEXTINST(CompleteGenerator);\n DISPATCH;\n }\n\n CASE(SaveGenerator) {\n DONT_CAPTURE_IP(\n saveGenerator(runtime, frameRegs, IPADD(ip->iSaveGenerator.op1)));\n ip = NEXTINST(SaveGenerator);\n DISPATCH;\n }\n CASE(SaveGeneratorLong) {\n DONT_CAPTURE_IP(saveGenerator(\n runtime, frameRegs, IPADD(ip->iSaveGeneratorLong.op1)));\n ip = NEXTINST(SaveGeneratorLong);\n DISPATCH;\n }\n\n CASE(StartGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n if (innerFn->getState() ==\n GeneratorInnerFunction::State::SuspendedStart) {\n nextIP = NEXTINST(StartGenerator);\n } else {\n nextIP = innerFn->getNextIP();\n innerFn->restoreStack(runtime);\n }\n innerFn->setState(GeneratorInnerFunction::State::Executing);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(ResumeGenerator) {\n auto *innerFn = vmcast(\n runtime->getCurrentFrame().getCalleeClosure());\n O1REG(ResumeGenerator) = innerFn->getResult();\n O2REG(ResumeGenerator) = HermesValue::encodeBoolValue(\n innerFn->getAction() == GeneratorInnerFunction::Action::Return);\n innerFn->clearResult(runtime);\n if (innerFn->getAction() == GeneratorInnerFunction::Action::Throw) {\n runtime->setThrownValue(O1REG(ResumeGenerator));\n goto exception;\n }\n ip = NEXTINST(ResumeGenerator);\n DISPATCH;\n }\n\n CASE(Ret) {\n#ifdef HERMES_ENABLE_DEBUGGER\n // Check for an async debugger request.\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n DISPATCH;\n }\n#endif\n\n PROFILER_EXIT_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->popCallStack();\n#endif\n\n // Store the return value.\n res = O1REG(Ret);\n\n ip = FRAME.getSavedIP();\n curCodeBlock = FRAME.getSavedCodeBlock();\n\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n SLOW_DEBUG(\n dbgs() << \"function exit: restored stackLevel=\"\n << runtime->getStackLevel() << \"\\n\");\n\n // Are we returning to native code?\n if (!curCodeBlock) {\n SLOW_DEBUG(dbgs() << \"function exit: returning to native code\\n\");\n return res;\n }\n\n// Return because of recursive calling structure\n#if defined(HERMESVM_PROFILER_EXTERN)\n return res;\n#endif\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n O1REG(Call) = res.getValue();\n ip = nextInstCall(ip);\n DISPATCH;\n }\n\n CASE(Catch) {\n assert(!runtime->thrownValue_.isEmpty() && \"Invalid thrown value\");\n assert(\n !isUncatchableError(runtime->thrownValue_) &&\n \"Uncatchable thrown value was caught\");\n O1REG(Catch) = runtime->thrownValue_;\n runtime->clearThrownValue();\n#ifdef HERMES_ENABLE_DEBUGGER\n // Signal to the debugger that we're done unwinding an exception,\n // and we can resume normal debugging flow.\n runtime->debugger_.finishedUnwindingException();\n#endif\n ip = NEXTINST(Catch);\n DISPATCH;\n }\n\n CASE(Throw) {\n runtime->thrownValue_ = O1REG(Throw);\n SLOW_DEBUG(\n dbgs() << \"Exception thrown: \"\n << DumpHermesValue(runtime->thrownValue_) << \"\\n\");\n goto exception;\n }\n\n CASE(ThrowIfUndefinedInst) {\n if (LLVM_UNLIKELY(O1REG(ThrowIfUndefinedInst).isUndefined())) {\n SLOW_DEBUG(\n dbgs() << \"Throwing ReferenceError for undefined variable\");\n CAPTURE_IP(runtime->raiseReferenceError(\n \"accessing an uninitialized variable\"));\n goto exception;\n }\n ip = NEXTINST(ThrowIfUndefinedInst);\n DISPATCH;\n }\n\n CASE(Debugger) {\n SLOW_DEBUG(dbgs() << \"debugger statement executed\\n\");\n#ifdef HERMES_ENABLE_DEBUGGER\n {\n if (!runtime->debugger_.isDebugging()) {\n // Only run the debugger if we're not already debugging.\n // Don't want to call it again and mess with its state.\n CAPTURE_IP_ASSIGN(\n auto res,\n runDebuggerUpdatingState(\n Debugger::RunReason::Opcode,\n runtime,\n curCodeBlock,\n ip,\n frameRegs));\n if (res == ExecutionStatus::EXCEPTION) {\n // If one of the internal steps threw,\n // then handle that here by jumping to where we're supposed to go.\n // If we're in mid-step, the breakpoint at the catch point\n // will have been set by the debugger.\n // We don't want to execute this instruction because it's already\n // thrown.\n goto exception;\n }\n }\n auto breakpointOpt = runtime->debugger_.getBreakpointLocation(ip);\n if (breakpointOpt.hasValue()) {\n // We're on a breakpoint but we're supposed to continue.\n curCodeBlock->uninstallBreakpointAtOffset(\n CUROFFSET, breakpointOpt->opCode);\n if (ip->opCode == OpCode::Debugger) {\n // Breakpointed a debugger instruction, so move past it\n // since we've already called the debugger on this instruction.\n ip = NEXTINST(Debugger);\n } else {\n InterpreterState newState{curCodeBlock, (uint32_t)CUROFFSET};\n CAPTURE_IP_ASSIGN(\n ExecutionStatus status, runtime->stepFunction(newState));\n curCodeBlock->installBreakpointAtOffset(CUROFFSET);\n if (status == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n curCodeBlock = newState.codeBlock;\n ip = newState.codeBlock->getOffsetPtr(newState.offset);\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n // Single-stepping should handle call stack management for us.\n frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();\n }\n } else if (ip->opCode == OpCode::Debugger) {\n // No breakpoint here and we've already run the debugger,\n // just continue on.\n // If the current instruction is no longer a debugger instruction,\n // we're just going to keep executing from the current IP.\n ip = NEXTINST(Debugger);\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n DISPATCH;\n#else\n ip = NEXTINST(Debugger);\n DISPATCH;\n#endif\n }\n\n CASE(AsyncBreakCheck) {\n if (LLVM_UNLIKELY(runtime->hasAsyncBreak())) {\n#ifdef HERMES_ENABLE_DEBUGGER\n if (uint8_t asyncFlags =\n runtime->testAndClearDebuggerAsyncBreakRequest()) {\n RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);\n }\n#endif\n if (runtime->testAndClearTimeoutAsyncBreakRequest()) {\n CAPTURE_IP_ASSIGN(auto nRes, runtime->notifyTimeout());\n if (nRes == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n\n ip = NEXTINST(AsyncBreakCheck);\n DISPATCH;\n }\n\n CASE(ProfilePoint) {\n#ifdef HERMESVM_PROFILER_BB\n auto pointIndex = ip->iProfilePoint.op1;\n SLOW_DEBUG(llvh::dbgs() << \"ProfilePoint: \" << pointIndex << \"\\n\");\n CAPTURE_IP(runtime->getBasicBlockExecutionInfo().executeBlock(\n curCodeBlock, pointIndex));\n#endif\n ip = NEXTINST(ProfilePoint);\n DISPATCH;\n }\n\n CASE(Unreachable) {\n llvm_unreachable(\"Hermes bug: unreachable instruction\");\n }\n\n CASE(CreateClosure) {\n idVal = ip->iCreateClosure.op3;\n nextIP = NEXTINST(CreateClosure);\n goto createClosure;\n }\n CASE(CreateClosureLongIndex) {\n idVal = ip->iCreateClosureLongIndex.op3;\n nextIP = NEXTINST(CreateClosureLongIndex);\n goto createClosure;\n }\n createClosure : {\n auto *runtimeModule = curCodeBlock->getRuntimeModule();\n CAPTURE_IP_ASSIGN(\n O1REG(CreateClosure),\n JSFunction::create(\n runtime,\n runtimeModule->getDomain(runtime),\n Handle::vmcast(&runtime->functionPrototype),\n Handle::vmcast(&O2REG(CreateClosure)),\n runtimeModule->getCodeBlockMayAllocate(idVal))\n .getHermesValue());\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(CreateGeneratorClosure) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGeneratorClosure(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateClosure.op3,\n Handle::vmcast(&O2REG(CreateGeneratorClosure))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorClosure) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorClosure);\n DISPATCH;\n }\n CASE(CreateGeneratorClosureLongIndex) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGeneratorClosure(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateClosureLongIndex.op3,\n Handle::vmcast(\n &O2REG(CreateGeneratorClosureLongIndex))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorClosureLongIndex) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorClosureLongIndex);\n DISPATCH;\n }\n\n CASE(CreateGenerator) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGenerator_RJS(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateGenerator.op3,\n Handle::vmcast(&O2REG(CreateGenerator)),\n FRAME.getNativeArgs()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGenerator) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGenerator);\n DISPATCH;\n }\n CASE(CreateGeneratorLongIndex) {\n CAPTURE_IP_ASSIGN(\n auto res,\n createGenerator_RJS(\n runtime,\n curCodeBlock->getRuntimeModule(),\n ip->iCreateGeneratorLongIndex.op3,\n Handle::vmcast(&O2REG(CreateGeneratorLongIndex)),\n FRAME.getNativeArgs()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(CreateGeneratorLongIndex) = res->getHermesValue();\n res->invalidate();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateGeneratorLongIndex);\n DISPATCH;\n }\n\n CASE(GetEnvironment) {\n // The currently executing function must exist, so get the environment.\n Environment *curEnv =\n FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime);\n for (unsigned level = ip->iGetEnvironment.op2; level; --level) {\n assert(curEnv && \"invalid environment relative level\");\n curEnv = curEnv->getParentEnvironment(runtime);\n }\n O1REG(GetEnvironment) = HermesValue::encodeObjectValue(curEnv);\n ip = NEXTINST(GetEnvironment);\n DISPATCH;\n }\n\n CASE(CreateEnvironment) {\n tmpHandle = HermesValue::encodeObjectValue(\n FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime));\n\n CAPTURE_IP_ASSIGN(\n res,\n Environment::create(\n runtime,\n tmpHandle->getPointer() ? Handle::vmcast(tmpHandle)\n : Handle::vmcast_or_null(\n &runtime->nullPointer_),\n curCodeBlock->getEnvironmentSize()));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(CreateEnvironment) = *res;\n#ifdef HERMES_ENABLE_DEBUGGER\n FRAME.getDebugEnvironmentRef() = *res;\n#endif\n tmpHandle = HermesValue::encodeUndefinedValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateEnvironment);\n DISPATCH;\n }\n\n CASE(StoreToEnvironment) {\n vmcast(O1REG(StoreToEnvironment))\n ->slot(ip->iStoreToEnvironment.op2)\n .set(O3REG(StoreToEnvironment), &runtime->getHeap());\n ip = NEXTINST(StoreToEnvironment);\n DISPATCH;\n }\n CASE(StoreToEnvironmentL) {\n vmcast(O1REG(StoreToEnvironmentL))\n ->slot(ip->iStoreToEnvironmentL.op2)\n .set(O3REG(StoreToEnvironmentL), &runtime->getHeap());\n ip = NEXTINST(StoreToEnvironmentL);\n DISPATCH;\n }\n\n CASE(StoreNPToEnvironment) {\n vmcast(O1REG(StoreNPToEnvironment))\n ->slot(ip->iStoreNPToEnvironment.op2)\n .setNonPtr(O3REG(StoreNPToEnvironment), &runtime->getHeap());\n ip = NEXTINST(StoreNPToEnvironment);\n DISPATCH;\n }\n CASE(StoreNPToEnvironmentL) {\n vmcast(O1REG(StoreNPToEnvironmentL))\n ->slot(ip->iStoreNPToEnvironmentL.op2)\n .setNonPtr(O3REG(StoreNPToEnvironmentL), &runtime->getHeap());\n ip = NEXTINST(StoreNPToEnvironmentL);\n DISPATCH;\n }\n\n CASE(LoadFromEnvironment) {\n O1REG(LoadFromEnvironment) =\n vmcast(O2REG(LoadFromEnvironment))\n ->slot(ip->iLoadFromEnvironment.op3);\n ip = NEXTINST(LoadFromEnvironment);\n DISPATCH;\n }\n\n CASE(LoadFromEnvironmentL) {\n O1REG(LoadFromEnvironmentL) =\n vmcast(O2REG(LoadFromEnvironmentL))\n ->slot(ip->iLoadFromEnvironmentL.op3);\n ip = NEXTINST(LoadFromEnvironmentL);\n DISPATCH;\n }\n\n CASE(GetGlobalObject) {\n O1REG(GetGlobalObject) = runtime->global_;\n ip = NEXTINST(GetGlobalObject);\n DISPATCH;\n }\n\n CASE(GetNewTarget) {\n O1REG(GetNewTarget) = FRAME.getNewTargetRef();\n ip = NEXTINST(GetNewTarget);\n DISPATCH;\n }\n\n CASE(DeclareGlobalVar) {\n DefinePropertyFlags dpf =\n DefinePropertyFlags::getDefaultNewPropertyFlags();\n dpf.configurable = 0;\n // Do not overwrite existing globals with undefined.\n dpf.setValue = 0;\n\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::defineOwnProperty(\n runtime->getGlobal(),\n runtime,\n ID(ip->iDeclareGlobalVar.op1),\n dpf,\n Runtime::getUndefinedValue(),\n PropOpFlags().plusThrowOnError()));\n if (res == ExecutionStatus::EXCEPTION) {\n assert(\n !runtime->getGlobal()->isProxyObject() &&\n \"global can't be a proxy object\");\n // If the property already exists, this should be a noop.\n // Instead of incurring the cost to check every time, do it\n // only if an exception is thrown, and swallow the exception\n // if it exists, since we didn't want to make the call,\n // anyway. This most likely means the property is\n // non-configurable.\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::getOwnNamedDescriptor(\n runtime->getGlobal(),\n runtime,\n ID(ip->iDeclareGlobalVar.op1),\n desc));\n if (!res) {\n goto exception;\n } else {\n runtime->clearThrownValue();\n }\n // fall through\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(DeclareGlobalVar);\n DISPATCH;\n }\n\n CASE(TryGetByIdLong) {\n tryProp = true;\n idVal = ip->iTryGetByIdLong.op4;\n nextIP = NEXTINST(TryGetByIdLong);\n goto getById;\n }\n CASE(GetByIdLong) {\n tryProp = false;\n idVal = ip->iGetByIdLong.op4;\n nextIP = NEXTINST(GetByIdLong);\n goto getById;\n }\n CASE(GetByIdShort) {\n tryProp = false;\n idVal = ip->iGetByIdShort.op4;\n nextIP = NEXTINST(GetByIdShort);\n goto getById;\n }\n CASE(TryGetById) {\n tryProp = true;\n idVal = ip->iTryGetById.op4;\n nextIP = NEXTINST(TryGetById);\n goto getById;\n }\n CASE(GetById) {\n tryProp = false;\n idVal = ip->iGetById.op4;\n nextIP = NEXTINST(GetById);\n }\n getById : {\n ++NumGetById;\n // NOTE: it is safe to use OnREG(GetById) here because all instructions\n // have the same layout: opcode, registers, non-register operands, i.e.\n // they only differ in the width of the last \"identifier\" field.\n CallResult propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetById).isObject())) {\n auto *obj = vmcast(O2REG(GetById));\n auto cacheIdx = ip->iGetById.op3;\n auto *cacheEntry = curCodeBlock->getReadCacheEntry(cacheIdx);\n\n#ifdef HERMESVM_PROFILER_BB\n {\n HERMES_SLOW_ASSERT(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"unaccounted handles were created\");\n auto objHandle = runtime->makeHandle(obj);\n auto cacheHCPtr = vmcast_or_null(static_cast(\n cacheEntry->clazz.get(runtime, &runtime->getHeap())));\n CAPTURE_IP(runtime->recordHiddenClass(\n curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));\n // obj may be moved by GC due to recordHiddenClass\n obj = objHandle.get();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n#endif\n auto clazzGCPtr = obj->getClassGCPtr();\n#ifndef NDEBUG\n if (clazzGCPtr.get(runtime)->isDictionary())\n ++NumGetByIdDict;\n#else\n (void)NumGetByIdDict;\n#endif\n\n // If we have a cache hit, reuse the cached offset and immediately\n // return the property.\n if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {\n ++NumGetByIdCacheHits;\n CAPTURE_IP_ASSIGN(\n O1REG(GetById),\n JSObject::getNamedSlotValue(\n obj, runtime, cacheEntry->slot));\n ip = nextIP;\n DISPATCH;\n }\n auto id = ID(idVal);\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n OptValue fastPathResult,\n JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));\n if (LLVM_LIKELY(\n fastPathResult.hasValue() && fastPathResult.getValue()) &&\n !desc.flags.accessor) {\n ++NumGetByIdFastPaths;\n\n // cacheIdx == 0 indicates no caching so don't update the cache in\n // those cases.\n auto *clazz = clazzGCPtr.getNonNull(runtime);\n if (LLVM_LIKELY(!clazz->isDictionaryNoCache()) &&\n LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {\n#ifdef HERMES_SLOW_DEBUG\n if (cacheEntry->clazz &&\n cacheEntry->clazz != clazzGCPtr.getStorageType())\n ++NumGetByIdCacheEvicts;\n#else\n (void)NumGetByIdCacheEvicts;\n#endif\n // Cache the class, id and property slot.\n cacheEntry->clazz = clazzGCPtr.getStorageType();\n cacheEntry->slot = desc.slot;\n }\n\n CAPTURE_IP_ASSIGN(\n O1REG(GetById), JSObject::getNamedSlotValue(obj, runtime, desc));\n ip = nextIP;\n DISPATCH;\n }\n\n // The cache may also be populated via the prototype of the object.\n // This value is only reliable if the fast path was a definite\n // not-found.\n if (fastPathResult.hasValue() && !fastPathResult.getValue() &&\n !obj->isProxyObject()) {\n CAPTURE_IP_ASSIGN(JSObject * parent, obj->getParent(runtime));\n // TODO: This isLazy check is because a lazy object is reported as\n // having no properties and therefore cannot contain the property.\n // This check does not belong here, it should be merged into\n // tryGetOwnNamedDescriptorFast().\n if (parent &&\n cacheEntry->clazz == parent->getClassGCPtr().getStorageType() &&\n LLVM_LIKELY(!obj->isLazy())) {\n ++NumGetByIdProtoHits;\n CAPTURE_IP_ASSIGN(\n O1REG(GetById),\n JSObject::getNamedSlotValue(parent, runtime, cacheEntry->slot));\n ip = nextIP;\n DISPATCH;\n }\n }\n\n#ifdef HERMES_SLOW_DEBUG\n CAPTURE_IP_ASSIGN(\n JSObject * propObj,\n JSObject::getNamedDescriptor(\n Handle::vmcast(&O2REG(GetById)), runtime, id, desc));\n if (propObj) {\n if (desc.flags.accessor)\n ++NumGetByIdAccessor;\n else if (propObj != vmcast(O2REG(GetById)))\n ++NumGetByIdProto;\n } else {\n ++NumGetByIdNotFound;\n }\n#else\n (void)NumGetByIdAccessor;\n (void)NumGetByIdProto;\n (void)NumGetByIdNotFound;\n#endif\n#ifdef HERMES_SLOW_DEBUG\n auto *savedClass = cacheIdx != hbc::PROPERTY_CACHING_DISABLED\n ? cacheEntry->clazz.get(runtime, &runtime->getHeap())\n : nullptr;\n#endif\n ++NumGetByIdSlow;\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getNamed_RJS(\n Handle::vmcast(&O2REG(GetById)),\n runtime,\n id,\n !tryProp ? defaultPropOpFlags\n : defaultPropOpFlags.plusMustExist(),\n cacheIdx != hbc::PROPERTY_CACHING_DISABLED ? cacheEntry\n : nullptr));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n#ifdef HERMES_SLOW_DEBUG\n if (cacheIdx != hbc::PROPERTY_CACHING_DISABLED && savedClass &&\n cacheEntry->clazz.get(runtime, &runtime->getHeap()) != savedClass) {\n ++NumGetByIdCacheEvicts;\n }\n#endif\n } else {\n ++NumGetByIdTransient;\n assert(!tryProp && \"TryGetById can only be used on the global object\");\n /* Slow path. */\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::getByIdTransient_RJS(\n runtime, Handle<>(&O2REG(GetById)), ID(idVal)));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n O1REG(GetById) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(TryPutByIdLong) {\n tryProp = true;\n idVal = ip->iTryPutByIdLong.op4;\n nextIP = NEXTINST(TryPutByIdLong);\n goto putById;\n }\n CASE(PutByIdLong) {\n tryProp = false;\n idVal = ip->iPutByIdLong.op4;\n nextIP = NEXTINST(PutByIdLong);\n goto putById;\n }\n CASE(TryPutById) {\n tryProp = true;\n idVal = ip->iTryPutById.op4;\n nextIP = NEXTINST(TryPutById);\n goto putById;\n }\n CASE(PutById) {\n tryProp = false;\n idVal = ip->iPutById.op4;\n nextIP = NEXTINST(PutById);\n }\n putById : {\n ++NumPutById;\n if (LLVM_LIKELY(O1REG(PutById).isObject())) {\n auto *obj = vmcast(O1REG(PutById));\n auto cacheIdx = ip->iPutById.op3;\n auto *cacheEntry = curCodeBlock->getWriteCacheEntry(cacheIdx);\n\n#ifdef HERMESVM_PROFILER_BB\n {\n HERMES_SLOW_ASSERT(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"unaccounted handles were created\");\n auto objHandle = runtime->makeHandle(obj);\n auto cacheHCPtr = vmcast_or_null(static_cast(\n cacheEntry->clazz.get(runtime, &runtime->getHeap())));\n CAPTURE_IP(runtime->recordHiddenClass(\n curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));\n // obj may be moved by GC due to recordHiddenClass\n obj = objHandle.get();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n#endif\n auto clazzGCPtr = obj->getClassGCPtr();\n // If we have a cache hit, reuse the cached offset and immediately\n // return the property.\n if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {\n ++NumPutByIdCacheHits;\n CAPTURE_IP(JSObject::setNamedSlotValue(\n obj, runtime, cacheEntry->slot, O2REG(PutById)));\n ip = nextIP;\n DISPATCH;\n }\n auto id = ID(idVal);\n NamedPropertyDescriptor desc;\n CAPTURE_IP_ASSIGN(\n OptValue hasOwnProp,\n JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));\n if (LLVM_LIKELY(hasOwnProp.hasValue() && hasOwnProp.getValue()) &&\n !desc.flags.accessor && desc.flags.writable &&\n !desc.flags.internalSetter) {\n ++NumPutByIdFastPaths;\n\n // cacheIdx == 0 indicates no caching so don't update the cache in\n // those cases.\n auto *clazz = clazzGCPtr.getNonNull(runtime);\n if (LLVM_LIKELY(!clazz->isDictionary()) &&\n LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {\n#ifdef HERMES_SLOW_DEBUG\n if (cacheEntry->clazz &&\n cacheEntry->clazz != clazzGCPtr.getStorageType())\n ++NumPutByIdCacheEvicts;\n#else\n (void)NumPutByIdCacheEvicts;\n#endif\n // Cache the class and property slot.\n cacheEntry->clazz = clazzGCPtr.getStorageType();\n cacheEntry->slot = desc.slot;\n }\n\n CAPTURE_IP(JSObject::setNamedSlotValue(\n obj, runtime, desc.slot, O2REG(PutById)));\n ip = nextIP;\n DISPATCH;\n }\n\n CAPTURE_IP_ASSIGN(\n auto putRes,\n JSObject::putNamed_RJS(\n Handle::vmcast(&O1REG(PutById)),\n runtime,\n id,\n Handle<>(&O2REG(PutById)),\n !tryProp ? defaultPropOpFlags\n : defaultPropOpFlags.plusMustExist()));\n if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n ++NumPutByIdTransient;\n assert(!tryProp && \"TryPutById can only be used on the global object\");\n CAPTURE_IP_ASSIGN(\n auto retStatus,\n Interpreter::putByIdTransient_RJS(\n runtime,\n Handle<>(&O1REG(PutById)),\n ID(idVal),\n Handle<>(&O2REG(PutById)),\n strictMode));\n if (retStatus == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(GetByVal) {\n CallResult propRes{ExecutionStatus::EXCEPTION};\n if (LLVM_LIKELY(O2REG(GetByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getComputed_RJS(\n Handle::vmcast(&O2REG(GetByVal)),\n runtime,\n Handle<>(&O3REG(GetByVal))));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::getByValTransient_RJS(\n runtime,\n Handle<>(&O2REG(GetByVal)),\n Handle<>(&O3REG(GetByVal))));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetByVal) = resPH->get();\n ip = NEXTINST(GetByVal);\n DISPATCH;\n }\n\n CASE(PutByVal) {\n if (LLVM_LIKELY(O1REG(PutByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto putRes,\n JSObject::putComputed_RJS(\n Handle::vmcast(&O1REG(PutByVal)),\n runtime,\n Handle<>(&O2REG(PutByVal)),\n Handle<>(&O3REG(PutByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(\n auto retStatus,\n Interpreter::putByValTransient_RJS(\n runtime,\n Handle<>(&O1REG(PutByVal)),\n Handle<>(&O2REG(PutByVal)),\n Handle<>(&O3REG(PutByVal)),\n strictMode));\n if (LLVM_UNLIKELY(retStatus == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(PutByVal);\n DISPATCH;\n }\n\n CASE(PutOwnByIndexL) {\n nextIP = NEXTINST(PutOwnByIndexL);\n idVal = ip->iPutOwnByIndexL.op3;\n goto putOwnByIndex;\n }\n CASE(PutOwnByIndex) {\n nextIP = NEXTINST(PutOwnByIndex);\n idVal = ip->iPutOwnByIndex.op3;\n }\n putOwnByIndex : {\n tmpHandle = HermesValue::encodeDoubleValue(idVal);\n CAPTURE_IP(JSObject::defineOwnComputedPrimitive(\n Handle::vmcast(&O1REG(PutOwnByIndex)),\n runtime,\n tmpHandle,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n Handle<>(&O2REG(PutOwnByIndex))));\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(GetPNameList) {\n CAPTURE_IP_ASSIGN(\n auto pRes, handleGetPNameList(runtime, frameRegs, ip));\n if (LLVM_UNLIKELY(pRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(GetPNameList);\n DISPATCH;\n }\n\n CASE(GetNextPName) {\n {\n assert(\n vmisa(O2REG(GetNextPName)) &&\n \"GetNextPName's second op must be BigStorage\");\n auto obj = Handle::vmcast(&O3REG(GetNextPName));\n auto arr = Handle::vmcast(&O2REG(GetNextPName));\n uint32_t idx = O4REG(GetNextPName).getNumber();\n uint32_t size = O5REG(GetNextPName).getNumber();\n MutableHandle propObj{runtime};\n // Loop until we find a property which is present.\n while (idx < size) {\n tmpHandle = arr->at(idx);\n ComputedPropertyDescriptor desc;\n CAPTURE_IP(JSObject::getComputedPrimitiveDescriptor(\n obj, runtime, tmpHandle, propObj, desc));\n if (LLVM_LIKELY(propObj))\n break;\n ++idx;\n }\n if (idx < size) {\n // We must return the property as a string\n if (tmpHandle->isNumber()) {\n CAPTURE_IP_ASSIGN(auto status, toString_RJS(runtime, tmpHandle));\n assert(\n status == ExecutionStatus::RETURNED &&\n \"toString on number cannot fail\");\n tmpHandle = status->getHermesValue();\n }\n O1REG(GetNextPName) = tmpHandle.get();\n O4REG(GetNextPName) = HermesValue::encodeNumberValue(idx + 1);\n } else {\n O1REG(GetNextPName) = HermesValue::encodeUndefinedValue();\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(GetNextPName);\n DISPATCH;\n }\n\n CASE(ToNumber) {\n if (LLVM_LIKELY(O2REG(ToNumber).isNumber())) {\n O1REG(ToNumber) = O2REG(ToNumber);\n ip = NEXTINST(ToNumber);\n } else {\n CAPTURE_IP_ASSIGN(\n res, toNumber_RJS(runtime, Handle<>(&O2REG(ToNumber))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(ToNumber) = res.getValue();\n ip = NEXTINST(ToNumber);\n }\n DISPATCH;\n }\n\n CASE(ToInt32) {\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(ToInt32))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(ToInt32) = res.getValue();\n ip = NEXTINST(ToInt32);\n DISPATCH;\n }\n\n CASE(AddEmptyString) {\n if (LLVM_LIKELY(O2REG(AddEmptyString).isString())) {\n O1REG(AddEmptyString) = O2REG(AddEmptyString);\n ip = NEXTINST(AddEmptyString);\n } else {\n CAPTURE_IP_ASSIGN(\n res,\n toPrimitive_RJS(\n runtime,\n Handle<>(&O2REG(AddEmptyString)),\n PreferredType::NONE));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))\n goto exception;\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(auto strRes, toString_RJS(runtime, tmpHandle));\n if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION))\n goto exception;\n tmpHandle.clear();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(AddEmptyString) = strRes->getHermesValue();\n ip = NEXTINST(AddEmptyString);\n }\n DISPATCH;\n }\n\n CASE(Jmp) {\n ip = IPADD(ip->iJmp.op1);\n DISPATCH;\n }\n CASE(JmpLong) {\n ip = IPADD(ip->iJmpLong.op1);\n DISPATCH;\n }\n CASE(JmpTrue) {\n if (toBoolean(O2REG(JmpTrue)))\n ip = IPADD(ip->iJmpTrue.op1);\n else\n ip = NEXTINST(JmpTrue);\n DISPATCH;\n }\n CASE(JmpTrueLong) {\n if (toBoolean(O2REG(JmpTrueLong)))\n ip = IPADD(ip->iJmpTrueLong.op1);\n else\n ip = NEXTINST(JmpTrueLong);\n DISPATCH;\n }\n CASE(JmpFalse) {\n if (!toBoolean(O2REG(JmpFalse)))\n ip = IPADD(ip->iJmpFalse.op1);\n else\n ip = NEXTINST(JmpFalse);\n DISPATCH;\n }\n CASE(JmpFalseLong) {\n if (!toBoolean(O2REG(JmpFalseLong)))\n ip = IPADD(ip->iJmpFalseLong.op1);\n else\n ip = NEXTINST(JmpFalseLong);\n DISPATCH;\n }\n CASE(JmpUndefined) {\n if (O2REG(JmpUndefined).isUndefined())\n ip = IPADD(ip->iJmpUndefined.op1);\n else\n ip = NEXTINST(JmpUndefined);\n DISPATCH;\n }\n CASE(JmpUndefinedLong) {\n if (O2REG(JmpUndefinedLong).isUndefined())\n ip = IPADD(ip->iJmpUndefinedLong.op1);\n else\n ip = NEXTINST(JmpUndefinedLong);\n DISPATCH;\n }\n CASE(Add) {\n if (LLVM_LIKELY(\n O2REG(Add).isNumber() &&\n O3REG(Add).isNumber())) { /* Fast-path. */\n CASE(AddN) {\n O1REG(Add) = HermesValue::encodeDoubleValue(\n O2REG(Add).getNumber() + O3REG(Add).getNumber());\n ip = NEXTINST(Add);\n DISPATCH;\n }\n }\n CAPTURE_IP_ASSIGN(\n res,\n addOp_RJS(runtime, Handle<>(&O2REG(Add)), Handle<>(&O3REG(Add))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Add) = res.getValue();\n ip = NEXTINST(Add);\n DISPATCH;\n }\n\n CASE(BitNot) {\n if (LLVM_LIKELY(O2REG(BitNot).isNumber())) { /* Fast-path. */\n O1REG(BitNot) = HermesValue::encodeDoubleValue(\n ~hermes::truncateToInt32(O2REG(BitNot).getNumber()));\n ip = NEXTINST(BitNot);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(BitNot))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(BitNot) = HermesValue::encodeDoubleValue(\n ~static_cast(res->getNumber()));\n ip = NEXTINST(BitNot);\n DISPATCH;\n }\n\n CASE(GetArgumentsLength) {\n // If the arguments object hasn't been created yet.\n if (O2REG(GetArgumentsLength).isUndefined()) {\n O1REG(GetArgumentsLength) =\n HermesValue::encodeNumberValue(FRAME.getArgCount());\n ip = NEXTINST(GetArgumentsLength);\n DISPATCH;\n }\n // The arguments object has been created, so this is a regular property\n // get.\n assert(\n O2REG(GetArgumentsLength).isObject() &&\n \"arguments lazy register is not an object\");\n CAPTURE_IP_ASSIGN(\n resPH,\n JSObject::getNamed_RJS(\n Handle::vmcast(&O2REG(GetArgumentsLength)),\n runtime,\n Predefined::getSymbolID(Predefined::length)));\n if (resPH == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetArgumentsLength) = resPH->get();\n ip = NEXTINST(GetArgumentsLength);\n DISPATCH;\n }\n\n CASE(GetArgumentsPropByVal) {\n // If the arguments object hasn't been created yet and we have a\n // valid integer index, we use the fast path.\n if (O3REG(GetArgumentsPropByVal).isUndefined()) {\n // If this is an integer index.\n if (auto index = toArrayIndexFastPath(O2REG(GetArgumentsPropByVal))) {\n // Is this an existing argument?\n if (*index < FRAME.getArgCount()) {\n O1REG(GetArgumentsPropByVal) = FRAME.getArgRef(*index);\n ip = NEXTINST(GetArgumentsPropByVal);\n DISPATCH;\n }\n }\n }\n // Slow path.\n CAPTURE_IP_ASSIGN(\n auto res,\n getArgumentsPropByValSlowPath_RJS(\n runtime,\n &O3REG(GetArgumentsPropByVal),\n &O2REG(GetArgumentsPropByVal),\n FRAME.getCalleeClosureHandleUnsafe(),\n strictMode));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(GetArgumentsPropByVal) = res->getHermesValue();\n ip = NEXTINST(GetArgumentsPropByVal);\n DISPATCH;\n }\n\n CASE(ReifyArguments) {\n // If the arguments object was already created, do nothing.\n if (!O1REG(ReifyArguments).isUndefined()) {\n assert(\n O1REG(ReifyArguments).isObject() &&\n \"arguments lazy register is not an object\");\n ip = NEXTINST(ReifyArguments);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(\n resArgs,\n reifyArgumentsSlowPath(\n runtime, FRAME.getCalleeClosureHandleUnsafe(), strictMode));\n if (LLVM_UNLIKELY(resArgs == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(ReifyArguments) = resArgs->getHermesValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(ReifyArguments);\n DISPATCH;\n }\n\n CASE(NewObject) {\n // Create a new object using the built-in constructor. Note that the\n // built-in constructor is empty, so we don't actually need to call\n // it.\n CAPTURE_IP_ASSIGN(\n O1REG(NewObject), JSObject::create(runtime).getHermesValue());\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"Should not create handles.\");\n ip = NEXTINST(NewObject);\n DISPATCH;\n }\n CASE(NewObjectWithParent) {\n CAPTURE_IP_ASSIGN(\n O1REG(NewObjectWithParent),\n JSObject::create(\n runtime,\n O2REG(NewObjectWithParent).isObject()\n ? Handle::vmcast(&O2REG(NewObjectWithParent))\n : O2REG(NewObjectWithParent).isNull()\n ? Runtime::makeNullHandle()\n : Handle::vmcast(&runtime->objectPrototype))\n .getHermesValue());\n assert(\n gcScope.getHandleCountDbg() == KEEP_HANDLES &&\n \"Should not create handles.\");\n ip = NEXTINST(NewObjectWithParent);\n DISPATCH;\n }\n\n CASE(NewObjectWithBuffer) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createObjectFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewObjectWithBuffer.op3,\n ip->iNewObjectWithBuffer.op4,\n ip->iNewObjectWithBuffer.op5));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewObjectWithBuffer) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewObjectWithBuffer);\n DISPATCH;\n }\n\n CASE(NewObjectWithBufferLong) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createObjectFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewObjectWithBufferLong.op3,\n ip->iNewObjectWithBufferLong.op4,\n ip->iNewObjectWithBufferLong.op5));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewObjectWithBufferLong) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewObjectWithBufferLong);\n DISPATCH;\n }\n\n CASE(NewArray) {\n // Create a new array using the built-in constructor. Note that the\n // built-in constructor is empty, so we don't actually need to call\n // it.\n CAPTURE_IP_ASSIGN(\n auto createRes,\n JSArray::create(runtime, ip->iNewArray.op2, ip->iNewArray.op2));\n if (createRes == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(NewArray) = createRes->getHermesValue();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(NewArray);\n DISPATCH;\n }\n\n CASE(NewArrayWithBuffer) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createArrayFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewArrayWithBuffer.op2,\n ip->iNewArrayWithBuffer.op3,\n ip->iNewArrayWithBuffer.op4));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewArrayWithBuffer) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(NewArrayWithBuffer);\n DISPATCH;\n }\n\n CASE(NewArrayWithBufferLong) {\n CAPTURE_IP_ASSIGN(\n resPH,\n Interpreter::createArrayFromBuffer(\n runtime,\n curCodeBlock,\n ip->iNewArrayWithBufferLong.op2,\n ip->iNewArrayWithBufferLong.op3,\n ip->iNewArrayWithBufferLong.op4));\n if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(NewArrayWithBufferLong) = resPH->get();\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(NewArrayWithBufferLong);\n DISPATCH;\n }\n\n CASE(CreateThis) {\n // Registers: output, prototype, closure.\n if (LLVM_UNLIKELY(!vmisa(O3REG(CreateThis)))) {\n CAPTURE_IP(runtime->raiseTypeError(\"constructor is not callable\"));\n goto exception;\n }\n CAPTURE_IP_ASSIGN(\n auto res,\n Callable::newObject(\n Handle::vmcast(&O3REG(CreateThis)),\n runtime,\n Handle::vmcast(\n O2REG(CreateThis).isObject() ? &O2REG(CreateThis)\n : &runtime->objectPrototype)));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(CreateThis) = res->getHermesValue();\n ip = NEXTINST(CreateThis);\n DISPATCH;\n }\n\n CASE(SelectObject) {\n // Registers: output, thisObject, constructorReturnValue.\n O1REG(SelectObject) = O3REG(SelectObject).isObject()\n ? O3REG(SelectObject)\n : O2REG(SelectObject);\n ip = NEXTINST(SelectObject);\n DISPATCH;\n }\n\n CASE(Eq)\n CASE(Neq) {\n CAPTURE_IP_ASSIGN(\n res,\n abstractEqualityTest_RJS(\n runtime, Handle<>(&O2REG(Eq)), Handle<>(&O3REG(Eq))));\n if (res == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Eq) = ip->opCode == OpCode::Eq\n ? res.getValue()\n : HermesValue::encodeBoolValue(!res->getBool());\n ip = NEXTINST(Eq);\n DISPATCH;\n }\n CASE(StrictEq) {\n O1REG(StrictEq) = HermesValue::encodeBoolValue(\n strictEqualityTest(O2REG(StrictEq), O3REG(StrictEq)));\n ip = NEXTINST(StrictEq);\n DISPATCH;\n }\n CASE(StrictNeq) {\n O1REG(StrictNeq) = HermesValue::encodeBoolValue(\n !strictEqualityTest(O2REG(StrictNeq), O3REG(StrictNeq)));\n ip = NEXTINST(StrictNeq);\n DISPATCH;\n }\n CASE(Not) {\n O1REG(Not) = HermesValue::encodeBoolValue(!toBoolean(O2REG(Not)));\n ip = NEXTINST(Not);\n DISPATCH;\n }\n CASE(Negate) {\n if (LLVM_LIKELY(O2REG(Negate).isNumber())) {\n O1REG(Negate) =\n HermesValue::encodeDoubleValue(-O2REG(Negate).getNumber());\n } else {\n CAPTURE_IP_ASSIGN(\n res, toNumber_RJS(runtime, Handle<>(&O2REG(Negate))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n gcScope.flushToSmallCount(KEEP_HANDLES);\n O1REG(Negate) = HermesValue::encodeDoubleValue(-res->getNumber());\n }\n ip = NEXTINST(Negate);\n DISPATCH;\n }\n CASE(TypeOf) {\n CAPTURE_IP_ASSIGN(\n O1REG(TypeOf), typeOf(runtime, Handle<>(&O2REG(TypeOf))));\n ip = NEXTINST(TypeOf);\n DISPATCH;\n }\n CASE(Mod) {\n // We use fmod here for simplicity. Theoretically fmod behaves slightly\n // differently than the ECMAScript Spec. fmod applies round-towards-zero\n // for the remainder when it's not representable by a double; while the\n // spec requires round-to-nearest. As an example, 5 % 0.7 will give\n // 0.10000000000000031 using fmod, but using the rounding style\n // described\n // by the spec, the output should really be 0.10000000000000053.\n // Such difference can be ignored in practice.\n if (LLVM_LIKELY(O2REG(Mod).isNumber() && O3REG(Mod).isNumber())) {\n /* Fast-path. */\n O1REG(Mod) = HermesValue::encodeDoubleValue(\n std::fmod(O2REG(Mod).getNumber(), O3REG(Mod).getNumber()));\n ip = NEXTINST(Mod);\n DISPATCH;\n }\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(Mod))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n double left = res->getDouble();\n CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(Mod))));\n if (res == ExecutionStatus::EXCEPTION)\n goto exception;\n O1REG(Mod) =\n HermesValue::encodeDoubleValue(std::fmod(left, res->getDouble()));\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(Mod);\n DISPATCH;\n }\n CASE(InstanceOf) {\n CAPTURE_IP_ASSIGN(\n auto result,\n instanceOfOperator_RJS(\n runtime,\n Handle<>(&O2REG(InstanceOf)),\n Handle<>(&O3REG(InstanceOf))));\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(InstanceOf) = HermesValue::encodeBoolValue(*result);\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(InstanceOf);\n DISPATCH;\n }\n CASE(IsIn) {\n {\n if (LLVM_UNLIKELY(!O3REG(IsIn).isObject())) {\n CAPTURE_IP(runtime->raiseTypeError(\n \"right operand of 'in' is not an object\"));\n goto exception;\n }\n CAPTURE_IP_ASSIGN(\n auto cr,\n JSObject::hasComputed(\n Handle::vmcast(&O3REG(IsIn)),\n runtime,\n Handle<>(&O2REG(IsIn))));\n if (cr == ExecutionStatus::EXCEPTION) {\n goto exception;\n }\n O1REG(IsIn) = HermesValue::encodeBoolValue(*cr);\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(IsIn);\n DISPATCH;\n }\n\n CASE(PutNewOwnByIdShort) {\n nextIP = NEXTINST(PutNewOwnByIdShort);\n idVal = ip->iPutNewOwnByIdShort.op3;\n goto putOwnById;\n }\n CASE(PutNewOwnNEByIdLong)\n CASE(PutNewOwnByIdLong) {\n nextIP = NEXTINST(PutNewOwnByIdLong);\n idVal = ip->iPutNewOwnByIdLong.op3;\n goto putOwnById;\n }\n CASE(PutNewOwnNEById)\n CASE(PutNewOwnById) {\n nextIP = NEXTINST(PutNewOwnById);\n idVal = ip->iPutNewOwnById.op3;\n }\n putOwnById : {\n assert(\n O1REG(PutNewOwnById).isObject() &&\n \"Object argument of PutNewOwnById must be an object\");\n CAPTURE_IP_ASSIGN(\n auto res,\n JSObject::defineNewOwnProperty(\n Handle::vmcast(&O1REG(PutNewOwnById)),\n runtime,\n ID(idVal),\n ip->opCode <= OpCode::PutNewOwnByIdLong\n ? PropertyFlags::defaultNewNamedPropertyFlags()\n : PropertyFlags::nonEnumerablePropertyFlags(),\n Handle<>(&O2REG(PutNewOwnById))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(DelByIdLong) {\n idVal = ip->iDelByIdLong.op3;\n nextIP = NEXTINST(DelByIdLong);\n goto DelById;\n }\n\n CASE(DelById) {\n idVal = ip->iDelById.op3;\n nextIP = NEXTINST(DelById);\n }\n DelById : {\n if (LLVM_LIKELY(O2REG(DelById).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteNamed(\n Handle::vmcast(&O2REG(DelById)),\n runtime,\n ID(idVal),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelById))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n // If an exception is thrown, likely we are trying to convert\n // undefined/null to an object. Passing over the name of the property\n // so that we could emit more meaningful error messages.\n CAPTURE_IP(amendPropAccessErrorMsgWithPropName(\n runtime, Handle<>(&O2REG(DelById)), \"delete\", ID(idVal)));\n goto exception;\n }\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteNamed(\n Handle::vmcast(tmpHandle),\n runtime,\n ID(idVal),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());\n tmpHandle.clear();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = nextIP;\n DISPATCH;\n }\n\n CASE(DelByVal) {\n if (LLVM_LIKELY(O2REG(DelByVal).isObject())) {\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteComputed(\n Handle::vmcast(&O2REG(DelByVal)),\n runtime,\n Handle<>(&O3REG(DelByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());\n } else {\n // This is the \"slow path\".\n CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelByVal))));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n tmpHandle = res.getValue();\n CAPTURE_IP_ASSIGN(\n auto status,\n JSObject::deleteComputed(\n Handle::vmcast(tmpHandle),\n runtime,\n Handle<>(&O3REG(DelByVal)),\n defaultPropOpFlags));\n if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n ip = NEXTINST(DelByVal);\n DISPATCH;\n }\n CASE(CreateRegExp) {\n {\n // Create the RegExp object.\n CAPTURE_IP_ASSIGN(auto re, JSRegExp::create(runtime));\n // Initialize the regexp.\n CAPTURE_IP_ASSIGN(\n auto pattern,\n runtime->makeHandle(curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iCreateRegExp.op2)));\n CAPTURE_IP_ASSIGN(\n auto flags,\n runtime->makeHandle(curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iCreateRegExp.op3)));\n CAPTURE_IP_ASSIGN(\n auto bytecode,\n curCodeBlock->getRuntimeModule()->getRegExpBytecodeFromRegExpID(\n ip->iCreateRegExp.op4));\n CAPTURE_IP_ASSIGN(\n auto initRes,\n JSRegExp::initialize(re, runtime, pattern, flags, bytecode));\n if (LLVM_UNLIKELY(initRes == ExecutionStatus::EXCEPTION)) {\n goto exception;\n }\n // Done, return the new object.\n O1REG(CreateRegExp) = re.getHermesValue();\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n ip = NEXTINST(CreateRegExp);\n DISPATCH;\n }\n\n CASE(SwitchImm) {\n if (LLVM_LIKELY(O1REG(SwitchImm).isNumber())) {\n double numVal = O1REG(SwitchImm).getNumber();\n uint32_t uintVal = (uint32_t)numVal;\n if (LLVM_LIKELY(numVal == uintVal) && // Only integers.\n LLVM_LIKELY(uintVal >= ip->iSwitchImm.op4) && // Bounds checking.\n LLVM_LIKELY(uintVal <= ip->iSwitchImm.op5)) // Bounds checking.\n {\n // Calculate the offset into the bytecode where the jump table for\n // this SwitchImm starts.\n const uint8_t *tablestart = (const uint8_t *)llvh::alignAddr(\n (const uint8_t *)ip + ip->iSwitchImm.op2, sizeof(uint32_t));\n\n // Read the offset from the table.\n // Must be signed to account for backwards branching.\n const int32_t *loc =\n (const int32_t *)tablestart + uintVal - ip->iSwitchImm.op4;\n\n ip = IPADD(*loc);\n DISPATCH;\n }\n }\n // Wrong type or out of range, jump to default.\n ip = IPADD(ip->iSwitchImm.op3);\n DISPATCH;\n }\n LOAD_CONST(\n LoadConstUInt8,\n HermesValue::encodeDoubleValue(ip->iLoadConstUInt8.op2));\n LOAD_CONST(\n LoadConstInt, HermesValue::encodeDoubleValue(ip->iLoadConstInt.op2));\n LOAD_CONST(\n LoadConstDouble,\n HermesValue::encodeDoubleValue(ip->iLoadConstDouble.op2));\n LOAD_CONST_CAPTURE_IP(\n LoadConstString,\n HermesValue::encodeStringValue(\n curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iLoadConstString.op2)));\n LOAD_CONST_CAPTURE_IP(\n LoadConstStringLongIndex,\n HermesValue::encodeStringValue(\n curCodeBlock->getRuntimeModule()\n ->getStringPrimFromStringIDMayAllocate(\n ip->iLoadConstStringLongIndex.op2)));\n LOAD_CONST(LoadConstUndefined, HermesValue::encodeUndefinedValue());\n LOAD_CONST(LoadConstNull, HermesValue::encodeNullValue());\n LOAD_CONST(LoadConstTrue, HermesValue::encodeBoolValue(true));\n LOAD_CONST(LoadConstFalse, HermesValue::encodeBoolValue(false));\n LOAD_CONST(LoadConstZero, HermesValue::encodeDoubleValue(0));\n BINOP(Sub, doSub);\n BINOP(Mul, doMult);\n BINOP(Div, doDiv);\n BITWISEBINOP(BitAnd, &);\n BITWISEBINOP(BitOr, |);\n BITWISEBINOP(BitXor, ^);\n // For LShift, we need to use toUInt32 first because lshift on negative\n // numbers is undefined behavior in theory.\n SHIFTOP(LShift, <<, toUInt32_RJS, uint32_t, int32_t);\n SHIFTOP(RShift, >>, toInt32_RJS, int32_t, int32_t);\n SHIFTOP(URshift, >>, toUInt32_RJS, uint32_t, uint32_t);\n CONDOP(Less, <, lessOp_RJS);\n CONDOP(LessEq, <=, lessEqualOp_RJS);\n CONDOP(Greater, >, greaterOp_RJS);\n CONDOP(GreaterEq, >=, greaterEqualOp_RJS);\n JCOND(Less, <, lessOp_RJS);\n JCOND(LessEqual, <=, lessEqualOp_RJS);\n JCOND(Greater, >, greaterOp_RJS);\n JCOND(GreaterEqual, >=, greaterEqualOp_RJS);\n\n JCOND_STRICT_EQ_IMPL(\n JStrictEqual, , IPADD(ip->iJStrictEqual.op1), NEXTINST(JStrictEqual));\n JCOND_STRICT_EQ_IMPL(\n JStrictEqual,\n Long,\n IPADD(ip->iJStrictEqualLong.op1),\n NEXTINST(JStrictEqualLong));\n JCOND_STRICT_EQ_IMPL(\n JStrictNotEqual,\n ,\n NEXTINST(JStrictNotEqual),\n IPADD(ip->iJStrictNotEqual.op1));\n JCOND_STRICT_EQ_IMPL(\n JStrictNotEqual,\n Long,\n NEXTINST(JStrictNotEqualLong),\n IPADD(ip->iJStrictNotEqualLong.op1));\n\n JCOND_EQ_IMPL(JEqual, , IPADD(ip->iJEqual.op1), NEXTINST(JEqual));\n JCOND_EQ_IMPL(\n JEqual, Long, IPADD(ip->iJEqualLong.op1), NEXTINST(JEqualLong));\n JCOND_EQ_IMPL(\n JNotEqual, , NEXTINST(JNotEqual), IPADD(ip->iJNotEqual.op1));\n JCOND_EQ_IMPL(\n JNotEqual,\n Long,\n NEXTINST(JNotEqualLong),\n IPADD(ip->iJNotEqualLong.op1));\n\n CASE_OUTOFLINE(PutOwnByVal);\n CASE_OUTOFLINE(PutOwnGetterSetterByVal);\n CASE_OUTOFLINE(DirectEval);\n\n CASE_OUTOFLINE(IteratorBegin);\n CASE_OUTOFLINE(IteratorNext);\n CASE(IteratorClose) {\n if (LLVM_UNLIKELY(O1REG(IteratorClose).isObject())) {\n // The iterator must be closed if it's still an object.\n // That means it was never an index and is not done iterating (a state\n // which is indicated by `undefined`).\n CAPTURE_IP_ASSIGN(\n auto res,\n iteratorClose(\n runtime,\n Handle::vmcast(&O1REG(IteratorClose)),\n Runtime::getEmptyValue()));\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n if (ip->iIteratorClose.op2 &&\n !isUncatchableError(runtime->thrownValue_)) {\n // Ignore inner exception.\n runtime->clearThrownValue();\n } else {\n goto exception;\n }\n }\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n ip = NEXTINST(IteratorClose);\n DISPATCH;\n }\n\n CASE(_last) {\n llvm_unreachable(\"Invalid opcode _last\");\n }\n }\n\n llvm_unreachable(\"unreachable\");\n\n // We arrive here if we couldn't allocate the registers for the current frame.\n stackOverflow:\n CAPTURE_IP(runtime->raiseStackOverflow(\n Runtime::StackOverflowKind::JSRegisterStack));\n\n // We arrive here when we raised an exception in a callee, but we don't want\n // the callee to be able to handle it.\n handleExceptionInParent:\n // Restore the caller code block and IP.\n curCodeBlock = FRAME.getSavedCodeBlock();\n ip = FRAME.getSavedIP();\n\n // Pop to the previous frame where technically the error happened.\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n // If we are coming from native code, return.\n if (!curCodeBlock)\n return ExecutionStatus::EXCEPTION;\n\n// Return because of recursive calling structure\n#ifdef HERMESVM_PROFILER_EXTERN\n return ExecutionStatus::EXCEPTION;\n#endif\n // Handle the exception.\n exception:\n UPDATE_OPCODE_TIME_SPENT;\n assert(\n !runtime->thrownValue_.isEmpty() &&\n \"thrownValue unavailable at exception\");\n\n bool catchable = true;\n // If this is an Error object that was thrown internally, it didn't have\n // access to the current codeblock and IP, so collect the stack trace here.\n if (auto *jsError = dyn_vmcast(runtime->thrownValue_)) {\n catchable = jsError->catchable();\n if (!jsError->getStackTrace()) {\n // Temporarily clear the thrown value for following operations.\n CAPTURE_IP_ASSIGN(\n auto errorHandle,\n runtime->makeHandle(vmcast(runtime->thrownValue_)));\n runtime->clearThrownValue();\n\n CAPTURE_IP(JSError::recordStackTrace(\n errorHandle, runtime, false, curCodeBlock, ip));\n\n // Restore the thrown value.\n runtime->setThrownValue(errorHandle.getHermesValue());\n }\n }\n\n gcScope.flushToSmallCount(KEEP_HANDLES);\n tmpHandle.clear();\n\n#ifdef HERMES_ENABLE_DEBUGGER\n if (SingleStep) {\n // If we're single stepping, don't bother with any more checks,\n // and simply signal that we should continue execution with an exception.\n state.codeBlock = curCodeBlock;\n state.offset = CUROFFSET;\n return ExecutionStatus::EXCEPTION;\n }\n\n using PauseOnThrowMode = facebook::hermes::debugger::PauseOnThrowMode;\n auto mode = runtime->debugger_.getPauseOnThrowMode();\n if (mode != PauseOnThrowMode::None) {\n if (!runtime->debugger_.isDebugging()) {\n // Determine whether the PauseOnThrowMode requires us to stop here.\n bool caught =\n runtime->debugger_\n .findCatchTarget(InterpreterState(curCodeBlock, CUROFFSET))\n .hasValue();\n bool shouldStop = mode == PauseOnThrowMode::All ||\n (mode == PauseOnThrowMode::Uncaught && !caught);\n if (shouldStop) {\n // When runDebugger is invoked after an exception,\n // stepping should never happen internally.\n // Any step is a step to an exception handler, which we do\n // directly here in the interpreter.\n // Thus, the result state should be the same as the input state.\n InterpreterState tmpState{curCodeBlock, (uint32_t)CUROFFSET};\n CAPTURE_IP_ASSIGN(\n ExecutionStatus resultStatus,\n runtime->debugger_.runDebugger(\n Debugger::RunReason::Exception, tmpState));\n (void)resultStatus;\n assert(\n tmpState == InterpreterState(curCodeBlock, CUROFFSET) &&\n \"not allowed to step internally in a pauseOnThrow\");\n gcScope.flushToSmallCount(KEEP_HANDLES);\n }\n }\n }\n#endif\n\n int32_t handlerOffset = 0;\n\n // If the exception is not catchable, skip found catch blocks.\n while (((handlerOffset = curCodeBlock->findCatchTargetOffset(CUROFFSET)) ==\n -1) ||\n !catchable) {\n PROFILER_EXIT_FUNCTION(curCodeBlock);\n\n#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES\n runtime->popCallStack();\n#endif\n\n // Restore the code block and IP.\n curCodeBlock = FRAME.getSavedCodeBlock();\n ip = FRAME.getSavedIP();\n\n // Pop a stack frame.\n frameRegs =\n &runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();\n\n SLOW_DEBUG(\n dbgs() << \"function exit with exception: restored stackLevel=\"\n << runtime->getStackLevel() << \"\\n\");\n\n // Are we returning to native code?\n if (!curCodeBlock) {\n SLOW_DEBUG(\n dbgs()\n << \"function exit with exception: returning to native code\\n\");\n return ExecutionStatus::EXCEPTION;\n }\n\n assert(\n isCallType(ip->opCode) &&\n \"return address is not Call-type instruction\");\n\n// Return because of recursive calling structure\n#ifdef HERMESVM_PROFILER_EXTERN\n return ExecutionStatus::EXCEPTION;\n#endif\n }\n\n INIT_STATE_FOR_CODEBLOCK(curCodeBlock);\n\n ip = IPADD(handlerOffset - CUROFFSET);\n }\n}", "project": "hermes", "hash": 289242997866177378156795426889881895518, "size": 2756, "commit_id": "b2021df620824627f5a8c96615edbd1eb7fdddfc", "message": "Fix CVE-2020-1914 by using NEXTINST for SaveGeneratorLong\n\nSummary:\nIf `SaveGeneratorLong` was emitted, it would accidentally jump to the\nwrong next instruction, based on how long SaveGenerator was.\n\nMake a callout function to handle the common case, and handle the dispatch\nwithin each case of the interpreter loop.\n\nFixes CVE-2020-1914\n\nReviewed By: neildhar\n\nDifferential Revision: D24024242\n\nfbshipit-source-id: 3bcb88daa740f0d50e91771a49eb212551ce8bd8", "target": 0, "dataset": "other", "idx": 295511} {"func": "rfbSendRectEncodingRaw(rfbClientPtr cl,\n int x,\n int y,\n int w,\n int h)\n{\n rfbFramebufferUpdateRectHeader rect;\n int nlines;\n int bytesPerLine = w * (cl->format.bitsPerPixel / 8);\n char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y)\n + (x * (cl->scaledScreen->bitsPerPixel / 8)));\n\n /* Flush the buffer to guarantee correct alignment for translateFn(). */\n if (cl->ublen > 0) {\n if (!rfbSendUpdateBuf(cl))\n return FALSE;\n }\n\n rect.r.x = Swap16IfLE(x);\n rect.r.y = Swap16IfLE(y);\n rect.r.w = Swap16IfLE(w);\n rect.r.h = Swap16IfLE(h);\n rect.encoding = Swap32IfLE(rfbEncodingRaw);\n\n memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader);\n cl->ublen += sz_rfbFramebufferUpdateRectHeader;\n\n\n rfbStatRecordEncodingSent(cl, rfbEncodingRaw, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h,\n sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h);\n\n nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine;\n\n while (TRUE) {\n if (nlines > h)\n nlines = h;\n\n (*cl->translateFn)(cl->translateLookupTable,\n\t\t\t &(cl->screen->serverFormat),\n &cl->format, fbptr, &cl->updateBuf[cl->ublen],\n cl->scaledScreen->paddedWidthInBytes, w, nlines);\n\n cl->ublen += nlines * bytesPerLine;\n h -= nlines;\n\n if (h == 0) /* rect fitted in buffer, do next one */\n return TRUE;\n\n /* buffer full - flush partial rect and do another nlines */\n\n if (!rfbSendUpdateBuf(cl))\n return FALSE;\n\n fbptr += (cl->scaledScreen->paddedWidthInBytes * nlines);\n\n nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine;\n if (nlines == 0) {\n rfbErr(\"rfbSendRectEncodingRaw: send buffer too small for %d \"\n \"bytes per line\\n\", bytesPerLine);\n rfbCloseClient(cl);\n return FALSE;\n }\n }\n}", "project": "libvncserver", "hash": 102805718309305214589410374720369949147, "size": 64, "commit_id": "673c07a75ed844d74676f3ccdcfdc706a7052dba", "message": "libvncserver/rfbserver: fix possible divide-by-zero\n\nCloses #409", "target": 1, "dataset": "other", "idx": 199948} {"func": "rfbSendRectEncodingRaw(rfbClientPtr cl,\n int x,\n int y,\n int w,\n int h)\n{\n rfbFramebufferUpdateRectHeader rect;\n int nlines;\n int bytesPerLine = w * (cl->format.bitsPerPixel / 8);\n char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y)\n + (x * (cl->scaledScreen->bitsPerPixel / 8)));\n\n if(!h || !w)\n\treturn TRUE; /* nothing to send */\n\n /* Flush the buffer to guarantee correct alignment for translateFn(). */\n if (cl->ublen > 0) {\n if (!rfbSendUpdateBuf(cl))\n return FALSE;\n }\n\n rect.r.x = Swap16IfLE(x);\n rect.r.y = Swap16IfLE(y);\n rect.r.w = Swap16IfLE(w);\n rect.r.h = Swap16IfLE(h);\n rect.encoding = Swap32IfLE(rfbEncodingRaw);\n\n memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader);\n cl->ublen += sz_rfbFramebufferUpdateRectHeader;\n\n\n rfbStatRecordEncodingSent(cl, rfbEncodingRaw, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h,\n sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h);\n\n nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine;\n\n while (TRUE) {\n if (nlines > h)\n nlines = h;\n\n (*cl->translateFn)(cl->translateLookupTable,\n\t\t\t &(cl->screen->serverFormat),\n &cl->format, fbptr, &cl->updateBuf[cl->ublen],\n cl->scaledScreen->paddedWidthInBytes, w, nlines);\n\n cl->ublen += nlines * bytesPerLine;\n h -= nlines;\n\n if (h == 0) /* rect fitted in buffer, do next one */\n return TRUE;\n\n /* buffer full - flush partial rect and do another nlines */\n\n if (!rfbSendUpdateBuf(cl))\n return FALSE;\n\n fbptr += (cl->scaledScreen->paddedWidthInBytes * nlines);\n\n nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine;\n if (nlines == 0) {\n rfbErr(\"rfbSendRectEncodingRaw: send buffer too small for %d \"\n \"bytes per line\\n\", bytesPerLine);\n rfbCloseClient(cl);\n return FALSE;\n }\n }\n}", "project": "libvncserver", "hash": 244759484708758165967165727952471421179, "size": 67, "commit_id": "673c07a75ed844d74676f3ccdcfdc706a7052dba", "message": "libvncserver/rfbserver: fix possible divide-by-zero\n\nCloses #409", "target": 0, "dataset": "other", "idx": 295864} {"func": "pixFewColorsOctcubeQuantMixed(PIX *pixs,\n l_int32 level,\n l_int32 darkthresh,\n l_int32 lightthresh,\n l_int32 diffthresh,\n l_float32 minfract,\n l_int32 maxspan)\n{\nl_int32 i, j, w, h, wplc, wplm, wpld, ncolors, index;\nl_int32 rval, gval, bval, val, minval, maxval;\nl_int32 *lut;\nl_uint32 *datac, *datam, *datad, *linec, *linem, *lined;\nPIX *pixc, *pixm, *pixg, *pixd;\nPIXCMAP *cmap, *cmapd;\n\n PROCNAME(\"pixFewColorsOctcubeQuantMixed\");\n\n if (!pixs || pixGetDepth(pixs) != 32)\n return (PIX *)ERROR_PTR(\"pixs undefined or not 32 bpp\", procName, NULL);\n if (level <= 0) level = 3;\n if (level > 6)\n return (PIX *)ERROR_PTR(\"invalid level\", procName, NULL);\n if (darkthresh <= 0) darkthresh = 20;\n if (lightthresh <= 0) lightthresh = 244;\n if (diffthresh <= 0) diffthresh = 20;\n if (minfract <= 0.0) minfract = 0.05;\n if (maxspan <= 2) maxspan = 15;\n\n /* Start with a simple fixed octcube quantizer. */\n if ((pixc = pixFewColorsOctcubeQuant1(pixs, level)) == NULL)\n return (PIX *)ERROR_PTR(\"too many colors\", procName, NULL);\n\n /* Identify and save color entries in the colormap. Set up a LUT\n * that returns -1 for any gray pixel. */\n cmap = pixGetColormap(pixc);\n ncolors = pixcmapGetCount(cmap);\n cmapd = pixcmapCreate(8);\n lut = (l_int32 *)LEPT_CALLOC(256, sizeof(l_int32));\n for (i = 0; i < 256; i++)\n lut[i] = -1;\n for (i = 0, index = 0; i < ncolors; i++) {\n pixcmapGetColor(cmap, i, &rval, &gval, &bval);\n minval = L_MIN(rval, gval);\n minval = L_MIN(minval, bval);\n if (minval > lightthresh) /* near white */\n continue;\n maxval = L_MAX(rval, gval);\n maxval = L_MAX(maxval, bval);\n if (maxval < darkthresh) /* near black */\n continue;\n\n /* Use the max diff between components to test for color */\n if (maxval - minval >= diffthresh) {\n pixcmapAddColor(cmapd, rval, gval, bval);\n lut[i] = index;\n index++;\n }\n }\n\n /* Generate dest pix with just the color pixels set to their\n * colormap indices. At the same time, make a 1 bpp mask\n * of the non-color pixels */\n pixGetDimensions(pixs, &w, &h, NULL);\n pixd = pixCreate(w, h, 8);\n pixSetColormap(pixd, cmapd);\n pixm = pixCreate(w, h, 1);\n datac = pixGetData(pixc);\n datam = pixGetData(pixm);\n datad = pixGetData(pixd);\n wplc = pixGetWpl(pixc);\n wplm = pixGetWpl(pixm);\n wpld = pixGetWpl(pixd);\n for (i = 0; i < h; i++) {\n linec = datac + i * wplc;\n linem = datam + i * wplm;\n lined = datad + i * wpld;\n for (j = 0; j < w; j++) {\n val = GET_DATA_BYTE(linec, j);\n if (lut[val] == -1)\n SET_DATA_BIT(linem, j);\n else\n SET_DATA_BYTE(lined, j, lut[val]);\n }\n }\n\n /* Fill in the gray values. Use a grayscale version of pixs\n * as input, along with the mask over the actual gray pixels. */\n pixg = pixConvertTo8(pixs, 0);\n pixGrayQuantFromHisto(pixd, pixg, pixm, minfract, maxspan);\n\n LEPT_FREE(lut);\n pixDestroy(&pixc);\n pixDestroy(&pixm);\n pixDestroy(&pixg);\n return pixd;\n}", "project": "leptonica", "hash": 189520668983998653093674301627277618692, "size": 96, "commit_id": "5ee24b398bb67666f6d173763eaaedd9c36fb1e5", "message": "Fixed issue 22140 in oss-fuzz: Heap-buffer-overflow\n* color quantized pix must be 8 bpp before extra colors are added.", "target": 1, "dataset": "other", "idx": 199976} {"func": "pixFewColorsOctcubeQuantMixed(PIX *pixs,\n l_int32 level,\n l_int32 darkthresh,\n l_int32 lightthresh,\n l_int32 diffthresh,\n l_float32 minfract,\n l_int32 maxspan)\n{\nl_int32 i, j, w, h, wplc, wplm, wpld, ncolors, index;\nl_int32 rval, gval, bval, val, minval, maxval;\nl_int32 *lut;\nl_uint32 *datac, *datam, *datad, *linec, *linem, *lined;\nPIX *pix1, *pixc, *pixm, *pixg, *pixd;\nPIXCMAP *cmap, *cmapd;\n\n PROCNAME(\"pixFewColorsOctcubeQuantMixed\");\n\n if (!pixs || pixGetDepth(pixs) != 32)\n return (PIX *)ERROR_PTR(\"pixs undefined or not 32 bpp\", procName, NULL);\n if (level <= 0) level = 3;\n if (level > 6)\n return (PIX *)ERROR_PTR(\"invalid level\", procName, NULL);\n if (darkthresh <= 0) darkthresh = 20;\n if (lightthresh <= 0) lightthresh = 244;\n if (diffthresh <= 0) diffthresh = 20;\n if (minfract <= 0.0) minfract = 0.05;\n if (maxspan <= 2) maxspan = 15;\n\n /* Start with a simple fixed octcube quantizer. */\n if ((pix1 = pixFewColorsOctcubeQuant1(pixs, level)) == NULL)\n return (PIX *)ERROR_PTR(\"too many colors\", procName, NULL);\n pixc = pixConvertTo8(pix1, 1); /* must be 8 bpp */\n pixDestroy(&pix1);\n\n /* Identify and save color entries in the colormap. Set up a LUT\n * that returns -1 for any gray pixel. */\n cmap = pixGetColormap(pixc);\n ncolors = pixcmapGetCount(cmap);\n cmapd = pixcmapCreate(8);\n lut = (l_int32 *)LEPT_CALLOC(256, sizeof(l_int32));\n for (i = 0; i < 256; i++)\n lut[i] = -1;\n for (i = 0, index = 0; i < ncolors; i++) {\n pixcmapGetColor(cmap, i, &rval, &gval, &bval);\n minval = L_MIN(rval, gval);\n minval = L_MIN(minval, bval);\n if (minval > lightthresh) /* near white */\n continue;\n maxval = L_MAX(rval, gval);\n maxval = L_MAX(maxval, bval);\n if (maxval < darkthresh) /* near black */\n continue;\n\n /* Use the max diff between components to test for color */\n if (maxval - minval >= diffthresh) {\n pixcmapAddColor(cmapd, rval, gval, bval);\n lut[i] = index;\n index++;\n }\n }\n\n /* Generate dest pix with just the color pixels set to their\n * colormap indices. At the same time, make a 1 bpp mask\n * of the non-color pixels */\n pixGetDimensions(pixs, &w, &h, NULL);\n pixd = pixCreate(w, h, 8);\n pixSetColormap(pixd, cmapd);\n pixm = pixCreate(w, h, 1);\n datac = pixGetData(pixc);\n datam = pixGetData(pixm);\n datad = pixGetData(pixd);\n wplc = pixGetWpl(pixc);\n wplm = pixGetWpl(pixm);\n wpld = pixGetWpl(pixd);\n for (i = 0; i < h; i++) {\n linec = datac + i * wplc;\n linem = datam + i * wplm;\n lined = datad + i * wpld;\n for (j = 0; j < w; j++) {\n val = GET_DATA_BYTE(linec, j);\n if (lut[val] == -1)\n SET_DATA_BIT(linem, j);\n else\n SET_DATA_BYTE(lined, j, lut[val]);\n }\n }\n\n /* Fill in the gray values. Use a grayscale version of pixs\n * as input, along with the mask over the actual gray pixels. */\n pixg = pixConvertTo8(pixs, 0);\n pixGrayQuantFromHisto(pixd, pixg, pixm, minfract, maxspan);\n\n LEPT_FREE(lut);\n pixDestroy(&pixc);\n pixDestroy(&pixm);\n pixDestroy(&pixg);\n return pixd;\n}", "project": "leptonica", "hash": 140231359431133457710971366870294387407, "size": 98, "commit_id": "5ee24b398bb67666f6d173763eaaedd9c36fb1e5", "message": "Fixed issue 22140 in oss-fuzz: Heap-buffer-overflow\n* color quantized pix must be 8 bpp before extra colors are added.", "target": 0, "dataset": "other", "idx": 296022} {"func": "void rfbScaledScreenUpdateRect(rfbScreenInfoPtr screen, rfbScreenInfoPtr ptr, int x0, int y0, int w0, int h0)\n{\n int x,y,w,v,z;\n int x1, y1, w1, h1;\n int bitsPerPixel, bytesPerPixel, bytesPerLine, areaX, areaY, area2;\n unsigned char *srcptr, *dstptr;\n\n /* Nothing to do!!! */\n if (screen==ptr) return;\n\n x1 = x0;\n y1 = y0;\n w1 = w0;\n h1 = h0;\n\n rfbScaledCorrection(screen, ptr, &x1, &y1, &w1, &h1, \"rfbScaledScreenUpdateRect\");\n x0 = ScaleX(ptr, screen, x1);\n y0 = ScaleY(ptr, screen, y1);\n w0 = ScaleX(ptr, screen, w1);\n h0 = ScaleY(ptr, screen, h1);\n\n bitsPerPixel = screen->bitsPerPixel;\n bytesPerPixel = bitsPerPixel / 8;\n bytesPerLine = w1 * bytesPerPixel;\n srcptr = (unsigned char *)(screen->frameBuffer +\n (y0 * screen->paddedWidthInBytes + x0 * bytesPerPixel));\n dstptr = (unsigned char *)(ptr->frameBuffer +\n ( y1 * ptr->paddedWidthInBytes + x1 * bytesPerPixel));\n /* The area of the source framebuffer for each destination pixel */\n areaX = ScaleX(ptr,screen,1);\n areaY = ScaleY(ptr,screen,1);\n area2 = areaX*areaY;\n\n\n /* Ensure that we do not go out of bounds */\n if ((x1+w1) > (ptr->width))\n {\n if (x1==0) w1=ptr->width; else x1 = ptr->width - w1;\n }\n if ((y1+h1) > (ptr->height))\n {\n if (y1==0) h1=ptr->height; else y1 = ptr->height - h1;\n }\n /*\n * rfbLog(\"rfbScaledScreenUpdateRect(%dXx%dY-%dWx%dH -> %dXx%dY-%dWx%dH <%dx%d>) {%dWx%dH -> %dWx%dH} 0x%p\\n\",\n * x0, y0, w0, h0, x1, y1, w1, h1, areaX, areaY,\n * screen->width, screen->height, ptr->width, ptr->height, ptr->frameBuffer);\n */\n\n if (screen->serverFormat.trueColour) { /* Blend neighbouring pixels together */\n unsigned char *srcptr2;\n unsigned long pixel_value, red, green, blue;\n unsigned int redShift = screen->serverFormat.redShift;\n unsigned int greenShift = screen->serverFormat.greenShift;\n unsigned int blueShift = screen->serverFormat.blueShift;\n unsigned long redMax = screen->serverFormat.redMax;\n unsigned long greenMax = screen->serverFormat.greenMax;\n unsigned long blueMax = screen->serverFormat.blueMax;\n\n /* for each *destination* pixel... */\n for (y = 0; y < h1; y++) {\n for (x = 0; x < w1; x++) {\n red = green = blue = 0;\n /* Get the totals for rgb from the source grid... */\n for (w = 0; w < areaX; w++) {\n for (v = 0; v < areaY; v++) {\n srcptr2 = &srcptr[(((x * areaX) + w) * bytesPerPixel) +\n (v * screen->paddedWidthInBytes)];\n pixel_value = 0;\n\n\n switch (bytesPerPixel) {\n case 4: pixel_value = *((unsigned int *)srcptr2); break;\n case 2: pixel_value = *((unsigned short *)srcptr2); break;\n case 1: pixel_value = *((unsigned char *)srcptr2); break;\n default:\n /* fixme: endianness problem? */\n for (z = 0; z < bytesPerPixel; z++)\n pixel_value += (srcptr2[z] << (8 * z));\n break;\n }\n /*\n srcptr2 += bytesPerPixel;\n */\n\n red += ((pixel_value >> redShift) & redMax);\n green += ((pixel_value >> greenShift) & greenMax);\n blue += ((pixel_value >> blueShift) & blueMax);\n\n }\n }\n /* We now have a total for all of the colors, find the average! */\n red /= area2;\n green /= area2;\n blue /= area2;\n /* Stuff the new value back into memory */\n pixel_value = ((red & redMax) << redShift) | ((green & greenMax) << greenShift) | ((blue & blueMax) << blueShift);\n\n switch (bytesPerPixel) {\n case 4: *((unsigned int *)dstptr) = (unsigned int) pixel_value; break;\n case 2: *((unsigned short *)dstptr) = (unsigned short) pixel_value; break;\n case 1: *((unsigned char *)dstptr) = (unsigned char) pixel_value; break;\n default:\n /* fixme: endianness problem? */\n for (z = 0; z < bytesPerPixel; z++)\n dstptr[z]=(pixel_value >> (8 * z)) & 0xff;\n break;\n }\n dstptr += bytesPerPixel;\n }\n srcptr += (screen->paddedWidthInBytes * areaY);\n dstptr += (ptr->paddedWidthInBytes - bytesPerLine);\n }\n } else\n { /* Not truecolour, so we can't blend. Just use the top-left pixel instead */\n for (y = y1; y < (y1+h1); y++) {\n for (x = x1; x < (x1+w1); x++)\n memcpy (&ptr->frameBuffer[(y *ptr->paddedWidthInBytes) + (x * bytesPerPixel)],\n &screen->frameBuffer[(y * areaY * screen->paddedWidthInBytes) + (x *areaX * bytesPerPixel)], bytesPerPixel);\n }\n }\n}", "project": "libvncserver", "hash": 295503009586478475692075987935889055828, "size": 122, "commit_id": "a6788d1da719ae006605b78d22f5a9f170b423af", "message": "libvncserver: scale: cast to 64 bit before shifting\n\nSince pixel_value is 64 bit the data type of the shift operand should\nbe 64 bit too to prevent integer overflows.", "target": 1, "dataset": "other", "idx": 199993} {"func": "void rfbScaledScreenUpdateRect(rfbScreenInfoPtr screen, rfbScreenInfoPtr ptr, int x0, int y0, int w0, int h0)\n{\n int x,y,w,v,z;\n int x1, y1, w1, h1;\n int bitsPerPixel, bytesPerPixel, bytesPerLine, areaX, areaY, area2;\n unsigned char *srcptr, *dstptr;\n\n /* Nothing to do!!! */\n if (screen==ptr) return;\n\n x1 = x0;\n y1 = y0;\n w1 = w0;\n h1 = h0;\n\n rfbScaledCorrection(screen, ptr, &x1, &y1, &w1, &h1, \"rfbScaledScreenUpdateRect\");\n x0 = ScaleX(ptr, screen, x1);\n y0 = ScaleY(ptr, screen, y1);\n w0 = ScaleX(ptr, screen, w1);\n h0 = ScaleY(ptr, screen, h1);\n\n bitsPerPixel = screen->bitsPerPixel;\n bytesPerPixel = bitsPerPixel / 8;\n bytesPerLine = w1 * bytesPerPixel;\n srcptr = (unsigned char *)(screen->frameBuffer +\n (y0 * screen->paddedWidthInBytes + x0 * bytesPerPixel));\n dstptr = (unsigned char *)(ptr->frameBuffer +\n ( y1 * ptr->paddedWidthInBytes + x1 * bytesPerPixel));\n /* The area of the source framebuffer for each destination pixel */\n areaX = ScaleX(ptr,screen,1);\n areaY = ScaleY(ptr,screen,1);\n area2 = areaX*areaY;\n\n\n /* Ensure that we do not go out of bounds */\n if ((x1+w1) > (ptr->width))\n {\n if (x1==0) w1=ptr->width; else x1 = ptr->width - w1;\n }\n if ((y1+h1) > (ptr->height))\n {\n if (y1==0) h1=ptr->height; else y1 = ptr->height - h1;\n }\n /*\n * rfbLog(\"rfbScaledScreenUpdateRect(%dXx%dY-%dWx%dH -> %dXx%dY-%dWx%dH <%dx%d>) {%dWx%dH -> %dWx%dH} 0x%p\\n\",\n * x0, y0, w0, h0, x1, y1, w1, h1, areaX, areaY,\n * screen->width, screen->height, ptr->width, ptr->height, ptr->frameBuffer);\n */\n\n if (screen->serverFormat.trueColour) { /* Blend neighbouring pixels together */\n unsigned char *srcptr2;\n unsigned long pixel_value, red, green, blue;\n unsigned int redShift = screen->serverFormat.redShift;\n unsigned int greenShift = screen->serverFormat.greenShift;\n unsigned int blueShift = screen->serverFormat.blueShift;\n unsigned long redMax = screen->serverFormat.redMax;\n unsigned long greenMax = screen->serverFormat.greenMax;\n unsigned long blueMax = screen->serverFormat.blueMax;\n\n /* for each *destination* pixel... */\n for (y = 0; y < h1; y++) {\n for (x = 0; x < w1; x++) {\n red = green = blue = 0;\n /* Get the totals for rgb from the source grid... */\n for (w = 0; w < areaX; w++) {\n for (v = 0; v < areaY; v++) {\n srcptr2 = &srcptr[(((x * areaX) + w) * bytesPerPixel) +\n (v * screen->paddedWidthInBytes)];\n pixel_value = 0;\n\n\n switch (bytesPerPixel) {\n case 4: pixel_value = *((unsigned int *)srcptr2); break;\n case 2: pixel_value = *((unsigned short *)srcptr2); break;\n case 1: pixel_value = *((unsigned char *)srcptr2); break;\n default:\n /* fixme: endianness problem? */\n for (z = 0; z < bytesPerPixel; z++)\n pixel_value += ((unsigned long)srcptr2[z] << (8 * z));\n break;\n }\n /*\n srcptr2 += bytesPerPixel;\n */\n\n red += ((pixel_value >> redShift) & redMax);\n green += ((pixel_value >> greenShift) & greenMax);\n blue += ((pixel_value >> blueShift) & blueMax);\n\n }\n }\n /* We now have a total for all of the colors, find the average! */\n red /= area2;\n green /= area2;\n blue /= area2;\n /* Stuff the new value back into memory */\n pixel_value = ((red & redMax) << redShift) | ((green & greenMax) << greenShift) | ((blue & blueMax) << blueShift);\n\n switch (bytesPerPixel) {\n case 4: *((unsigned int *)dstptr) = (unsigned int) pixel_value; break;\n case 2: *((unsigned short *)dstptr) = (unsigned short) pixel_value; break;\n case 1: *((unsigned char *)dstptr) = (unsigned char) pixel_value; break;\n default:\n /* fixme: endianness problem? */\n for (z = 0; z < bytesPerPixel; z++)\n dstptr[z]=(pixel_value >> (8 * z)) & 0xff;\n break;\n }\n dstptr += bytesPerPixel;\n }\n srcptr += (screen->paddedWidthInBytes * areaY);\n dstptr += (ptr->paddedWidthInBytes - bytesPerLine);\n }\n } else\n { /* Not truecolour, so we can't blend. Just use the top-left pixel instead */\n for (y = y1; y < (y1+h1); y++) {\n for (x = x1; x < (x1+w1); x++)\n memcpy (&ptr->frameBuffer[(y *ptr->paddedWidthInBytes) + (x * bytesPerPixel)],\n &screen->frameBuffer[(y * areaY * screen->paddedWidthInBytes) + (x *areaX * bytesPerPixel)], bytesPerPixel);\n }\n }\n}", "project": "libvncserver", "hash": 85794347889118649475691237939536661528, "size": 122, "commit_id": "a6788d1da719ae006605b78d22f5a9f170b423af", "message": "libvncserver: scale: cast to 64 bit before shifting\n\nSince pixel_value is 64 bit the data type of the shift operand should\nbe 64 bit too to prevent integer overflows.", "target": 0, "dataset": "other", "idx": 296799} {"func": " yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum,\n TSK_DADDR_T numblock, int32_t sec_skew)\n{\n TSK_FS_META *fs_meta;\n TSK_FS_FILE *fs_file;\n YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs;\n char ls[12];\n YAFFSFS_PRINT_ADDR print;\n char timeBuf[32];\n YaffsCacheObject * obj = NULL;\n YaffsCacheVersion * version = NULL;\n YaffsHeader * header = NULL;\n\n yaffscache_version_find_by_inode(yfs, inum, &version, &obj);\n\n if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) {\n return 1;\n }\n fs_meta = fs_file->meta;\n\n tsk_fprintf(hFile, \"inode: %\" PRIuINUM \"\\n\", inum);\n tsk_fprintf(hFile, \"%sAllocated\\n\",\n (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? \"\" : \"Not \");\n\n if (fs_meta->link)\n tsk_fprintf(hFile, \"symbolic link to: %s\\n\", fs_meta->link);\n\n tsk_fprintf(hFile, \"uid / gid: %\" PRIuUID \" / %\" PRIuGID \"\\n\",\n fs_meta->uid, fs_meta->gid);\n\n tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls));\n tsk_fprintf(hFile, \"mode: %s\\n\", ls);\n\n tsk_fprintf(hFile, \"size: %\" PRIdOFF \"\\n\", fs_meta->size);\n tsk_fprintf(hFile, \"num of links: %d\\n\", fs_meta->nlink);\n\n if(version != NULL){\n yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset);\n if(header != NULL){\n tsk_fprintf(hFile, \"Name: %s\\n\", header->name);\n }\n }\n\n if (sec_skew != 0) {\n tsk_fprintf(hFile, \"\\nAdjusted Inode Times:\\n\");\n fs_meta->mtime -= sec_skew;\n fs_meta->atime -= sec_skew;\n fs_meta->ctime -= sec_skew;\n\n tsk_fprintf(hFile, \"Accessed:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->atime, timeBuf));\n tsk_fprintf(hFile, \"File Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->mtime, timeBuf));\n tsk_fprintf(hFile, \"Inode Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->ctime, timeBuf));\n\n fs_meta->mtime += sec_skew;\n fs_meta->atime += sec_skew;\n fs_meta->ctime += sec_skew;\n\n tsk_fprintf(hFile, \"\\nOriginal Inode Times:\\n\");\n }\n else {\n tsk_fprintf(hFile, \"\\nInode Times:\\n\");\n }\n\n tsk_fprintf(hFile, \"Accessed:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->atime, timeBuf));\n tsk_fprintf(hFile, \"File Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->mtime, timeBuf));\n tsk_fprintf(hFile, \"Inode Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->ctime, timeBuf));\n\n if(version != NULL){\n tsk_fprintf(hFile, \"\\nHeader Chunk:\\n\");\n tsk_fprintf(hFile, \"%\" PRIuDADDR \"\\n\", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size)));\n }\n\n if (numblock > 0) {\n TSK_OFF_T lower_size = numblock * fs->block_size;\n fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size);\n }\n tsk_fprintf(hFile, \"\\nData Chunks:\\n\");\n\n\n if (flags & TSK_FS_ISTAT_RUNLIST){\n const TSK_FS_ATTR *fs_attr_default =\n tsk_fs_file_attr_get_type(fs_file,\n TSK_FS_ATTR_TYPE_DEFAULT, 0, 0);\n if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) {\n if (tsk_fs_attr_print(fs_attr_default, hFile)) {\n tsk_fprintf(hFile, \"\\nError creating run lists \");\n tsk_error_print(hFile);\n tsk_error_reset();\n }\n }\n }\n else {\n print.idx = 0;\n print.hFile = hFile;\n\n if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY,\n (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) {\n tsk_fprintf(hFile, \"\\nError reading file: \");\n tsk_error_print(hFile);\n tsk_error_reset();\n }\n else if (print.idx != 0) {\n tsk_fprintf(hFile, \"\\n\");\n }\n }\n\n tsk_fs_file_close(fs_file);\n\n return 0;\n}", "project": "sleuthkit", "hash": 315622372000357176371289570991066181436, "size": 116, "commit_id": "459ae818fc8dae717549810150de4d191ce158f1", "message": "Fix stack buffer overflow in yaffsfs_istat\n\nPrevent a stack buffer overflow in yaffsfs_istat by increasing the buffer size to the size required by tsk_fs_time_to_str.", "target": 1, "dataset": "other", "idx": 200108} {"func": " yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum,\n TSK_DADDR_T numblock, int32_t sec_skew)\n{\n TSK_FS_META *fs_meta;\n TSK_FS_FILE *fs_file;\n YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs;\n char ls[12];\n YAFFSFS_PRINT_ADDR print;\n char timeBuf[128];\n YaffsCacheObject * obj = NULL;\n YaffsCacheVersion * version = NULL;\n YaffsHeader * header = NULL;\n\n yaffscache_version_find_by_inode(yfs, inum, &version, &obj);\n\n if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) {\n return 1;\n }\n fs_meta = fs_file->meta;\n\n tsk_fprintf(hFile, \"inode: %\" PRIuINUM \"\\n\", inum);\n tsk_fprintf(hFile, \"%sAllocated\\n\",\n (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? \"\" : \"Not \");\n\n if (fs_meta->link)\n tsk_fprintf(hFile, \"symbolic link to: %s\\n\", fs_meta->link);\n\n tsk_fprintf(hFile, \"uid / gid: %\" PRIuUID \" / %\" PRIuGID \"\\n\",\n fs_meta->uid, fs_meta->gid);\n\n tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls));\n tsk_fprintf(hFile, \"mode: %s\\n\", ls);\n\n tsk_fprintf(hFile, \"size: %\" PRIdOFF \"\\n\", fs_meta->size);\n tsk_fprintf(hFile, \"num of links: %d\\n\", fs_meta->nlink);\n\n if(version != NULL){\n yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset);\n if(header != NULL){\n tsk_fprintf(hFile, \"Name: %s\\n\", header->name);\n }\n }\n\n if (sec_skew != 0) {\n tsk_fprintf(hFile, \"\\nAdjusted Inode Times:\\n\");\n fs_meta->mtime -= sec_skew;\n fs_meta->atime -= sec_skew;\n fs_meta->ctime -= sec_skew;\n\n tsk_fprintf(hFile, \"Accessed:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->atime, timeBuf));\n tsk_fprintf(hFile, \"File Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->mtime, timeBuf));\n tsk_fprintf(hFile, \"Inode Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->ctime, timeBuf));\n\n fs_meta->mtime += sec_skew;\n fs_meta->atime += sec_skew;\n fs_meta->ctime += sec_skew;\n\n tsk_fprintf(hFile, \"\\nOriginal Inode Times:\\n\");\n }\n else {\n tsk_fprintf(hFile, \"\\nInode Times:\\n\");\n }\n\n tsk_fprintf(hFile, \"Accessed:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->atime, timeBuf));\n tsk_fprintf(hFile, \"File Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->mtime, timeBuf));\n tsk_fprintf(hFile, \"Inode Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->ctime, timeBuf));\n\n if(version != NULL){\n tsk_fprintf(hFile, \"\\nHeader Chunk:\\n\");\n tsk_fprintf(hFile, \"%\" PRIuDADDR \"\\n\", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size)));\n }\n\n if (numblock > 0) {\n TSK_OFF_T lower_size = numblock * fs->block_size;\n fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size);\n }\n tsk_fprintf(hFile, \"\\nData Chunks:\\n\");\n\n\n if (flags & TSK_FS_ISTAT_RUNLIST){\n const TSK_FS_ATTR *fs_attr_default =\n tsk_fs_file_attr_get_type(fs_file,\n TSK_FS_ATTR_TYPE_DEFAULT, 0, 0);\n if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) {\n if (tsk_fs_attr_print(fs_attr_default, hFile)) {\n tsk_fprintf(hFile, \"\\nError creating run lists \");\n tsk_error_print(hFile);\n tsk_error_reset();\n }\n }\n }\n else {\n print.idx = 0;\n print.hFile = hFile;\n\n if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY,\n (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) {\n tsk_fprintf(hFile, \"\\nError reading file: \");\n tsk_error_print(hFile);\n tsk_error_reset();\n }\n else if (print.idx != 0) {\n tsk_fprintf(hFile, \"\\n\");\n }\n }\n\n tsk_fs_file_close(fs_file);\n\n return 0;\n}", "project": "sleuthkit", "hash": 172760896741279150306338467662761860668, "size": 116, "commit_id": "459ae818fc8dae717549810150de4d191ce158f1", "message": "Fix stack buffer overflow in yaffsfs_istat\n\nPrevent a stack buffer overflow in yaffsfs_istat by increasing the buffer size to the size required by tsk_fs_time_to_str.", "target": 0, "dataset": "other", "idx": 299134} {"func": "xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc, xmlSAXHandlerPtr sax,\n void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst,\n int recover) {\n xmlParserCtxtPtr ctxt;\n xmlDocPtr newDoc;\n xmlSAXHandlerPtr oldsax = NULL;\n xmlNodePtr content, newRoot;\n int size;\n int ret = 0;\n\n if (depth > 40) {\n\treturn(XML_ERR_ENTITY_LOOP);\n }\n\n\n if (lst != NULL)\n *lst = NULL;\n if (string == NULL)\n return(-1);\n\n size = xmlStrlen(string);\n\n ctxt = xmlCreateMemoryParserCtxt((char *) string, size);\n if (ctxt == NULL) return(-1);\n ctxt->userData = ctxt;\n if (sax != NULL) {\n\toldsax = ctxt->sax;\n ctxt->sax = sax;\n\tif (user_data != NULL)\n\t ctxt->userData = user_data;\n }\n newDoc = xmlNewDoc(BAD_CAST \"1.0\");\n if (newDoc == NULL) {\n\txmlFreeParserCtxt(ctxt);\n\treturn(-1);\n }\n newDoc->properties = XML_DOC_INTERNAL;\n if ((doc != NULL) && (doc->dict != NULL)) {\n xmlDictFree(ctxt->dict);\n\tctxt->dict = doc->dict;\n\txmlDictReference(ctxt->dict);\n\tctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST \"xml\", 3);\n\tctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST \"xmlns\", 5);\n\tctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);\n\tctxt->dictNames = 1;\n } else {\n\txmlCtxtUseOptionsInternal(ctxt, XML_PARSE_NODICT, NULL);\n }\n if (doc != NULL) {\n\tnewDoc->intSubset = doc->intSubset;\n\tnewDoc->extSubset = doc->extSubset;\n }\n newRoot = xmlNewDocNode(newDoc, NULL, BAD_CAST \"pseudoroot\", NULL);\n if (newRoot == NULL) {\n\tif (sax != NULL)\n\t ctxt->sax = oldsax;\n\txmlFreeParserCtxt(ctxt);\n\tnewDoc->intSubset = NULL;\n\tnewDoc->extSubset = NULL;\n xmlFreeDoc(newDoc);\n\treturn(-1);\n }\n xmlAddChild((xmlNodePtr) newDoc, newRoot);\n nodePush(ctxt, newRoot);\n if (doc == NULL) {\n\tctxt->myDoc = newDoc;\n } else {\n\tctxt->myDoc = newDoc;\n\tnewDoc->children->doc = doc;\n\t/* Ensure that doc has XML spec namespace */\n\txmlSearchNsByHref(doc, (xmlNodePtr)doc, XML_XML_NAMESPACE);\n\tnewDoc->oldNs = doc->oldNs;\n }\n ctxt->instate = XML_PARSER_CONTENT;\n ctxt->input_id = 2;\n ctxt->depth = depth;\n\n /*\n * Doing validity checking on chunk doesn't make sense\n */\n ctxt->validate = 0;\n ctxt->loadsubset = 0;\n xmlDetectSAX2(ctxt);\n\n if ( doc != NULL ){\n content = doc->children;\n doc->children = NULL;\n xmlParseContent(ctxt);\n doc->children = content;\n }\n else {\n xmlParseContent(ctxt);\n }\n if ((RAW == '<') && (NXT(1) == '/')) {\n\txmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);\n } else if (RAW != 0) {\n\txmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);\n }\n if (ctxt->node != newDoc->children) {\n\txmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);\n }\n\n if (!ctxt->wellFormed) {\n if (ctxt->errNo == 0)\n\t ret = 1;\n\telse\n\t ret = ctxt->errNo;\n } else {\n ret = 0;\n }\n\n if ((lst != NULL) && ((ret == 0) || (recover == 1))) {\n\txmlNodePtr cur;\n\n\t/*\n\t * Return the newly created nodeset after unlinking it from\n\t * they pseudo parent.\n\t */\n\tcur = newDoc->children->children;\n\t*lst = cur;\n\twhile (cur != NULL) {\n\t xmlSetTreeDoc(cur, doc);\n\t cur->parent = NULL;\n\t cur = cur->next;\n\t}\n\tnewDoc->children->children = NULL;\n }\n\n if (sax != NULL)\n\tctxt->sax = oldsax;\n xmlFreeParserCtxt(ctxt);\n newDoc->intSubset = NULL;\n newDoc->extSubset = NULL;\n newDoc->oldNs = NULL;\n xmlFreeDoc(newDoc);\n\n return(ret);\n}", "project": "libxml2", "hash": 277853729283418525736722021066110830468, "size": 138, "commit_id": "5a02583c7e683896d84878bd90641d8d9b0d0549", "message": "Fix memory leak in xmlParseBalancedChunkMemoryRecover\n\nWhen doc is NULL, namespace created in xmlTreeEnsureXMLDecl\nis bind to newDoc->oldNs, in this case, set newDoc->oldNs to\nNULL and free newDoc will cause a memory leak.\n\nFound with libFuzzer.\n\nCloses #82.", "target": 1, "dataset": "other", "idx": 200109} {"func": "xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc, xmlSAXHandlerPtr sax,\n void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst,\n int recover) {\n xmlParserCtxtPtr ctxt;\n xmlDocPtr newDoc;\n xmlSAXHandlerPtr oldsax = NULL;\n xmlNodePtr content, newRoot;\n int size;\n int ret = 0;\n\n if (depth > 40) {\n\treturn(XML_ERR_ENTITY_LOOP);\n }\n\n\n if (lst != NULL)\n *lst = NULL;\n if (string == NULL)\n return(-1);\n\n size = xmlStrlen(string);\n\n ctxt = xmlCreateMemoryParserCtxt((char *) string, size);\n if (ctxt == NULL) return(-1);\n ctxt->userData = ctxt;\n if (sax != NULL) {\n\toldsax = ctxt->sax;\n ctxt->sax = sax;\n\tif (user_data != NULL)\n\t ctxt->userData = user_data;\n }\n newDoc = xmlNewDoc(BAD_CAST \"1.0\");\n if (newDoc == NULL) {\n\txmlFreeParserCtxt(ctxt);\n\treturn(-1);\n }\n newDoc->properties = XML_DOC_INTERNAL;\n if ((doc != NULL) && (doc->dict != NULL)) {\n xmlDictFree(ctxt->dict);\n\tctxt->dict = doc->dict;\n\txmlDictReference(ctxt->dict);\n\tctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST \"xml\", 3);\n\tctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST \"xmlns\", 5);\n\tctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);\n\tctxt->dictNames = 1;\n } else {\n\txmlCtxtUseOptionsInternal(ctxt, XML_PARSE_NODICT, NULL);\n }\n if (doc != NULL) {\n\tnewDoc->intSubset = doc->intSubset;\n\tnewDoc->extSubset = doc->extSubset;\n }\n newRoot = xmlNewDocNode(newDoc, NULL, BAD_CAST \"pseudoroot\", NULL);\n if (newRoot == NULL) {\n\tif (sax != NULL)\n\t ctxt->sax = oldsax;\n\txmlFreeParserCtxt(ctxt);\n\tnewDoc->intSubset = NULL;\n\tnewDoc->extSubset = NULL;\n xmlFreeDoc(newDoc);\n\treturn(-1);\n }\n xmlAddChild((xmlNodePtr) newDoc, newRoot);\n nodePush(ctxt, newRoot);\n if (doc == NULL) {\n\tctxt->myDoc = newDoc;\n } else {\n\tctxt->myDoc = newDoc;\n\tnewDoc->children->doc = doc;\n\t/* Ensure that doc has XML spec namespace */\n\txmlSearchNsByHref(doc, (xmlNodePtr)doc, XML_XML_NAMESPACE);\n\tnewDoc->oldNs = doc->oldNs;\n }\n ctxt->instate = XML_PARSER_CONTENT;\n ctxt->input_id = 2;\n ctxt->depth = depth;\n\n /*\n * Doing validity checking on chunk doesn't make sense\n */\n ctxt->validate = 0;\n ctxt->loadsubset = 0;\n xmlDetectSAX2(ctxt);\n\n if ( doc != NULL ){\n content = doc->children;\n doc->children = NULL;\n xmlParseContent(ctxt);\n doc->children = content;\n }\n else {\n xmlParseContent(ctxt);\n }\n if ((RAW == '<') && (NXT(1) == '/')) {\n\txmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);\n } else if (RAW != 0) {\n\txmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);\n }\n if (ctxt->node != newDoc->children) {\n\txmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);\n }\n\n if (!ctxt->wellFormed) {\n if (ctxt->errNo == 0)\n\t ret = 1;\n\telse\n\t ret = ctxt->errNo;\n } else {\n ret = 0;\n }\n\n if ((lst != NULL) && ((ret == 0) || (recover == 1))) {\n\txmlNodePtr cur;\n\n\t/*\n\t * Return the newly created nodeset after unlinking it from\n\t * they pseudo parent.\n\t */\n\tcur = newDoc->children->children;\n\t*lst = cur;\n\twhile (cur != NULL) {\n\t xmlSetTreeDoc(cur, doc);\n\t cur->parent = NULL;\n\t cur = cur->next;\n\t}\n\tnewDoc->children->children = NULL;\n }\n\n if (sax != NULL)\n\tctxt->sax = oldsax;\n xmlFreeParserCtxt(ctxt);\n newDoc->intSubset = NULL;\n newDoc->extSubset = NULL;\n if(doc != NULL)\n\tnewDoc->oldNs = NULL;\n xmlFreeDoc(newDoc);\n\n return(ret);\n}", "project": "libxml2", "hash": 142613781580222883758493860092065921257, "size": 139, "commit_id": "5a02583c7e683896d84878bd90641d8d9b0d0549", "message": "Fix memory leak in xmlParseBalancedChunkMemoryRecover\n\nWhen doc is NULL, namespace created in xmlTreeEnsureXMLDecl\nis bind to newDoc->oldNs, in this case, set newDoc->oldNs to\nNULL and free newDoc will cause a memory leak.\n\nFound with libFuzzer.\n\nCloses #82.", "target": 0, "dataset": "other", "idx": 299179} {"func": "string_vformat(uschar *buffer, int buflen, char *format, va_list ap)\n{\nenum { L_NORMAL, L_SHORT, L_LONG, L_LONGLONG, L_LONGDOUBLE };\n\nBOOL yield = TRUE;\nint width, precision;\nchar *fp = format; /* Deliberately not unsigned */\nuschar *p = buffer;\nuschar *last = buffer + buflen - 1;\n\nstring_datestamp_offset = -1; /* Datestamp not inserted */\n\n/* Scan the format and handle the insertions */\n\nwhile (*fp != 0)\n {\n int length = L_NORMAL;\n int *nptr;\n int slen;\n char *null = \"NULL\"; /* ) These variables */\n char *item_start, *s; /* ) are deliberately */\n char newformat[16]; /* ) not unsigned */\n\n /* Non-% characters just get copied verbatim */\n\n if (*fp != '%')\n {\n if (p >= last) { yield = FALSE; break; }\n *p++ = (uschar)*fp++;\n continue;\n }\n\n /* Deal with % characters. Pick off the width and precision, for checking\n strings, skipping over the flag and modifier characters. */\n\n item_start = fp;\n width = precision = -1;\n\n if (strchr(\"-+ #0\", *(++fp)) != NULL)\n {\n if (*fp == '#') null = \"\";\n fp++;\n }\n\n if (isdigit((uschar)*fp))\n {\n width = *fp++ - '0';\n while (isdigit((uschar)*fp)) width = width * 10 + *fp++ - '0';\n }\n else if (*fp == '*')\n {\n width = va_arg(ap, int);\n fp++;\n }\n\n if (*fp == '.')\n {\n if (*(++fp) == '*')\n {\n precision = va_arg(ap, int);\n fp++;\n }\n else\n {\n precision = 0;\n while (isdigit((uschar)*fp))\n precision = precision*10 + *fp++ - '0';\n }\n }\n\n /* Skip over 'h', 'L', 'l', and 'll', remembering the item length */\n\n if (*fp == 'h')\n { fp++; length = L_SHORT; }\n else if (*fp == 'L')\n { fp++; length = L_LONGDOUBLE; }\n else if (*fp == 'l')\n {\n if (fp[1] == 'l')\n {\n fp += 2;\n length = L_LONGLONG;\n }\n else\n {\n fp++;\n length = L_LONG;\n }\n }\n\n /* Handle each specific format type. */\n\n switch (*fp++)\n {\n case 'n':\n nptr = va_arg(ap, int *);\n *nptr = p - buffer;\n break;\n\n case 'd':\n case 'o':\n case 'u':\n case 'x':\n case 'X':\n if (p >= last - ((length > L_LONG)? 24 : 12))\n { yield = FALSE; goto END_FORMAT; }\n strncpy(newformat, item_start, fp - item_start);\n newformat[fp - item_start] = 0;\n\n /* Short int is promoted to int when passing through ..., so we must use\n int for va_arg(). */\n\n switch(length)\n {\n case L_SHORT:\n case L_NORMAL: sprintf(CS p, newformat, va_arg(ap, int)); break;\n case L_LONG: sprintf(CS p, newformat, va_arg(ap, long int)); break;\n case L_LONGLONG: sprintf(CS p, newformat, va_arg(ap, LONGLONG_T)); break;\n }\n while (*p) p++;\n break;\n\n case 'p':\n if (p >= last - 24) { yield = FALSE; goto END_FORMAT; }\n strncpy(newformat, item_start, fp - item_start);\n newformat[fp - item_start] = 0;\n sprintf(CS p, newformat, va_arg(ap, void *));\n while (*p) p++;\n break;\n\n /* %f format is inherently insecure if the numbers that it may be\n handed are unknown (e.g. 1e300). However, in Exim, %f is used for\n printing load averages, and these are actually stored as integers\n (load average * 1000) so the size of the numbers is constrained.\n It is also used for formatting sending rates, where the simplicity\n of the format prevents overflow. */\n\n case 'f':\n case 'e':\n case 'E':\n case 'g':\n case 'G':\n if (precision < 0) precision = 6;\n if (p >= last - precision - 8) { yield = FALSE; goto END_FORMAT; }\n strncpy(newformat, item_start, fp - item_start);\n newformat[fp-item_start] = 0;\n if (length == L_LONGDOUBLE)\n sprintf(CS p, newformat, va_arg(ap, long double));\n else\n sprintf(CS p, newformat, va_arg(ap, double));\n while (*p) p++;\n break;\n\n /* String types */\n\n case '%':\n if (p >= last) { yield = FALSE; goto END_FORMAT; }\n *p++ = '%';\n break;\n\n case 'c':\n if (p >= last) { yield = FALSE; goto END_FORMAT; }\n *p++ = va_arg(ap, int);\n break;\n\n case 'D': /* Insert datestamp for log file names */\n s = CS tod_stamp(tod_log_datestamp);\n string_datestamp_offset = p - buffer; /* Passed back via global */\n goto INSERT_STRING;\n\n case 's':\n case 'S': /* Forces *lower* case */\n s = va_arg(ap, char *);\n\n INSERT_STRING: /* Come to from %D above */\n if (s == NULL) s = null;\n slen = Ustrlen(s);\n\n /* If the width is specified, check that there is a precision\n set; if not, set it to the width to prevent overruns of long\n strings. */\n\n if (width >= 0)\n {\n if (precision < 0) precision = width;\n }\n\n /* If a width is not specified and the precision is specified, set\n the width to the precision, or the string length if shorted. */\n\n else if (precision >= 0)\n {\n width = (precision < slen)? precision : slen;\n }\n\n /* If neither are specified, set them both to the string length. */\n\n else width = precision = slen;\n\n /* Check string space, and add the string to the buffer if ok. If\n not OK, add part of the string (debugging uses this to show as\n much as possible). */\n\n if (p >= last - width)\n {\n yield = FALSE;\n width = precision = last - p - 1;\n }\n sprintf(CS p, \"%*.*s\", width, precision, s);\n if (fp[-1] == 'S')\n while (*p) { *p = tolower(*p); p++; }\n else\n while (*p) p++;\n if (!yield) goto END_FORMAT;\n break;\n\n /* Some things are never used in Exim; also catches junk. */\n\n default:\n strncpy(newformat, item_start, fp - item_start);\n newformat[fp-item_start] = 0;\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"string_format: unsupported type \"\n \"in \\\"%s\\\" in \\\"%s\\\"\", newformat, format);\n break;\n }\n }\n\n/* Ensure string is complete; return TRUE if got to the end of the format */\n\nEND_FORMAT:\n\n*p = 0;\nreturn yield;\n}", "project": "exim", "hash": 320005744502620398274420421250934351064, "size": 234, "commit_id": "24c929a27415c7cfc7126c47e4cad39acf3efa6b", "message": "Buffer overrun fix. fixes: bug #787", "target": 1, "dataset": "other", "idx": 200316} {"func": "string_vformat(uschar *buffer, int buflen, char *format, va_list ap)\n{\nenum { L_NORMAL, L_SHORT, L_LONG, L_LONGLONG, L_LONGDOUBLE };\n\nBOOL yield = TRUE;\nint width, precision;\nchar *fp = format; /* Deliberately not unsigned */\nuschar *p = buffer;\nuschar *last = buffer + buflen - 1;\n\nstring_datestamp_offset = -1; /* Datestamp not inserted */\n\n/* Scan the format and handle the insertions */\n\nwhile (*fp != 0)\n {\n int length = L_NORMAL;\n int *nptr;\n int slen;\n char *null = \"NULL\"; /* ) These variables */\n char *item_start, *s; /* ) are deliberately */\n char newformat[16]; /* ) not unsigned */\n\n /* Non-% characters just get copied verbatim */\n\n if (*fp != '%')\n {\n if (p >= last) { yield = FALSE; break; }\n *p++ = (uschar)*fp++;\n continue;\n }\n\n /* Deal with % characters. Pick off the width and precision, for checking\n strings, skipping over the flag and modifier characters. */\n\n item_start = fp;\n width = precision = -1;\n\n if (strchr(\"-+ #0\", *(++fp)) != NULL)\n {\n if (*fp == '#') null = \"\";\n fp++;\n }\n\n if (isdigit((uschar)*fp))\n {\n width = *fp++ - '0';\n while (isdigit((uschar)*fp)) width = width * 10 + *fp++ - '0';\n }\n else if (*fp == '*')\n {\n width = va_arg(ap, int);\n fp++;\n }\n\n if (*fp == '.')\n {\n if (*(++fp) == '*')\n {\n precision = va_arg(ap, int);\n fp++;\n }\n else\n {\n precision = 0;\n while (isdigit((uschar)*fp))\n precision = precision*10 + *fp++ - '0';\n }\n }\n\n /* Skip over 'h', 'L', 'l', and 'll', remembering the item length */\n\n if (*fp == 'h')\n { fp++; length = L_SHORT; }\n else if (*fp == 'L')\n { fp++; length = L_LONGDOUBLE; }\n else if (*fp == 'l')\n {\n if (fp[1] == 'l')\n {\n fp += 2;\n length = L_LONGLONG;\n }\n else\n {\n fp++;\n length = L_LONG;\n }\n }\n\n /* Handle each specific format type. */\n\n switch (*fp++)\n {\n case 'n':\n nptr = va_arg(ap, int *);\n *nptr = p - buffer;\n break;\n\n case 'd':\n case 'o':\n case 'u':\n case 'x':\n case 'X':\n if (p >= last - ((length > L_LONG)? 24 : 12))\n { yield = FALSE; goto END_FORMAT; }\n strncpy(newformat, item_start, fp - item_start);\n newformat[fp - item_start] = 0;\n\n /* Short int is promoted to int when passing through ..., so we must use\n int for va_arg(). */\n\n switch(length)\n {\n case L_SHORT:\n case L_NORMAL: sprintf(CS p, newformat, va_arg(ap, int)); break;\n case L_LONG: sprintf(CS p, newformat, va_arg(ap, long int)); break;\n case L_LONGLONG: sprintf(CS p, newformat, va_arg(ap, LONGLONG_T)); break;\n }\n while (*p) p++;\n break;\n\n case 'p':\n if (p >= last - 24) { yield = FALSE; goto END_FORMAT; }\n strncpy(newformat, item_start, fp - item_start);\n newformat[fp - item_start] = 0;\n sprintf(CS p, newformat, va_arg(ap, void *));\n while (*p) p++;\n break;\n\n /* %f format is inherently insecure if the numbers that it may be\n handed are unknown (e.g. 1e300). However, in Exim, %f is used for\n printing load averages, and these are actually stored as integers\n (load average * 1000) so the size of the numbers is constrained.\n It is also used for formatting sending rates, where the simplicity\n of the format prevents overflow. */\n\n case 'f':\n case 'e':\n case 'E':\n case 'g':\n case 'G':\n if (precision < 0) precision = 6;\n if (p >= last - precision - 8) { yield = FALSE; goto END_FORMAT; }\n strncpy(newformat, item_start, fp - item_start);\n newformat[fp-item_start] = 0;\n if (length == L_LONGDOUBLE)\n sprintf(CS p, newformat, va_arg(ap, long double));\n else\n sprintf(CS p, newformat, va_arg(ap, double));\n while (*p) p++;\n break;\n\n /* String types */\n\n case '%':\n if (p >= last) { yield = FALSE; goto END_FORMAT; }\n *p++ = '%';\n break;\n\n case 'c':\n if (p >= last) { yield = FALSE; goto END_FORMAT; }\n *p++ = va_arg(ap, int);\n break;\n\n case 'D': /* Insert datestamp for log file names */\n s = CS tod_stamp(tod_log_datestamp);\n string_datestamp_offset = p - buffer; /* Passed back via global */\n goto INSERT_STRING;\n\n case 's':\n case 'S': /* Forces *lower* case */\n s = va_arg(ap, char *);\n\n INSERT_STRING: /* Come to from %D above */\n if (s == NULL) s = null;\n slen = Ustrlen(s);\n\n /* If the width is specified, check that there is a precision\n set; if not, set it to the width to prevent overruns of long\n strings. */\n\n if (width >= 0)\n {\n if (precision < 0) precision = width;\n }\n\n /* If a width is not specified and the precision is specified, set\n the width to the precision, or the string length if shorted. */\n\n else if (precision >= 0)\n {\n width = (precision < slen)? precision : slen;\n }\n\n /* If neither are specified, set them both to the string length. */\n\n else width = precision = slen;\n\n /* Check string space, and add the string to the buffer if ok. If\n not OK, add part of the string (debugging uses this to show as\n much as possible). */\n\n if (p == last)\n {\n yield = FALSE;\n goto END_FORMAT;\n }\n if (p >= last - width)\n {\n yield = FALSE;\n width = precision = last - p - 1;\n if (width < 0) width = 0;\n if (precision < 0) precision = 0;\n }\n sprintf(CS p, \"%*.*s\", width, precision, s);\n if (fp[-1] == 'S')\n while (*p) { *p = tolower(*p); p++; }\n else\n while (*p) p++;\n if (!yield) goto END_FORMAT;\n break;\n\n /* Some things are never used in Exim; also catches junk. */\n\n default:\n strncpy(newformat, item_start, fp - item_start);\n newformat[fp-item_start] = 0;\n log_write(0, LOG_MAIN|LOG_PANIC_DIE, \"string_format: unsupported type \"\n \"in \\\"%s\\\" in \\\"%s\\\"\", newformat, format);\n break;\n }\n }\n\n/* Ensure string is complete; return TRUE if got to the end of the format */\n\nEND_FORMAT:\n\n*p = 0;\nreturn yield;\n}", "project": "exim", "hash": 29493622242225405401141093763393293838, "size": 241, "commit_id": "24c929a27415c7cfc7126c47e4cad39acf3efa6b", "message": "Buffer overrun fix. fixes: bug #787", "target": 0, "dataset": "other", "idx": 301211} {"func": "void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source TSRMLS_DC)\n{\n\tvoid **old_p, *retval;\n\n\tif (zend_hash_index_find(&xlat_table, (ulong)source, (void **)&old_p) == SUCCESS) {\n\t\t/* we already duplicated this pointer */\n\t\treturn *old_p;\n\t}\n\tretval = ZCG(mem);;\n\tZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size));\n\tmemcpy(retval, source, size);\n\tif (free_source) {\n\t\tinterned_efree((char*)source);\n\t}\n\tzend_shared_alloc_register_xlat_entry(source, retval);\n\treturn retval;\n}", "project": "php-src", "hash": 299352734408075147829433838475904463433, "size": 17, "commit_id": "0a8f28b43212cc2ddbc1f2df710e37b1bec0addd", "message": "Fixed bug #68677 (Use After Free in OPcache)\n\n(cherry picked from commit 777c39f4042327eac4b63c7ee87dc1c7a09a3115)", "target": 1, "dataset": "other", "idx": 200327} {"func": "void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source TSRMLS_DC)\n{\n\tvoid **old_p, *retval;\n\n\tif (zend_hash_index_find(&xlat_table, (ulong)source, (void **)&old_p) == SUCCESS) {\n\t\t/* we already duplicated this pointer */\n\t\treturn *old_p;\n\t}\n\tretval = ZCG(mem);;\n\tZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size));\n\tmemcpy(retval, source, size);\n\tzend_shared_alloc_register_xlat_entry(source, retval);\n\tif (free_source) {\n\t\tinterned_efree((char*)source);\n\t}\n\treturn retval;\n}", "project": "php-src", "hash": 122228126921376440226435604693610853668, "size": 17, "commit_id": "0a8f28b43212cc2ddbc1f2df710e37b1bec0addd", "message": "Fixed bug #68677 (Use After Free in OPcache)\n\n(cherry picked from commit 777c39f4042327eac4b63c7ee87dc1c7a09a3115)", "target": 0, "dataset": "other", "idx": 301530} {"func": "xmlEncodeEntitiesInternal(xmlDocPtr doc, const xmlChar *input, int attr) {\n const xmlChar *cur = input;\n xmlChar *buffer = NULL;\n xmlChar *out = NULL;\n size_t buffer_size = 0;\n int html = 0;\n\n if (input == NULL) return(NULL);\n if (doc != NULL)\n html = (doc->type == XML_HTML_DOCUMENT_NODE);\n\n /*\n * allocate an translation buffer.\n */\n buffer_size = 1000;\n buffer = (xmlChar *) xmlMalloc(buffer_size * sizeof(xmlChar));\n if (buffer == NULL) {\n xmlEntitiesErrMemory(\"xmlEncodeEntities: malloc failed\");\n\treturn(NULL);\n }\n out = buffer;\n\n while (*cur != '\\0') {\n size_t indx = out - buffer;\n if (indx + 100 > buffer_size) {\n\n\t growBufferReentrant();\n\t out = &buffer[indx];\n\t}\n\n\t/*\n\t * By default one have to encode at least '<', '>', '\"' and '&' !\n\t */\n\tif (*cur == '<') {\n\t const xmlChar *end;\n\n\t /*\n\t * Special handling of server side include in HTML attributes\n\t */\n\t if (html && attr &&\n\t (cur[1] == '!') && (cur[2] == '-') && (cur[3] == '-') &&\n\t ((end = xmlStrstr(cur, BAD_CAST \"-->\")) != NULL)) {\n\t while (cur != end) {\n\t\t *out++ = *cur++;\n\t\t indx = out - buffer;\n\t\t if (indx + 100 > buffer_size) {\n\t\t\tgrowBufferReentrant();\n\t\t\tout = &buffer[indx];\n\t\t }\n\t\t}\n\t\t*out++ = *cur++;\n\t\t*out++ = *cur++;\n\t\t*out++ = *cur++;\n\t\tcontinue;\n\t }\n\t *out++ = '&';\n\t *out++ = 'l';\n\t *out++ = 't';\n\t *out++ = ';';\n\t} else if (*cur == '>') {\n\t *out++ = '&';\n\t *out++ = 'g';\n\t *out++ = 't';\n\t *out++ = ';';\n\t} else if (*cur == '&') {\n\t /*\n\t * Special handling of &{...} construct from HTML 4, see\n\t * http://www.w3.org/TR/html401/appendix/notes.html#h-B.7.1\n\t */\n\t if (html && attr && (cur[1] == '{') &&\n\t (strchr((const char *) cur, '}'))) {\n\t while (*cur != '}') {\n\t\t *out++ = *cur++;\n\t\t indx = out - buffer;\n\t\t if (indx + 100 > buffer_size) {\n\t\t\tgrowBufferReentrant();\n\t\t\tout = &buffer[indx];\n\t\t }\n\t\t}\n\t\t*out++ = *cur++;\n\t\tcontinue;\n\t }\n\t *out++ = '&';\n\t *out++ = 'a';\n\t *out++ = 'm';\n\t *out++ = 'p';\n\t *out++ = ';';\n\t} else if (((*cur >= 0x20) && (*cur < 0x80)) ||\n\t (*cur == '\\n') || (*cur == '\\t') || ((html) && (*cur == '\\r'))) {\n\t /*\n\t * default case, just copy !\n\t */\n\t *out++ = *cur;\n\t} else if (*cur >= 0x80) {\n\t if (((doc != NULL) && (doc->encoding != NULL)) || (html)) {\n\t\t/*\n\t\t * Bj\u00f8rn Reese provided the patch\n\t xmlChar xc;\n\t xc = (*cur & 0x3F) << 6;\n\t if (cur[1] != 0) {\n\t\t xc += *(++cur) & 0x3F;\n\t\t *out++ = xc;\n\t } else\n\t\t */\n\t\t*out++ = *cur;\n\t } else {\n\t\t/*\n\t\t * We assume we have UTF-8 input.\n\t\t */\n\t\tchar buf[11], *ptr;\n\t\tint val = 0, l = 1;\n\n\t\tif (*cur < 0xC0) {\n\t\t xmlEntitiesErr(XML_CHECK_NOT_UTF8,\n\t\t\t \"xmlEncodeEntities: input not UTF-8\");\n\t\t if (doc != NULL)\n\t\t\tdoc->encoding = xmlStrdup(BAD_CAST \"ISO-8859-1\");\n\t\t snprintf(buf, sizeof(buf), \"&#%d;\", *cur);\n\t\t buf[sizeof(buf) - 1] = 0;\n\t\t ptr = buf;\n\t\t while (*ptr != 0) *out++ = *ptr++;\n\t\t cur++;\n\t\t continue;\n\t\t} else if (*cur < 0xE0) {\n val = (cur[0]) & 0x1F;\n\t\t val <<= 6;\n\t\t val |= (cur[1]) & 0x3F;\n\t\t l = 2;\n\t\t} else if (*cur < 0xF0) {\n val = (cur[0]) & 0x0F;\n\t\t val <<= 6;\n\t\t val |= (cur[1]) & 0x3F;\n\t\t val <<= 6;\n\t\t val |= (cur[2]) & 0x3F;\n\t\t l = 3;\n\t\t} else if (*cur < 0xF8) {\n val = (cur[0]) & 0x07;\n\t\t val <<= 6;\n\t\t val |= (cur[1]) & 0x3F;\n\t\t val <<= 6;\n\t\t val |= (cur[2]) & 0x3F;\n\t\t val <<= 6;\n\t\t val |= (cur[3]) & 0x3F;\n\t\t l = 4;\n\t\t}\n\t\tif ((l == 1) || (!IS_CHAR(val))) {\n\t\t xmlEntitiesErr(XML_ERR_INVALID_CHAR,\n\t\t\t\"xmlEncodeEntities: char out of range\\n\");\n\t\t if (doc != NULL)\n\t\t\tdoc->encoding = xmlStrdup(BAD_CAST \"ISO-8859-1\");\n\t\t snprintf(buf, sizeof(buf), \"&#%d;\", *cur);\n\t\t buf[sizeof(buf) - 1] = 0;\n\t\t ptr = buf;\n\t\t while (*ptr != 0) *out++ = *ptr++;\n\t\t cur++;\n\t\t continue;\n\t\t}\n\t\t/*\n\t\t * We could do multiple things here. Just save as a char ref\n\t\t */\n\t\tsnprintf(buf, sizeof(buf), \"&#x%X;\", val);\n\t\tbuf[sizeof(buf) - 1] = 0;\n\t\tptr = buf;\n\t\twhile (*ptr != 0) *out++ = *ptr++;\n\t\tcur += l;\n\t\tcontinue;\n\t }\n\t} else if (IS_BYTE_CHAR(*cur)) {\n\t char buf[11], *ptr;\n\n\t snprintf(buf, sizeof(buf), \"&#%d;\", *cur);\n\t buf[sizeof(buf) - 1] = 0;\n ptr = buf;\n\t while (*ptr != 0) *out++ = *ptr++;\n\t}\n\tcur++;\n }\n *out = 0;\n return(buffer);\n\nmem_error:\n xmlEntitiesErrMemory(\"xmlEncodeEntities: realloc failed\");\n xmlFree(buffer);\n return(NULL);\n}", "project": "libxml2", "hash": 295556253642103349169033769733719269138, "size": 185, "commit_id": "bf22713507fe1fc3a2c4b525cf0a88c2dc87a3a2", "message": "Validate UTF8 in xmlEncodeEntities\n\nCode is currently assuming UTF-8 without validating. Truncated UTF-8\ninput can cause out-of-bounds array access.\n\nAdds further checks to partial fix in 50f06b3e.\n\nFixes #178", "target": 1, "dataset": "other", "idx": 200381} {"func": "xmlEncodeEntitiesInternal(xmlDocPtr doc, const xmlChar *input, int attr) {\n const xmlChar *cur = input;\n xmlChar *buffer = NULL;\n xmlChar *out = NULL;\n size_t buffer_size = 0;\n int html = 0;\n\n if (input == NULL) return(NULL);\n if (doc != NULL)\n html = (doc->type == XML_HTML_DOCUMENT_NODE);\n\n /*\n * allocate an translation buffer.\n */\n buffer_size = 1000;\n buffer = (xmlChar *) xmlMalloc(buffer_size * sizeof(xmlChar));\n if (buffer == NULL) {\n xmlEntitiesErrMemory(\"xmlEncodeEntities: malloc failed\");\n\treturn(NULL);\n }\n out = buffer;\n\n while (*cur != '\\0') {\n size_t indx = out - buffer;\n if (indx + 100 > buffer_size) {\n\n\t growBufferReentrant();\n\t out = &buffer[indx];\n\t}\n\n\t/*\n\t * By default one have to encode at least '<', '>', '\"' and '&' !\n\t */\n\tif (*cur == '<') {\n\t const xmlChar *end;\n\n\t /*\n\t * Special handling of server side include in HTML attributes\n\t */\n\t if (html && attr &&\n\t (cur[1] == '!') && (cur[2] == '-') && (cur[3] == '-') &&\n\t ((end = xmlStrstr(cur, BAD_CAST \"-->\")) != NULL)) {\n\t while (cur != end) {\n\t\t *out++ = *cur++;\n\t\t indx = out - buffer;\n\t\t if (indx + 100 > buffer_size) {\n\t\t\tgrowBufferReentrant();\n\t\t\tout = &buffer[indx];\n\t\t }\n\t\t}\n\t\t*out++ = *cur++;\n\t\t*out++ = *cur++;\n\t\t*out++ = *cur++;\n\t\tcontinue;\n\t }\n\t *out++ = '&';\n\t *out++ = 'l';\n\t *out++ = 't';\n\t *out++ = ';';\n\t} else if (*cur == '>') {\n\t *out++ = '&';\n\t *out++ = 'g';\n\t *out++ = 't';\n\t *out++ = ';';\n\t} else if (*cur == '&') {\n\t /*\n\t * Special handling of &{...} construct from HTML 4, see\n\t * http://www.w3.org/TR/html401/appendix/notes.html#h-B.7.1\n\t */\n\t if (html && attr && (cur[1] == '{') &&\n\t (strchr((const char *) cur, '}'))) {\n\t while (*cur != '}') {\n\t\t *out++ = *cur++;\n\t\t indx = out - buffer;\n\t\t if (indx + 100 > buffer_size) {\n\t\t\tgrowBufferReentrant();\n\t\t\tout = &buffer[indx];\n\t\t }\n\t\t}\n\t\t*out++ = *cur++;\n\t\tcontinue;\n\t }\n\t *out++ = '&';\n\t *out++ = 'a';\n\t *out++ = 'm';\n\t *out++ = 'p';\n\t *out++ = ';';\n\t} else if (((*cur >= 0x20) && (*cur < 0x80)) ||\n\t (*cur == '\\n') || (*cur == '\\t') || ((html) && (*cur == '\\r'))) {\n\t /*\n\t * default case, just copy !\n\t */\n\t *out++ = *cur;\n\t} else if (*cur >= 0x80) {\n\t if (((doc != NULL) && (doc->encoding != NULL)) || (html)) {\n\t\t/*\n\t\t * Bj\u00f8rn Reese provided the patch\n\t xmlChar xc;\n\t xc = (*cur & 0x3F) << 6;\n\t if (cur[1] != 0) {\n\t\t xc += *(++cur) & 0x3F;\n\t\t *out++ = xc;\n\t } else\n\t\t */\n\t\t*out++ = *cur;\n\t } else {\n\t\t/*\n\t\t * We assume we have UTF-8 input.\n\t\t * It must match either:\n\t\t * 110xxxxx 10xxxxxx\n\t\t * 1110xxxx 10xxxxxx 10xxxxxx\n\t\t * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n\t\t * That is:\n\t\t * cur[0] is 11xxxxxx\n\t\t * cur[1] is 10xxxxxx\n\t\t * cur[2] is 10xxxxxx if cur[0] is 111xxxxx\n\t\t * cur[3] is 10xxxxxx if cur[0] is 1111xxxx\n\t\t * cur[0] is not 11111xxx\n\t\t */\n\t\tchar buf[11], *ptr;\n\t\tint val = 0, l = 1;\n\n\t\tif (((cur[0] & 0xC0) != 0xC0) ||\n\t\t ((cur[1] & 0xC0) != 0x80) ||\n\t\t (((cur[0] & 0xE0) == 0xE0) && ((cur[2] & 0xC0) != 0x80)) ||\n\t\t (((cur[0] & 0xF0) == 0xF0) && ((cur[3] & 0xC0) != 0x80)) ||\n\t\t (((cur[0] & 0xF8) == 0xF8))) {\n\t\t xmlEntitiesErr(XML_CHECK_NOT_UTF8,\n\t\t\t \"xmlEncodeEntities: input not UTF-8\");\n\t\t if (doc != NULL)\n\t\t\tdoc->encoding = xmlStrdup(BAD_CAST \"ISO-8859-1\");\n\t\t snprintf(buf, sizeof(buf), \"&#%d;\", *cur);\n\t\t buf[sizeof(buf) - 1] = 0;\n\t\t ptr = buf;\n\t\t while (*ptr != 0) *out++ = *ptr++;\n\t\t cur++;\n\t\t continue;\n\t\t} else if (*cur < 0xE0) {\n val = (cur[0]) & 0x1F;\n\t\t val <<= 6;\n\t\t val |= (cur[1]) & 0x3F;\n\t\t l = 2;\n\t\t} else if (*cur < 0xF0) {\n val = (cur[0]) & 0x0F;\n\t\t val <<= 6;\n\t\t val |= (cur[1]) & 0x3F;\n\t\t val <<= 6;\n\t\t val |= (cur[2]) & 0x3F;\n\t\t l = 3;\n\t\t} else if (*cur < 0xF8) {\n val = (cur[0]) & 0x07;\n\t\t val <<= 6;\n\t\t val |= (cur[1]) & 0x3F;\n\t\t val <<= 6;\n\t\t val |= (cur[2]) & 0x3F;\n\t\t val <<= 6;\n\t\t val |= (cur[3]) & 0x3F;\n\t\t l = 4;\n\t\t}\n\t\tif ((l == 1) || (!IS_CHAR(val))) {\n\t\t xmlEntitiesErr(XML_ERR_INVALID_CHAR,\n\t\t\t\"xmlEncodeEntities: char out of range\\n\");\n\t\t if (doc != NULL)\n\t\t\tdoc->encoding = xmlStrdup(BAD_CAST \"ISO-8859-1\");\n\t\t snprintf(buf, sizeof(buf), \"&#%d;\", *cur);\n\t\t buf[sizeof(buf) - 1] = 0;\n\t\t ptr = buf;\n\t\t while (*ptr != 0) *out++ = *ptr++;\n\t\t cur++;\n\t\t continue;\n\t\t}\n\t\t/*\n\t\t * We could do multiple things here. Just save as a char ref\n\t\t */\n\t\tsnprintf(buf, sizeof(buf), \"&#x%X;\", val);\n\t\tbuf[sizeof(buf) - 1] = 0;\n\t\tptr = buf;\n\t\twhile (*ptr != 0) *out++ = *ptr++;\n\t\tcur += l;\n\t\tcontinue;\n\t }\n\t} else if (IS_BYTE_CHAR(*cur)) {\n\t char buf[11], *ptr;\n\n\t snprintf(buf, sizeof(buf), \"&#%d;\", *cur);\n\t buf[sizeof(buf) - 1] = 0;\n ptr = buf;\n\t while (*ptr != 0) *out++ = *ptr++;\n\t}\n\tcur++;\n }\n *out = 0;\n return(buffer);\n\nmem_error:\n xmlEntitiesErrMemory(\"xmlEncodeEntities: realloc failed\");\n xmlFree(buffer);\n return(NULL);\n}", "project": "libxml2", "hash": 116537115844529615353413364142450888793, "size": 199, "commit_id": "bf22713507fe1fc3a2c4b525cf0a88c2dc87a3a2", "message": "Validate UTF8 in xmlEncodeEntities\n\nCode is currently assuming UTF-8 without validating. Truncated UTF-8\ninput can cause out-of-bounds array access.\n\nAdds further checks to partial fix in 50f06b3e.\n\nFixes #178", "target": 0, "dataset": "other", "idx": 302155} {"func": "sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Cookie *cookie)\n{\n int rc;\n BerElement *ber;\n struct berval *bvp;\n char *uuid;\n Slapi_Attr *attr;\n Slapi_Value *val;\n\n if (type == LDAP_SYNC_NONE || ctrlp == NULL || (ber = der_alloc()) == NULL) {\n return (LDAP_OPERATIONS_ERROR);\n }\n\n *ctrlp = NULL;\n\n slapi_entry_attr_find(e, SLAPI_ATTR_UNIQUEID, &attr);\n slapi_attr_first_value(attr, &val);\n uuid = sync_nsuniqueid2uuid(slapi_value_get_string(val));\n if ((rc = ber_printf(ber, \"{eo\", type, uuid, 16)) != -1) {\n if (cookie) {\n char *cookiestr = sync_cookie2str(cookie);\n rc = ber_printf(ber, \"s}\", cookiestr);\n slapi_ch_free((void **)&cookiestr);\n } else {\n rc = ber_printf(ber, \"}\");\n }\n }\n if (rc != -1) {\n rc = ber_flatten(ber, &bvp);\n }\n ber_free(ber, 1);\n slapi_ch_free((void **)&uuid);\n\n if (rc == -1) {\n return (LDAP_OPERATIONS_ERROR);\n }\n\n *ctrlp = (LDAPControl *)slapi_ch_malloc(sizeof(LDAPControl));\n (*ctrlp)->ldctl_iscritical = 0;\n (*ctrlp)->ldctl_oid = slapi_ch_strdup(LDAP_CONTROL_SYNC_STATE);\n (*ctrlp)->ldctl_value = *bvp; /* struct copy */\n\n bvp->bv_val = NULL;\n ber_bvfree(bvp);\n\n return (LDAP_SUCCESS);\n}", "project": "389-ds-base", "hash": 282180238928437160976107800273334393083, "size": 47, "commit_id": "2e5b526012612d1d6ccace46398bee679a730271", "message": "Issue 4711 - SIGSEV with sync_repl (#4738)\n\nBug description:\n\tsync_repl sends back entries identified with a unique\n\tidentifier that is 'nsuniqueid'. If 'nsuniqueid' is\n\tmissing, then it may crash\n\nFix description:\n\tCheck a nsuniqueid is available else returns OP_ERR\n\nrelates: https://github.com/389ds/389-ds-base/issues/4711\n\nReviewed by: Pierre Rogier, James Chapman, William Brown (Thanks!)\n\nPlatforms tested: F33", "target": 1, "dataset": "other", "idx": 200413} {"func": "sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Cookie *cookie)\n{\n int rc;\n BerElement *ber;\n struct berval *bvp;\n char *uuid;\n Slapi_Attr *attr = NULL;\n Slapi_Value *val = NULL;\n\n if (type == LDAP_SYNC_NONE || ctrlp == NULL || (ber = der_alloc()) == NULL) {\n return (LDAP_OPERATIONS_ERROR);\n }\n\n *ctrlp = NULL;\n\n slapi_entry_attr_find(e, SLAPI_ATTR_UNIQUEID, &attr);\n slapi_attr_first_value(attr, &val);\n if ((attr == NULL) || (val == NULL)) {\n /* It may happen with entries in special backends\n * such like cn=config, cn=shema, cn=monitor...\n */\n slapi_log_err(SLAPI_LOG_ERR, SYNC_PLUGIN_SUBSYSTEM,\n\t\t \"sync_create_state_control - Entries are missing nsuniqueid. Unable to proceed.\\n\");\n return (LDAP_OPERATIONS_ERROR);\n }\n uuid = sync_nsuniqueid2uuid(slapi_value_get_string(val));\n if ((rc = ber_printf(ber, \"{eo\", type, uuid, 16)) != -1) {\n if (cookie) {\n char *cookiestr = sync_cookie2str(cookie);\n rc = ber_printf(ber, \"s}\", cookiestr);\n slapi_ch_free((void **)&cookiestr);\n } else {\n rc = ber_printf(ber, \"}\");\n }\n }\n if (rc != -1) {\n rc = ber_flatten(ber, &bvp);\n }\n ber_free(ber, 1);\n slapi_ch_free((void **)&uuid);\n\n if (rc == -1) {\n return (LDAP_OPERATIONS_ERROR);\n }\n\n *ctrlp = (LDAPControl *)slapi_ch_malloc(sizeof(LDAPControl));\n (*ctrlp)->ldctl_iscritical = 0;\n (*ctrlp)->ldctl_oid = slapi_ch_strdup(LDAP_CONTROL_SYNC_STATE);\n (*ctrlp)->ldctl_value = *bvp; /* struct copy */\n\n bvp->bv_val = NULL;\n ber_bvfree(bvp);\n\n return (LDAP_SUCCESS);\n}", "project": "389-ds-base", "hash": 215302344452509467283235451332534852906, "size": 55, "commit_id": "2e5b526012612d1d6ccace46398bee679a730271", "message": "Issue 4711 - SIGSEV with sync_repl (#4738)\n\nBug description:\n\tsync_repl sends back entries identified with a unique\n\tidentifier that is 'nsuniqueid'. If 'nsuniqueid' is\n\tmissing, then it may crash\n\nFix description:\n\tCheck a nsuniqueid is available else returns OP_ERR\n\nrelates: https://github.com/389ds/389-ds-base/issues/4711\n\nReviewed by: Pierre Rogier, James Chapman, William Brown (Thanks!)\n\nPlatforms tested: F33", "target": 0, "dataset": "other", "idx": 302826} {"func": "static int blosc_c(struct thread_context* thread_context, int32_t bsize,\n int32_t leftoverblock, int32_t ntbytes, int32_t maxbytes,\n const uint8_t* src, const int32_t offset, uint8_t* dest,\n uint8_t* tmp, uint8_t* tmp2) {\n blosc2_context* context = thread_context->parent_context;\n int dont_split = (context->header_flags & 0x10) >> 4;\n int dict_training = context->use_dict && context->dict_cdict == NULL;\n int32_t j, neblock, nstreams;\n int32_t cbytes; /* number of compressed bytes in split */\n int32_t ctbytes = 0; /* number of compressed bytes in block */\n int64_t maxout;\n int32_t typesize = context->typesize;\n const char* compname;\n int accel;\n const uint8_t* _src;\n uint8_t *_tmp = tmp, *_tmp2 = tmp2;\n uint8_t *_tmp3 = thread_context->tmp4;\n int last_filter_index = last_filter(context->filters, 'c');\n bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED;\n\n if (last_filter_index >= 0 || context->prefilter != NULL) {\n /* Apply the filter pipeline just for the prefilter */\n if (memcpyed && context->prefilter != NULL) {\n // We only need the prefilter output\n _src = pipeline_c(thread_context, bsize, src, offset, dest, _tmp2, _tmp3);\n\n if (_src == NULL) {\n return -9; // signals a problem with the filter pipeline\n }\n return bsize;\n }\n /* Apply regular filter pipeline */\n _src = pipeline_c(thread_context, bsize, src, offset, _tmp, _tmp2, _tmp3);\n\n if (_src == NULL) {\n return -9; // signals a problem with the filter pipeline\n }\n } else {\n _src = src + offset;\n }\n\n assert(context->clevel > 0);\n\n /* Calculate acceleration for different compressors */\n accel = get_accel(context);\n\n /* The number of compressed data streams for this block */\n if (!dont_split && !leftoverblock && !dict_training) {\n nstreams = (int32_t)typesize;\n }\n else {\n nstreams = 1;\n }\n neblock = bsize / nstreams;\n for (j = 0; j < nstreams; j++) {\n if (!dict_training) {\n dest += sizeof(int32_t);\n ntbytes += sizeof(int32_t);\n ctbytes += sizeof(int32_t);\n }\n\n // See if we have a run here\n const uint8_t* ip = (uint8_t*)_src + j * neblock;\n const uint8_t* ipbound = (uint8_t*)_src + (j + 1) * neblock;\n if (get_run(ip, ipbound)) {\n // A run. Encode the repeated byte as a negative length in the length of the split.\n int32_t value = _src[j * neblock];\n _sw32(dest - 4, -value);\n continue;\n }\n\n maxout = neblock;\n #if defined(HAVE_SNAPPY)\n if (context->compcode == BLOSC_SNAPPY) {\n maxout = (int32_t)snappy_max_compressed_length((size_t)neblock);\n }\n #endif /* HAVE_SNAPPY */\n if (ntbytes + maxout > maxbytes) {\n /* avoid buffer * overrun */\n maxout = (int64_t)maxbytes - (int64_t)ntbytes;\n if (maxout <= 0) {\n return 0; /* non-compressible block */\n }\n }\n if (dict_training) {\n // We are in the build dict state, so don't compress\n // TODO: copy only a percentage for sampling\n memcpy(dest, _src + j * neblock, (unsigned int)neblock);\n cbytes = (int32_t)neblock;\n }\n else if (context->compcode == BLOSC_BLOSCLZ) {\n cbytes = blosclz_compress(context->clevel, _src + j * neblock,\n (int)neblock, dest, (int)maxout);\n }\n #if defined(HAVE_LZ4)\n else if (context->compcode == BLOSC_LZ4) {\n void *hash_table = NULL;\n #ifdef HAVE_IPP\n hash_table = (void*)thread_context->lz4_hash_table;\n #endif\n cbytes = lz4_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, accel, hash_table);\n }\n else if (context->compcode == BLOSC_LZ4HC) {\n cbytes = lz4hc_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, context->clevel);\n }\n #endif /* HAVE_LZ4 */\n #if defined(HAVE_LIZARD)\n else if (context->compcode == BLOSC_LIZARD) {\n cbytes = lizard_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, accel);\n }\n #endif /* HAVE_LIZARD */\n #if defined(HAVE_SNAPPY)\n else if (context->compcode == BLOSC_SNAPPY) {\n cbytes = snappy_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout);\n }\n #endif /* HAVE_SNAPPY */\n #if defined(HAVE_ZLIB)\n else if (context->compcode == BLOSC_ZLIB) {\n cbytes = zlib_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, context->clevel);\n }\n #endif /* HAVE_ZLIB */\n #if defined(HAVE_ZSTD)\n else if (context->compcode == BLOSC_ZSTD) {\n cbytes = zstd_wrap_compress(thread_context,\n (char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, context->clevel);\n }\n #endif /* HAVE_ZSTD */\n\n else {\n blosc_compcode_to_compname(context->compcode, &compname);\n fprintf(stderr, \"Blosc has not been compiled with '%s' \", compname);\n fprintf(stderr, \"compression support. Please use one having it.\");\n return -5; /* signals no compression support */\n }\n\n if (cbytes > maxout) {\n /* Buffer overrun caused by compression (should never happen) */\n return -1;\n }\n if (cbytes < 0) {\n /* cbytes should never be negative */\n return -2;\n }\n if (!dict_training) {\n if (cbytes == 0 || cbytes == neblock) {\n /* The compressor has been unable to compress data at all. */\n /* Before doing the copy, check that we are not running into a\n buffer overflow. */\n if ((ntbytes + neblock) > maxbytes) {\n return 0; /* Non-compressible data */\n }\n memcpy(dest, _src + j * neblock, (unsigned int)neblock);\n cbytes = neblock;\n }\n _sw32(dest - 4, cbytes);\n }\n dest += cbytes;\n ntbytes += cbytes;\n ctbytes += cbytes;\n } /* Closes j < nstreams */\n\n //printf(\"c%d\", ctbytes);\n return ctbytes;\n}", "project": "c-blosc2", "hash": 33213175756612861371893504542614898630, "size": 170, "commit_id": "c4c6470e88210afc95262c8b9fcc27e30ca043ee", "message": "Fixed asan heap buffer overflow when not enough space to write compressed block size.", "target": 1, "dataset": "other", "idx": 200450} {"func": "static int blosc_c(struct thread_context* thread_context, int32_t bsize,\n int32_t leftoverblock, int32_t ntbytes, int32_t destsize,\n const uint8_t* src, const int32_t offset, uint8_t* dest,\n uint8_t* tmp, uint8_t* tmp2) {\n blosc2_context* context = thread_context->parent_context;\n int dont_split = (context->header_flags & 0x10) >> 4;\n int dict_training = context->use_dict && context->dict_cdict == NULL;\n int32_t j, neblock, nstreams;\n int32_t cbytes; /* number of compressed bytes in split */\n int32_t ctbytes = 0; /* number of compressed bytes in block */\n int64_t maxout;\n int32_t typesize = context->typesize;\n const char* compname;\n int accel;\n const uint8_t* _src;\n uint8_t *_tmp = tmp, *_tmp2 = tmp2;\n uint8_t *_tmp3 = thread_context->tmp4;\n int last_filter_index = last_filter(context->filters, 'c');\n bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED;\n\n if (last_filter_index >= 0 || context->prefilter != NULL) {\n /* Apply the filter pipeline just for the prefilter */\n if (memcpyed && context->prefilter != NULL) {\n // We only need the prefilter output\n _src = pipeline_c(thread_context, bsize, src, offset, dest, _tmp2, _tmp3);\n\n if (_src == NULL) {\n return -9; // signals a problem with the filter pipeline\n }\n return bsize;\n }\n /* Apply regular filter pipeline */\n _src = pipeline_c(thread_context, bsize, src, offset, _tmp, _tmp2, _tmp3);\n\n if (_src == NULL) {\n return -9; // signals a problem with the filter pipeline\n }\n } else {\n _src = src + offset;\n }\n\n assert(context->clevel > 0);\n\n /* Calculate acceleration for different compressors */\n accel = get_accel(context);\n\n /* The number of compressed data streams for this block */\n if (!dont_split && !leftoverblock && !dict_training) {\n nstreams = (int32_t)typesize;\n }\n else {\n nstreams = 1;\n }\n neblock = bsize / nstreams;\n for (j = 0; j < nstreams; j++) {\n if (!dict_training) {\n dest += sizeof(int32_t);\n ntbytes += sizeof(int32_t);\n ctbytes += sizeof(int32_t);\n }\n\n // See if we have a run here\n const uint8_t* ip = (uint8_t*)_src + j * neblock;\n const uint8_t* ipbound = (uint8_t*)_src + (j + 1) * neblock;\n if (get_run(ip, ipbound)) {\n // A run. Encode the repeated byte as a negative length in the length of the split.\n int32_t value = _src[j * neblock];\n if (ntbytes > destsize) {\n /* Not enough space to write out compressed block size */\n return -1;\n }\n _sw32(dest - 4, -value);\n continue;\n }\n\n maxout = neblock;\n #if defined(HAVE_SNAPPY)\n if (context->compcode == BLOSC_SNAPPY) {\n maxout = (int32_t)snappy_max_compressed_length((size_t)neblock);\n }\n #endif /* HAVE_SNAPPY */\n if (ntbytes + maxout > destsize) {\n /* avoid buffer * overrun */\n maxout = (int64_t)destsize - (int64_t)ntbytes;\n if (maxout <= 0) {\n return 0; /* non-compressible block */\n }\n }\n if (dict_training) {\n // We are in the build dict state, so don't compress\n // TODO: copy only a percentage for sampling\n memcpy(dest, _src + j * neblock, (unsigned int)neblock);\n cbytes = (int32_t)neblock;\n }\n else if (context->compcode == BLOSC_BLOSCLZ) {\n cbytes = blosclz_compress(context->clevel, _src + j * neblock,\n (int)neblock, dest, (int)maxout);\n }\n #if defined(HAVE_LZ4)\n else if (context->compcode == BLOSC_LZ4) {\n void *hash_table = NULL;\n #ifdef HAVE_IPP\n hash_table = (void*)thread_context->lz4_hash_table;\n #endif\n cbytes = lz4_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, accel, hash_table);\n }\n else if (context->compcode == BLOSC_LZ4HC) {\n cbytes = lz4hc_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, context->clevel);\n }\n #endif /* HAVE_LZ4 */\n #if defined(HAVE_LIZARD)\n else if (context->compcode == BLOSC_LIZARD) {\n cbytes = lizard_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, accel);\n }\n #endif /* HAVE_LIZARD */\n #if defined(HAVE_SNAPPY)\n else if (context->compcode == BLOSC_SNAPPY) {\n cbytes = snappy_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout);\n }\n #endif /* HAVE_SNAPPY */\n #if defined(HAVE_ZLIB)\n else if (context->compcode == BLOSC_ZLIB) {\n cbytes = zlib_wrap_compress((char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, context->clevel);\n }\n #endif /* HAVE_ZLIB */\n #if defined(HAVE_ZSTD)\n else if (context->compcode == BLOSC_ZSTD) {\n cbytes = zstd_wrap_compress(thread_context,\n (char*)_src + j * neblock, (size_t)neblock,\n (char*)dest, (size_t)maxout, context->clevel);\n }\n #endif /* HAVE_ZSTD */\n\n else {\n blosc_compcode_to_compname(context->compcode, &compname);\n fprintf(stderr, \"Blosc has not been compiled with '%s' \", compname);\n fprintf(stderr, \"compression support. Please use one having it.\");\n return -5; /* signals no compression support */\n }\n\n if (cbytes > maxout) {\n /* Buffer overrun caused by compression (should never happen) */\n return -1;\n }\n if (cbytes < 0) {\n /* cbytes should never be negative */\n return -2;\n }\n if (!dict_training) {\n if (cbytes == 0 || cbytes == neblock) {\n /* The compressor has been unable to compress data at all. */\n /* Before doing the copy, check that we are not running into a\n buffer overflow. */\n if ((ntbytes + neblock) > destsize) {\n return 0; /* Non-compressible data */\n }\n memcpy(dest, _src + j * neblock, (unsigned int)neblock);\n cbytes = neblock;\n }\n _sw32(dest - 4, cbytes);\n }\n dest += cbytes;\n ntbytes += cbytes;\n ctbytes += cbytes;\n } /* Closes j < nstreams */\n\n //printf(\"c%d\", ctbytes);\n return ctbytes;\n}", "project": "c-blosc2", "hash": 111230234594530939158768630350968281026, "size": 174, "commit_id": "c4c6470e88210afc95262c8b9fcc27e30ca043ee", "message": "Fixed asan heap buffer overflow when not enough space to write compressed block size.", "target": 0, "dataset": "other", "idx": 303085} {"func": "copy_ciphersuites(gnutls_session_t session,\n\t\t gnutls_buffer_st * cdata, int add_scsv)\n{\n\tint ret;\n\tuint8_t cipher_suites[MAX_CIPHERSUITE_SIZE + 2]; /* allow space for SCSV */\n\tint cipher_suites_size;\n\tsize_t init_length = cdata->length;\n\n\tret =\n\t _gnutls_supported_ciphersuites(session, cipher_suites,\n\t\t\t\t\t sizeof(cipher_suites) - 2);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\t/* Here we remove any ciphersuite that does not conform\n\t * the certificate requested, or to the\n\t * authentication requested (eg SRP).\n\t */\n\tret =\n\t _gnutls_remove_unwanted_ciphersuites(session, cipher_suites,\n\t\t\t\t\t\t ret, NULL, 0);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\t/* If no cipher suites were enabled.\n\t */\n\tif (ret == 0)\n\t\treturn\n\t\t gnutls_assert_val(GNUTLS_E_INSUFFICIENT_CREDENTIALS);\n\n\tcipher_suites_size = ret;\n\tif (add_scsv) {\n\t\tcipher_suites[cipher_suites_size] = 0x00;\n\t\tcipher_suites[cipher_suites_size + 1] = 0xff;\n\t\tcipher_suites_size += 2;\n\n\t\tret = _gnutls_ext_sr_send_cs(session);\n\t\tif (ret < 0)\n\t\t\treturn gnutls_assert_val(ret);\n\t}\n\n\tret =\n\t _gnutls_buffer_append_data_prefix(cdata, 16, cipher_suites,\n\t\t\t\t\t cipher_suites_size);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tret = cdata->length - init_length;\n\n\treturn ret;\n}", "project": "gnutls", "hash": 266014162039389037407122294619920511067, "size": 51, "commit_id": "21f89efad7014a5ee0debd4cd3d59e27774b29e6", "message": "handshake: add FALLBACK_SCSV priority option\n\nThis allows clients to enable the TLS_FALLBACK_SCSV mechanism during\nthe handshake, as defined in RFC7507.", "target": 1, "dataset": "other", "idx": 200462} {"func": "copy_ciphersuites(gnutls_session_t session,\n\t\t gnutls_buffer_st * cdata, int add_scsv)\n{\n\tint ret;\n\tuint8_t cipher_suites[MAX_CIPHERSUITE_SIZE + 4]; /* allow space for SCSV */\n\tint cipher_suites_size;\n\tsize_t init_length = cdata->length;\n\n\tret =\n\t _gnutls_supported_ciphersuites(session, cipher_suites,\n\t\t\t\t\t sizeof(cipher_suites) - 2);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\t/* Here we remove any ciphersuite that does not conform\n\t * the certificate requested, or to the\n\t * authentication requested (eg SRP).\n\t */\n\tret =\n\t _gnutls_remove_unwanted_ciphersuites(session, cipher_suites,\n\t\t\t\t\t\t ret, NULL, 0);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\t/* If no cipher suites were enabled.\n\t */\n\tif (ret == 0)\n\t\treturn\n\t\t gnutls_assert_val(GNUTLS_E_INSUFFICIENT_CREDENTIALS);\n\n\tcipher_suites_size = ret;\n\tif (add_scsv) {\n\t\tcipher_suites[cipher_suites_size] = 0x00;\n\t\tcipher_suites[cipher_suites_size + 1] = 0xff;\n\t\tcipher_suites_size += 2;\n\n\t\tret = _gnutls_ext_sr_send_cs(session);\n\t\tif (ret < 0)\n\t\t\treturn gnutls_assert_val(ret);\n\t}\n\n\tif (session->internals.priorities.fallback) {\n\t\tcipher_suites[cipher_suites_size] =\n\t\t\tGNUTLS_FALLBACK_SCSV_MAJOR;\n\t\tcipher_suites[cipher_suites_size + 1] =\n\t\t\tGNUTLS_FALLBACK_SCSV_MINOR;\n\t\tcipher_suites_size += 2;\n\t}\n\n\tret =\n\t _gnutls_buffer_append_data_prefix(cdata, 16, cipher_suites,\n\t\t\t\t\t cipher_suites_size);\n\tif (ret < 0)\n\t\treturn gnutls_assert_val(ret);\n\n\tret = cdata->length - init_length;\n\n\treturn ret;\n}", "project": "gnutls", "hash": 247092967394331613424979076891944757849, "size": 59, "commit_id": "21f89efad7014a5ee0debd4cd3d59e27774b29e6", "message": "handshake: add FALLBACK_SCSV priority option\n\nThis allows clients to enable the TLS_FALLBACK_SCSV mechanism during\nthe handshake, as defined in RFC7507.", "target": 0, "dataset": "other", "idx": 303482} {"func": "gdImagePtr gdImageCreateFromXpm (char *filename)\n{\n\tXpmInfo info;\n\tXpmImage image;\n\tint i, j, k, number;\n\tchar buf[5];\n\tgdImagePtr im = 0;\n\tint *pointer;\n\tint red = 0, green = 0, blue = 0;\n\tint *colors;\n\tint ret;\n\n\tret = XpmReadFileToXpmImage(filename, &image, &info);\n\tif (ret != XpmSuccess) {\n\t\treturn 0;\n\t}\n\n\tif (!(im = gdImageCreate(image.width, image.height))) {\n\t\tgoto done;\n\t}\n\n\tnumber = image.ncolors;\n\tcolors = (int *) safe_emalloc(number, sizeof(int), 0);\n\tfor (i = 0; i < number; i++) {\n\t\tswitch (strlen (image.colorTable[i].c_color)) {\n\t\t\tcase 4:\n\t\t\t\tbuf[1] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[2];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[3];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tbreak;\n\n\t\t\tcase 7:\n\t\t\t\tbuf[2] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[2];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[3];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[4];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[5];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[6];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tbreak;\n\n\t\t\tcase 10:\n\t\t\t\tbuf[3] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[2];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[3];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\t\t\t\tred /= 64;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[4];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[5];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[6];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\t\t\t\tgreen /= 64;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[7];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[8];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[9];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tblue /= 64;\n\t\t\t\tbreak;\n\n\t\t\tcase 13:\n\t\t\t\tbuf[4] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[2];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[3];\n\t\t\t\tbuf[3] = image.colorTable[i].c_color[4];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\t\t\t\tred /= 256;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[5];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[6];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[7];\n\t\t\t\tbuf[3] = image.colorTable[i].c_color[8];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\t\t\t\tgreen /= 256;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[9];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[10];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[11];\n\t\t\t\tbuf[3] = image.colorTable[i].c_color[12];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tblue /= 256;\n\t\t\t\tbreak;\n\t\t}\n\n\n\t\tcolors[i] = gdImageColorResolve(im, red, green, blue);\n\t}\n\n\tpointer = (int *) image.data;\n\tfor (i = 0; i < image.height; i++) {\n\t\tfor (j = 0; j < image.width; j++) {\n\t\t\tk = *pointer++;\n\t\t\tgdImageSetPixel(im, j, i, colors[k]);\n\t\t}\n\t}\n\n\tgdFree(colors);\n done:\n\tXpmFreeXpmImage(&image);\n\tXpmFreeXpmInfo(&info);\n\treturn im;\n}", "project": "php-src", "hash": 52478760808659547393823496374843686575, "size": 116, "commit_id": "cf4753691dc55999373d1c576f62ecb298723420", "message": "Fixed Bug #66901 php-gd 'c_color' NULL pointer dereference\n\nUpstream https://bitbucket.org/libgd/gd-libgd/commits/463c3bd09bfe8e924e19acad7a2a6af16953a704\n\nNotice: this fix don't manage monochrome/monovisual values\nbut just fix the security issue CVE-2014-2497\nfailing when trying to load such an image", "target": 1, "dataset": "other", "idx": 200525} {"func": "gdImagePtr gdImageCreateFromXpm (char *filename)\n{\n\tXpmInfo info;\n\tXpmImage image;\n\tint i, j, k, number;\n\tchar buf[5];\n\tgdImagePtr im = 0;\n\tint *pointer;\n\tint red = 0, green = 0, blue = 0;\n\tint *colors;\n\tint ret;\n\n\tret = XpmReadFileToXpmImage(filename, &image, &info);\n\tif (ret != XpmSuccess) {\n\t\treturn 0;\n\t}\n\tnumber = image.ncolors;\n\tfor(i = 0; i < number; i++) {\n\t\tif (!image.colorTable[i].c_color) {\n\t\t\tgoto done;\n\t\t}\n\t}\n\n\tif (!(im = gdImageCreate(image.width, image.height))) {\n\t\tgoto done;\n\t}\n\n\tcolors = (int *) safe_emalloc(number, sizeof(int), 0);\n\tfor (i = 0; i < number; i++) {\n\t\tswitch (strlen (image.colorTable[i].c_color)) {\n\t\t\tcase 4:\n\t\t\t\tbuf[1] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[2];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[3];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tbreak;\n\n\t\t\tcase 7:\n\t\t\t\tbuf[2] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[2];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[3];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[4];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[5];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[6];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tbreak;\n\n\t\t\tcase 10:\n\t\t\t\tbuf[3] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[2];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[3];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\t\t\t\tred /= 64;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[4];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[5];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[6];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\t\t\t\tgreen /= 64;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[7];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[8];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[9];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tblue /= 64;\n\t\t\t\tbreak;\n\n\t\t\tcase 13:\n\t\t\t\tbuf[4] = '\\0';\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[1];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[2];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[3];\n\t\t\t\tbuf[3] = image.colorTable[i].c_color[4];\n\t\t\t\tred = strtol(buf, NULL, 16);\n\t\t\t\tred /= 256;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[5];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[6];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[7];\n\t\t\t\tbuf[3] = image.colorTable[i].c_color[8];\n\t\t\t\tgreen = strtol(buf, NULL, 16);\n\t\t\t\tgreen /= 256;\n\n\t\t\t\tbuf[0] = image.colorTable[i].c_color[9];\n\t\t\t\tbuf[1] = image.colorTable[i].c_color[10];\n\t\t\t\tbuf[2] = image.colorTable[i].c_color[11];\n\t\t\t\tbuf[3] = image.colorTable[i].c_color[12];\n\t\t\t\tblue = strtol(buf, NULL, 16);\n\t\t\t\tblue /= 256;\n\t\t\t\tbreak;\n\t\t}\n\n\n\t\tcolors[i] = gdImageColorResolve(im, red, green, blue);\n\t}\n\n\tpointer = (int *) image.data;\n\tfor (i = 0; i < image.height; i++) {\n\t\tfor (j = 0; j < image.width; j++) {\n\t\t\tk = *pointer++;\n\t\t\tgdImageSetPixel(im, j, i, colors[k]);\n\t\t}\n\t}\n\n\tgdFree(colors);\n done:\n\tXpmFreeXpmImage(&image);\n\tXpmFreeXpmInfo(&info);\n\treturn im;\n}", "project": "php-src", "hash": 108615700401399758911645753719088620741, "size": 121, "commit_id": "cf4753691dc55999373d1c576f62ecb298723420", "message": "Fixed Bug #66901 php-gd 'c_color' NULL pointer dereference\n\nUpstream https://bitbucket.org/libgd/gd-libgd/commits/463c3bd09bfe8e924e19acad7a2a6af16953a704\n\nNotice: this fix don't manage monochrome/monovisual values\nbut just fix the security issue CVE-2014-2497\nfailing when trying to load such an image", "target": 0, "dataset": "other", "idx": 304857} {"func": "static TPM_RESULT SWTPM_NVRAM_Lock_Lockfile(const char *directory,\n int *fd)\n{\n TPM_RESULT rc = 0;\n char *lockfile = NULL;\n struct flock flock = {\n .l_type = F_WRLCK,\n .l_whence = SEEK_SET,\n .l_start = 0,\n .l_len = 0,\n };\n\n if (asprintf(&lockfile, \"%s/.lock\", directory) < 0) {\n logprintf(STDERR_FILENO,\n \"SWTPM_NVRAM_Lock_Lockfile: Could not asprintf lock filename\\n\");\n return TPM_FAIL;\n }\n\n *fd = open(lockfile, O_WRONLY|O_CREAT|O_TRUNC, 0660);\n if (*fd < 0) {\n logprintf(STDERR_FILENO,\n \"SWTPM_NVRAM_Lock_Lockfile: Could not open lockfile: %s\\n\",\n strerror(errno));\n rc = TPM_FAIL;\n goto exit;\n }\n\n if (fcntl(*fd, F_SETLK, &flock) < 0) {\n logprintf(STDERR_FILENO,\n \"SWTPM_NVRAM_Lock_Lockfile: Could not lock access to lockfile: %s\\n\",\n strerror(errno));\n rc = TPM_FAIL;\n close(*fd);\n *fd = -1;\n }\nexit:\n free(lockfile);\n\n return rc;\n}", "project": "swtpm", "hash": 300279316673534479735790981739540156268, "size": 40, "commit_id": "cae5991423826f21b11f7a5bc7f7b2b538bde2a2", "message": "swtpm: Do not follow symlinks when opening lockfile (CVE-2020-28407)\n\nThis patch addresses CVE-2020-28407.\n\nPrevent us from following symliks when we open the lockfile\nfor writing.\n\nSigned-off-by: Stefan Berger ", "target": 1, "dataset": "other", "idx": 200558} {"func": "static TPM_RESULT SWTPM_NVRAM_Lock_Lockfile(const char *directory,\n int *fd)\n{\n TPM_RESULT rc = 0;\n char *lockfile = NULL;\n struct flock flock = {\n .l_type = F_WRLCK,\n .l_whence = SEEK_SET,\n .l_start = 0,\n .l_len = 0,\n };\n\n if (asprintf(&lockfile, \"%s/.lock\", directory) < 0) {\n logprintf(STDERR_FILENO,\n \"SWTPM_NVRAM_Lock_Lockfile: Could not asprintf lock filename\\n\");\n return TPM_FAIL;\n }\n\n *fd = open(lockfile, O_WRONLY|O_CREAT|O_TRUNC|O_NOFOLLOW, 0660);\n if (*fd < 0) {\n logprintf(STDERR_FILENO,\n \"SWTPM_NVRAM_Lock_Lockfile: Could not open lockfile: %s\\n\",\n strerror(errno));\n rc = TPM_FAIL;\n goto exit;\n }\n\n if (fcntl(*fd, F_SETLK, &flock) < 0) {\n logprintf(STDERR_FILENO,\n \"SWTPM_NVRAM_Lock_Lockfile: Could not lock access to lockfile: %s\\n\",\n strerror(errno));\n rc = TPM_FAIL;\n close(*fd);\n *fd = -1;\n }\nexit:\n free(lockfile);\n\n return rc;\n}", "project": "swtpm", "hash": 227292187414569762413855551049878784834, "size": 40, "commit_id": "cae5991423826f21b11f7a5bc7f7b2b538bde2a2", "message": "swtpm: Do not follow symlinks when opening lockfile (CVE-2020-28407)\n\nThis patch addresses CVE-2020-28407.\n\nPrevent us from following symliks when we open the lockfile\nfor writing.\n\nSigned-off-by: Stefan Berger ", "target": 0, "dataset": "other", "idx": 305346} {"func": "static void ov511_mode_init_regs(struct sd *sd)\n{\n\tstruct gspca_dev *gspca_dev = (struct gspca_dev *)sd;\n\tint hsegs, vsegs, packet_size, fps, needed;\n\tint interlaced = 0;\n\tstruct usb_host_interface *alt;\n\tstruct usb_interface *intf;\n\n\tintf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);\n\talt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);\n\tif (!alt) {\n\t\tgspca_err(gspca_dev, \"Couldn't get altsetting\\n\");\n\t\tsd->gspca_dev.usb_err = -EIO;\n\t\treturn;\n\t}\n\n\tpacket_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);\n\treg_w(sd, R51x_FIFO_PSIZE, packet_size >> 5);\n\n\treg_w(sd, R511_CAM_UV_EN, 0x01);\n\treg_w(sd, R511_SNAP_UV_EN, 0x01);\n\treg_w(sd, R511_SNAP_OPTS, 0x03);\n\n\t/* Here I'm assuming that snapshot size == image size.\n\t * I hope that's always true. --claudio\n\t */\n\thsegs = (sd->gspca_dev.pixfmt.width >> 3) - 1;\n\tvsegs = (sd->gspca_dev.pixfmt.height >> 3) - 1;\n\n\treg_w(sd, R511_CAM_PXCNT, hsegs);\n\treg_w(sd, R511_CAM_LNCNT, vsegs);\n\treg_w(sd, R511_CAM_PXDIV, 0x00);\n\treg_w(sd, R511_CAM_LNDIV, 0x00);\n\n\t/* YUV420, low pass filter on */\n\treg_w(sd, R511_CAM_OPTS, 0x03);\n\n\t/* Snapshot additions */\n\treg_w(sd, R511_SNAP_PXCNT, hsegs);\n\treg_w(sd, R511_SNAP_LNCNT, vsegs);\n\treg_w(sd, R511_SNAP_PXDIV, 0x00);\n\treg_w(sd, R511_SNAP_LNDIV, 0x00);\n\n\t/******** Set the framerate ********/\n\tif (frame_rate > 0)\n\t\tsd->frame_rate = frame_rate;\n\n\tswitch (sd->sensor) {\n\tcase SEN_OV6620:\n\t\t/* No framerate control, doesn't like higher rates yet */\n\t\tsd->clockdiv = 3;\n\t\tbreak;\n\n\t/* Note once the FIXME's in mode_init_ov_sensor_regs() are fixed\n\t for more sensors we need to do this for them too */\n\tcase SEN_OV7620:\n\tcase SEN_OV7620AE:\n\tcase SEN_OV7640:\n\tcase SEN_OV7648:\n\tcase SEN_OV76BE:\n\t\tif (sd->gspca_dev.pixfmt.width == 320)\n\t\t\tinterlaced = 1;\n\t\t/* Fall through */\n\tcase SEN_OV6630:\n\tcase SEN_OV7610:\n\tcase SEN_OV7670:\n\t\tswitch (sd->frame_rate) {\n\t\tcase 30:\n\t\tcase 25:\n\t\t\t/* Not enough bandwidth to do 640x480 @ 30 fps */\n\t\t\tif (sd->gspca_dev.pixfmt.width != 640) {\n\t\t\t\tsd->clockdiv = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* For 640x480 case */\n\t\t\t/* fall through */\n\t\tdefault:\n/*\t\tcase 20: */\n/*\t\tcase 15: */\n\t\t\tsd->clockdiv = 1;\n\t\t\tbreak;\n\t\tcase 10:\n\t\t\tsd->clockdiv = 2;\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tsd->clockdiv = 5;\n\t\t\tbreak;\n\t\t}\n\t\tif (interlaced) {\n\t\t\tsd->clockdiv = (sd->clockdiv + 1) * 2 - 1;\n\t\t\t/* Higher then 10 does not work */\n\t\t\tif (sd->clockdiv > 10)\n\t\t\t\tsd->clockdiv = 10;\n\t\t}\n\t\tbreak;\n\n\tcase SEN_OV8610:\n\t\t/* No framerate control ?? */\n\t\tsd->clockdiv = 0;\n\t\tbreak;\n\t}\n\n\t/* Check if we have enough bandwidth to disable compression */\n\tfps = (interlaced ? 60 : 30) / (sd->clockdiv + 1) + 1;\n\tneeded = fps * sd->gspca_dev.pixfmt.width *\n\t\t\tsd->gspca_dev.pixfmt.height * 3 / 2;\n\t/* 1000 isoc packets/sec */\n\tif (needed > 1000 * packet_size) {\n\t\t/* Enable Y and UV quantization and compression */\n\t\treg_w(sd, R511_COMP_EN, 0x07);\n\t\treg_w(sd, R511_COMP_LUT_EN, 0x03);\n\t} else {\n\t\treg_w(sd, R511_COMP_EN, 0x06);\n\t\treg_w(sd, R511_COMP_LUT_EN, 0x00);\n\t}\n\n\treg_w(sd, R51x_SYS_RESET, OV511_RESET_OMNICE);\n\treg_w(sd, R51x_SYS_RESET, 0);\n}", "project": "linux", "hash": 207420910822850441672571201896199052237, "size": 119, "commit_id": "998912346c0da53a6dbb71fab3a138586b596b30", "message": "media: ov519: add missing endpoint sanity checks\n\nMake sure to check that we have at least one endpoint before accessing\nthe endpoint array to avoid dereferencing a NULL-pointer on stream\nstart.\n\nNote that these sanity checks are not redundant as the driver is mixing\nlooking up altsettings by index and by number, which need not coincide.\n\nFixes: 1876bb923c98 (\"V4L/DVB (12079): gspca_ov519: add support for the ov511 bridge\")\nFixes: b282d87332f5 (\"V4L/DVB (12080): gspca_ov519: Fix ov518+ with OV7620AE (Trust spacecam 320)\")\nCc: stable # 2.6.31\nCc: Hans de Goede \nSigned-off-by: Johan Hovold \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab ", "target": 1, "dataset": "other", "idx": 200621} {"func": "static void ov511_mode_init_regs(struct sd *sd)\n{\n\tstruct gspca_dev *gspca_dev = (struct gspca_dev *)sd;\n\tint hsegs, vsegs, packet_size, fps, needed;\n\tint interlaced = 0;\n\tstruct usb_host_interface *alt;\n\tstruct usb_interface *intf;\n\n\tintf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);\n\talt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);\n\tif (!alt) {\n\t\tgspca_err(gspca_dev, \"Couldn't get altsetting\\n\");\n\t\tsd->gspca_dev.usb_err = -EIO;\n\t\treturn;\n\t}\n\n\tif (alt->desc.bNumEndpoints < 1) {\n\t\tsd->gspca_dev.usb_err = -ENODEV;\n\t\treturn;\n\t}\n\n\tpacket_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);\n\treg_w(sd, R51x_FIFO_PSIZE, packet_size >> 5);\n\n\treg_w(sd, R511_CAM_UV_EN, 0x01);\n\treg_w(sd, R511_SNAP_UV_EN, 0x01);\n\treg_w(sd, R511_SNAP_OPTS, 0x03);\n\n\t/* Here I'm assuming that snapshot size == image size.\n\t * I hope that's always true. --claudio\n\t */\n\thsegs = (sd->gspca_dev.pixfmt.width >> 3) - 1;\n\tvsegs = (sd->gspca_dev.pixfmt.height >> 3) - 1;\n\n\treg_w(sd, R511_CAM_PXCNT, hsegs);\n\treg_w(sd, R511_CAM_LNCNT, vsegs);\n\treg_w(sd, R511_CAM_PXDIV, 0x00);\n\treg_w(sd, R511_CAM_LNDIV, 0x00);\n\n\t/* YUV420, low pass filter on */\n\treg_w(sd, R511_CAM_OPTS, 0x03);\n\n\t/* Snapshot additions */\n\treg_w(sd, R511_SNAP_PXCNT, hsegs);\n\treg_w(sd, R511_SNAP_LNCNT, vsegs);\n\treg_w(sd, R511_SNAP_PXDIV, 0x00);\n\treg_w(sd, R511_SNAP_LNDIV, 0x00);\n\n\t/******** Set the framerate ********/\n\tif (frame_rate > 0)\n\t\tsd->frame_rate = frame_rate;\n\n\tswitch (sd->sensor) {\n\tcase SEN_OV6620:\n\t\t/* No framerate control, doesn't like higher rates yet */\n\t\tsd->clockdiv = 3;\n\t\tbreak;\n\n\t/* Note once the FIXME's in mode_init_ov_sensor_regs() are fixed\n\t for more sensors we need to do this for them too */\n\tcase SEN_OV7620:\n\tcase SEN_OV7620AE:\n\tcase SEN_OV7640:\n\tcase SEN_OV7648:\n\tcase SEN_OV76BE:\n\t\tif (sd->gspca_dev.pixfmt.width == 320)\n\t\t\tinterlaced = 1;\n\t\t/* Fall through */\n\tcase SEN_OV6630:\n\tcase SEN_OV7610:\n\tcase SEN_OV7670:\n\t\tswitch (sd->frame_rate) {\n\t\tcase 30:\n\t\tcase 25:\n\t\t\t/* Not enough bandwidth to do 640x480 @ 30 fps */\n\t\t\tif (sd->gspca_dev.pixfmt.width != 640) {\n\t\t\t\tsd->clockdiv = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* For 640x480 case */\n\t\t\t/* fall through */\n\t\tdefault:\n/*\t\tcase 20: */\n/*\t\tcase 15: */\n\t\t\tsd->clockdiv = 1;\n\t\t\tbreak;\n\t\tcase 10:\n\t\t\tsd->clockdiv = 2;\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tsd->clockdiv = 5;\n\t\t\tbreak;\n\t\t}\n\t\tif (interlaced) {\n\t\t\tsd->clockdiv = (sd->clockdiv + 1) * 2 - 1;\n\t\t\t/* Higher then 10 does not work */\n\t\t\tif (sd->clockdiv > 10)\n\t\t\t\tsd->clockdiv = 10;\n\t\t}\n\t\tbreak;\n\n\tcase SEN_OV8610:\n\t\t/* No framerate control ?? */\n\t\tsd->clockdiv = 0;\n\t\tbreak;\n\t}\n\n\t/* Check if we have enough bandwidth to disable compression */\n\tfps = (interlaced ? 60 : 30) / (sd->clockdiv + 1) + 1;\n\tneeded = fps * sd->gspca_dev.pixfmt.width *\n\t\t\tsd->gspca_dev.pixfmt.height * 3 / 2;\n\t/* 1000 isoc packets/sec */\n\tif (needed > 1000 * packet_size) {\n\t\t/* Enable Y and UV quantization and compression */\n\t\treg_w(sd, R511_COMP_EN, 0x07);\n\t\treg_w(sd, R511_COMP_LUT_EN, 0x03);\n\t} else {\n\t\treg_w(sd, R511_COMP_EN, 0x06);\n\t\treg_w(sd, R511_COMP_LUT_EN, 0x00);\n\t}\n\n\treg_w(sd, R51x_SYS_RESET, OV511_RESET_OMNICE);\n\treg_w(sd, R51x_SYS_RESET, 0);\n}", "project": "linux", "hash": 66031367225502192060724962502262196162, "size": 124, "commit_id": "998912346c0da53a6dbb71fab3a138586b596b30", "message": "media: ov519: add missing endpoint sanity checks\n\nMake sure to check that we have at least one endpoint before accessing\nthe endpoint array to avoid dereferencing a NULL-pointer on stream\nstart.\n\nNote that these sanity checks are not redundant as the driver is mixing\nlooking up altsettings by index and by number, which need not coincide.\n\nFixes: 1876bb923c98 (\"V4L/DVB (12079): gspca_ov519: add support for the ov511 bridge\")\nFixes: b282d87332f5 (\"V4L/DVB (12080): gspca_ov519: Fix ov518+ with OV7620AE (Trust spacecam 320)\")\nCc: stable # 2.6.31\nCc: Hans de Goede \nSigned-off-by: Johan Hovold \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab ", "target": 0, "dataset": "other", "idx": 306343} {"func": "static void ov518_mode_init_regs(struct sd *sd)\n{\n\tstruct gspca_dev *gspca_dev = (struct gspca_dev *)sd;\n\tint hsegs, vsegs, packet_size;\n\tstruct usb_host_interface *alt;\n\tstruct usb_interface *intf;\n\n\tintf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);\n\talt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);\n\tif (!alt) {\n\t\tgspca_err(gspca_dev, \"Couldn't get altsetting\\n\");\n\t\tsd->gspca_dev.usb_err = -EIO;\n\t\treturn;\n\t}\n\n\tpacket_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);\n\tov518_reg_w32(sd, R51x_FIFO_PSIZE, packet_size & ~7, 2);\n\n\t/******** Set the mode ********/\n\treg_w(sd, 0x2b, 0);\n\treg_w(sd, 0x2c, 0);\n\treg_w(sd, 0x2d, 0);\n\treg_w(sd, 0x2e, 0);\n\treg_w(sd, 0x3b, 0);\n\treg_w(sd, 0x3c, 0);\n\treg_w(sd, 0x3d, 0);\n\treg_w(sd, 0x3e, 0);\n\n\tif (sd->bridge == BRIDGE_OV518) {\n\t\t/* Set 8-bit (YVYU) input format */\n\t\treg_w_mask(sd, 0x20, 0x08, 0x08);\n\n\t\t/* Set 12-bit (4:2:0) output format */\n\t\treg_w_mask(sd, 0x28, 0x80, 0xf0);\n\t\treg_w_mask(sd, 0x38, 0x80, 0xf0);\n\t} else {\n\t\treg_w(sd, 0x28, 0x80);\n\t\treg_w(sd, 0x38, 0x80);\n\t}\n\n\thsegs = sd->gspca_dev.pixfmt.width / 16;\n\tvsegs = sd->gspca_dev.pixfmt.height / 4;\n\n\treg_w(sd, 0x29, hsegs);\n\treg_w(sd, 0x2a, vsegs);\n\n\treg_w(sd, 0x39, hsegs);\n\treg_w(sd, 0x3a, vsegs);\n\n\t/* Windows driver does this here; who knows why */\n\treg_w(sd, 0x2f, 0x80);\n\n\t/******** Set the framerate ********/\n\tif (sd->bridge == BRIDGE_OV518PLUS && sd->revision == 0 &&\n\t\t\t\t\t sd->sensor == SEN_OV7620AE)\n\t\tsd->clockdiv = 0;\n\telse\n\t\tsd->clockdiv = 1;\n\n\t/* Mode independent, but framerate dependent, regs */\n\t/* 0x51: Clock divider; Only works on some cams which use 2 crystals */\n\treg_w(sd, 0x51, 0x04);\n\treg_w(sd, 0x22, 0x18);\n\treg_w(sd, 0x23, 0xff);\n\n\tif (sd->bridge == BRIDGE_OV518PLUS) {\n\t\tswitch (sd->sensor) {\n\t\tcase SEN_OV7620AE:\n\t\t\t/*\n\t\t\t * HdG: 640x480 needs special handling on device\n\t\t\t * revision 2, we check for device revision > 0 to\n\t\t\t * avoid regressions, as we don't know the correct\n\t\t\t * thing todo for revision 1.\n\t\t\t *\n\t\t\t * Also this likely means we don't need to\n\t\t\t * differentiate between the OV7620 and OV7620AE,\n\t\t\t * earlier testing hitting this same problem likely\n\t\t\t * happened to be with revision < 2 cams using an\n\t\t\t * OV7620 and revision 2 cams using an OV7620AE.\n\t\t\t */\n\t\t\tif (sd->revision > 0 &&\n\t\t\t\t\tsd->gspca_dev.pixfmt.width == 640) {\n\t\t\t\treg_w(sd, 0x20, 0x60);\n\t\t\t\treg_w(sd, 0x21, 0x1f);\n\t\t\t} else {\n\t\t\t\treg_w(sd, 0x20, 0x00);\n\t\t\t\treg_w(sd, 0x21, 0x19);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SEN_OV7620:\n\t\t\treg_w(sd, 0x20, 0x00);\n\t\t\treg_w(sd, 0x21, 0x19);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treg_w(sd, 0x21, 0x19);\n\t\t}\n\t} else\n\t\treg_w(sd, 0x71, 0x17);\t/* Compression-related? */\n\n\t/* FIXME: Sensor-specific */\n\t/* Bit 5 is what matters here. Of course, it is \"reserved\" */\n\ti2c_w(sd, 0x54, 0x23);\n\n\treg_w(sd, 0x2f, 0x80);\n\n\tif (sd->bridge == BRIDGE_OV518PLUS) {\n\t\treg_w(sd, 0x24, 0x94);\n\t\treg_w(sd, 0x25, 0x90);\n\t\tov518_reg_w32(sd, 0xc4, 400, 2);\t/* 190h */\n\t\tov518_reg_w32(sd, 0xc6, 540, 2);\t/* 21ch */\n\t\tov518_reg_w32(sd, 0xc7, 540, 2);\t/* 21ch */\n\t\tov518_reg_w32(sd, 0xc8, 108, 2);\t/* 6ch */\n\t\tov518_reg_w32(sd, 0xca, 131098, 3);\t/* 2001ah */\n\t\tov518_reg_w32(sd, 0xcb, 532, 2);\t/* 214h */\n\t\tov518_reg_w32(sd, 0xcc, 2400, 2);\t/* 960h */\n\t\tov518_reg_w32(sd, 0xcd, 32, 2);\t/* 20h */\n\t\tov518_reg_w32(sd, 0xce, 608, 2);\t/* 260h */\n\t} else {\n\t\treg_w(sd, 0x24, 0x9f);\n\t\treg_w(sd, 0x25, 0x90);\n\t\tov518_reg_w32(sd, 0xc4, 400, 2);\t/* 190h */\n\t\tov518_reg_w32(sd, 0xc6, 381, 2);\t/* 17dh */\n\t\tov518_reg_w32(sd, 0xc7, 381, 2);\t/* 17dh */\n\t\tov518_reg_w32(sd, 0xc8, 128, 2);\t/* 80h */\n\t\tov518_reg_w32(sd, 0xca, 183331, 3);\t/* 2cc23h */\n\t\tov518_reg_w32(sd, 0xcb, 746, 2);\t/* 2eah */\n\t\tov518_reg_w32(sd, 0xcc, 1750, 2);\t/* 6d6h */\n\t\tov518_reg_w32(sd, 0xcd, 45, 2);\t/* 2dh */\n\t\tov518_reg_w32(sd, 0xce, 851, 2);\t/* 353h */\n\t}\n\n\treg_w(sd, 0x2f, 0x80);\n}", "project": "linux", "hash": 263247290990414325966345455466875763387, "size": 133, "commit_id": "998912346c0da53a6dbb71fab3a138586b596b30", "message": "media: ov519: add missing endpoint sanity checks\n\nMake sure to check that we have at least one endpoint before accessing\nthe endpoint array to avoid dereferencing a NULL-pointer on stream\nstart.\n\nNote that these sanity checks are not redundant as the driver is mixing\nlooking up altsettings by index and by number, which need not coincide.\n\nFixes: 1876bb923c98 (\"V4L/DVB (12079): gspca_ov519: add support for the ov511 bridge\")\nFixes: b282d87332f5 (\"V4L/DVB (12080): gspca_ov519: Fix ov518+ with OV7620AE (Trust spacecam 320)\")\nCc: stable # 2.6.31\nCc: Hans de Goede \nSigned-off-by: Johan Hovold \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab ", "target": 1, "dataset": "other", "idx": 200622} {"func": "static void ov518_mode_init_regs(struct sd *sd)\n{\n\tstruct gspca_dev *gspca_dev = (struct gspca_dev *)sd;\n\tint hsegs, vsegs, packet_size;\n\tstruct usb_host_interface *alt;\n\tstruct usb_interface *intf;\n\n\tintf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);\n\talt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);\n\tif (!alt) {\n\t\tgspca_err(gspca_dev, \"Couldn't get altsetting\\n\");\n\t\tsd->gspca_dev.usb_err = -EIO;\n\t\treturn;\n\t}\n\n\tif (alt->desc.bNumEndpoints < 1) {\n\t\tsd->gspca_dev.usb_err = -ENODEV;\n\t\treturn;\n\t}\n\n\tpacket_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);\n\tov518_reg_w32(sd, R51x_FIFO_PSIZE, packet_size & ~7, 2);\n\n\t/******** Set the mode ********/\n\treg_w(sd, 0x2b, 0);\n\treg_w(sd, 0x2c, 0);\n\treg_w(sd, 0x2d, 0);\n\treg_w(sd, 0x2e, 0);\n\treg_w(sd, 0x3b, 0);\n\treg_w(sd, 0x3c, 0);\n\treg_w(sd, 0x3d, 0);\n\treg_w(sd, 0x3e, 0);\n\n\tif (sd->bridge == BRIDGE_OV518) {\n\t\t/* Set 8-bit (YVYU) input format */\n\t\treg_w_mask(sd, 0x20, 0x08, 0x08);\n\n\t\t/* Set 12-bit (4:2:0) output format */\n\t\treg_w_mask(sd, 0x28, 0x80, 0xf0);\n\t\treg_w_mask(sd, 0x38, 0x80, 0xf0);\n\t} else {\n\t\treg_w(sd, 0x28, 0x80);\n\t\treg_w(sd, 0x38, 0x80);\n\t}\n\n\thsegs = sd->gspca_dev.pixfmt.width / 16;\n\tvsegs = sd->gspca_dev.pixfmt.height / 4;\n\n\treg_w(sd, 0x29, hsegs);\n\treg_w(sd, 0x2a, vsegs);\n\n\treg_w(sd, 0x39, hsegs);\n\treg_w(sd, 0x3a, vsegs);\n\n\t/* Windows driver does this here; who knows why */\n\treg_w(sd, 0x2f, 0x80);\n\n\t/******** Set the framerate ********/\n\tif (sd->bridge == BRIDGE_OV518PLUS && sd->revision == 0 &&\n\t\t\t\t\t sd->sensor == SEN_OV7620AE)\n\t\tsd->clockdiv = 0;\n\telse\n\t\tsd->clockdiv = 1;\n\n\t/* Mode independent, but framerate dependent, regs */\n\t/* 0x51: Clock divider; Only works on some cams which use 2 crystals */\n\treg_w(sd, 0x51, 0x04);\n\treg_w(sd, 0x22, 0x18);\n\treg_w(sd, 0x23, 0xff);\n\n\tif (sd->bridge == BRIDGE_OV518PLUS) {\n\t\tswitch (sd->sensor) {\n\t\tcase SEN_OV7620AE:\n\t\t\t/*\n\t\t\t * HdG: 640x480 needs special handling on device\n\t\t\t * revision 2, we check for device revision > 0 to\n\t\t\t * avoid regressions, as we don't know the correct\n\t\t\t * thing todo for revision 1.\n\t\t\t *\n\t\t\t * Also this likely means we don't need to\n\t\t\t * differentiate between the OV7620 and OV7620AE,\n\t\t\t * earlier testing hitting this same problem likely\n\t\t\t * happened to be with revision < 2 cams using an\n\t\t\t * OV7620 and revision 2 cams using an OV7620AE.\n\t\t\t */\n\t\t\tif (sd->revision > 0 &&\n\t\t\t\t\tsd->gspca_dev.pixfmt.width == 640) {\n\t\t\t\treg_w(sd, 0x20, 0x60);\n\t\t\t\treg_w(sd, 0x21, 0x1f);\n\t\t\t} else {\n\t\t\t\treg_w(sd, 0x20, 0x00);\n\t\t\t\treg_w(sd, 0x21, 0x19);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SEN_OV7620:\n\t\t\treg_w(sd, 0x20, 0x00);\n\t\t\treg_w(sd, 0x21, 0x19);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treg_w(sd, 0x21, 0x19);\n\t\t}\n\t} else\n\t\treg_w(sd, 0x71, 0x17);\t/* Compression-related? */\n\n\t/* FIXME: Sensor-specific */\n\t/* Bit 5 is what matters here. Of course, it is \"reserved\" */\n\ti2c_w(sd, 0x54, 0x23);\n\n\treg_w(sd, 0x2f, 0x80);\n\n\tif (sd->bridge == BRIDGE_OV518PLUS) {\n\t\treg_w(sd, 0x24, 0x94);\n\t\treg_w(sd, 0x25, 0x90);\n\t\tov518_reg_w32(sd, 0xc4, 400, 2);\t/* 190h */\n\t\tov518_reg_w32(sd, 0xc6, 540, 2);\t/* 21ch */\n\t\tov518_reg_w32(sd, 0xc7, 540, 2);\t/* 21ch */\n\t\tov518_reg_w32(sd, 0xc8, 108, 2);\t/* 6ch */\n\t\tov518_reg_w32(sd, 0xca, 131098, 3);\t/* 2001ah */\n\t\tov518_reg_w32(sd, 0xcb, 532, 2);\t/* 214h */\n\t\tov518_reg_w32(sd, 0xcc, 2400, 2);\t/* 960h */\n\t\tov518_reg_w32(sd, 0xcd, 32, 2);\t/* 20h */\n\t\tov518_reg_w32(sd, 0xce, 608, 2);\t/* 260h */\n\t} else {\n\t\treg_w(sd, 0x24, 0x9f);\n\t\treg_w(sd, 0x25, 0x90);\n\t\tov518_reg_w32(sd, 0xc4, 400, 2);\t/* 190h */\n\t\tov518_reg_w32(sd, 0xc6, 381, 2);\t/* 17dh */\n\t\tov518_reg_w32(sd, 0xc7, 381, 2);\t/* 17dh */\n\t\tov518_reg_w32(sd, 0xc8, 128, 2);\t/* 80h */\n\t\tov518_reg_w32(sd, 0xca, 183331, 3);\t/* 2cc23h */\n\t\tov518_reg_w32(sd, 0xcb, 746, 2);\t/* 2eah */\n\t\tov518_reg_w32(sd, 0xcc, 1750, 2);\t/* 6d6h */\n\t\tov518_reg_w32(sd, 0xcd, 45, 2);\t/* 2dh */\n\t\tov518_reg_w32(sd, 0xce, 851, 2);\t/* 353h */\n\t}\n\n\treg_w(sd, 0x2f, 0x80);\n}", "project": "linux", "hash": 205218704415973742418430089136769528517, "size": 138, "commit_id": "998912346c0da53a6dbb71fab3a138586b596b30", "message": "media: ov519: add missing endpoint sanity checks\n\nMake sure to check that we have at least one endpoint before accessing\nthe endpoint array to avoid dereferencing a NULL-pointer on stream\nstart.\n\nNote that these sanity checks are not redundant as the driver is mixing\nlooking up altsettings by index and by number, which need not coincide.\n\nFixes: 1876bb923c98 (\"V4L/DVB (12079): gspca_ov519: add support for the ov511 bridge\")\nFixes: b282d87332f5 (\"V4L/DVB (12080): gspca_ov519: Fix ov518+ with OV7620AE (Trust spacecam 320)\")\nCc: stable # 2.6.31\nCc: Hans de Goede \nSigned-off-by: Johan Hovold \nSigned-off-by: Hans Verkuil \nSigned-off-by: Mauro Carvalho Chehab ", "target": 0, "dataset": "other", "idx": 306292} {"func": "urnParseReply(const char *inbuf, const HttpRequestMethod& m)\n{\n char *buf = xstrdup(inbuf);\n char *token;\n url_entry *list;\n url_entry *old;\n int n = 32;\n int i = 0;\n debugs(52, 3, \"urnParseReply\");\n list = (url_entry *)xcalloc(n + 1, sizeof(*list));\n\n for (token = strtok(buf, crlf); token; token = strtok(NULL, crlf)) {\n debugs(52, 3, \"urnParseReply: got '\" << token << \"'\");\n\n if (i == n) {\n old = list;\n n <<= 2;\n list = (url_entry *)xcalloc(n + 1, sizeof(*list));\n memcpy(list, old, i * sizeof(*list));\n safe_free(old);\n }\n\n AnyP::Uri uri;\n if (!uri.parse(m, SBuf(token)) || !*uri.host())\n continue;\n\n#if USE_ICMP\n list[i].rtt = netdbHostRtt(uri.host());\n\n if (0 == list[i].rtt) {\n debugs(52, 3, \"Pinging \" << uri.host());\n netdbPingSite(uri.host());\n }\n#else\n list[i].rtt = 0;\n#endif\n\n list[i].url = xstrdup(uri.absolute().c_str());\n list[i].host = xstrdup(uri.host());\n // TODO: Use storeHas() or lock/unlock entry to avoid creating unlocked\n // ones.\n list[i].flags.cached = storeGetPublic(list[i].url, m) ? 1 : 0;\n ++i;\n }\n\n debugs(52, 3, \"urnParseReply: Found \" << i << \" URLs\");\n return list;\n}", "project": "squid", "hash": 111230701440294531243041412971285423945, "size": 48, "commit_id": "47a085ff06598b64817875769022b8707a0af7db", "message": "Bug 5104: Memory leak in RFC 2169 response parsing (#778)\n\nA temporary parsing buffer was not being released when\nparsing completed.", "target": 1, "dataset": "other", "idx": 200632} {"func": "urnParseReply(const char *inbuf, const HttpRequestMethod& m)\n{\n char *buf = xstrdup(inbuf);\n char *token;\n url_entry *list;\n url_entry *old;\n int n = 32;\n int i = 0;\n debugs(52, 3, \"urnParseReply\");\n list = (url_entry *)xcalloc(n + 1, sizeof(*list));\n\n for (token = strtok(buf, crlf); token; token = strtok(NULL, crlf)) {\n debugs(52, 3, \"urnParseReply: got '\" << token << \"'\");\n\n if (i == n) {\n old = list;\n n <<= 2;\n list = (url_entry *)xcalloc(n + 1, sizeof(*list));\n memcpy(list, old, i * sizeof(*list));\n safe_free(old);\n }\n\n AnyP::Uri uri;\n if (!uri.parse(m, SBuf(token)) || !*uri.host())\n continue;\n\n#if USE_ICMP\n list[i].rtt = netdbHostRtt(uri.host());\n\n if (0 == list[i].rtt) {\n debugs(52, 3, \"Pinging \" << uri.host());\n netdbPingSite(uri.host());\n }\n#else\n list[i].rtt = 0;\n#endif\n\n list[i].url = xstrdup(uri.absolute().c_str());\n list[i].host = xstrdup(uri.host());\n // TODO: Use storeHas() or lock/unlock entry to avoid creating unlocked\n // ones.\n list[i].flags.cached = storeGetPublic(list[i].url, m) ? 1 : 0;\n ++i;\n }\n\n debugs(52, 3, \"urnParseReply: Found \" << i << \" URLs\");\n xfree(buf);\n return list;\n}", "project": "squid", "hash": 263080633568694329448297146517615992184, "size": 49, "commit_id": "47a085ff06598b64817875769022b8707a0af7db", "message": "Bug 5104: Memory leak in RFC 2169 response parsing (#778)\n\nA temporary parsing buffer was not being released when\nparsing completed.", "target": 0, "dataset": "other", "idx": 306747} {"func": "user_lookup (pam_handle_t *pamh, const char *database, const char *cryptmode,\n\t const char *user, const char *pass, int ctrl)\n{\n DBM *dbm;\n datum key, data;\n\n /* Open the DB file. */\n dbm = dbm_open(database, O_RDONLY, 0644);\n if (dbm == NULL) {\n\tpam_syslog(pamh, LOG_ERR,\n\t\t \"user_lookup: could not open database `%s': %m\", database);\n\treturn -2;\n }\n\n /* dump out the database contents for debugging */\n if (ctrl & PAM_DUMP_ARG) {\n\tpam_syslog(pamh, LOG_INFO, \"Database dump:\");\n\tfor (key = dbm_firstkey(dbm); key.dptr != NULL;\n\t key = dbm_nextkey(dbm)) {\n\t data = dbm_fetch(dbm, key);\n\t pam_syslog(pamh, LOG_INFO,\n\t\t \"key[len=%d] = `%s', data[len=%d] = `%s'\",\n\t\t key.dsize, key.dptr, data.dsize, data.dptr);\n\t}\n }\n\n /* do some more init work */\n memset(&key, 0, sizeof(key));\n memset(&data, 0, sizeof(data));\n if (ctrl & PAM_KEY_ONLY_ARG) {\n\tif (asprintf(&key.dptr, \"%s-%s\", user, pass) < 0)\n\t key.dptr = NULL;\n\telse\n\t key.dsize = strlen(key.dptr);\n } else {\n key.dptr = x_strdup(user);\n key.dsize = strlen(user);\n }\n\n if (key.dptr) {\n\tdata = dbm_fetch(dbm, key);\n\tmemset(key.dptr, 0, key.dsize);\n\tfree(key.dptr);\n }\n\n if (ctrl & PAM_DEBUG_ARG) {\n\tpam_syslog(pamh, LOG_INFO,\n\t\t \"password in database is [%p]`%.*s', len is %d\",\n\t\t data.dptr, data.dsize, (char *) data.dptr, data.dsize);\n }\n\n if (data.dptr != NULL) {\n\tint compare = 0;\n\n\tif (ctrl & PAM_KEY_ONLY_ARG)\n\t {\n\t dbm_close (dbm);\n\t return 0; /* found it, data contents don't matter */\n\t}\n\n\tif (cryptmode && strncasecmp(cryptmode, \"crypt\", 5) == 0) {\n\n\t /* crypt(3) password storage */\n\n\t char *cryptpw;\n\n\t if (data.dsize < 13) {\n\t compare = -2;\n\t } else if (ctrl & PAM_ICASE_ARG) {\n\t compare = -2;\n\t } else {\n\t cryptpw = crypt (pass, data.dptr);\n\n\t if (cryptpw) {\n\t compare = strncasecmp (data.dptr, cryptpw, data.dsize);\n\t } else {\n\t compare = -2;\n\t if (ctrl & PAM_DEBUG_ARG) {\n\t\tpam_syslog(pamh, LOG_INFO, \"crypt() returned NULL\");\n\t }\n\t };\n\n\t };\n\n\t} else {\n\n\t /* Unknown password encryption method -\n\t * default to plaintext password storage\n\t */\n\n\t if (strlen(pass) != (size_t)data.dsize) {\n\t compare = 1; /* wrong password len -> wrong password */\n\t } else if (ctrl & PAM_ICASE_ARG) {\n\t compare = strncasecmp(data.dptr, pass, data.dsize);\n\t } else {\n\t compare = strncmp(data.dptr, pass, data.dsize);\n\t }\n\n\t if (cryptmode && strncasecmp(cryptmode, \"none\", 4)\n\t\t&& (ctrl & PAM_DEBUG_ARG)) {\n\t pam_syslog(pamh, LOG_INFO, \"invalid value for crypt parameter: %s\",\n\t\t cryptmode);\n\t pam_syslog(pamh, LOG_INFO, \"defaulting to plaintext password mode\");\n\t }\n\n\t}\n\n\tdbm_close(dbm);\n\tif (compare == 0)\n\t return 0; /* match */\n\telse\n\t return -1; /* wrong */\n } else {\n int saw_user = 0;\n\n\tif (ctrl & PAM_DEBUG_ARG) {\n\t pam_syslog(pamh, LOG_INFO, \"error returned by dbm_fetch: %m\");\n\t}\n\n\t/* probably we should check dbm_error() here */\n\n if ((ctrl & PAM_KEY_ONLY_ARG) == 0) {\n\t dbm_close(dbm);\n return 1; /* not key_only, so no entry => no entry for the user */\n }\n\n /* now handle the key_only case */\n for (key = dbm_firstkey(dbm);\n key.dptr != NULL;\n key = dbm_nextkey(dbm)) {\n int compare;\n /* first compare the user portion (case sensitive) */\n compare = strncmp(key.dptr, user, strlen(user));\n if (compare == 0) {\n /* assume failure */\n compare = -1;\n /* if we have the divider where we expect it to be... */\n if (key.dptr[strlen(user)] == '-') {\n\t\t saw_user = 1;\n\t\t if ((size_t)key.dsize == strlen(user) + 1 + strlen(pass)) {\n\t\t if (ctrl & PAM_ICASE_ARG) {\n\t\t\t /* compare the password portion (case insensitive)*/\n compare = strncasecmp(key.dptr + strlen(user) + 1,\n pass,\n strlen(pass));\n\t\t } else {\n /* compare the password portion (case sensitive) */\n compare = strncmp(key.dptr + strlen(user) + 1,\n pass,\n strlen(pass));\n\t\t }\n\t\t }\n }\n if (compare == 0) {\n dbm_close(dbm);\n return 0; /* match */\n }\n }\n }\n dbm_close(dbm);\n\tif (saw_user)\n\t return -1; /* saw the user, but password mismatch */\n\telse\n\t return 1; /* not found */\n }\n\n /* NOT REACHED */\n return -2;\n}", "project": "linux-pam", "hash": 112434099628297315187231061836027553571, "size": 169, "commit_id": "57a1e2b274d0a6376d92ada9926e5c5741e7da20", "message": "pam_userdb: fix password hash comparison\n\nStarting with commit Linux-PAM-0-77-28-g0b3e583 that introduced hashed\npasswords support in pam_userdb, hashes are compared case-insensitively.\nThis bug leads to accepting hashes for completely different passwords in\naddition to those that should be accepted.\n\nAdditionally, commit Linux-PAM-1_1_6-13-ge2a8187 that added support for\nmodern password hashes with different lengths and settings, did not\nupdate the hash comparison accordingly, which leads to accepting\ncomputed hashes longer than stored hashes when the latter is a prefix\nof the former.\n\n* modules/pam_userdb/pam_userdb.c (user_lookup): Reject the computed\nhash whose length differs from the stored hash length.\nCompare computed and stored hashes case-sensitively.\nFixes CVE-2013-7041.\n\nBug-Debian: http://bugs.debian.org/731368", "target": 1, "dataset": "other", "idx": 200647} {"func": "user_lookup (pam_handle_t *pamh, const char *database, const char *cryptmode,\n\t const char *user, const char *pass, int ctrl)\n{\n DBM *dbm;\n datum key, data;\n\n /* Open the DB file. */\n dbm = dbm_open(database, O_RDONLY, 0644);\n if (dbm == NULL) {\n\tpam_syslog(pamh, LOG_ERR,\n\t\t \"user_lookup: could not open database `%s': %m\", database);\n\treturn -2;\n }\n\n /* dump out the database contents for debugging */\n if (ctrl & PAM_DUMP_ARG) {\n\tpam_syslog(pamh, LOG_INFO, \"Database dump:\");\n\tfor (key = dbm_firstkey(dbm); key.dptr != NULL;\n\t key = dbm_nextkey(dbm)) {\n\t data = dbm_fetch(dbm, key);\n\t pam_syslog(pamh, LOG_INFO,\n\t\t \"key[len=%d] = `%s', data[len=%d] = `%s'\",\n\t\t key.dsize, key.dptr, data.dsize, data.dptr);\n\t}\n }\n\n /* do some more init work */\n memset(&key, 0, sizeof(key));\n memset(&data, 0, sizeof(data));\n if (ctrl & PAM_KEY_ONLY_ARG) {\n\tif (asprintf(&key.dptr, \"%s-%s\", user, pass) < 0)\n\t key.dptr = NULL;\n\telse\n\t key.dsize = strlen(key.dptr);\n } else {\n key.dptr = x_strdup(user);\n key.dsize = strlen(user);\n }\n\n if (key.dptr) {\n\tdata = dbm_fetch(dbm, key);\n\tmemset(key.dptr, 0, key.dsize);\n\tfree(key.dptr);\n }\n\n if (ctrl & PAM_DEBUG_ARG) {\n\tpam_syslog(pamh, LOG_INFO,\n\t\t \"password in database is [%p]`%.*s', len is %d\",\n\t\t data.dptr, data.dsize, (char *) data.dptr, data.dsize);\n }\n\n if (data.dptr != NULL) {\n\tint compare = 0;\n\n\tif (ctrl & PAM_KEY_ONLY_ARG)\n\t {\n\t dbm_close (dbm);\n\t return 0; /* found it, data contents don't matter */\n\t}\n\n\tif (cryptmode && strncasecmp(cryptmode, \"crypt\", 5) == 0) {\n\n\t /* crypt(3) password storage */\n\n\t char *cryptpw;\n\n\t if (data.dsize < 13) {\n\t compare = -2;\n\t } else if (ctrl & PAM_ICASE_ARG) {\n\t compare = -2;\n\t } else {\n\t cryptpw = crypt (pass, data.dptr);\n\n\t if (cryptpw && strlen(cryptpw) == (size_t)data.dsize) {\n\t compare = memcmp(data.dptr, cryptpw, data.dsize);\n\t } else {\n\t compare = -2;\n\t if (ctrl & PAM_DEBUG_ARG) {\n\t\tif (cryptpw)\n\t\t pam_syslog(pamh, LOG_INFO, \"lengths of computed and stored hashes differ\");\n\t\telse\n\t\t pam_syslog(pamh, LOG_INFO, \"crypt() returned NULL\");\n\t }\n\t };\n\n\t };\n\n\t} else {\n\n\t /* Unknown password encryption method -\n\t * default to plaintext password storage\n\t */\n\n\t if (strlen(pass) != (size_t)data.dsize) {\n\t compare = 1; /* wrong password len -> wrong password */\n\t } else if (ctrl & PAM_ICASE_ARG) {\n\t compare = strncasecmp(data.dptr, pass, data.dsize);\n\t } else {\n\t compare = strncmp(data.dptr, pass, data.dsize);\n\t }\n\n\t if (cryptmode && strncasecmp(cryptmode, \"none\", 4)\n\t\t&& (ctrl & PAM_DEBUG_ARG)) {\n\t pam_syslog(pamh, LOG_INFO, \"invalid value for crypt parameter: %s\",\n\t\t cryptmode);\n\t pam_syslog(pamh, LOG_INFO, \"defaulting to plaintext password mode\");\n\t }\n\n\t}\n\n\tdbm_close(dbm);\n\tif (compare == 0)\n\t return 0; /* match */\n\telse\n\t return -1; /* wrong */\n } else {\n int saw_user = 0;\n\n\tif (ctrl & PAM_DEBUG_ARG) {\n\t pam_syslog(pamh, LOG_INFO, \"error returned by dbm_fetch: %m\");\n\t}\n\n\t/* probably we should check dbm_error() here */\n\n if ((ctrl & PAM_KEY_ONLY_ARG) == 0) {\n\t dbm_close(dbm);\n return 1; /* not key_only, so no entry => no entry for the user */\n }\n\n /* now handle the key_only case */\n for (key = dbm_firstkey(dbm);\n key.dptr != NULL;\n key = dbm_nextkey(dbm)) {\n int compare;\n /* first compare the user portion (case sensitive) */\n compare = strncmp(key.dptr, user, strlen(user));\n if (compare == 0) {\n /* assume failure */\n compare = -1;\n /* if we have the divider where we expect it to be... */\n if (key.dptr[strlen(user)] == '-') {\n\t\t saw_user = 1;\n\t\t if ((size_t)key.dsize == strlen(user) + 1 + strlen(pass)) {\n\t\t if (ctrl & PAM_ICASE_ARG) {\n\t\t\t /* compare the password portion (case insensitive)*/\n compare = strncasecmp(key.dptr + strlen(user) + 1,\n pass,\n strlen(pass));\n\t\t } else {\n /* compare the password portion (case sensitive) */\n compare = strncmp(key.dptr + strlen(user) + 1,\n pass,\n strlen(pass));\n\t\t }\n\t\t }\n }\n if (compare == 0) {\n dbm_close(dbm);\n return 0; /* match */\n }\n }\n }\n dbm_close(dbm);\n\tif (saw_user)\n\t return -1; /* saw the user, but password mismatch */\n\telse\n\t return 1; /* not found */\n }\n\n /* NOT REACHED */\n return -2;\n}", "project": "linux-pam", "hash": 121873383550116916687105523985397910680, "size": 172, "commit_id": "57a1e2b274d0a6376d92ada9926e5c5741e7da20", "message": "pam_userdb: fix password hash comparison\n\nStarting with commit Linux-PAM-0-77-28-g0b3e583 that introduced hashed\npasswords support in pam_userdb, hashes are compared case-insensitively.\nThis bug leads to accepting hashes for completely different passwords in\naddition to those that should be accepted.\n\nAdditionally, commit Linux-PAM-1_1_6-13-ge2a8187 that added support for\nmodern password hashes with different lengths and settings, did not\nupdate the hash comparison accordingly, which leads to accepting\ncomputed hashes longer than stored hashes when the latter is a prefix\nof the former.\n\n* modules/pam_userdb/pam_userdb.c (user_lookup): Reject the computed\nhash whose length differs from the stored hash length.\nCompare computed and stored hashes case-sensitively.\nFixes CVE-2013-7041.\n\nBug-Debian: http://bugs.debian.org/731368", "target": 0, "dataset": "other", "idx": 307216} {"func": "entityValueInitProcessor(XML_Parser parser,\n const char *s,\n const char *end,\n const char **nextPtr)\n{\n int tok;\n const char *start = s;\n const char *next = start;\n eventPtr = start;\n\n for (;;) {\n tok = XmlPrologTok(encoding, start, end, &next);\n eventEndPtr = next;\n if (tok <= 0) {\n if (!ps_finalBuffer && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_NONE: /* start == end */\n default:\n break;\n }\n /* found end of entity value - can store it now */\n return storeEntityValue(parser, encoding, s, end);\n }\n else if (tok == XML_TOK_XML_DECL) {\n enum XML_Error result;\n result = processXmlDecl(parser, 0, start, next);\n if (result != XML_ERROR_NONE)\n return result;\n switch (ps_parsing) {\n case XML_SUSPENDED:\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n return XML_ERROR_ABORTED;\n default:\n *nextPtr = next;\n }\n /* stop scanning for text declaration - we found one */\n processor = entityValueProcessor;\n return entityValueProcessor(parser, next, end, nextPtr);\n }\n /* If we are at the end of the buffer, this would cause XmlPrologTok to\n return XML_TOK_NONE on the next call, which would then cause the\n function to exit with *nextPtr set to s - that is what we want for other\n tokens, but not for the BOM - we would rather like to skip it;\n then, when this routine is entered the next time, XmlPrologTok will\n return XML_TOK_INVALID, since the BOM is still in the buffer\n */\n else if (tok == XML_TOK_BOM && next == end && !ps_finalBuffer) {\n *nextPtr = next;\n return XML_ERROR_NONE;\n }\n start = next;\n eventPtr = start;\n }\n}", "project": "libexpat", "hash": 337998318068132835707143746781218093260, "size": 65, "commit_id": "c4bf96bb51dd2a1b0e185374362ee136fe2c9d7f", "message": "xmlparse.c: Fix external entity infinite loop bug (CVE-2017-9233)", "target": 1, "dataset": "other", "idx": 200711} {"func": "entityValueInitProcessor(XML_Parser parser,\n const char *s,\n const char *end,\n const char **nextPtr)\n{\n int tok;\n const char *start = s;\n const char *next = start;\n eventPtr = start;\n\n for (;;) {\n tok = XmlPrologTok(encoding, start, end, &next);\n eventEndPtr = next;\n if (tok <= 0) {\n if (!ps_finalBuffer && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_NONE: /* start == end */\n default:\n break;\n }\n /* found end of entity value - can store it now */\n return storeEntityValue(parser, encoding, s, end);\n }\n else if (tok == XML_TOK_XML_DECL) {\n enum XML_Error result;\n result = processXmlDecl(parser, 0, start, next);\n if (result != XML_ERROR_NONE)\n return result;\n switch (ps_parsing) {\n case XML_SUSPENDED:\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n return XML_ERROR_ABORTED;\n default:\n *nextPtr = next;\n }\n /* stop scanning for text declaration - we found one */\n processor = entityValueProcessor;\n return entityValueProcessor(parser, next, end, nextPtr);\n }\n /* If we are at the end of the buffer, this would cause XmlPrologTok to\n return XML_TOK_NONE on the next call, which would then cause the\n function to exit with *nextPtr set to s - that is what we want for other\n tokens, but not for the BOM - we would rather like to skip it;\n then, when this routine is entered the next time, XmlPrologTok will\n return XML_TOK_INVALID, since the BOM is still in the buffer\n */\n else if (tok == XML_TOK_BOM && next == end && !ps_finalBuffer) {\n *nextPtr = next;\n return XML_ERROR_NONE;\n }\n /* If we get this token, we have the start of what might be a\n normal tag, but not a declaration (i.e. it doesn't begin with\n \" 0 && phdr < H2_PHDR_NUM_ENTRIES) {\n\t\t\t/* insert a pseudo header by its index (in phdr) and value (in value) */\n\t\t\tif (fields & ((1 << phdr) | H2_PHDR_FND_NONE)) {\n\t\t\t\tif (fields & H2_PHDR_FND_NONE) {\n\t\t\t\t\t/* pseudo header field after regular headers */\n\t\t\t\t\tgoto fail;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t/* repeated pseudo header field */\n\t\t\t\t\tgoto fail;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfields |= 1 << phdr;\n\t\t\tphdr_val[phdr] = list[idx].v;\n\t\t\tcontinue;\n\t\t}\n\t\telse if (phdr != 0) {\n\t\t\t/* invalid pseudo header -- should never happen here */\n\t\t\tgoto fail;\n\t\t}\n\n\t\t/* regular header field in (name,value) */\n\t\tif (unlikely(!(fields & H2_PHDR_FND_NONE))) {\n\t\t\t/* no more pseudo-headers, time to build the request line */\n\t\t\tsl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf);\n\t\t\tif (!sl)\n\t\t\t\tgoto fail;\n\t\t\tfields |= H2_PHDR_FND_NONE;\n\t\t}\n\n\t\tif (isteq(list[idx].n, ist(\"host\")))\n\t\t\tfields |= H2_PHDR_FND_HOST;\n\n\t\tif (isteq(list[idx].n, ist(\"content-length\"))) {\n\t\t\tret = h2_parse_cont_len_header(msgf, &list[idx].v, body_len);\n\t\t\tif (ret < 0)\n\t\t\t\tgoto fail;\n\n\t\t\tsl_flags |= HTX_SL_F_CLEN;\n\t\t\tif (ret == 0)\n\t\t\t\tcontinue; // skip this duplicate\n\t\t}\n\n\t\t/* these ones are forbidden in requests (RFC7540#8.1.2.2) */\n\t\tif (isteq(list[idx].n, ist(\"connection\")) ||\n\t\t isteq(list[idx].n, ist(\"proxy-connection\")) ||\n\t\t isteq(list[idx].n, ist(\"keep-alive\")) ||\n\t\t isteq(list[idx].n, ist(\"upgrade\")) ||\n\t\t isteq(list[idx].n, ist(\"transfer-encoding\")))\n\t\t\tgoto fail;\n\n\t\tif (isteq(list[idx].n, ist(\"te\")) && !isteq(list[idx].v, ist(\"trailers\")))\n\t\t\tgoto fail;\n\n\t\t/* cookie requires special processing at the end */\n\t\tif (isteq(list[idx].n, ist(\"cookie\"))) {\n\t\t\tlist[idx].n.len = -1;\n\n\t\t\tif (ck < 0)\n\t\t\t\tck = idx;\n\t\t\telse\n\t\t\t\tlist[lck].n.len = idx;\n\n\t\t\tlck = idx;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!htx_add_header(htx, list[idx].n, list[idx].v))\n\t\t\tgoto fail;\n\t}\n\n\t/* RFC7540#8.1.2.1 mandates to reject response pseudo-headers (:status) */\n\tif (fields & H2_PHDR_FND_STAT)\n\t\tgoto fail;\n\n\t/* Let's dump the request now if not yet emitted. */\n\tif (!(fields & H2_PHDR_FND_NONE)) {\n\t\tsl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf);\n\t\tif (!sl)\n\t\t\tgoto fail;\n\t}\n\n\tif (*msgf & H2_MSGF_BODY_TUNNEL)\n\t\t*msgf &= ~(H2_MSGF_BODY|H2_MSGF_BODY_CL);\n\n\tif (!(*msgf & H2_MSGF_BODY) || ((*msgf & H2_MSGF_BODY_CL) && *body_len == 0) ||\n\t (*msgf & H2_MSGF_BODY_TUNNEL)) {\n\t\t/* Request without body or tunnel requested */\n\t\tsl_flags |= HTX_SL_F_BODYLESS;\n\t\thtx->flags |= HTX_FL_EOM;\n\t}\n\n\tif (*msgf & H2_MSGF_EXT_CONNECT) {\n\t\tif (!htx_add_header(htx, ist(\"upgrade\"), phdr_val[H2_PHDR_IDX_PROT]))\n\t\t\tgoto fail;\n\t\tif (!htx_add_header(htx, ist(\"connection\"), ist(\"upgrade\")))\n\t\t\tgoto fail;\n\t\tsl_flags |= HTX_SL_F_CONN_UPG;\n\t}\n\n\t/* update the start line with last detected header info */\n\tsl->flags |= sl_flags;\n\n\t/* complete with missing Host if needed */\n\tif ((fields & (H2_PHDR_FND_HOST|H2_PHDR_FND_AUTH)) == H2_PHDR_FND_AUTH) {\n\t\t/* missing Host field, use :authority instead */\n\t\tif (!htx_add_header(htx, ist(\"host\"), phdr_val[H2_PHDR_IDX_AUTH]))\n\t\t\tgoto fail;\n\t}\n\n\t/* now we may have to build a cookie list. We'll dump the values of all\n\t * visited headers.\n\t */\n\tif (ck >= 0) {\n\t\tuint32_t fs; // free space\n\t\tuint32_t bs; // block size\n\t\tuint32_t vl; // value len\n\t\tuint32_t tl; // total length\n\t\tstruct htx_blk *blk;\n\n\t\tblk = htx_add_header(htx, ist(\"cookie\"), list[ck].v);\n\t\tif (!blk)\n\t\t\tgoto fail;\n\n\t\ttl = list[ck].v.len;\n\t\tfs = htx_free_data_space(htx);\n\t\tbs = htx_get_blksz(blk);\n\n\t\t/* for each extra cookie, we'll extend the cookie's value and\n\t\t * insert \"; \" before the new value.\n\t\t */\n\t\tfs += tl; // first one is already counted\n\t\twhile ((ck = list[ck].n.len) >= 0) {\n\t\t\tvl = list[ck].v.len;\n\t\t\ttl += vl + 2;\n\t\t\tif (tl > fs)\n\t\t\t\tgoto fail;\n\n\t\t\thtx_change_blk_value_len(htx, blk, tl);\n\t\t\t*(char *)(htx_get_blk_ptr(htx, blk) + bs + 0) = ';';\n\t\t\t*(char *)(htx_get_blk_ptr(htx, blk) + bs + 1) = ' ';\n\t\t\tmemcpy(htx_get_blk_ptr(htx, blk) + bs + 2, list[ck].v.ptr, vl);\n\t\t\tbs += vl + 2;\n\t\t}\n\n\t}\n\n\t/* now send the end of headers marker */\n\tif (!htx_add_endof(htx, HTX_BLK_EOH))\n\t\tgoto fail;\n\n\t/* proceed to scheme-based normalization on target-URI */\n\tif (fields & H2_PHDR_FND_SCHM)\n\t\thttp_scheme_based_normalize(htx);\n\n\tret = 1;\n\treturn ret;\n\n fail:\n\treturn -1;\n}", "project": "haproxy", "hash": 15719751322204847922271508601509064692, "size": 203, "commit_id": "b5d2b9e154d78e4075db163826c5e0f6d31b2ab1", "message": "BUG/MEDIUM: h2: give :authority precedence over Host\n\nThe wording regarding Host vs :authority in RFC7540 is ambiguous as it\nsays that an intermediary must produce a host header from :authority if\nHost is missing, but, contrary to HTTP/1.1, doesn't say anything regarding\nthe possibility that Host and :authority differ, which leaves Host with\nhigher precedence there. In addition it mentions that clients should use\n:authority *instead* of Host, and that H1->H2 should use :authority only\nif the original request was in authority form. This leaves some gray\narea in the middle of the chain for fully valid H2 requests arboring a\nHost header that are forwarded to the other side where it's possible to\ndrop the Host header and use the authority only after forwarding to a\nsecond H2 layer, thus possibly seeing two different values of Host at\na different stage. There's no such issue when forwarding from H2 to H1\nas the authority is dropped only only the Host is kept.\n\nNote that the following request is sufficient to re-normalize such a\nrequest:\n\n http-request set-header host %[req.hdr(host)]\n\nThe new spec in progress (draft-ietf-httpbis-http2bis-03) addresses\nthis trouble by being a bit is stricter on these rules. It clarifies\nthat :authority must always be used instead of Host and that Host ought\nto be ignored. This is much saner as it avoids to convey two distinct\nvalues along the chain. This becomes the protocol-level equivalent of:\n\n http-request set-uri %[url]\n\nSo this patch does exactly this, which we were initially a bit reluctant\nto do initially by lack of visibility about other implementations'\nexpectations. In addition it slightly simplifies the Host header field\ncreation by always placing it first in the list of headers instead of\nlast; this could also speed up the look up a little bit.\n\nThis needs to be backported to 2.0. Non-HTX versions are safe regarding\nthis because they drop the URI during the conversion to HTTP/1.1 so\nonly Host is used and transmitted.\n\nThanks to Tim D\ufffdsterhus for reporting that one.", "target": 1, "dataset": "other", "idx": 200767} {"func": "int h2_make_htx_request(struct http_hdr *list, struct htx *htx, unsigned int *msgf, unsigned long long *body_len)\n{\n\tstruct ist phdr_val[H2_PHDR_NUM_ENTRIES];\n\tuint32_t fields; /* bit mask of H2_PHDR_FND_* */\n\tuint32_t idx;\n\tint ck, lck; /* cookie index and last cookie index */\n\tint phdr;\n\tint ret;\n\tint i;\n\tstruct htx_sl *sl = NULL;\n\tunsigned int sl_flags = 0;\n\tconst char *ctl;\n\n\tlck = ck = -1; // no cookie for now\n\tfields = 0;\n\tfor (idx = 0; list[idx].n.len != 0; idx++) {\n\t\tif (!list[idx].n.ptr) {\n\t\t\t/* this is an indexed pseudo-header */\n\t\t\tphdr = list[idx].n.len;\n\t\t}\n\t\telse {\n\t\t\t/* this can be any type of header */\n\t\t\t/* RFC7540#8.1.2: upper case not allowed in header field names.\n\t\t\t * #10.3: header names must be valid (i.e. match a token).\n\t\t\t * For pseudo-headers we check from 2nd char and for other ones\n\t\t\t * from the first char, because HTTP_IS_TOKEN() also excludes\n\t\t\t * the colon.\n\t\t\t */\n\t\t\tphdr = h2_str_to_phdr(list[idx].n);\n\n\t\t\tfor (i = !!phdr; i < list[idx].n.len; i++)\n\t\t\t\tif ((uint8_t)(list[idx].n.ptr[i] - 'A') < 'Z' - 'A' || !HTTP_IS_TOKEN(list[idx].n.ptr[i]))\n\t\t\t\t\tgoto fail;\n\t\t}\n\n\t\t/* RFC7540#10.3: intermediaries forwarding to HTTP/1 must take care of\n\t\t * rejecting NUL, CR and LF characters.\n\t\t */\n\t\tctl = ist_find_ctl(list[idx].v);\n\t\tif (unlikely(ctl) && has_forbidden_char(list[idx].v, ctl))\n\t\t\tgoto fail;\n\n\t\tif (phdr > 0 && phdr < H2_PHDR_NUM_ENTRIES) {\n\t\t\t/* insert a pseudo header by its index (in phdr) and value (in value) */\n\t\t\tif (fields & ((1 << phdr) | H2_PHDR_FND_NONE)) {\n\t\t\t\tif (fields & H2_PHDR_FND_NONE) {\n\t\t\t\t\t/* pseudo header field after regular headers */\n\t\t\t\t\tgoto fail;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t/* repeated pseudo header field */\n\t\t\t\t\tgoto fail;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfields |= 1 << phdr;\n\t\t\tphdr_val[phdr] = list[idx].v;\n\t\t\tcontinue;\n\t\t}\n\t\telse if (phdr != 0) {\n\t\t\t/* invalid pseudo header -- should never happen here */\n\t\t\tgoto fail;\n\t\t}\n\n\t\t/* regular header field in (name,value) */\n\t\tif (unlikely(!(fields & H2_PHDR_FND_NONE))) {\n\t\t\t/* no more pseudo-headers, time to build the request line */\n\t\t\tsl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf);\n\t\t\tif (!sl)\n\t\t\t\tgoto fail;\n\t\t\tfields |= H2_PHDR_FND_NONE;\n\n\t\t\t/* http2bis draft recommends to drop Host in favor of :authority when\n\t\t\t * the latter is present. This is required to make sure there is no\n\t\t\t * discrepancy between the authority and the host header, especially\n\t\t\t * since routing rules usually involve Host. Here we already know if\n\t\t\t * :authority was found so we can emit it right now and mark the host\n\t\t\t * as filled so that it's skipped later.\n\t\t\t */\n\t\t\tif (fields & H2_PHDR_FND_AUTH) {\n\t\t\t\tif (!htx_add_header(htx, ist(\"host\"), phdr_val[H2_PHDR_IDX_AUTH]))\n\t\t\t\t\tgoto fail;\n\t\t\t\tfields |= H2_PHDR_FND_HOST;\n\t\t\t}\n\t\t}\n\n\t\tif (isteq(list[idx].n, ist(\"host\"))) {\n\t\t\tif (fields & H2_PHDR_FND_HOST)\n\t\t\t\tcontinue;\n\n\t\t\tfields |= H2_PHDR_FND_HOST;\n\t\t}\n\n\t\tif (isteq(list[idx].n, ist(\"content-length\"))) {\n\t\t\tret = h2_parse_cont_len_header(msgf, &list[idx].v, body_len);\n\t\t\tif (ret < 0)\n\t\t\t\tgoto fail;\n\n\t\t\tsl_flags |= HTX_SL_F_CLEN;\n\t\t\tif (ret == 0)\n\t\t\t\tcontinue; // skip this duplicate\n\t\t}\n\n\t\t/* these ones are forbidden in requests (RFC7540#8.1.2.2) */\n\t\tif (isteq(list[idx].n, ist(\"connection\")) ||\n\t\t isteq(list[idx].n, ist(\"proxy-connection\")) ||\n\t\t isteq(list[idx].n, ist(\"keep-alive\")) ||\n\t\t isteq(list[idx].n, ist(\"upgrade\")) ||\n\t\t isteq(list[idx].n, ist(\"transfer-encoding\")))\n\t\t\tgoto fail;\n\n\t\tif (isteq(list[idx].n, ist(\"te\")) && !isteq(list[idx].v, ist(\"trailers\")))\n\t\t\tgoto fail;\n\n\t\t/* cookie requires special processing at the end */\n\t\tif (isteq(list[idx].n, ist(\"cookie\"))) {\n\t\t\tlist[idx].n.len = -1;\n\n\t\t\tif (ck < 0)\n\t\t\t\tck = idx;\n\t\t\telse\n\t\t\t\tlist[lck].n.len = idx;\n\n\t\t\tlck = idx;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!htx_add_header(htx, list[idx].n, list[idx].v))\n\t\t\tgoto fail;\n\t}\n\n\t/* RFC7540#8.1.2.1 mandates to reject response pseudo-headers (:status) */\n\tif (fields & H2_PHDR_FND_STAT)\n\t\tgoto fail;\n\n\t/* Let's dump the request now if not yet emitted. */\n\tif (!(fields & H2_PHDR_FND_NONE)) {\n\t\tsl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf);\n\t\tif (!sl)\n\t\t\tgoto fail;\n\t}\n\n\tif (*msgf & H2_MSGF_BODY_TUNNEL)\n\t\t*msgf &= ~(H2_MSGF_BODY|H2_MSGF_BODY_CL);\n\n\tif (!(*msgf & H2_MSGF_BODY) || ((*msgf & H2_MSGF_BODY_CL) && *body_len == 0) ||\n\t (*msgf & H2_MSGF_BODY_TUNNEL)) {\n\t\t/* Request without body or tunnel requested */\n\t\tsl_flags |= HTX_SL_F_BODYLESS;\n\t\thtx->flags |= HTX_FL_EOM;\n\t}\n\n\tif (*msgf & H2_MSGF_EXT_CONNECT) {\n\t\tif (!htx_add_header(htx, ist(\"upgrade\"), phdr_val[H2_PHDR_IDX_PROT]))\n\t\t\tgoto fail;\n\t\tif (!htx_add_header(htx, ist(\"connection\"), ist(\"upgrade\")))\n\t\t\tgoto fail;\n\t\tsl_flags |= HTX_SL_F_CONN_UPG;\n\t}\n\n\t/* update the start line with last detected header info */\n\tsl->flags |= sl_flags;\n\n\t/* complete with missing Host if needed (we may validate this test if\n\t * no regular header was found).\n\t */\n\tif ((fields & (H2_PHDR_FND_HOST|H2_PHDR_FND_AUTH)) == H2_PHDR_FND_AUTH) {\n\t\t/* missing Host field, use :authority instead */\n\t\tif (!htx_add_header(htx, ist(\"host\"), phdr_val[H2_PHDR_IDX_AUTH]))\n\t\t\tgoto fail;\n\t}\n\n\t/* now we may have to build a cookie list. We'll dump the values of all\n\t * visited headers.\n\t */\n\tif (ck >= 0) {\n\t\tuint32_t fs; // free space\n\t\tuint32_t bs; // block size\n\t\tuint32_t vl; // value len\n\t\tuint32_t tl; // total length\n\t\tstruct htx_blk *blk;\n\n\t\tblk = htx_add_header(htx, ist(\"cookie\"), list[ck].v);\n\t\tif (!blk)\n\t\t\tgoto fail;\n\n\t\ttl = list[ck].v.len;\n\t\tfs = htx_free_data_space(htx);\n\t\tbs = htx_get_blksz(blk);\n\n\t\t/* for each extra cookie, we'll extend the cookie's value and\n\t\t * insert \"; \" before the new value.\n\t\t */\n\t\tfs += tl; // first one is already counted\n\t\twhile ((ck = list[ck].n.len) >= 0) {\n\t\t\tvl = list[ck].v.len;\n\t\t\ttl += vl + 2;\n\t\t\tif (tl > fs)\n\t\t\t\tgoto fail;\n\n\t\t\thtx_change_blk_value_len(htx, blk, tl);\n\t\t\t*(char *)(htx_get_blk_ptr(htx, blk) + bs + 0) = ';';\n\t\t\t*(char *)(htx_get_blk_ptr(htx, blk) + bs + 1) = ' ';\n\t\t\tmemcpy(htx_get_blk_ptr(htx, blk) + bs + 2, list[ck].v.ptr, vl);\n\t\t\tbs += vl + 2;\n\t\t}\n\n\t}\n\n\t/* now send the end of headers marker */\n\tif (!htx_add_endof(htx, HTX_BLK_EOH))\n\t\tgoto fail;\n\n\t/* proceed to scheme-based normalization on target-URI */\n\tif (fields & H2_PHDR_FND_SCHM)\n\t\thttp_scheme_based_normalize(htx);\n\n\tret = 1;\n\treturn ret;\n\n fail:\n\treturn -1;\n}", "project": "haproxy", "hash": 266045474504989259384704744141280674190, "size": 222, "commit_id": "b5d2b9e154d78e4075db163826c5e0f6d31b2ab1", "message": "BUG/MEDIUM: h2: give :authority precedence over Host\n\nThe wording regarding Host vs :authority in RFC7540 is ambiguous as it\nsays that an intermediary must produce a host header from :authority if\nHost is missing, but, contrary to HTTP/1.1, doesn't say anything regarding\nthe possibility that Host and :authority differ, which leaves Host with\nhigher precedence there. In addition it mentions that clients should use\n:authority *instead* of Host, and that H1->H2 should use :authority only\nif the original request was in authority form. This leaves some gray\narea in the middle of the chain for fully valid H2 requests arboring a\nHost header that are forwarded to the other side where it's possible to\ndrop the Host header and use the authority only after forwarding to a\nsecond H2 layer, thus possibly seeing two different values of Host at\na different stage. There's no such issue when forwarding from H2 to H1\nas the authority is dropped only only the Host is kept.\n\nNote that the following request is sufficient to re-normalize such a\nrequest:\n\n http-request set-header host %[req.hdr(host)]\n\nThe new spec in progress (draft-ietf-httpbis-http2bis-03) addresses\nthis trouble by being a bit is stricter on these rules. It clarifies\nthat :authority must always be used instead of Host and that Host ought\nto be ignored. This is much saner as it avoids to convey two distinct\nvalues along the chain. This becomes the protocol-level equivalent of:\n\n http-request set-uri %[url]\n\nSo this patch does exactly this, which we were initially a bit reluctant\nto do initially by lack of visibility about other implementations'\nexpectations. In addition it slightly simplifies the Host header field\ncreation by always placing it first in the list of headers instead of\nlast; this could also speed up the look up a little bit.\n\nThis needs to be backported to 2.0. Non-HTX versions are safe regarding\nthis because they drop the URI during the conversion to HTTP/1.1 so\nonly Host is used and transmitted.\n\nThanks to Tim D\ufffdsterhus for reporting that one.", "target": 0, "dataset": "other", "idx": 309702} {"func": "static void create_power_zone_common_attributes(\n\t\t\t\t\tstruct powercap_zone *power_zone)\n{\n\tint count = 0;\n\n\tpower_zone->zone_dev_attrs[count++] = &dev_attr_name.attr;\n\tif (power_zone->ops->get_max_energy_range_uj)\n\t\tpower_zone->zone_dev_attrs[count++] =\n\t\t\t\t\t&dev_attr_max_energy_range_uj.attr;\n\tif (power_zone->ops->get_energy_uj) {\n\t\tif (power_zone->ops->reset_energy_uj)\n\t\t\tdev_attr_energy_uj.attr.mode = S_IWUSR | S_IRUGO;\n\t\telse\n\t\t\tdev_attr_energy_uj.attr.mode = S_IRUGO;\n\t\tpower_zone->zone_dev_attrs[count++] =\n\t\t\t\t\t&dev_attr_energy_uj.attr;\n\t}\n\tif (power_zone->ops->get_power_uw)\n\t\tpower_zone->zone_dev_attrs[count++] =\n\t\t\t\t\t&dev_attr_power_uw.attr;\n\tif (power_zone->ops->get_max_power_range_uw)\n\t\tpower_zone->zone_dev_attrs[count++] =\n\t\t\t\t\t&dev_attr_max_power_range_uw.attr;\n\tpower_zone->zone_dev_attrs[count] = NULL;\n\tpower_zone->zone_attr_count = count;\n}", "project": "linux", "hash": 52467361752463996065834465628288893561, "size": 26, "commit_id": "949dd0104c496fa7c14991a23c03c62e44637e71", "message": "powercap: restrict energy meter to root access\n\nRemove non-privileged user access to power data contained in\n/sys/class/powercap/intel-rapl*/*/energy_uj\n\nNon-privileged users currently have read access to power data and can\nuse this data to form a security attack. Some privileged\ndrivers/applications need read access to this data, but don't expose it\nto non-privileged users.\n\nFor example, thermald uses this data to ensure that power management\nworks correctly. Thus removing non-privileged access is preferred over\ncompletely disabling this power reporting capability with\nCONFIG_INTEL_RAPL=n.\n\nFixes: 95677a9a3847 (\"PowerCap: Fix mode for energy counter\")\n\nSigned-off-by: Len Brown \nCc: stable@vger.kernel.org", "target": 1, "dataset": "other", "idx": 200832} {"func": "static void create_power_zone_common_attributes(\n\t\t\t\t\tstruct powercap_zone *power_zone)\n{\n\tint count = 0;\n\n\tpower_zone->zone_dev_attrs[count++] = &dev_attr_name.attr;\n\tif (power_zone->ops->get_max_energy_range_uj)\n\t\tpower_zone->zone_dev_attrs[count++] =\n\t\t\t\t\t&dev_attr_max_energy_range_uj.attr;\n\tif (power_zone->ops->get_energy_uj) {\n\t\tif (power_zone->ops->reset_energy_uj)\n\t\t\tdev_attr_energy_uj.attr.mode = S_IWUSR | S_IRUSR;\n\t\telse\n\t\t\tdev_attr_energy_uj.attr.mode = S_IRUSR;\n\t\tpower_zone->zone_dev_attrs[count++] =\n\t\t\t\t\t&dev_attr_energy_uj.attr;\n\t}\n\tif (power_zone->ops->get_power_uw)\n\t\tpower_zone->zone_dev_attrs[count++] =\n\t\t\t\t\t&dev_attr_power_uw.attr;\n\tif (power_zone->ops->get_max_power_range_uw)\n\t\tpower_zone->zone_dev_attrs[count++] =\n\t\t\t\t\t&dev_attr_max_power_range_uw.attr;\n\tpower_zone->zone_dev_attrs[count] = NULL;\n\tpower_zone->zone_attr_count = count;\n}", "project": "linux", "hash": 212688182015870014729078339472072838837, "size": 26, "commit_id": "949dd0104c496fa7c14991a23c03c62e44637e71", "message": "powercap: restrict energy meter to root access\n\nRemove non-privileged user access to power data contained in\n/sys/class/powercap/intel-rapl*/*/energy_uj\n\nNon-privileged users currently have read access to power data and can\nuse this data to form a security attack. Some privileged\ndrivers/applications need read access to this data, but don't expose it\nto non-privileged users.\n\nFor example, thermald uses this data to ensure that power management\nworks correctly. Thus removing non-privileged access is preferred over\ncompletely disabling this power reporting capability with\nCONFIG_INTEL_RAPL=n.\n\nFixes: 95677a9a3847 (\"PowerCap: Fix mode for energy counter\")\n\nSigned-off-by: Len Brown \nCc: stable@vger.kernel.org", "target": 0, "dataset": "other", "idx": 310345} {"func": "DLLEXPORT int DLLCALL tjDecompressToYUVPlanes(tjhandle handle,\n\tconst unsigned char *jpegBuf, unsigned long jpegSize,\n\tunsigned char **dstPlanes, int width, int *strides, int height, int flags)\n{\n\tint i, sfi, row, retval=0; JSAMPROW *outbuf[MAX_COMPONENTS];\n\tint jpegwidth, jpegheight, jpegSubsamp, scaledw, scaledh;\n\tint pw[MAX_COMPONENTS], ph[MAX_COMPONENTS], iw[MAX_COMPONENTS],\n\t\ttmpbufsize=0, usetmpbuf=0, th[MAX_COMPONENTS];\n\tJSAMPLE *_tmpbuf=NULL, *ptr; JSAMPROW *tmpbuf[MAX_COMPONENTS];\n\tint dctsize;\n\n\tgetdinstance(handle);\n\n\tfor(i=0; iinit&DECOMPRESS)==0)\n\t\t_throw(\"tjDecompressToYUVPlanes(): Instance has not been initialized for decompression\");\n\n\tif(jpegBuf==NULL || jpegSize<=0 || !dstPlanes || !dstPlanes[0] || width<0\n\t\t|| height<0)\n\t\t_throw(\"tjDecompressToYUVPlanes(): Invalid argument\");\n\n#ifndef NO_PUTENV\n\tif(flags&TJFLAG_FORCEMMX) putenv(\"JSIMD_FORCEMMX=1\");\n\telse if(flags&TJFLAG_FORCESSE) putenv(\"JSIMD_FORCESSE=1\");\n\telse if(flags&TJFLAG_FORCESSE2) putenv(\"JSIMD_FORCESSE2=1\");\n#endif\n\n\tif(setjmp(this->jerr.setjmp_buffer))\n\t{\n\t\t/* If we get here, the JPEG code has signaled an error. */\n\t\tretval=-1; goto bailout;\n\t}\n\n\tif(!this->headerRead)\n\t{\n\t\tjpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);\n\t\tjpeg_read_header(dinfo, TRUE);\n\t}\n\tthis->headerRead=0;\n\tjpegSubsamp=getSubsamp(dinfo);\n\tif(jpegSubsamp<0)\n\t\t_throw(\"tjDecompressToYUVPlanes(): Could not determine subsampling type for JPEG image\");\n\n\tif(jpegSubsamp!=TJSAMP_GRAY && (!dstPlanes[1] || !dstPlanes[2]))\n\t\t_throw(\"tjDecompressToYUVPlanes(): Invalid argument\");\n\n\tjpegwidth=dinfo->image_width; jpegheight=dinfo->image_height;\n\tif(width==0) width=jpegwidth;\n\tif(height==0) height=jpegheight;\n\tfor(i=0; i=NUMSF)\n\t\t_throw(\"tjDecompressToYUVPlanes(): Could not scale down to desired image dimensions\");\n\tif(dinfo->num_components>3)\n\t\t_throw(\"tjDecompressToYUVPlanes(): JPEG image must have 3 or fewer components\");\n\n\twidth=scaledw; height=scaledh;\n\tdinfo->scale_num=sf[i].num;\n\tdinfo->scale_denom=sf[i].denom;\n\tsfi=i;\n\tjpeg_calc_output_dimensions(dinfo);\n\n\tdctsize=DCTSIZE*sf[sfi].num/sf[sfi].denom;\n\n\tfor(i=0; inum_components; i++)\n\t{\n\t\tjpeg_component_info *compptr=&dinfo->comp_info[i];\n\t\tint ih;\n\t\tiw[i]=compptr->width_in_blocks*dctsize;\n\t\tih=compptr->height_in_blocks*dctsize;\n\t\tpw[i]=PAD(dinfo->output_width, dinfo->max_h_samp_factor)\n\t\t\t*compptr->h_samp_factor/dinfo->max_h_samp_factor;\n\t\tph[i]=PAD(dinfo->output_height, dinfo->max_v_samp_factor)\n\t\t\t*compptr->v_samp_factor/dinfo->max_v_samp_factor;\n\t\tif(iw[i]!=pw[i] || ih!=ph[i]) usetmpbuf=1;\n\t\tth[i]=compptr->v_samp_factor*dctsize;\n\t\ttmpbufsize+=iw[i]*th[i];\n\t\tif((outbuf[i]=(JSAMPROW *)malloc(sizeof(JSAMPROW)*ph[i]))==NULL)\n\t\t\t_throw(\"tjDecompressToYUVPlanes(): Memory allocation failure\");\n\t\tptr=dstPlanes[i];\n\t\tfor(row=0; rownum_components; i++)\n\t\t{\n\t\t\tif((tmpbuf[i]=(JSAMPROW *)malloc(sizeof(JSAMPROW)*th[i]))==NULL)\n\t\t\t\t_throw(\"tjDecompressToYUVPlanes(): Memory allocation failure\");\n\t\t\tfor(row=0; rowjerr.setjmp_buffer))\n\t{\n\t\t/* If we get here, the JPEG code has signaled an error. */\n\t\tretval=-1; goto bailout;\n\t}\n\n\tif(flags&TJFLAG_FASTUPSAMPLE) dinfo->do_fancy_upsampling=FALSE;\n\tif(flags&TJFLAG_FASTDCT) dinfo->dct_method=JDCT_FASTEST;\n\tdinfo->raw_data_out=TRUE;\n\n\tjpeg_start_decompress(dinfo);\n\tfor(row=0; row<(int)dinfo->output_height;\n\t\trow+=dinfo->max_v_samp_factor*dinfo->_min_DCT_scaled_size)\n\t{\n\t\tJSAMPARRAY yuvptr[MAX_COMPONENTS];\n\t\tint crow[MAX_COMPONENTS];\n\t\tfor(i=0; inum_components; i++)\n\t\t{\n\t\t\tjpeg_component_info *compptr=&dinfo->comp_info[i];\n\t\t\tif(jpegSubsamp==TJ_420)\n\t\t\t{\n\t\t\t\t/* When 4:2:0 subsampling is used with IDCT scaling, libjpeg will try\n\t\t\t\t to be clever and use the IDCT to perform upsampling on the U and V\n\t\t\t\t planes. For instance, if the output image is to be scaled by 1/2\n\t\t\t\t relative to the JPEG image, then the scaling factor and upsampling\n\t\t\t\t effectively cancel each other, so a normal 8x8 IDCT can be used.\n\t\t\t\t However, this is not desirable when using the decompress-to-YUV\n\t\t\t\t functionality in TurboJPEG, since we want to output the U and V\n\t\t\t\t planes in their subsampled form. Thus, we have to override some\n\t\t\t\t internal libjpeg parameters to force it to use the \"scaled\" IDCT\n\t\t\t\t functions on the U and V planes. */\n\t\t\t\tcompptr->_DCT_scaled_size=dctsize;\n\t\t\t\tcompptr->MCU_sample_width=tjMCUWidth[jpegSubsamp]*\n\t\t\t\t\tsf[sfi].num/sf[sfi].denom*\n\t\t\t\t\tcompptr->v_samp_factor/dinfo->max_v_samp_factor;\n\t\t\t\tdinfo->idct->inverse_DCT[i] = dinfo->idct->inverse_DCT[0];\n\t\t\t}\n\t\t\tcrow[i]=row*compptr->v_samp_factor/dinfo->max_v_samp_factor;\n\t\t\tif(usetmpbuf) yuvptr[i]=tmpbuf[i];\n\t\t\telse yuvptr[i]=&outbuf[i][crow[i]];\n\t\t}\n\t\tjpeg_read_raw_data(dinfo, yuvptr,\n\t\t\tdinfo->max_v_samp_factor*dinfo->_min_DCT_scaled_size);\n\t\tif(usetmpbuf)\n\t\t{\n\t\t\tint j;\n\t\t\tfor(i=0; inum_components; i++)\n\t\t\t{\n\t\t\t\tfor(j=0; jglobal_state>DSTATE_START) jpeg_abort_decompress(dinfo);\n\tfor(i=0; ijerr.warning) retval=-1;\n\treturn retval;\n}", "project": "libjpeg-turbo", "hash": 169277103039170376241754039304908975481, "size": 180, "commit_id": "dab6be4cfb2f9307b5378d2d1dc74d9080383dc2", "message": "tjDecompressToYUV*(): Fix OOB write/double free\n\n... when attempting to decompress grayscale JPEG images with sampling\nfactors != 1.\n\nFixes #387", "target": 1, "dataset": "other", "idx": 200866} {"func": "DLLEXPORT int DLLCALL tjDecompressToYUVPlanes(tjhandle handle,\n\tconst unsigned char *jpegBuf, unsigned long jpegSize,\n\tunsigned char **dstPlanes, int width, int *strides, int height, int flags)\n{\n\tint i, sfi, row, retval=0; JSAMPROW *outbuf[MAX_COMPONENTS];\n\tint jpegwidth, jpegheight, jpegSubsamp, scaledw, scaledh;\n\tint pw[MAX_COMPONENTS], ph[MAX_COMPONENTS], iw[MAX_COMPONENTS],\n\t\ttmpbufsize=0, usetmpbuf=0, th[MAX_COMPONENTS];\n\tJSAMPLE *_tmpbuf=NULL, *ptr; JSAMPROW *tmpbuf[MAX_COMPONENTS];\n\tint dctsize;\n\n\tgetdinstance(handle);\n\n\tfor(i=0; iinit&DECOMPRESS)==0)\n\t\t_throw(\"tjDecompressToYUVPlanes(): Instance has not been initialized for decompression\");\n\n\tif(jpegBuf==NULL || jpegSize<=0 || !dstPlanes || !dstPlanes[0] || width<0\n\t\t|| height<0)\n\t\t_throw(\"tjDecompressToYUVPlanes(): Invalid argument\");\n\n#ifndef NO_PUTENV\n\tif(flags&TJFLAG_FORCEMMX) putenv(\"JSIMD_FORCEMMX=1\");\n\telse if(flags&TJFLAG_FORCESSE) putenv(\"JSIMD_FORCESSE=1\");\n\telse if(flags&TJFLAG_FORCESSE2) putenv(\"JSIMD_FORCESSE2=1\");\n#endif\n\n\tif(setjmp(this->jerr.setjmp_buffer))\n\t{\n\t\t/* If we get here, the JPEG code has signaled an error. */\n\t\tretval=-1; goto bailout;\n\t}\n\n\tif(!this->headerRead)\n\t{\n\t\tjpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);\n\t\tjpeg_read_header(dinfo, TRUE);\n\t}\n\tthis->headerRead=0;\n\tjpegSubsamp=getSubsamp(dinfo);\n\tif(jpegSubsamp<0)\n\t\t_throw(\"tjDecompressToYUVPlanes(): Could not determine subsampling type for JPEG image\");\n\n\tif(jpegSubsamp!=TJSAMP_GRAY && (!dstPlanes[1] || !dstPlanes[2]))\n\t\t_throw(\"tjDecompressToYUVPlanes(): Invalid argument\");\n\n\tjpegwidth=dinfo->image_width; jpegheight=dinfo->image_height;\n\tif(width==0) width=jpegwidth;\n\tif(height==0) height=jpegheight;\n\tfor(i=0; i=NUMSF)\n\t\t_throw(\"tjDecompressToYUVPlanes(): Could not scale down to desired image dimensions\");\n\tif(dinfo->num_components>3)\n\t\t_throw(\"tjDecompressToYUVPlanes(): JPEG image must have 3 or fewer components\");\n\n\twidth=scaledw; height=scaledh;\n\tdinfo->scale_num=sf[i].num;\n\tdinfo->scale_denom=sf[i].denom;\n\tsfi=i;\n\tjpeg_calc_output_dimensions(dinfo);\n\n\tdctsize=DCTSIZE*sf[sfi].num/sf[sfi].denom;\n\n\tfor(i=0; inum_components; i++)\n\t{\n\t\tjpeg_component_info *compptr=&dinfo->comp_info[i];\n\t\tint ih;\n\t\tiw[i]=compptr->width_in_blocks*dctsize;\n\t\tih=compptr->height_in_blocks*dctsize;\n\t\tpw[i]=tjPlaneWidth(i, dinfo->output_width, jpegSubsamp);\n\t\tph[i]=tjPlaneHeight(i, dinfo->output_height, jpegSubsamp);\n\t\tif(iw[i]!=pw[i] || ih!=ph[i]) usetmpbuf=1;\n\t\tth[i]=compptr->v_samp_factor*dctsize;\n\t\ttmpbufsize+=iw[i]*th[i];\n\t\tif((outbuf[i]=(JSAMPROW *)malloc(sizeof(JSAMPROW)*ph[i]))==NULL)\n\t\t\t_throw(\"tjDecompressToYUVPlanes(): Memory allocation failure\");\n\t\tptr=dstPlanes[i];\n\t\tfor(row=0; rownum_components; i++)\n\t\t{\n\t\t\tif((tmpbuf[i]=(JSAMPROW *)malloc(sizeof(JSAMPROW)*th[i]))==NULL)\n\t\t\t\t_throw(\"tjDecompressToYUVPlanes(): Memory allocation failure\");\n\t\t\tfor(row=0; rowjerr.setjmp_buffer))\n\t{\n\t\t/* If we get here, the JPEG code has signaled an error. */\n\t\tretval=-1; goto bailout;\n\t}\n\n\tif(flags&TJFLAG_FASTUPSAMPLE) dinfo->do_fancy_upsampling=FALSE;\n\tif(flags&TJFLAG_FASTDCT) dinfo->dct_method=JDCT_FASTEST;\n\tdinfo->raw_data_out=TRUE;\n\n\tjpeg_start_decompress(dinfo);\n\tfor(row=0; row<(int)dinfo->output_height;\n\t\trow+=dinfo->max_v_samp_factor*dinfo->_min_DCT_scaled_size)\n\t{\n\t\tJSAMPARRAY yuvptr[MAX_COMPONENTS];\n\t\tint crow[MAX_COMPONENTS];\n\t\tfor(i=0; inum_components; i++)\n\t\t{\n\t\t\tjpeg_component_info *compptr=&dinfo->comp_info[i];\n\t\t\tif(jpegSubsamp==TJ_420)\n\t\t\t{\n\t\t\t\t/* When 4:2:0 subsampling is used with IDCT scaling, libjpeg will try\n\t\t\t\t to be clever and use the IDCT to perform upsampling on the U and V\n\t\t\t\t planes. For instance, if the output image is to be scaled by 1/2\n\t\t\t\t relative to the JPEG image, then the scaling factor and upsampling\n\t\t\t\t effectively cancel each other, so a normal 8x8 IDCT can be used.\n\t\t\t\t However, this is not desirable when using the decompress-to-YUV\n\t\t\t\t functionality in TurboJPEG, since we want to output the U and V\n\t\t\t\t planes in their subsampled form. Thus, we have to override some\n\t\t\t\t internal libjpeg parameters to force it to use the \"scaled\" IDCT\n\t\t\t\t functions on the U and V planes. */\n\t\t\t\tcompptr->_DCT_scaled_size=dctsize;\n\t\t\t\tcompptr->MCU_sample_width=tjMCUWidth[jpegSubsamp]*\n\t\t\t\t\tsf[sfi].num/sf[sfi].denom*\n\t\t\t\t\tcompptr->v_samp_factor/dinfo->max_v_samp_factor;\n\t\t\t\tdinfo->idct->inverse_DCT[i] = dinfo->idct->inverse_DCT[0];\n\t\t\t}\n\t\t\tcrow[i]=row*compptr->v_samp_factor/dinfo->max_v_samp_factor;\n\t\t\tif(usetmpbuf) yuvptr[i]=tmpbuf[i];\n\t\t\telse yuvptr[i]=&outbuf[i][crow[i]];\n\t\t}\n\t\tjpeg_read_raw_data(dinfo, yuvptr,\n\t\t\tdinfo->max_v_samp_factor*dinfo->_min_DCT_scaled_size);\n\t\tif(usetmpbuf)\n\t\t{\n\t\t\tint j;\n\t\t\tfor(i=0; inum_components; i++)\n\t\t\t{\n\t\t\t\tfor(j=0; jglobal_state>DSTATE_START) jpeg_abort_decompress(dinfo);\n\tfor(i=0; ijerr.warning) retval=-1;\n\treturn retval;\n}", "project": "libjpeg-turbo", "hash": 117971814043960851220573612576267403876, "size": 178, "commit_id": "dab6be4cfb2f9307b5378d2d1dc74d9080383dc2", "message": "tjDecompressToYUV*(): Fix OOB write/double free\n\n... when attempting to decompress grayscale JPEG images with sampling\nfactors != 1.\n\nFixes #387", "target": 0, "dataset": "other", "idx": 311112} {"func": "xfs_dinode_verify(\n\tstruct xfs_mount\t*mp,\n\txfs_ino_t\t\tino,\n\tstruct xfs_dinode\t*dip)\n{\n\tuint16_t\t\tmode;\n\tuint16_t\t\tflags;\n\tuint64_t\t\tflags2;\n\tuint64_t\t\tdi_size;\n\n\tif (dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC))\n\t\treturn __this_address;\n\n\t/* Verify v3 integrity information first */\n\tif (dip->di_version >= 3) {\n\t\tif (!xfs_sb_version_hascrc(&mp->m_sb))\n\t\t\treturn __this_address;\n\t\tif (!xfs_verify_cksum((char *)dip, mp->m_sb.sb_inodesize,\n\t\t\t\t XFS_DINODE_CRC_OFF))\n\t\t\treturn __this_address;\n\t\tif (be64_to_cpu(dip->di_ino) != ino)\n\t\t\treturn __this_address;\n\t\tif (!uuid_equal(&dip->di_uuid, &mp->m_sb.sb_meta_uuid))\n\t\t\treturn __this_address;\n\t}\n\n\t/* don't allow invalid i_size */\n\tdi_size = be64_to_cpu(dip->di_size);\n\tif (di_size & (1ULL << 63))\n\t\treturn __this_address;\n\n\tmode = be16_to_cpu(dip->di_mode);\n\tif (mode && xfs_mode_to_ftype(mode) == XFS_DIR3_FT_UNKNOWN)\n\t\treturn __this_address;\n\n\t/* No zero-length symlinks/dirs. */\n\tif ((S_ISLNK(mode) || S_ISDIR(mode)) && di_size == 0)\n\t\treturn __this_address;\n\n\t/* Fork checks carried over from xfs_iformat_fork */\n\tif (mode &&\n\t be32_to_cpu(dip->di_nextents) + be16_to_cpu(dip->di_anextents) >\n\t\t\tbe64_to_cpu(dip->di_nblocks))\n\t\treturn __this_address;\n\n\tif (mode && XFS_DFORK_BOFF(dip) > mp->m_sb.sb_inodesize)\n\t\treturn __this_address;\n\n\tflags = be16_to_cpu(dip->di_flags);\n\n\tif (mode && (flags & XFS_DIFLAG_REALTIME) && !mp->m_rtdev_targp)\n\t\treturn __this_address;\n\n\t/* Do we have appropriate data fork formats for the mode? */\n\tswitch (mode & S_IFMT) {\n\tcase S_IFIFO:\n\tcase S_IFCHR:\n\tcase S_IFBLK:\n\tcase S_IFSOCK:\n\t\tif (dip->di_format != XFS_DINODE_FMT_DEV)\n\t\t\treturn __this_address;\n\t\tbreak;\n\tcase S_IFREG:\n\tcase S_IFLNK:\n\tcase S_IFDIR:\n\t\tswitch (dip->di_format) {\n\t\tcase XFS_DINODE_FMT_LOCAL:\n\t\t\t/*\n\t\t\t * no local regular files yet\n\t\t\t */\n\t\t\tif (S_ISREG(mode))\n\t\t\t\treturn __this_address;\n\t\t\tif (di_size > XFS_DFORK_DSIZE(dip, mp))\n\t\t\t\treturn __this_address;\n\t\t\t/* fall through */\n\t\tcase XFS_DINODE_FMT_EXTENTS:\n\t\tcase XFS_DINODE_FMT_BTREE:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn __this_address;\n\t\t}\n\t\tbreak;\n\tcase 0:\n\t\t/* Uninitialized inode ok. */\n\t\tbreak;\n\tdefault:\n\t\treturn __this_address;\n\t}\n\n\tif (XFS_DFORK_Q(dip)) {\n\t\tswitch (dip->di_aformat) {\n\t\tcase XFS_DINODE_FMT_LOCAL:\n\t\tcase XFS_DINODE_FMT_EXTENTS:\n\t\tcase XFS_DINODE_FMT_BTREE:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn __this_address;\n\t\t}\n\t}\n\n\t/* only version 3 or greater inodes are extensively verified here */\n\tif (dip->di_version < 3)\n\t\treturn NULL;\n\n\tflags2 = be64_to_cpu(dip->di_flags2);\n\n\t/* don't allow reflink/cowextsize if we don't have reflink */\n\tif ((flags2 & (XFS_DIFLAG2_REFLINK | XFS_DIFLAG2_COWEXTSIZE)) &&\n !xfs_sb_version_hasreflink(&mp->m_sb))\n\t\treturn __this_address;\n\n\t/* only regular files get reflink */\n\tif ((flags2 & XFS_DIFLAG2_REFLINK) && (mode & S_IFMT) != S_IFREG)\n\t\treturn __this_address;\n\n\t/* don't let reflink and realtime mix */\n\tif ((flags2 & XFS_DIFLAG2_REFLINK) && (flags & XFS_DIFLAG_REALTIME))\n\t\treturn __this_address;\n\n\t/* don't let reflink and dax mix */\n\tif ((flags2 & XFS_DIFLAG2_REFLINK) && (flags2 & XFS_DIFLAG2_DAX))\n\t\treturn __this_address;\n\n\treturn NULL;\n}", "project": "linux", "hash": 101398170972394773795376226616025225850, "size": 125, "commit_id": "b42db0860e13067fcc7cbfba3966c9e652668bbc", "message": "xfs: enhance dinode verifier\n\nAdd several more validations to xfs_dinode_verify:\n\n- For LOCAL data fork formats, di_nextents must be 0.\n- For LOCAL attr fork formats, di_anextents must be 0.\n- For inodes with no attr fork offset,\n - format must be XFS_DINODE_FMT_EXTENTS if set at all\n - di_anextents must be 0.\n\nThanks to dchinner for pointing out a couple related checks I had\nforgotten to add.\n\nSigned-off-by: Eric Sandeen \nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199377\nReviewed-by: Darrick J. Wong \nSigned-off-by: Darrick J. Wong ", "target": 1, "dataset": "other", "idx": 200867} {"func": "xfs_dinode_verify(\n\tstruct xfs_mount\t*mp,\n\txfs_ino_t\t\tino,\n\tstruct xfs_dinode\t*dip)\n{\n\tuint16_t\t\tmode;\n\tuint16_t\t\tflags;\n\tuint64_t\t\tflags2;\n\tuint64_t\t\tdi_size;\n\n\tif (dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC))\n\t\treturn __this_address;\n\n\t/* Verify v3 integrity information first */\n\tif (dip->di_version >= 3) {\n\t\tif (!xfs_sb_version_hascrc(&mp->m_sb))\n\t\t\treturn __this_address;\n\t\tif (!xfs_verify_cksum((char *)dip, mp->m_sb.sb_inodesize,\n\t\t\t\t XFS_DINODE_CRC_OFF))\n\t\t\treturn __this_address;\n\t\tif (be64_to_cpu(dip->di_ino) != ino)\n\t\t\treturn __this_address;\n\t\tif (!uuid_equal(&dip->di_uuid, &mp->m_sb.sb_meta_uuid))\n\t\t\treturn __this_address;\n\t}\n\n\t/* don't allow invalid i_size */\n\tdi_size = be64_to_cpu(dip->di_size);\n\tif (di_size & (1ULL << 63))\n\t\treturn __this_address;\n\n\tmode = be16_to_cpu(dip->di_mode);\n\tif (mode && xfs_mode_to_ftype(mode) == XFS_DIR3_FT_UNKNOWN)\n\t\treturn __this_address;\n\n\t/* No zero-length symlinks/dirs. */\n\tif ((S_ISLNK(mode) || S_ISDIR(mode)) && di_size == 0)\n\t\treturn __this_address;\n\n\t/* Fork checks carried over from xfs_iformat_fork */\n\tif (mode &&\n\t be32_to_cpu(dip->di_nextents) + be16_to_cpu(dip->di_anextents) >\n\t\t\tbe64_to_cpu(dip->di_nblocks))\n\t\treturn __this_address;\n\n\tif (mode && XFS_DFORK_BOFF(dip) > mp->m_sb.sb_inodesize)\n\t\treturn __this_address;\n\n\tflags = be16_to_cpu(dip->di_flags);\n\n\tif (mode && (flags & XFS_DIFLAG_REALTIME) && !mp->m_rtdev_targp)\n\t\treturn __this_address;\n\n\t/* Do we have appropriate data fork formats for the mode? */\n\tswitch (mode & S_IFMT) {\n\tcase S_IFIFO:\n\tcase S_IFCHR:\n\tcase S_IFBLK:\n\tcase S_IFSOCK:\n\t\tif (dip->di_format != XFS_DINODE_FMT_DEV)\n\t\t\treturn __this_address;\n\t\tbreak;\n\tcase S_IFREG:\n\tcase S_IFLNK:\n\tcase S_IFDIR:\n\t\tswitch (dip->di_format) {\n\t\tcase XFS_DINODE_FMT_LOCAL:\n\t\t\t/*\n\t\t\t * no local regular files yet\n\t\t\t */\n\t\t\tif (S_ISREG(mode))\n\t\t\t\treturn __this_address;\n\t\t\tif (di_size > XFS_DFORK_DSIZE(dip, mp))\n\t\t\t\treturn __this_address;\n\t\t\tif (dip->di_nextents)\n\t\t\t\treturn __this_address;\n\t\t\t/* fall through */\n\t\tcase XFS_DINODE_FMT_EXTENTS:\n\t\tcase XFS_DINODE_FMT_BTREE:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn __this_address;\n\t\t}\n\t\tbreak;\n\tcase 0:\n\t\t/* Uninitialized inode ok. */\n\t\tbreak;\n\tdefault:\n\t\treturn __this_address;\n\t}\n\n\tif (XFS_DFORK_Q(dip)) {\n\t\tswitch (dip->di_aformat) {\n\t\tcase XFS_DINODE_FMT_LOCAL:\n\t\t\tif (dip->di_anextents)\n\t\t\t\treturn __this_address;\n\t\t/* fall through */\n\t\tcase XFS_DINODE_FMT_EXTENTS:\n\t\tcase XFS_DINODE_FMT_BTREE:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn __this_address;\n\t\t}\n\t} else {\n\t\t/*\n\t\t * If there is no fork offset, this may be a freshly-made inode\n\t\t * in a new disk cluster, in which case di_aformat is zeroed.\n\t\t * Otherwise, such an inode must be in EXTENTS format; this goes\n\t\t * for freed inodes as well.\n\t\t */\n\t\tswitch (dip->di_aformat) {\n\t\tcase 0:\n\t\tcase XFS_DINODE_FMT_EXTENTS:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn __this_address;\n\t\t}\n\t\tif (dip->di_anextents)\n\t\t\treturn __this_address;\n\t}\n\n\t/* only version 3 or greater inodes are extensively verified here */\n\tif (dip->di_version < 3)\n\t\treturn NULL;\n\n\tflags2 = be64_to_cpu(dip->di_flags2);\n\n\t/* don't allow reflink/cowextsize if we don't have reflink */\n\tif ((flags2 & (XFS_DIFLAG2_REFLINK | XFS_DIFLAG2_COWEXTSIZE)) &&\n !xfs_sb_version_hasreflink(&mp->m_sb))\n\t\treturn __this_address;\n\n\t/* only regular files get reflink */\n\tif ((flags2 & XFS_DIFLAG2_REFLINK) && (mode & S_IFMT) != S_IFREG)\n\t\treturn __this_address;\n\n\t/* don't let reflink and realtime mix */\n\tif ((flags2 & XFS_DIFLAG2_REFLINK) && (flags & XFS_DIFLAG_REALTIME))\n\t\treturn __this_address;\n\n\t/* don't let reflink and dax mix */\n\tif ((flags2 & XFS_DIFLAG2_REFLINK) && (flags2 & XFS_DIFLAG2_DAX))\n\t\treturn __this_address;\n\n\treturn NULL;\n}", "project": "linux", "hash": 153900552675857552774292769547701110591, "size": 146, "commit_id": "b42db0860e13067fcc7cbfba3966c9e652668bbc", "message": "xfs: enhance dinode verifier\n\nAdd several more validations to xfs_dinode_verify:\n\n- For LOCAL data fork formats, di_nextents must be 0.\n- For LOCAL attr fork formats, di_anextents must be 0.\n- For inodes with no attr fork offset,\n - format must be XFS_DINODE_FMT_EXTENTS if set at all\n - di_anextents must be 0.\n\nThanks to dchinner for pointing out a couple related checks I had\nforgotten to add.\n\nSigned-off-by: Eric Sandeen \nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199377\nReviewed-by: Darrick J. Wong \nSigned-off-by: Darrick J. Wong ", "target": 0, "dataset": "other", "idx": 311147} {"func": "unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name)\n{\n int\t\ti;\n u_entry_T\t*uep;\n char_u\t**array;\n char_u\t*line;\n int\t\tline_len;\n\n uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T));\n if (uep == NULL)\n\treturn NULL;\n vim_memset(uep, 0, sizeof(u_entry_T));\n#ifdef U_DEBUG\n uep->ue_magic = UE_MAGIC;\n#endif\n uep->ue_top = undo_read_4c(bi);\n uep->ue_bot = undo_read_4c(bi);\n uep->ue_lcount = undo_read_4c(bi);\n uep->ue_size = undo_read_4c(bi);\n if (uep->ue_size > 0)\n {\n\tarray = (char_u **)U_ALLOC_LINE(sizeof(char_u *) * uep->ue_size);\n\tif (array == NULL)\n\t{\n\t *error = TRUE;\n\t return uep;\n\t}\n\tvim_memset(array, 0, sizeof(char_u *) * uep->ue_size);\n }\n else\n\tarray = NULL;\n uep->ue_array = array;\n\n for (i = 0; i < uep->ue_size; ++i)\n {\n\tline_len = undo_read_4c(bi);\n\tif (line_len >= 0)\n\t line = read_string_decrypt(bi, line_len);\n\telse\n\t{\n\t line = NULL;\n\t corruption_error(\"line length\", file_name);\n\t}\n\tif (line == NULL)\n\t{\n\t *error = TRUE;\n\t return uep;\n\t}\n\tarray[i] = line;\n }\n return uep;\n}", "project": "vim", "hash": 220930485853172651933814434689792902407, "size": 52, "commit_id": "0c8485f0e4931463c0f7986e1ea84a7d79f10c75", "message": "patch 8.0.0378: possible overflow when reading corrupted undo file\n\nProblem: Another possible overflow when reading corrupted undo file.\nSolution: Check if allocated size is not too big. (King)", "target": 1, "dataset": "other", "idx": 200929} {"func": "unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name)\n{\n int\t\ti;\n u_entry_T\t*uep;\n char_u\t**array = NULL;\n char_u\t*line;\n int\t\tline_len;\n\n uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T));\n if (uep == NULL)\n\treturn NULL;\n vim_memset(uep, 0, sizeof(u_entry_T));\n#ifdef U_DEBUG\n uep->ue_magic = UE_MAGIC;\n#endif\n uep->ue_top = undo_read_4c(bi);\n uep->ue_bot = undo_read_4c(bi);\n uep->ue_lcount = undo_read_4c(bi);\n uep->ue_size = undo_read_4c(bi);\n if (uep->ue_size > 0)\n {\n\tif (uep->ue_size < LONG_MAX / (int)sizeof(char_u *))\n\t array = (char_u **)U_ALLOC_LINE(sizeof(char_u *) * uep->ue_size);\n\tif (array == NULL)\n\t{\n\t *error = TRUE;\n\t return uep;\n\t}\n\tvim_memset(array, 0, sizeof(char_u *) * uep->ue_size);\n }\n uep->ue_array = array;\n\n for (i = 0; i < uep->ue_size; ++i)\n {\n\tline_len = undo_read_4c(bi);\n\tif (line_len >= 0)\n\t line = read_string_decrypt(bi, line_len);\n\telse\n\t{\n\t line = NULL;\n\t corruption_error(\"line length\", file_name);\n\t}\n\tif (line == NULL)\n\t{\n\t *error = TRUE;\n\t return uep;\n\t}\n\tarray[i] = line;\n }\n return uep;\n}", "project": "vim", "hash": 113002822976245590429503739327047580863, "size": 51, "commit_id": "0c8485f0e4931463c0f7986e1ea84a7d79f10c75", "message": "patch 8.0.0378: possible overflow when reading corrupted undo file\n\nProblem: Another possible overflow when reading corrupted undo file.\nSolution: Check if allocated size is not too big. (King)", "target": 0, "dataset": "other", "idx": 313017} {"func": "ares_parse_naptr_reply (const unsigned char *abuf, int alen,\n struct ares_naptr_reply **naptr_out)\n{\n unsigned int qdcount, ancount, i;\n const unsigned char *aptr, *vptr;\n int status, rr_type, rr_class, rr_len;\n long len;\n char *hostname = NULL, *rr_name = NULL;\n struct ares_naptr_reply *naptr_head = NULL;\n struct ares_naptr_reply *naptr_last = NULL;\n struct ares_naptr_reply *naptr_curr;\n\n /* Set *naptr_out to NULL for all failure cases. */\n *naptr_out = NULL;\n\n /* Give up if abuf doesn't have room for a header. */\n if (alen < HFIXEDSZ)\n return ARES_EBADRESP;\n\n /* Fetch the question and answer count from the header. */\n qdcount = DNS_HEADER_QDCOUNT (abuf);\n ancount = DNS_HEADER_ANCOUNT (abuf);\n if (qdcount != 1)\n return ARES_EBADRESP;\n if (ancount == 0)\n return ARES_ENODATA;\n\n /* Expand the name from the question, and skip past the question. */\n aptr = abuf + HFIXEDSZ;\n status = ares_expand_name (aptr, abuf, alen, &hostname, &len);\n if (status != ARES_SUCCESS)\n return status;\n\n if (aptr + len + QFIXEDSZ > abuf + alen)\n {\n ares_free (hostname);\n return ARES_EBADRESP;\n }\n aptr += len + QFIXEDSZ;\n\n /* Examine each answer resource record (RR) in turn. */\n for (i = 0; i < ancount; i++)\n {\n /* Decode the RR up to the data field. */\n status = ares_expand_name (aptr, abuf, alen, &rr_name, &len);\n if (status != ARES_SUCCESS)\n {\n break;\n }\n aptr += len;\n if (aptr + RRFIXEDSZ > abuf + alen)\n {\n status = ARES_EBADRESP;\n break;\n }\n rr_type = DNS_RR_TYPE (aptr);\n rr_class = DNS_RR_CLASS (aptr);\n rr_len = DNS_RR_LEN (aptr);\n aptr += RRFIXEDSZ;\n if (aptr + rr_len > abuf + alen)\n {\n status = ARES_EBADRESP;\n break;\n }\n /* RR must contain at least 7 bytes = 2 x int16 + 3 x name */\n if (rr_len < 7)\n {\n status = ARES_EBADRESP;\n break;\n }\n\n /* Check if we are really looking at a NAPTR record */\n if (rr_class == C_IN && rr_type == T_NAPTR)\n {\n /* parse the NAPTR record itself */\n\n /* Allocate storage for this NAPTR answer appending it to the list */\n naptr_curr = ares_malloc_data(ARES_DATATYPE_NAPTR_REPLY);\n if (!naptr_curr)\n {\n status = ARES_ENOMEM;\n break;\n }\n if (naptr_last)\n {\n naptr_last->next = naptr_curr;\n }\n else\n {\n naptr_head = naptr_curr;\n }\n naptr_last = naptr_curr;\n\n vptr = aptr;\n naptr_curr->order = DNS__16BIT(vptr);\n vptr += sizeof(unsigned short);\n naptr_curr->preference = DNS__16BIT(vptr);\n vptr += sizeof(unsigned short);\n\n status = ares_expand_string(vptr, abuf, alen, &naptr_curr->flags, &len);\n if (status != ARES_SUCCESS)\n break;\n vptr += len;\n\n status = ares_expand_string(vptr, abuf, alen, &naptr_curr->service, &len);\n if (status != ARES_SUCCESS)\n break;\n vptr += len;\n\n status = ares_expand_string(vptr, abuf, alen, &naptr_curr->regexp, &len);\n if (status != ARES_SUCCESS)\n break;\n vptr += len;\n\n status = ares_expand_name(vptr, abuf, alen, &naptr_curr->replacement, &len);\n if (status != ARES_SUCCESS)\n break;\n }\n\n /* Don't lose memory in the next iteration */\n ares_free (rr_name);\n rr_name = NULL;\n\n /* Move on to the next record */\n aptr += rr_len;\n }\n\n if (hostname)\n ares_free (hostname);\n if (rr_name)\n ares_free (rr_name);\n\n /* clean up on error */\n if (status != ARES_SUCCESS)\n {\n if (naptr_head)\n ares_free_data (naptr_head);\n return status;\n }\n\n /* everything looks fine, return the data */\n *naptr_out = naptr_head;\n\n return ARES_SUCCESS;\n}", "project": "c-ares", "hash": 92817310620354776498914521339641206707, "size": 145, "commit_id": "18ea99693d63f957ecb670045adbd2c1da8a4641", "message": "ares_parse_naptr_reply: make buffer length check more accurate\n\n9478908a490a6bf009ba58d81de8c1d06d50a117 introduced a length check\nfor records parsed by `ares_parse_naptr_reply()`. However, that\nfunction is designed to parse replies which also contain non-NAPTR\nrecords; for A records, the `rr_len > 7` check will fail as there\nare only 4 bytes of payload.\nIn particular, parsing ANY replies for NAPTR records was broken\nby that patch.\n\nFix that by moving the check into the case in which it is already\nknown that the record is a NAPTR record.", "target": 1, "dataset": "other", "idx": 201328} {"func": "ares_parse_naptr_reply (const unsigned char *abuf, int alen,\n struct ares_naptr_reply **naptr_out)\n{\n unsigned int qdcount, ancount, i;\n const unsigned char *aptr, *vptr;\n int status, rr_type, rr_class, rr_len;\n long len;\n char *hostname = NULL, *rr_name = NULL;\n struct ares_naptr_reply *naptr_head = NULL;\n struct ares_naptr_reply *naptr_last = NULL;\n struct ares_naptr_reply *naptr_curr;\n\n /* Set *naptr_out to NULL for all failure cases. */\n *naptr_out = NULL;\n\n /* Give up if abuf doesn't have room for a header. */\n if (alen < HFIXEDSZ)\n return ARES_EBADRESP;\n\n /* Fetch the question and answer count from the header. */\n qdcount = DNS_HEADER_QDCOUNT (abuf);\n ancount = DNS_HEADER_ANCOUNT (abuf);\n if (qdcount != 1)\n return ARES_EBADRESP;\n if (ancount == 0)\n return ARES_ENODATA;\n\n /* Expand the name from the question, and skip past the question. */\n aptr = abuf + HFIXEDSZ;\n status = ares_expand_name (aptr, abuf, alen, &hostname, &len);\n if (status != ARES_SUCCESS)\n return status;\n\n if (aptr + len + QFIXEDSZ > abuf + alen)\n {\n ares_free (hostname);\n return ARES_EBADRESP;\n }\n aptr += len + QFIXEDSZ;\n\n /* Examine each answer resource record (RR) in turn. */\n for (i = 0; i < ancount; i++)\n {\n /* Decode the RR up to the data field. */\n status = ares_expand_name (aptr, abuf, alen, &rr_name, &len);\n if (status != ARES_SUCCESS)\n {\n break;\n }\n aptr += len;\n if (aptr + RRFIXEDSZ > abuf + alen)\n {\n status = ARES_EBADRESP;\n break;\n }\n rr_type = DNS_RR_TYPE (aptr);\n rr_class = DNS_RR_CLASS (aptr);\n rr_len = DNS_RR_LEN (aptr);\n aptr += RRFIXEDSZ;\n if (aptr + rr_len > abuf + alen)\n {\n status = ARES_EBADRESP;\n break;\n }\n\n /* Check if we are really looking at a NAPTR record */\n if (rr_class == C_IN && rr_type == T_NAPTR)\n {\n /* parse the NAPTR record itself */\n\n /* RR must contain at least 7 bytes = 2 x int16 + 3 x name */\n if (rr_len < 7)\n {\n status = ARES_EBADRESP;\n break;\n }\n\n /* Allocate storage for this NAPTR answer appending it to the list */\n naptr_curr = ares_malloc_data(ARES_DATATYPE_NAPTR_REPLY);\n if (!naptr_curr)\n {\n status = ARES_ENOMEM;\n break;\n }\n if (naptr_last)\n {\n naptr_last->next = naptr_curr;\n }\n else\n {\n naptr_head = naptr_curr;\n }\n naptr_last = naptr_curr;\n\n vptr = aptr;\n naptr_curr->order = DNS__16BIT(vptr);\n vptr += sizeof(unsigned short);\n naptr_curr->preference = DNS__16BIT(vptr);\n vptr += sizeof(unsigned short);\n\n status = ares_expand_string(vptr, abuf, alen, &naptr_curr->flags, &len);\n if (status != ARES_SUCCESS)\n break;\n vptr += len;\n\n status = ares_expand_string(vptr, abuf, alen, &naptr_curr->service, &len);\n if (status != ARES_SUCCESS)\n break;\n vptr += len;\n\n status = ares_expand_string(vptr, abuf, alen, &naptr_curr->regexp, &len);\n if (status != ARES_SUCCESS)\n break;\n vptr += len;\n\n status = ares_expand_name(vptr, abuf, alen, &naptr_curr->replacement, &len);\n if (status != ARES_SUCCESS)\n break;\n }\n\n /* Don't lose memory in the next iteration */\n ares_free (rr_name);\n rr_name = NULL;\n\n /* Move on to the next record */\n aptr += rr_len;\n }\n\n if (hostname)\n ares_free (hostname);\n if (rr_name)\n ares_free (rr_name);\n\n /* clean up on error */\n if (status != ARES_SUCCESS)\n {\n if (naptr_head)\n ares_free_data (naptr_head);\n return status;\n }\n\n /* everything looks fine, return the data */\n *naptr_out = naptr_head;\n\n return ARES_SUCCESS;\n}", "project": "c-ares", "hash": 198334055271059055129109951088542752271, "size": 146, "commit_id": "18ea99693d63f957ecb670045adbd2c1da8a4641", "message": "ares_parse_naptr_reply: make buffer length check more accurate\n\n9478908a490a6bf009ba58d81de8c1d06d50a117 introduced a length check\nfor records parsed by `ares_parse_naptr_reply()`. However, that\nfunction is designed to parse replies which also contain non-NAPTR\nrecords; for A records, the `rr_len > 7` check will fail as there\nare only 4 bytes of payload.\nIn particular, parsing ANY replies for NAPTR records was broken\nby that patch.\n\nFix that by moving the check into the case in which it is already\nknown that the record is a NAPTR record.", "target": 0, "dataset": "other", "idx": 316665} {"func": "static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info,\n const PrimitiveInfo *primitive_info,ExceptionInfo *exception)\n{\n#define MaxStrokePad (6*BezierQuantum+360)\n#define CheckPathExtent(pad_p,pad_q) \\\n{ \\\n if ((pad_p) > MaxBezierCoordinates) \\\n stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \\\n else \\\n if ((ssize_t) (p+(pad_p)) >= (ssize_t) extent_p) \\\n { \\\n if (~extent_p < (pad_p)) \\\n stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \\\n else \\\n { \\\n extent_p+=(pad_p); \\\n stroke_p=(PointInfo *) ResizeQuantumMemory(stroke_p,extent_p+ \\\n MaxStrokePad,sizeof(*stroke_p)); \\\n } \\\n } \\\n if ((pad_q) > MaxBezierCoordinates) \\\n stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \\\n else \\\n if ((ssize_t) (q+(pad_q)) >= (ssize_t) extent_q) \\\n { \\\n if (~extent_q < (pad_q)) \\\n stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \\\n else \\\n { \\\n extent_q+=(pad_q); \\\n stroke_q=(PointInfo *) ResizeQuantumMemory(stroke_q,extent_q+ \\\n MaxStrokePad,sizeof(*stroke_q)); \\\n } \\\n } \\\n if ((stroke_p == (PointInfo *) NULL) || (stroke_q == (PointInfo *) NULL)) \\\n { \\\n if (stroke_p != (PointInfo *) NULL) \\\n stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \\\n if (stroke_q != (PointInfo *) NULL) \\\n stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \\\n polygon_primitive=(PrimitiveInfo *) \\\n RelinquishMagickMemory(polygon_primitive); \\\n (void) ThrowMagickException(exception,GetMagickModule(), \\\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\"); \\\n return((PrimitiveInfo *) NULL); \\\n } \\\n}\n\n typedef struct _StrokeSegment\n {\n double\n p,\n q;\n } StrokeSegment;\n\n double\n delta_theta,\n dot_product,\n mid,\n miterlimit;\n\n MagickBooleanType\n closed_path;\n\n PointInfo\n box_p[5],\n box_q[5],\n center,\n offset,\n *stroke_p,\n *stroke_q;\n\n PrimitiveInfo\n *polygon_primitive,\n *stroke_polygon;\n\n ssize_t\n i;\n\n size_t\n arc_segments,\n extent_p,\n extent_q,\n number_vertices;\n\n ssize_t\n j,\n n,\n p,\n q;\n\n StrokeSegment\n dx = {0.0, 0.0},\n dy = {0.0, 0.0},\n inverse_slope = {0.0, 0.0},\n slope = {0.0, 0.0},\n theta = {0.0, 0.0};\n\n /*\n Allocate paths.\n */\n number_vertices=primitive_info->coordinates;\n polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t)\n number_vertices+2UL,sizeof(*polygon_primitive));\n if (polygon_primitive == (PrimitiveInfo *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return((PrimitiveInfo *) NULL);\n }\n (void) memcpy(polygon_primitive,primitive_info,(size_t) number_vertices*\n sizeof(*polygon_primitive));\n offset.x=primitive_info[number_vertices-1].point.x-primitive_info[0].point.x;\n offset.y=primitive_info[number_vertices-1].point.y-primitive_info[0].point.y;\n closed_path=(fabs(offset.x) < MagickEpsilon) &&\n (fabs(offset.y) < MagickEpsilon) ? MagickTrue : MagickFalse;\n if (((draw_info->linejoin == RoundJoin) ||\n (draw_info->linejoin == MiterJoin)) && (closed_path != MagickFalse))\n {\n polygon_primitive[number_vertices]=primitive_info[1];\n number_vertices++;\n }\n polygon_primitive[number_vertices].primitive=UndefinedPrimitive;\n /*\n Compute the slope for the first line segment, p.\n */\n dx.p=0.0;\n dy.p=0.0;\n for (n=1; n < (ssize_t) number_vertices; n++)\n {\n dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x;\n dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y;\n if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon))\n break;\n }\n if (n == (ssize_t) number_vertices)\n {\n if ((draw_info->linecap != RoundCap) || (closed_path != MagickFalse))\n {\n /*\n Zero length subpath.\n */\n stroke_polygon=(PrimitiveInfo *) AcquireCriticalMemory(\n sizeof(*stroke_polygon));\n stroke_polygon[0]=polygon_primitive[0];\n stroke_polygon[0].coordinates=0;\n polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(\n polygon_primitive);\n return(stroke_polygon);\n }\n n=(ssize_t) number_vertices-1L;\n }\n extent_p=2*number_vertices;\n extent_q=2*number_vertices;\n stroke_p=(PointInfo *) AcquireQuantumMemory((size_t) extent_p+MaxStrokePad,\n sizeof(*stroke_p));\n stroke_q=(PointInfo *) AcquireQuantumMemory((size_t) extent_q+MaxStrokePad,\n sizeof(*stroke_q));\n if ((stroke_p == (PointInfo *) NULL) || (stroke_q == (PointInfo *) NULL))\n {\n if (stroke_p != (PointInfo *) NULL)\n stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p);\n if (stroke_q != (PointInfo *) NULL)\n stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q);\n polygon_primitive=(PrimitiveInfo *)\n RelinquishMagickMemory(polygon_primitive);\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return((PrimitiveInfo *) NULL);\n }\n slope.p=0.0;\n inverse_slope.p=0.0;\n if (fabs(dx.p) < MagickEpsilon)\n {\n if (dx.p >= 0.0)\n slope.p=dy.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;\n else\n slope.p=dy.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;\n }\n else\n if (fabs(dy.p) < MagickEpsilon)\n {\n if (dy.p >= 0.0)\n inverse_slope.p=dx.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;\n else\n inverse_slope.p=dx.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;\n }\n else\n {\n slope.p=dy.p/dx.p;\n inverse_slope.p=(-1.0/slope.p);\n }\n mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;\n miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*mid*mid);\n if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse))\n (void) TraceSquareLinecap(polygon_primitive,number_vertices,mid);\n offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0)));\n offset.y=(double) (offset.x*inverse_slope.p);\n if ((dy.p*offset.x-dx.p*offset.y) > 0.0)\n {\n box_p[0].x=polygon_primitive[0].point.x-offset.x;\n box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p;\n box_p[1].x=polygon_primitive[n].point.x-offset.x;\n box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p;\n box_q[0].x=polygon_primitive[0].point.x+offset.x;\n box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p;\n box_q[1].x=polygon_primitive[n].point.x+offset.x;\n box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p;\n }\n else\n {\n box_p[0].x=polygon_primitive[0].point.x+offset.x;\n box_p[0].y=polygon_primitive[0].point.y+offset.y;\n box_p[1].x=polygon_primitive[n].point.x+offset.x;\n box_p[1].y=polygon_primitive[n].point.y+offset.y;\n box_q[0].x=polygon_primitive[0].point.x-offset.x;\n box_q[0].y=polygon_primitive[0].point.y-offset.y;\n box_q[1].x=polygon_primitive[n].point.x-offset.x;\n box_q[1].y=polygon_primitive[n].point.y-offset.y;\n }\n /*\n Create strokes for the line join attribute: bevel, miter, round.\n */\n p=0;\n q=0;\n stroke_q[p++]=box_q[0];\n stroke_p[q++]=box_p[0];\n for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++)\n {\n /*\n Compute the slope for this line segment, q.\n */\n dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x;\n dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y;\n dot_product=dx.q*dx.q+dy.q*dy.q;\n if (dot_product < 0.25)\n continue;\n slope.q=0.0;\n inverse_slope.q=0.0;\n if (fabs(dx.q) < MagickEpsilon)\n {\n if (dx.q >= 0.0)\n slope.q=dy.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;\n else\n slope.q=dy.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;\n }\n else\n if (fabs(dy.q) < MagickEpsilon)\n {\n if (dy.q >= 0.0)\n inverse_slope.q=dx.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;\n else\n inverse_slope.q=dx.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;\n }\n else\n {\n slope.q=dy.q/dx.q;\n inverse_slope.q=(-1.0/slope.q);\n }\n offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0)));\n offset.y=(double) (offset.x*inverse_slope.q);\n dot_product=dy.q*offset.x-dx.q*offset.y;\n if (dot_product > 0.0)\n {\n box_p[2].x=polygon_primitive[n].point.x-offset.x;\n box_p[2].y=polygon_primitive[n].point.y-offset.y;\n box_p[3].x=polygon_primitive[i].point.x-offset.x;\n box_p[3].y=polygon_primitive[i].point.y-offset.y;\n box_q[2].x=polygon_primitive[n].point.x+offset.x;\n box_q[2].y=polygon_primitive[n].point.y+offset.y;\n box_q[3].x=polygon_primitive[i].point.x+offset.x;\n box_q[3].y=polygon_primitive[i].point.y+offset.y;\n }\n else\n {\n box_p[2].x=polygon_primitive[n].point.x+offset.x;\n box_p[2].y=polygon_primitive[n].point.y+offset.y;\n box_p[3].x=polygon_primitive[i].point.x+offset.x;\n box_p[3].y=polygon_primitive[i].point.y+offset.y;\n box_q[2].x=polygon_primitive[n].point.x-offset.x;\n box_q[2].y=polygon_primitive[n].point.y-offset.y;\n box_q[3].x=polygon_primitive[i].point.x-offset.x;\n box_q[3].y=polygon_primitive[i].point.y-offset.y;\n }\n if (fabs((double) (slope.p-slope.q)) < MagickEpsilon)\n {\n box_p[4]=box_p[1];\n box_q[4]=box_q[1];\n }\n else\n {\n box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+\n box_p[3].y)/(slope.p-slope.q));\n box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y);\n box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+\n box_q[3].y)/(slope.p-slope.q));\n box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y);\n }\n CheckPathExtent(MaxStrokePad,MaxStrokePad);\n dot_product=dx.q*dy.p-dx.p*dy.q;\n if (dot_product <= 0.0)\n switch (draw_info->linejoin)\n {\n case BevelJoin:\n {\n stroke_q[q++]=box_q[1];\n stroke_q[q++]=box_q[2];\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n stroke_p[p++]=box_p[4];\n else\n {\n stroke_p[p++]=box_p[1];\n stroke_p[p++]=box_p[2];\n }\n break;\n }\n case MiterJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n {\n stroke_q[q++]=box_q[4];\n stroke_p[p++]=box_p[4];\n }\n else\n {\n stroke_q[q++]=box_q[1];\n stroke_q[q++]=box_q[2];\n stroke_p[p++]=box_p[1];\n stroke_p[p++]=box_p[2];\n }\n break;\n }\n case RoundJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n stroke_p[p++]=box_p[4];\n else\n {\n stroke_p[p++]=box_p[1];\n stroke_p[p++]=box_p[2];\n }\n center=polygon_primitive[n].point;\n theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x);\n theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x);\n if (theta.q < theta.p)\n theta.q+=2.0*MagickPI;\n arc_segments=(size_t) CastDoubleToLong(ceil((double) ((theta.q-\n theta.p)/(2.0*sqrt(PerceptibleReciprocal(mid))))));\n CheckPathExtent(MaxStrokePad,arc_segments+MaxStrokePad);\n stroke_q[q].x=box_q[1].x;\n stroke_q[q].y=box_q[1].y;\n q++;\n for (j=1; j < (ssize_t) arc_segments; j++)\n {\n delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);\n stroke_q[q].x=(double) (center.x+mid*cos(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n stroke_q[q].y=(double) (center.y+mid*sin(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n q++;\n }\n stroke_q[q++]=box_q[2];\n break;\n }\n default:\n break;\n }\n else\n switch (draw_info->linejoin)\n {\n case BevelJoin:\n {\n stroke_p[p++]=box_p[1];\n stroke_p[p++]=box_p[2];\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n stroke_q[q++]=box_q[4];\n else\n {\n stroke_q[q++]=box_q[1];\n stroke_q[q++]=box_q[2];\n }\n break;\n }\n case MiterJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n {\n stroke_q[q++]=box_q[4];\n stroke_p[p++]=box_p[4];\n }\n else\n {\n stroke_q[q++]=box_q[1];\n stroke_q[q++]=box_q[2];\n stroke_p[p++]=box_p[1];\n stroke_p[p++]=box_p[2];\n }\n break;\n }\n case RoundJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n stroke_q[q++]=box_q[4];\n else\n {\n stroke_q[q++]=box_q[1];\n stroke_q[q++]=box_q[2];\n }\n center=polygon_primitive[n].point;\n theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x);\n theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x);\n if (theta.p < theta.q)\n theta.p+=2.0*MagickPI;\n arc_segments=(size_t) CastDoubleToLong(ceil((double) ((theta.p-\n theta.q)/(2.0*sqrt((double) (1.0/mid))))));\n CheckPathExtent(arc_segments+MaxStrokePad,MaxStrokePad);\n stroke_p[p++]=box_p[1];\n for (j=1; j < (ssize_t) arc_segments; j++)\n {\n delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);\n stroke_p[p].x=(double) (center.x+mid*cos(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n stroke_p[p].y=(double) (center.y+mid*sin(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n p++;\n }\n stroke_p[p++]=box_p[2];\n break;\n }\n default:\n break;\n }\n slope.p=slope.q;\n inverse_slope.p=inverse_slope.q;\n box_p[0]=box_p[2];\n box_p[1]=box_p[3];\n box_q[0]=box_q[2];\n box_q[1]=box_q[3];\n dx.p=dx.q;\n dy.p=dy.q;\n n=i;\n }\n stroke_p[p++]=box_p[1];\n stroke_q[q++]=box_q[1];\n /*\n Trace stroked polygon.\n */\n stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)\n (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon));\n if (stroke_polygon == (PrimitiveInfo *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p);\n stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q);\n polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(\n polygon_primitive);\n return(stroke_polygon);\n }\n for (i=0; i < (ssize_t) p; i++)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_p[i];\n }\n if (closed_path != MagickFalse)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[0].point;\n i++;\n }\n for ( ; i < (ssize_t) (p+q+closed_path); i++)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_q[p+q+closed_path-(i+1)];\n }\n if (closed_path != MagickFalse)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[p+closed_path].point;\n i++;\n }\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[0].point;\n i++;\n stroke_polygon[i].primitive=UndefinedPrimitive;\n stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1);\n stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p);\n stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q);\n polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive);\n return(stroke_polygon);\n}", "project": "ImageMagick6", "hash": 300731361585622607899630210795115991097, "size": 503, "commit_id": "9a94877f7823b0b8a41d50638dd105229d91fa89", "message": "https://github.com/ImageMagick/ImageMagick/issues/3339", "target": 1, "dataset": "other", "idx": 201329} {"func": "static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info,\n const PrimitiveInfo *primitive_info,ExceptionInfo *exception)\n{\n#define MaxStrokePad (6*BezierQuantum+360)\n#define CheckPathExtent(pad_p,pad_q) \\\n{ \\\n if ((pad_p) > MaxBezierCoordinates) \\\n stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \\\n else \\\n if ((ssize_t) (p+(pad_p)) >= (ssize_t) extent_p) \\\n { \\\n if (~extent_p < (pad_p)) \\\n stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \\\n else \\\n { \\\n extent_p+=(pad_p); \\\n stroke_p=(PointInfo *) ResizeQuantumMemory(stroke_p,extent_p+ \\\n MaxStrokePad,sizeof(*stroke_p)); \\\n } \\\n } \\\n if ((pad_q) > MaxBezierCoordinates) \\\n stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \\\n else \\\n if ((ssize_t) (q+(pad_q)) >= (ssize_t) extent_q) \\\n { \\\n if (~extent_q < (pad_q)) \\\n stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \\\n else \\\n { \\\n extent_q+=(pad_q); \\\n stroke_q=(PointInfo *) ResizeQuantumMemory(stroke_q,extent_q+ \\\n MaxStrokePad,sizeof(*stroke_q)); \\\n } \\\n } \\\n if ((stroke_p == (PointInfo *) NULL) || (stroke_q == (PointInfo *) NULL)) \\\n { \\\n if (stroke_p != (PointInfo *) NULL) \\\n stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \\\n if (stroke_q != (PointInfo *) NULL) \\\n stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \\\n polygon_primitive=(PrimitiveInfo *) \\\n RelinquishMagickMemory(polygon_primitive); \\\n (void) ThrowMagickException(exception,GetMagickModule(), \\\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\"); \\\n return((PrimitiveInfo *) NULL); \\\n } \\\n}\n\n typedef struct _StrokeSegment\n {\n double\n p,\n q;\n } StrokeSegment;\n\n double\n delta_theta,\n dot_product,\n mid,\n miterlimit;\n\n MagickBooleanType\n closed_path;\n\n PointInfo\n box_p[5],\n box_q[5],\n center,\n offset,\n *stroke_p,\n *stroke_q;\n\n PrimitiveInfo\n *polygon_primitive,\n *stroke_polygon;\n\n ssize_t\n i;\n\n size_t\n arc_segments,\n extent_p,\n extent_q,\n number_vertices;\n\n ssize_t\n j,\n n,\n p,\n q;\n\n StrokeSegment\n dx = {0.0, 0.0},\n dy = {0.0, 0.0},\n inverse_slope = {0.0, 0.0},\n slope = {0.0, 0.0},\n theta = {0.0, 0.0};\n\n /*\n Allocate paths.\n */\n number_vertices=primitive_info->coordinates;\n polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t)\n number_vertices+2UL,sizeof(*polygon_primitive));\n if (polygon_primitive == (PrimitiveInfo *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return((PrimitiveInfo *) NULL);\n }\n (void) memcpy(polygon_primitive,primitive_info,(size_t) number_vertices*\n sizeof(*polygon_primitive));\n offset.x=primitive_info[number_vertices-1].point.x-primitive_info[0].point.x;\n offset.y=primitive_info[number_vertices-1].point.y-primitive_info[0].point.y;\n closed_path=(fabs(offset.x) < MagickEpsilon) &&\n (fabs(offset.y) < MagickEpsilon) ? MagickTrue : MagickFalse;\n if (((draw_info->linejoin == RoundJoin) ||\n (draw_info->linejoin == MiterJoin)) && (closed_path != MagickFalse))\n {\n polygon_primitive[number_vertices]=primitive_info[1];\n number_vertices++;\n }\n polygon_primitive[number_vertices].primitive=UndefinedPrimitive;\n /*\n Compute the slope for the first line segment, p.\n */\n dx.p=0.0;\n dy.p=0.0;\n for (n=1; n < (ssize_t) number_vertices; n++)\n {\n dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x;\n dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y;\n if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon))\n break;\n }\n if (n == (ssize_t) number_vertices)\n {\n if ((draw_info->linecap != RoundCap) || (closed_path != MagickFalse))\n {\n /*\n Zero length subpath.\n */\n stroke_polygon=(PrimitiveInfo *) AcquireCriticalMemory(\n sizeof(*stroke_polygon));\n stroke_polygon[0]=polygon_primitive[0];\n stroke_polygon[0].coordinates=0;\n polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(\n polygon_primitive);\n return(stroke_polygon);\n }\n n=(ssize_t) number_vertices-1L;\n }\n extent_p=2*number_vertices;\n extent_q=2*number_vertices;\n stroke_p=(PointInfo *) AcquireQuantumMemory((size_t) extent_p+MaxStrokePad,\n sizeof(*stroke_p));\n stroke_q=(PointInfo *) AcquireQuantumMemory((size_t) extent_q+MaxStrokePad,\n sizeof(*stroke_q));\n if ((stroke_p == (PointInfo *) NULL) || (stroke_q == (PointInfo *) NULL))\n {\n if (stroke_p != (PointInfo *) NULL)\n stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p);\n if (stroke_q != (PointInfo *) NULL)\n stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q);\n polygon_primitive=(PrimitiveInfo *)\n RelinquishMagickMemory(polygon_primitive);\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return((PrimitiveInfo *) NULL);\n }\n slope.p=0.0;\n inverse_slope.p=0.0;\n if (fabs(dx.p) < MagickEpsilon)\n {\n if (dx.p >= 0.0)\n slope.p=dy.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;\n else\n slope.p=dy.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;\n }\n else\n if (fabs(dy.p) < MagickEpsilon)\n {\n if (dy.p >= 0.0)\n inverse_slope.p=dx.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;\n else\n inverse_slope.p=dx.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;\n }\n else\n {\n slope.p=dy.p/dx.p;\n inverse_slope.p=(-1.0/slope.p);\n }\n mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;\n miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*mid*mid);\n if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse))\n (void) TraceSquareLinecap(polygon_primitive,number_vertices,mid);\n offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0)));\n offset.y=(double) (offset.x*inverse_slope.p);\n if ((dy.p*offset.x-dx.p*offset.y) > 0.0)\n {\n box_p[0].x=polygon_primitive[0].point.x-offset.x;\n box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p;\n box_p[1].x=polygon_primitive[n].point.x-offset.x;\n box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p;\n box_q[0].x=polygon_primitive[0].point.x+offset.x;\n box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p;\n box_q[1].x=polygon_primitive[n].point.x+offset.x;\n box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p;\n }\n else\n {\n box_p[0].x=polygon_primitive[0].point.x+offset.x;\n box_p[0].y=polygon_primitive[0].point.y+offset.y;\n box_p[1].x=polygon_primitive[n].point.x+offset.x;\n box_p[1].y=polygon_primitive[n].point.y+offset.y;\n box_q[0].x=polygon_primitive[0].point.x-offset.x;\n box_q[0].y=polygon_primitive[0].point.y-offset.y;\n box_q[1].x=polygon_primitive[n].point.x-offset.x;\n box_q[1].y=polygon_primitive[n].point.y-offset.y;\n }\n /*\n Create strokes for the line join attribute: bevel, miter, round.\n */\n p=0;\n q=0;\n stroke_q[p++]=box_q[0];\n stroke_p[q++]=box_p[0];\n for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++)\n {\n /*\n Compute the slope for this line segment, q.\n */\n dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x;\n dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y;\n dot_product=dx.q*dx.q+dy.q*dy.q;\n if (dot_product < 0.25)\n continue;\n slope.q=0.0;\n inverse_slope.q=0.0;\n if (fabs(dx.q) < MagickEpsilon)\n {\n if (dx.q >= 0.0)\n slope.q=dy.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;\n else\n slope.q=dy.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;\n }\n else\n if (fabs(dy.q) < MagickEpsilon)\n {\n if (dy.q >= 0.0)\n inverse_slope.q=dx.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;\n else\n inverse_slope.q=dx.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;\n }\n else\n {\n slope.q=dy.q/dx.q;\n inverse_slope.q=(-1.0/slope.q);\n }\n offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0)));\n offset.y=(double) (offset.x*inverse_slope.q);\n dot_product=dy.q*offset.x-dx.q*offset.y;\n if (dot_product > 0.0)\n {\n box_p[2].x=polygon_primitive[n].point.x-offset.x;\n box_p[2].y=polygon_primitive[n].point.y-offset.y;\n box_p[3].x=polygon_primitive[i].point.x-offset.x;\n box_p[3].y=polygon_primitive[i].point.y-offset.y;\n box_q[2].x=polygon_primitive[n].point.x+offset.x;\n box_q[2].y=polygon_primitive[n].point.y+offset.y;\n box_q[3].x=polygon_primitive[i].point.x+offset.x;\n box_q[3].y=polygon_primitive[i].point.y+offset.y;\n }\n else\n {\n box_p[2].x=polygon_primitive[n].point.x+offset.x;\n box_p[2].y=polygon_primitive[n].point.y+offset.y;\n box_p[3].x=polygon_primitive[i].point.x+offset.x;\n box_p[3].y=polygon_primitive[i].point.y+offset.y;\n box_q[2].x=polygon_primitive[n].point.x-offset.x;\n box_q[2].y=polygon_primitive[n].point.y-offset.y;\n box_q[3].x=polygon_primitive[i].point.x-offset.x;\n box_q[3].y=polygon_primitive[i].point.y-offset.y;\n }\n if (fabs((double) (slope.p-slope.q)) < MagickEpsilon)\n {\n box_p[4]=box_p[1];\n box_q[4]=box_q[1];\n }\n else\n {\n box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+\n box_p[3].y)/(slope.p-slope.q));\n box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y);\n box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+\n box_q[3].y)/(slope.p-slope.q));\n box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y);\n }\n CheckPathExtent(MaxStrokePad,MaxStrokePad);\n dot_product=dx.q*dy.p-dx.p*dy.q;\n if (dot_product <= 0.0)\n switch (draw_info->linejoin)\n {\n case BevelJoin:\n {\n stroke_q[q++]=box_q[1];\n stroke_q[q++]=box_q[2];\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n stroke_p[p++]=box_p[4];\n else\n {\n stroke_p[p++]=box_p[1];\n stroke_p[p++]=box_p[2];\n }\n break;\n }\n case MiterJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n {\n stroke_q[q++]=box_q[4];\n stroke_p[p++]=box_p[4];\n }\n else\n {\n stroke_q[q++]=box_q[1];\n stroke_q[q++]=box_q[2];\n stroke_p[p++]=box_p[1];\n stroke_p[p++]=box_p[2];\n }\n break;\n }\n case RoundJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n stroke_p[p++]=box_p[4];\n else\n {\n stroke_p[p++]=box_p[1];\n stroke_p[p++]=box_p[2];\n }\n center=polygon_primitive[n].point;\n theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x);\n theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x);\n if (theta.q < theta.p)\n theta.q+=2.0*MagickPI;\n arc_segments=(size_t) CastDoubleToLong(ceil((double) ((theta.q-\n theta.p)/(2.0*sqrt(PerceptibleReciprocal(mid))))));\n CheckPathExtent(MaxStrokePad,arc_segments+MaxStrokePad);\n stroke_q[q].x=box_q[1].x;\n stroke_q[q].y=box_q[1].y;\n q++;\n for (j=1; j < (ssize_t) arc_segments; j++)\n {\n delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);\n stroke_q[q].x=(double) (center.x+mid*cos(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n stroke_q[q].y=(double) (center.y+mid*sin(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n q++;\n }\n stroke_q[q++]=box_q[2];\n break;\n }\n default:\n break;\n }\n else\n switch (draw_info->linejoin)\n {\n case BevelJoin:\n {\n stroke_p[p++]=box_p[1];\n stroke_p[p++]=box_p[2];\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n stroke_q[q++]=box_q[4];\n else\n {\n stroke_q[q++]=box_q[1];\n stroke_q[q++]=box_q[2];\n }\n break;\n }\n case MiterJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n {\n stroke_q[q++]=box_q[4];\n stroke_p[p++]=box_p[4];\n }\n else\n {\n stroke_q[q++]=box_q[1];\n stroke_q[q++]=box_q[2];\n stroke_p[p++]=box_p[1];\n stroke_p[p++]=box_p[2];\n }\n break;\n }\n case RoundJoin:\n {\n dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+\n (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);\n if (dot_product <= miterlimit)\n stroke_q[q++]=box_q[4];\n else\n {\n stroke_q[q++]=box_q[1];\n stroke_q[q++]=box_q[2];\n }\n center=polygon_primitive[n].point;\n theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x);\n theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x);\n if (theta.p < theta.q)\n theta.p+=2.0*MagickPI;\n arc_segments=(size_t) CastDoubleToLong(ceil((double) ((theta.p-\n theta.q)/(2.0*sqrt((double) (PerceptibleReciprocal(mid)))))));\n CheckPathExtent(arc_segments+MaxStrokePad,MaxStrokePad);\n stroke_p[p++]=box_p[1];\n for (j=1; j < (ssize_t) arc_segments; j++)\n {\n delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);\n stroke_p[p].x=(double) (center.x+mid*cos(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n stroke_p[p].y=(double) (center.y+mid*sin(fmod((double)\n (theta.p+delta_theta),DegreesToRadians(360.0))));\n p++;\n }\n stroke_p[p++]=box_p[2];\n break;\n }\n default:\n break;\n }\n slope.p=slope.q;\n inverse_slope.p=inverse_slope.q;\n box_p[0]=box_p[2];\n box_p[1]=box_p[3];\n box_q[0]=box_q[2];\n box_q[1]=box_q[3];\n dx.p=dx.q;\n dy.p=dy.q;\n n=i;\n }\n stroke_p[p++]=box_p[1];\n stroke_q[q++]=box_q[1];\n /*\n Trace stroked polygon.\n */\n stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)\n (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon));\n if (stroke_polygon == (PrimitiveInfo *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p);\n stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q);\n polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(\n polygon_primitive);\n return(stroke_polygon);\n }\n for (i=0; i < (ssize_t) p; i++)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_p[i];\n }\n if (closed_path != MagickFalse)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[0].point;\n i++;\n }\n for ( ; i < (ssize_t) (p+q+closed_path); i++)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_q[p+q+closed_path-(i+1)];\n }\n if (closed_path != MagickFalse)\n {\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[p+closed_path].point;\n i++;\n }\n stroke_polygon[i]=polygon_primitive[0];\n stroke_polygon[i].point=stroke_polygon[0].point;\n i++;\n stroke_polygon[i].primitive=UndefinedPrimitive;\n stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1);\n stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p);\n stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q);\n polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive);\n return(stroke_polygon);\n}", "project": "ImageMagick6", "hash": 23882718594748933673379097067447163572, "size": 503, "commit_id": "9a94877f7823b0b8a41d50638dd105229d91fa89", "message": "https://github.com/ImageMagick/ImageMagick/issues/3339", "target": 0, "dataset": "other", "idx": 316687} {"func": "rpmRC hdrblobInit(const void *uh, size_t uc,\n\t\trpmTagVal regionTag, int exact_size,\n\t\tstruct hdrblob_s *blob, char **emsg)\n{\n rpmRC rc = RPMRC_FAIL;\n\n memset(blob, 0, sizeof(*blob));\n blob->ei = (int32_t *) uh; /* discards const */\n blob->il = ntohl(blob->ei[0]);\n blob->dl = ntohl(blob->ei[1]);\n blob->pe = (entryInfo) &(blob->ei[2]);\n blob->pvlen = sizeof(blob->il) + sizeof(blob->dl) +\n\t\t (blob->il * sizeof(*blob->pe)) + blob->dl;\n blob->dataStart = (uint8_t *) (blob->pe + blob->il);\n blob->dataEnd = blob->dataStart + blob->dl;\n\n /* Is the blob the right size? */\n if (blob->pvlen >= headerMaxbytes || (uc && blob->pvlen != uc)) {\n\trasprintf(emsg, _(\"blob size(%d): BAD, 8 + 16 * il(%d) + dl(%d)\"),\n\t\t\tblob->pvlen, blob->il, blob->dl);\n\tgoto exit;\n }\n\n if (hdrblobVerifyRegion(regionTag, exact_size, blob, emsg) == RPMRC_FAIL)\n\tgoto exit;\n\n /* Sanity check the rest of the header structure. */\n if (hdrblobVerifyInfo(blob, emsg))\n\tgoto exit;\n\n rc = RPMRC_OK;\n\nexit:\n return rc;\n}", "project": "rpm", "hash": 221870817089961992144312998012828797980, "size": 35, "commit_id": "8f4b3c3cab8922a2022b9e47c71f1ecf906077ef", "message": "hdrblobInit() needs bounds checks too\n\nUsers can pass untrusted data to hdrblobInit() and it must be robust\nagainst this.", "target": 1, "dataset": "other", "idx": 201363} {"func": "rpmRC hdrblobInit(const void *uh, size_t uc,\n\t\trpmTagVal regionTag, int exact_size,\n\t\tstruct hdrblob_s *blob, char **emsg)\n{\n rpmRC rc = RPMRC_FAIL;\n memset(blob, 0, sizeof(*blob));\n if (uc && uc < 8) {\n\trasprintf(emsg, _(\"hdr length: BAD\"));\n\tgoto exit;\n }\n\n blob->ei = (int32_t *) uh; /* discards const */\n blob->il = ntohl((uint32_t)(blob->ei[0]));\n blob->dl = ntohl((uint32_t)(blob->ei[1]));\n if (hdrblobVerifyLengths(regionTag, blob->il, blob->dl, emsg) != RPMRC_OK)\n\tgoto exit;\n\n blob->pe = (entryInfo) &(blob->ei[2]);\n blob->pvlen = sizeof(blob->il) + sizeof(blob->dl) +\n\t\t (blob->il * sizeof(*blob->pe)) + blob->dl;\n blob->dataStart = (uint8_t *) (blob->pe + blob->il);\n blob->dataEnd = blob->dataStart + blob->dl;\n\n /* Is the blob the right size? */\n if (blob->pvlen >= headerMaxbytes || (uc && blob->pvlen != uc)) {\n\trasprintf(emsg, _(\"blob size(%d): BAD, 8 + 16 * il(%d) + dl(%d)\"),\n\t\t\tblob->pvlen, blob->il, blob->dl);\n\tgoto exit;\n }\n\n if (hdrblobVerifyRegion(regionTag, exact_size, blob, emsg) == RPMRC_FAIL)\n\tgoto exit;\n\n /* Sanity check the rest of the header structure. */\n if (hdrblobVerifyInfo(blob, emsg))\n\tgoto exit;\n\n rc = RPMRC_OK;\n\nexit:\n return rc;\n}", "project": "rpm", "hash": 315069287843193856684881977313831062424, "size": 42, "commit_id": "8f4b3c3cab8922a2022b9e47c71f1ecf906077ef", "message": "hdrblobInit() needs bounds checks too\n\nUsers can pass untrusted data to hdrblobInit() and it must be robust\nagainst this.", "target": 0, "dataset": "other", "idx": 318167} {"func": "static x3f_huffnode_t *new_node(x3f_hufftree_t *tree)\n{\n x3f_huffnode_t *t = &tree->nodes[tree->free_node_index];\n\n t->branch[0] = NULL;\n t->branch[1] = NULL;\n t->leaf = UNDEFINED_LEAF;\n\n tree->free_node_index++;\n\n return t;\n}", "project": "LibRaw", "hash": 123416413605001745719792443480718508652, "size": 12, "commit_id": "11c4db253ef2c9bb44247b578f5caa57c66a1eeb", "message": "X3F: check huffman tree size", "target": 1, "dataset": "other", "idx": 201415} {"func": "static x3f_huffnode_t *new_node(x3f_hufftree_t *tree)\n{\n\tif (tree->free_node_index >= tree->total_node_index)\n\t\tthrow LIBRAW_EXCEPTION_IO_CORRUPT;\n x3f_huffnode_t *t = &tree->nodes[tree->free_node_index];\n\n t->branch[0] = NULL;\n t->branch[1] = NULL;\n t->leaf = UNDEFINED_LEAF;\n\n tree->free_node_index++;\n\n return t;\n}", "project": "LibRaw", "hash": 271692711028990488717832420931979417790, "size": 14, "commit_id": "11c4db253ef2c9bb44247b578f5caa57c66a1eeb", "message": "X3F: check huffman tree size", "target": 0, "dataset": "other", "idx": 319168} {"func": "static int rawsock_create(struct net *net, struct socket *sock,\n\t\t\t const struct nfc_protocol *nfc_proto, int kern)\n{\n\tstruct sock *sk;\n\n\tpr_debug(\"sock=%p\\n\", sock);\n\n\tif ((sock->type != SOCK_SEQPACKET) && (sock->type != SOCK_RAW))\n\t\treturn -ESOCKTNOSUPPORT;\n\n\tif (sock->type == SOCK_RAW)\n\t\tsock->ops = &rawsock_raw_ops;\n\telse\n\t\tsock->ops = &rawsock_ops;\n\n\tsk = sk_alloc(net, PF_NFC, GFP_ATOMIC, nfc_proto->proto, kern);\n\tif (!sk)\n\t\treturn -ENOMEM;\n\n\tsock_init_data(sock, sk);\n\tsk->sk_protocol = nfc_proto->id;\n\tsk->sk_destruct = rawsock_destruct;\n\tsock->state = SS_UNCONNECTED;\n\tif (sock->type == SOCK_RAW)\n\t\tnfc_sock_link(&raw_sk_list, sk);\n\telse {\n\t\tINIT_WORK(&nfc_rawsock(sk)->tx_work, rawsock_tx_work);\n\t\tnfc_rawsock(sk)->tx_work_scheduled = false;\n\t}\n\n\treturn 0;\n}", "project": "linux", "hash": 76158006236225806046621099350006167099, "size": 32, "commit_id": "26896f01467a28651f7a536143fe5ac8449d4041", "message": "net/nfc/rawsock.c: add CAP_NET_RAW check.\n\nWhen creating a raw AF_NFC socket, CAP_NET_RAW needs to be checked first.\n\nSigned-off-by: Qingyu Li \nSigned-off-by: David S. Miller ", "target": 1, "dataset": "other", "idx": 201423} {"func": "static int rawsock_create(struct net *net, struct socket *sock,\n\t\t\t const struct nfc_protocol *nfc_proto, int kern)\n{\n\tstruct sock *sk;\n\n\tpr_debug(\"sock=%p\\n\", sock);\n\n\tif ((sock->type != SOCK_SEQPACKET) && (sock->type != SOCK_RAW))\n\t\treturn -ESOCKTNOSUPPORT;\n\n\tif (sock->type == SOCK_RAW) {\n\t\tif (!capable(CAP_NET_RAW))\n\t\t\treturn -EPERM;\n\t\tsock->ops = &rawsock_raw_ops;\n\t} else {\n\t\tsock->ops = &rawsock_ops;\n\t}\n\n\tsk = sk_alloc(net, PF_NFC, GFP_ATOMIC, nfc_proto->proto, kern);\n\tif (!sk)\n\t\treturn -ENOMEM;\n\n\tsock_init_data(sock, sk);\n\tsk->sk_protocol = nfc_proto->id;\n\tsk->sk_destruct = rawsock_destruct;\n\tsock->state = SS_UNCONNECTED;\n\tif (sock->type == SOCK_RAW)\n\t\tnfc_sock_link(&raw_sk_list, sk);\n\telse {\n\t\tINIT_WORK(&nfc_rawsock(sk)->tx_work, rawsock_tx_work);\n\t\tnfc_rawsock(sk)->tx_work_scheduled = false;\n\t}\n\n\treturn 0;\n}", "project": "linux", "hash": 284654099723487976419252796131361945863, "size": 35, "commit_id": "26896f01467a28651f7a536143fe5ac8449d4041", "message": "net/nfc/rawsock.c: add CAP_NET_RAW check.\n\nWhen creating a raw AF_NFC socket, CAP_NET_RAW needs to be checked first.\n\nSigned-off-by: Qingyu Li \nSigned-off-by: David S. Miller ", "target": 0, "dataset": "other", "idx": 319215} {"func": "int LibRaw::ljpeg_start(struct jhead *jh, int info_only)\n{\n ushort c, tag, len;\n int cnt = 0;\n uchar data[0x10000];\n const uchar *dp;\n\n memset(jh, 0, sizeof *jh);\n jh->restart = INT_MAX;\n if ((fgetc(ifp), fgetc(ifp)) != 0xd8)\n return 0;\n do\n {\n if (feof(ifp))\n return 0;\n if (cnt++ > 1024)\n return 0; // 1024 tags limit\n if (!fread(data, 2, 2, ifp))\n return 0;\n tag = data[0] << 8 | data[1];\n len = (data[2] << 8 | data[3]) - 2;\n if (tag <= 0xff00)\n return 0;\n fread(data, 1, len, ifp);\n switch (tag)\n {\n case 0xffc3: // start of frame; lossless, Huffman\n jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;\n case 0xffc1:\n case 0xffc0:\n jh->algo = tag & 0xff;\n jh->bits = data[0];\n jh->high = data[1] << 8 | data[2];\n jh->wide = data[3] << 8 | data[4];\n jh->clrs = data[5] + jh->sraw;\n if (len == 9 && !dng_version)\n getc(ifp);\n break;\n case 0xffc4: // define Huffman tables\n if (info_only)\n break;\n for (dp = data; dp < data + len && !((c = *dp++) & -20);)\n jh->free[c] = jh->huff[c] = make_decoder_ref(&dp);\n break;\n case 0xffda: // start of scan\n jh->psv = data[1 + data[0] * 2];\n jh->bits -= data[3 + data[0] * 2] & 15;\n break;\n case 0xffdb:\n FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2];\n break;\n case 0xffdd:\n jh->restart = data[0] << 8 | data[1];\n }\n } while (tag != 0xffda);\n if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide ||\n !jh->clrs)\n return 0;\n if (info_only)\n return 1;\n if (!jh->huff[0])\n return 0;\n FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c];\n if (jh->sraw)\n {\n FORC(4) jh->huff[2 + c] = jh->huff[1];\n FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0];\n }\n jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4);\n merror(jh->row, \"ljpeg_start()\");\n return zero_after_ff = 1;\n}", "project": "LibRaw", "hash": 17018590345339261485668035454434752810, "size": 72, "commit_id": "a6937d4046a7c4742b683a04c8564605fd9be4fb", "message": "more room for ljpeg row", "target": 1, "dataset": "other", "idx": 201452} {"func": "int LibRaw::ljpeg_start(struct jhead *jh, int info_only)\n{\n ushort c, tag, len;\n int cnt = 0;\n uchar data[0x10000];\n const uchar *dp;\n\n memset(jh, 0, sizeof *jh);\n jh->restart = INT_MAX;\n if ((fgetc(ifp), fgetc(ifp)) != 0xd8)\n return 0;\n do\n {\n if (feof(ifp))\n return 0;\n if (cnt++ > 1024)\n return 0; // 1024 tags limit\n if (!fread(data, 2, 2, ifp))\n return 0;\n tag = data[0] << 8 | data[1];\n len = (data[2] << 8 | data[3]) - 2;\n if (tag <= 0xff00)\n return 0;\n fread(data, 1, len, ifp);\n switch (tag)\n {\n case 0xffc3: // start of frame; lossless, Huffman\n jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;\n case 0xffc1:\n case 0xffc0:\n jh->algo = tag & 0xff;\n jh->bits = data[0];\n jh->high = data[1] << 8 | data[2];\n jh->wide = data[3] << 8 | data[4];\n jh->clrs = data[5] + jh->sraw;\n if (len == 9 && !dng_version)\n getc(ifp);\n break;\n case 0xffc4: // define Huffman tables\n if (info_only)\n break;\n for (dp = data; dp < data + len && !((c = *dp++) & -20);)\n jh->free[c] = jh->huff[c] = make_decoder_ref(&dp);\n break;\n case 0xffda: // start of scan\n jh->psv = data[1 + data[0] * 2];\n jh->bits -= data[3 + data[0] * 2] & 15;\n break;\n case 0xffdb:\n FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2];\n break;\n case 0xffdd:\n jh->restart = data[0] << 8 | data[1];\n }\n } while (tag != 0xffda);\n if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide ||\n !jh->clrs)\n return 0;\n if (info_only)\n return 1;\n if (!jh->huff[0])\n return 0;\n FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c];\n if (jh->sraw)\n {\n FORC(4) jh->huff[2 + c] = jh->huff[1];\n FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0];\n }\n jh->row = (ushort *)calloc(jh->wide * jh->clrs, 16);\n merror(jh->row, \"ljpeg_start()\");\n return zero_after_ff = 1;\n}", "project": "LibRaw", "hash": 172933929170343697197974643398947672843, "size": 72, "commit_id": "a6937d4046a7c4742b683a04c8564605fd9be4fb", "message": "more room for ljpeg row", "target": 0, "dataset": "other", "idx": 319453} {"func": "unsigned long move_page_tables(struct vm_area_struct *vma,\n\t\tunsigned long old_addr, struct vm_area_struct *new_vma,\n\t\tunsigned long new_addr, unsigned long len,\n\t\tbool need_rmap_locks)\n{\n\tunsigned long extent, next, old_end;\n\tstruct mmu_notifier_range range;\n\tpmd_t *old_pmd, *new_pmd;\n\n\told_end = old_addr + len;\n\tflush_cache_range(vma, old_addr, old_end);\n\n\tmmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,\n\t\t\t\told_addr, old_end);\n\tmmu_notifier_invalidate_range_start(&range);\n\n\tfor (; old_addr < old_end; old_addr += extent, new_addr += extent) {\n\t\tcond_resched();\n\t\tnext = (old_addr + PMD_SIZE) & PMD_MASK;\n\t\t/* even if next overflowed, extent below will be ok */\n\t\textent = next - old_addr;\n\t\tif (extent > old_end - old_addr)\n\t\t\textent = old_end - old_addr;\n\t\told_pmd = get_old_pmd(vma->vm_mm, old_addr);\n\t\tif (!old_pmd)\n\t\t\tcontinue;\n\t\tnew_pmd = alloc_new_pmd(vma->vm_mm, vma, new_addr);\n\t\tif (!new_pmd)\n\t\t\tbreak;\n\t\tif (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd)) {\n\t\t\tif (extent == HPAGE_PMD_SIZE) {\n\t\t\t\tbool moved;\n\t\t\t\t/* See comment in move_ptes() */\n\t\t\t\tif (need_rmap_locks)\n\t\t\t\t\ttake_rmap_locks(vma);\n\t\t\t\tmoved = move_huge_pmd(vma, old_addr, new_addr,\n\t\t\t\t\t\t old_end, old_pmd, new_pmd);\n\t\t\t\tif (need_rmap_locks)\n\t\t\t\t\tdrop_rmap_locks(vma);\n\t\t\t\tif (moved)\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsplit_huge_pmd(vma, old_pmd, old_addr);\n\t\t\tif (pmd_trans_unstable(old_pmd))\n\t\t\t\tcontinue;\n\t\t} else if (extent == PMD_SIZE) {\n#ifdef CONFIG_HAVE_MOVE_PMD\n\t\t\t/*\n\t\t\t * If the extent is PMD-sized, try to speed the move by\n\t\t\t * moving at the PMD level if possible.\n\t\t\t */\n\t\t\tbool moved;\n\n\t\t\tif (need_rmap_locks)\n\t\t\t\ttake_rmap_locks(vma);\n\t\t\tmoved = move_normal_pmd(vma, old_addr, new_addr,\n\t\t\t\t\told_end, old_pmd, new_pmd);\n\t\t\tif (need_rmap_locks)\n\t\t\t\tdrop_rmap_locks(vma);\n\t\t\tif (moved)\n\t\t\t\tcontinue;\n#endif\n\t\t}\n\n\t\tif (pte_alloc(new_vma->vm_mm, new_pmd))\n\t\t\tbreak;\n\t\tnext = (new_addr + PMD_SIZE) & PMD_MASK;\n\t\tif (extent > next - new_addr)\n\t\t\textent = next - new_addr;\n\t\tmove_ptes(vma, old_pmd, old_addr, old_addr + extent, new_vma,\n\t\t\t new_pmd, new_addr, need_rmap_locks);\n\t}\n\n\tmmu_notifier_invalidate_range_end(&range);\n\n\treturn len + old_addr - old_end;\t/* how much done */\n}", "project": "linux", "hash": 322406925399934688200484412754502215496, "size": 77, "commit_id": "5bfea2d9b17f1034a68147a8b03b9789af5700f9", "message": "mm: Fix mremap not considering huge pmd devmap\n\nThe original code in mm/mremap.c checks huge pmd by:\n\n\t\tif (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd)) {\n\nHowever, a DAX mapped nvdimm is mapped as huge page (by default) but it\nis not transparent huge page (_PAGE_PSE | PAGE_DEVMAP). This commit\nchanges the condition to include the case.\n\nThis addresses CVE-2020-10757.\n\nFixes: 5c7fb56e5e3f (\"mm, dax: dax-pmd vs thp-pmd vs hugetlbfs-pmd\")\nCc: \nReported-by: Fan Yang \nSigned-off-by: Fan Yang \nTested-by: Fan Yang \nTested-by: Dan Williams \nReviewed-by: Dan Williams \nAcked-by: Kirill A. Shutemov \nSigned-off-by: Linus Torvalds ", "target": 1, "dataset": "other", "idx": 201788} {"func": "unsigned long move_page_tables(struct vm_area_struct *vma,\n\t\tunsigned long old_addr, struct vm_area_struct *new_vma,\n\t\tunsigned long new_addr, unsigned long len,\n\t\tbool need_rmap_locks)\n{\n\tunsigned long extent, next, old_end;\n\tstruct mmu_notifier_range range;\n\tpmd_t *old_pmd, *new_pmd;\n\n\told_end = old_addr + len;\n\tflush_cache_range(vma, old_addr, old_end);\n\n\tmmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,\n\t\t\t\told_addr, old_end);\n\tmmu_notifier_invalidate_range_start(&range);\n\n\tfor (; old_addr < old_end; old_addr += extent, new_addr += extent) {\n\t\tcond_resched();\n\t\tnext = (old_addr + PMD_SIZE) & PMD_MASK;\n\t\t/* even if next overflowed, extent below will be ok */\n\t\textent = next - old_addr;\n\t\tif (extent > old_end - old_addr)\n\t\t\textent = old_end - old_addr;\n\t\told_pmd = get_old_pmd(vma->vm_mm, old_addr);\n\t\tif (!old_pmd)\n\t\t\tcontinue;\n\t\tnew_pmd = alloc_new_pmd(vma->vm_mm, vma, new_addr);\n\t\tif (!new_pmd)\n\t\t\tbreak;\n\t\tif (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd) || pmd_devmap(*old_pmd)) {\n\t\t\tif (extent == HPAGE_PMD_SIZE) {\n\t\t\t\tbool moved;\n\t\t\t\t/* See comment in move_ptes() */\n\t\t\t\tif (need_rmap_locks)\n\t\t\t\t\ttake_rmap_locks(vma);\n\t\t\t\tmoved = move_huge_pmd(vma, old_addr, new_addr,\n\t\t\t\t\t\t old_end, old_pmd, new_pmd);\n\t\t\t\tif (need_rmap_locks)\n\t\t\t\t\tdrop_rmap_locks(vma);\n\t\t\t\tif (moved)\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsplit_huge_pmd(vma, old_pmd, old_addr);\n\t\t\tif (pmd_trans_unstable(old_pmd))\n\t\t\t\tcontinue;\n\t\t} else if (extent == PMD_SIZE) {\n#ifdef CONFIG_HAVE_MOVE_PMD\n\t\t\t/*\n\t\t\t * If the extent is PMD-sized, try to speed the move by\n\t\t\t * moving at the PMD level if possible.\n\t\t\t */\n\t\t\tbool moved;\n\n\t\t\tif (need_rmap_locks)\n\t\t\t\ttake_rmap_locks(vma);\n\t\t\tmoved = move_normal_pmd(vma, old_addr, new_addr,\n\t\t\t\t\told_end, old_pmd, new_pmd);\n\t\t\tif (need_rmap_locks)\n\t\t\t\tdrop_rmap_locks(vma);\n\t\t\tif (moved)\n\t\t\t\tcontinue;\n#endif\n\t\t}\n\n\t\tif (pte_alloc(new_vma->vm_mm, new_pmd))\n\t\t\tbreak;\n\t\tnext = (new_addr + PMD_SIZE) & PMD_MASK;\n\t\tif (extent > next - new_addr)\n\t\t\textent = next - new_addr;\n\t\tmove_ptes(vma, old_pmd, old_addr, old_addr + extent, new_vma,\n\t\t\t new_pmd, new_addr, need_rmap_locks);\n\t}\n\n\tmmu_notifier_invalidate_range_end(&range);\n\n\treturn len + old_addr - old_end;\t/* how much done */\n}", "project": "linux", "hash": 70690057593979156175552450811161004469, "size": 77, "commit_id": "5bfea2d9b17f1034a68147a8b03b9789af5700f9", "message": "mm: Fix mremap not considering huge pmd devmap\n\nThe original code in mm/mremap.c checks huge pmd by:\n\n\t\tif (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd)) {\n\nHowever, a DAX mapped nvdimm is mapped as huge page (by default) but it\nis not transparent huge page (_PAGE_PSE | PAGE_DEVMAP). This commit\nchanges the condition to include the case.\n\nThis addresses CVE-2020-10757.\n\nFixes: 5c7fb56e5e3f (\"mm, dax: dax-pmd vs thp-pmd vs hugetlbfs-pmd\")\nCc: \nReported-by: Fan Yang \nSigned-off-by: Fan Yang \nTested-by: Fan Yang \nTested-by: Dan Williams \nReviewed-by: Dan Williams \nAcked-by: Kirill A. Shutemov \nSigned-off-by: Linus Torvalds ", "target": 0, "dataset": "other", "idx": 321574} {"func": "Sfdouble_t sh_strnum(Shell_t *shp, const char *str, char **ptr, int mode) {\n Sfdouble_t d;\n char *last;\n\n if (*str == 0) {\n if (ptr) *ptr = (char *)str;\n return 0;\n }\n errno = 0;\n d = number(str, &last, shp->inarith ? 0 : 10, NULL);\n if (*last) {\n if (*last != '.' || last[1] != '.') {\n d = strval(shp, str, &last, arith, mode);\n Varsubscript = true;\n }\n if (!ptr && *last && mode > 0) errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *last, str);\n } else if (!d && *str == '-') {\n d = -0.0;\n }\n if (ptr) *ptr = last;\n return d;\n}", "project": "ast", "hash": 309916825304971174344136967868648417012, "size": 22, "commit_id": "c7de8b641266bac7c77942239ac659edfee9ecd2", "message": "Harden env var imports", "target": 1, "dataset": "other", "idx": 201806} {"func": "Sfdouble_t sh_strnum(Shell_t *shp, const char *str, char **ptr, int mode) {\n Sfdouble_t d;\n char *last;\n\n if (*str == 0) {\n d = 0.0;\n last = (char *)str;\n } else {\n d = number(str, &last, shp->inarith ? 0 : 10, NULL);\n if (*last && !shp->inarith && sh_isstate(shp, SH_INIT)) {\n // This call is to handle \"base#value\" literals if we're importing untrusted env vars.\n d = number(str, &last, 0, NULL);\n }\n if (*last) {\n if (sh_isstate(shp, SH_INIT)) {\n // Initializing means importing untrusted env vars. Since the string does not appear\n // to be a recognized numeric literal give up. We can't safely call strval() since\n // that allows arbitrary expressions which would create a security vulnerability.\n d = 0.0;\n } else {\n if (*last != '.' || last[1] != '.') {\n d = strval(shp, str, &last, arith, mode);\n Varsubscript = true;\n }\n if (!ptr && *last && mode > 0) {\n errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *last, str);\n }\n }\n } else if (d == 0.0 && *str == '-') {\n d = -0.0;\n }\n }\n if (ptr) *ptr = last;\n return d;\n}", "project": "ast", "hash": 84029568395809826570711187865149217968, "size": 35, "commit_id": "c7de8b641266bac7c77942239ac659edfee9ecd2", "message": "Harden env var imports", "target": 0, "dataset": "other", "idx": 321871} {"func": "int pidfile_write(pid_t pid)\n{\n FILE *f;\n\n if (g_pidfile) {\n f = fopen(g_pidfile, \"w+\");\n } else if (pidfilefd >= 0) {\n f = fdopen(pidfilefd, \"w\");\n if (f) {\n g_pidfile = fd_to_filename(pidfilefd);\n if (!g_pidfile)\n goto error;\n }\n } else {\n return 0;\n }\n\n if (!f) {\n logprintf(STDERR_FILENO, \"Could not open pidfile %s : %s\\n\",\n g_pidfile, strerror(errno));\n goto error;\n }\n\n if (fprintf(f, \"%d\", pid) < 0) {\n logprintf(STDERR_FILENO, \"Could not write to pidfile : %s\\n\",\n strerror(errno));\n goto error;\n }\n\n fclose(f);\n\n return 0;\n\nerror:\n if (f)\n fclose(f);\n return -1;\n}", "project": "swtpm", "hash": 34254869638229224588717382596225694876, "size": 38, "commit_id": "634b6294000fb785b9f12e13b852c18a0888b01e", "message": "swtpm: Switch to open() from fopen() for the pidfile (CVE-2020-28407)\n\nThis patch addresses CVE-2020-28407.\n\nUse the open() call rather than the fopen() call when creating a pidfile.\nAlso prevent us from following symbolic links when opening the pidfile for\nwriting.\n\nSigned-off-by: Stefan Berger ", "target": 1, "dataset": "other", "idx": 201812} {"func": "int pidfile_write(pid_t pid)\n{\n int fd;\n char buffer[32];\n ssize_t nwritten;\n\n if (g_pidfile) {\n fd = open(g_pidfile, O_WRONLY|O_CREAT|O_TRUNC|O_NOFOLLOW,\n S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);\n } else if (pidfilefd >= 0) {\n fd = pidfilefd;\n g_pidfile = fd_to_filename(pidfilefd);\n if (!g_pidfile)\n goto error;\n } else {\n return 0;\n }\n\n if (fd < 0) {\n logprintf(STDERR_FILENO, \"Could not open pidfile %s : %s\\n\",\n g_pidfile, strerror(errno));\n goto error;\n }\n\n if (snprintf(buffer, sizeof(buffer), \"%d\", pid) >= (int)sizeof(buffer)) {\n logprintf(STDERR_FILENO, \"Could not write pid to buffer\\n\");\n goto error_close;\n }\n\n nwritten = write_full(fd, buffer, strlen(buffer));\n if (nwritten < 0 || nwritten != (ssize_t)strlen(buffer)) {\n logprintf(STDERR_FILENO, \"Could not write to pidfile : %s\\n\",\n strerror(errno));\n goto error_close;\n }\n\n close(fd);\n\n return 0;\n\nerror_close:\n if (fd != pidfilefd)\n close(fd);\n\nerror:\n return -1;\n}", "project": "swtpm", "hash": 20375191730023779922313833710750581834, "size": 47, "commit_id": "634b6294000fb785b9f12e13b852c18a0888b01e", "message": "swtpm: Switch to open() from fopen() for the pidfile (CVE-2020-28407)\n\nThis patch addresses CVE-2020-28407.\n\nUse the open() call rather than the fopen() call when creating a pidfile.\nAlso prevent us from following symbolic links when opening the pidfile for\nwriting.\n\nSigned-off-by: Stefan Berger ", "target": 0, "dataset": "other", "idx": 322084} {"func": "extern int x11_set_xauth(char *xauthority, char *cookie,\n\t\t\t char *host, uint16_t display)\n{\n\tint i=0, status;\n\tchar *result;\n\tchar **xauth_argv;\n\n\txauth_argv = xmalloc(sizeof(char *) * 10);\n\txauth_argv[i++] = xstrdup(\"xauth\");\n\txauth_argv[i++] = xstrdup(\"-v\");\n\txauth_argv[i++] = xstrdup(\"-f\");\n\txauth_argv[i++] = xstrdup(xauthority);\n\txauth_argv[i++] = xstrdup(\"add\");\n\txauth_argv[i++] = xstrdup_printf(\"%s/unix:%u\", host, display);\n\txauth_argv[i++] = xstrdup(\"MIT-MAGIC-COOKIE-1\");\n\txauth_argv[i++] = xstrdup(cookie);\n\txauth_argv[i++] = NULL;\n\txassert(i < 10);\n\n\tresult = run_command(\"xauth\", XAUTH_PATH, xauth_argv, 10000, 0,\n\t\t\t &status);\n\n\tfree_command_argv(xauth_argv);\n\n\tdebug2(\"%s: result from xauth: %s\", __func__, result);\n\txfree(result);\n\n\treturn status;\n}", "project": "slurm", "hash": 84215474414950344258573648975773029635, "size": 29, "commit_id": "07309deb45c33e735e191faf9dd31cca1054a15c", "message": "X11 forwarding - avoid unsafe use of magic cookie as arg to xauth command.\n\nMagic cookie can leak through /proc this way. There is a race here between\nthis usually short-lived xauth command running and an attacker scraping\nthe value from /proc. This can be exacerbated through use of\nX11Parameters=home_xauthority on a cluster with a shared home directory\nunder heavy load.\n\nCVE-2020-27746.", "target": 1, "dataset": "other", "idx": 201848} {"func": "extern int x11_delete_xauth(char *xauthority, char *host, uint16_t display)\n{\n\tint i=0, status;\n\tchar *result;\n\tchar **xauth_argv;\n\n\txauth_argv = xmalloc(sizeof(char *) * 10);\n\txauth_argv[i++] = xstrdup(\"xauth\");\n\txauth_argv[i++] = xstrdup(\"-v\");\n\txauth_argv[i++] = xstrdup(\"-f\");\n\txauth_argv[i++] = xstrdup(xauthority);\n\txauth_argv[i++] = xstrdup(\"remove\");\n\txauth_argv[i++] = xstrdup_printf(\"%s/unix:%u\", host, display);\n\txauth_argv[i++] = NULL;\n\txassert(i < 10);\n\n\tresult = run_command(\"xauth\", XAUTH_PATH, xauth_argv, 10000, 0,\n\t\t\t &status);\n\n\tfree_command_argv(xauth_argv);\n\n\tdebug2(\"%s: result from xauth: %s\", __func__, result);\n\txfree(result);\n\n\treturn status;\n}", "project": "slurm", "hash": 128496414230349176263839705694684206156, "size": 26, "commit_id": "07309deb45c33e735e191faf9dd31cca1054a15c", "message": "X11 forwarding - avoid unsafe use of magic cookie as arg to xauth command.\n\nMagic cookie can leak through /proc this way. There is a race here between\nthis usually short-lived xauth command running and an attacker scraping\nthe value from /proc. This can be exacerbated through use of\nX11Parameters=home_xauthority on a cluster with a shared home directory\nunder heavy load.\n\nCVE-2020-27746.", "target": 0, "dataset": "other", "idx": 323088} {"func": "int do_madvise(unsigned long start, size_t len_in, int behavior)\n{\n\tunsigned long end, tmp;\n\tstruct vm_area_struct *vma, *prev;\n\tint unmapped_error = 0;\n\tint error = -EINVAL;\n\tint write;\n\tsize_t len;\n\tstruct blk_plug plug;\n\n\tstart = untagged_addr(start);\n\n\tif (!madvise_behavior_valid(behavior))\n\t\treturn error;\n\n\tif (!PAGE_ALIGNED(start))\n\t\treturn error;\n\tlen = PAGE_ALIGN(len_in);\n\n\t/* Check to see whether len was rounded up from small -ve to zero */\n\tif (len_in && !len)\n\t\treturn error;\n\n\tend = start + len;\n\tif (end < start)\n\t\treturn error;\n\n\terror = 0;\n\tif (end == start)\n\t\treturn error;\n\n#ifdef CONFIG_MEMORY_FAILURE\n\tif (behavior == MADV_HWPOISON || behavior == MADV_SOFT_OFFLINE)\n\t\treturn madvise_inject_error(behavior, start, start + len_in);\n#endif\n\n\twrite = madvise_need_mmap_write(behavior);\n\tif (write) {\n\t\tif (down_write_killable(¤t->mm->mmap_sem))\n\t\t\treturn -EINTR;\n\t} else {\n\t\tdown_read(¤t->mm->mmap_sem);\n\t}\n\n\t/*\n\t * If the interval [start,end) covers some unmapped address\n\t * ranges, just ignore them, but return -ENOMEM at the end.\n\t * - different from the way of handling in mlock etc.\n\t */\n\tvma = find_vma_prev(current->mm, start, &prev);\n\tif (vma && start > vma->vm_start)\n\t\tprev = vma;\n\n\tblk_start_plug(&plug);\n\tfor (;;) {\n\t\t/* Still start < end. */\n\t\terror = -ENOMEM;\n\t\tif (!vma)\n\t\t\tgoto out;\n\n\t\t/* Here start < (end|vma->vm_end). */\n\t\tif (start < vma->vm_start) {\n\t\t\tunmapped_error = -ENOMEM;\n\t\t\tstart = vma->vm_start;\n\t\t\tif (start >= end)\n\t\t\t\tgoto out;\n\t\t}\n\n\t\t/* Here vma->vm_start <= start < (end|vma->vm_end) */\n\t\ttmp = vma->vm_end;\n\t\tif (end < tmp)\n\t\t\ttmp = end;\n\n\t\t/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */\n\t\terror = madvise_vma(vma, &prev, start, tmp, behavior);\n\t\tif (error)\n\t\t\tgoto out;\n\t\tstart = tmp;\n\t\tif (prev && start < prev->vm_end)\n\t\t\tstart = prev->vm_end;\n\t\terror = unmapped_error;\n\t\tif (start >= end)\n\t\t\tgoto out;\n\t\tif (prev)\n\t\t\tvma = prev->vm_next;\n\t\telse\t/* madvise_remove dropped mmap_sem */\n\t\t\tvma = find_vma(current->mm, start);\n\t}\nout:\n\tblk_finish_plug(&plug);\n\tif (write)\n\t\tup_write(¤t->mm->mmap_sem);\n\telse\n\t\tup_read(¤t->mm->mmap_sem);\n\n\treturn error;\n}", "project": "linux", "hash": 112062203693169171312729510010872998987, "size": 97, "commit_id": "bc0c4d1e176eeb614dc8734fc3ace34292771f11", "message": "mm: check that mm is still valid in madvise()\n\nIORING_OP_MADVISE can end up basically doing mprotect() on the VM of\nanother process, which means that it can race with our crazy core dump\nhandling which accesses the VM state without holding the mmap_sem\n(because it incorrectly thinks that it is the final user).\n\nThis is clearly a core dumping problem, but we've never fixed it the\nright way, and instead have the notion of \"check that the mm is still\nok\" using mmget_still_valid() after getting the mmap_sem for writing in\nany situation where we're not the original VM thread.\n\nSee commit 04f5866e41fb (\"coredump: fix race condition between\nmmget_not_zero()/get_task_mm() and core dumping\") for more background on\nthis whole mmget_still_valid() thing. You might want to have a barf bag\nhandy when you do.\n\nWe're discussing just fixing this properly in the only remaining core\ndumping routines. But even if we do that, let's make do_madvise() do\nthe right thing, and then when we fix core dumping, we can remove all\nthese mmget_still_valid() checks.\n\nReported-and-tested-by: Jann Horn \nFixes: c1ca757bd6f4 (\"io_uring: add IORING_OP_MADVISE\")\nAcked-by: Jens Axboe \nSigned-off-by: Linus Torvalds ", "target": 1, "dataset": "other", "idx": 201869} {"func": "int do_madvise(unsigned long start, size_t len_in, int behavior)\n{\n\tunsigned long end, tmp;\n\tstruct vm_area_struct *vma, *prev;\n\tint unmapped_error = 0;\n\tint error = -EINVAL;\n\tint write;\n\tsize_t len;\n\tstruct blk_plug plug;\n\n\tstart = untagged_addr(start);\n\n\tif (!madvise_behavior_valid(behavior))\n\t\treturn error;\n\n\tif (!PAGE_ALIGNED(start))\n\t\treturn error;\n\tlen = PAGE_ALIGN(len_in);\n\n\t/* Check to see whether len was rounded up from small -ve to zero */\n\tif (len_in && !len)\n\t\treturn error;\n\n\tend = start + len;\n\tif (end < start)\n\t\treturn error;\n\n\terror = 0;\n\tif (end == start)\n\t\treturn error;\n\n#ifdef CONFIG_MEMORY_FAILURE\n\tif (behavior == MADV_HWPOISON || behavior == MADV_SOFT_OFFLINE)\n\t\treturn madvise_inject_error(behavior, start, start + len_in);\n#endif\n\n\twrite = madvise_need_mmap_write(behavior);\n\tif (write) {\n\t\tif (down_write_killable(¤t->mm->mmap_sem))\n\t\t\treturn -EINTR;\n\n\t\t/*\n\t\t * We may have stolen the mm from another process\n\t\t * that is undergoing core dumping.\n\t\t *\n\t\t * Right now that's io_ring, in the future it may\n\t\t * be remote process management and not \"current\"\n\t\t * at all.\n\t\t *\n\t\t * We need to fix core dumping to not do this,\n\t\t * but for now we have the mmget_still_valid()\n\t\t * model.\n\t\t */\n\t\tif (!mmget_still_valid(current->mm)) {\n\t\t\tup_write(¤t->mm->mmap_sem);\n\t\t\treturn -EINTR;\n\t\t}\n\t} else {\n\t\tdown_read(¤t->mm->mmap_sem);\n\t}\n\n\t/*\n\t * If the interval [start,end) covers some unmapped address\n\t * ranges, just ignore them, but return -ENOMEM at the end.\n\t * - different from the way of handling in mlock etc.\n\t */\n\tvma = find_vma_prev(current->mm, start, &prev);\n\tif (vma && start > vma->vm_start)\n\t\tprev = vma;\n\n\tblk_start_plug(&plug);\n\tfor (;;) {\n\t\t/* Still start < end. */\n\t\terror = -ENOMEM;\n\t\tif (!vma)\n\t\t\tgoto out;\n\n\t\t/* Here start < (end|vma->vm_end). */\n\t\tif (start < vma->vm_start) {\n\t\t\tunmapped_error = -ENOMEM;\n\t\t\tstart = vma->vm_start;\n\t\t\tif (start >= end)\n\t\t\t\tgoto out;\n\t\t}\n\n\t\t/* Here vma->vm_start <= start < (end|vma->vm_end) */\n\t\ttmp = vma->vm_end;\n\t\tif (end < tmp)\n\t\t\ttmp = end;\n\n\t\t/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */\n\t\terror = madvise_vma(vma, &prev, start, tmp, behavior);\n\t\tif (error)\n\t\t\tgoto out;\n\t\tstart = tmp;\n\t\tif (prev && start < prev->vm_end)\n\t\t\tstart = prev->vm_end;\n\t\terror = unmapped_error;\n\t\tif (start >= end)\n\t\t\tgoto out;\n\t\tif (prev)\n\t\t\tvma = prev->vm_next;\n\t\telse\t/* madvise_remove dropped mmap_sem */\n\t\t\tvma = find_vma(current->mm, start);\n\t}\nout:\n\tblk_finish_plug(&plug);\n\tif (write)\n\t\tup_write(¤t->mm->mmap_sem);\n\telse\n\t\tup_read(¤t->mm->mmap_sem);\n\n\treturn error;\n}", "project": "linux", "hash": 262379304761782825761220862266520319644, "size": 114, "commit_id": "bc0c4d1e176eeb614dc8734fc3ace34292771f11", "message": "mm: check that mm is still valid in madvise()\n\nIORING_OP_MADVISE can end up basically doing mprotect() on the VM of\nanother process, which means that it can race with our crazy core dump\nhandling which accesses the VM state without holding the mmap_sem\n(because it incorrectly thinks that it is the final user).\n\nThis is clearly a core dumping problem, but we've never fixed it the\nright way, and instead have the notion of \"check that the mm is still\nok\" using mmget_still_valid() after getting the mmap_sem for writing in\nany situation where we're not the original VM thread.\n\nSee commit 04f5866e41fb (\"coredump: fix race condition between\nmmget_not_zero()/get_task_mm() and core dumping\") for more background on\nthis whole mmget_still_valid() thing. You might want to have a barf bag\nhandy when you do.\n\nWe're discussing just fixing this properly in the only remaining core\ndumping routines. But even if we do that, let's make do_madvise() do\nthe right thing, and then when we fix core dumping, we can remove all\nthese mmget_still_valid() checks.\n\nReported-and-tested-by: Jann Horn \nFixes: c1ca757bd6f4 (\"io_uring: add IORING_OP_MADVISE\")\nAcked-by: Jens Axboe \nSigned-off-by: Linus Torvalds ", "target": 0, "dataset": "other", "idx": 323578} {"func": "archive_string_append_from_wcs(struct archive_string *as,\n const wchar_t *w, size_t len)\n{\n\t/* We cannot use the standard wcstombs() here because it\n\t * cannot tell us how big the output buffer should be. So\n\t * I've built a loop around wcrtomb() or wctomb() that\n\t * converts a character at a time and resizes the string as\n\t * needed. We prefer wcrtomb() when it's available because\n\t * it's thread-safe. */\n\tint n, ret_val = 0;\n\tchar *p;\n\tchar *end;\n#if HAVE_WCRTOMB\n\tmbstate_t shift_state;\n\n\tmemset(&shift_state, 0, sizeof(shift_state));\n#else\n\t/* Clear the shift state before starting. */\n\twctomb(NULL, L'\\0');\n#endif\n\t/*\n\t * Allocate buffer for MBS.\n\t * We need this allocation here since it is possible that\n\t * as->s is still NULL.\n\t */\n\tif (archive_string_ensure(as, as->length + len + 1) == NULL)\n\t\treturn (-1);\n\n\tp = as->s + as->length;\n\tend = as->s + as->buffer_length - MB_CUR_MAX -1;\n\twhile (*w != L'\\0' && len > 0) {\n\t\tif (p >= end) {\n\t\t\tas->length = p - as->s;\n\t\t\tas->s[as->length] = '\\0';\n\t\t\t/* Re-allocate buffer for MBS. */\n\t\t\tif (archive_string_ensure(as,\n\t\t\t as->length + len * 2 + 1) == NULL)\n\t\t\t\treturn (-1);\n\t\t\tp = as->s + as->length;\n\t\t\tend = as->s + as->buffer_length - MB_CUR_MAX -1;\n\t\t}\n#if HAVE_WCRTOMB\n\t\tn = wcrtomb(p, *w++, &shift_state);\n#else\n\t\tn = wctomb(p, *w++);\n#endif\n\t\tif (n == -1) {\n\t\t\tif (errno == EILSEQ) {\n\t\t\t\t/* Skip an illegal wide char. */\n\t\t\t\t*p++ = '?';\n\t\t\t\tret_val = -1;\n\t\t\t} else {\n\t\t\t\tret_val = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else\n\t\t\tp += n;\n\t\tlen--;\n\t}\n\tas->length = p - as->s;\n\tas->s[as->length] = '\\0';\n\treturn (ret_val);\n}", "project": "libarchive", "hash": 267706670982642914719821262234524237398, "size": 63, "commit_id": "4f085eea879e2be745f4d9bf57e8513ae48157f4", "message": "Fix a possible heap-buffer-overflow in archive_string_append_from_wcs()\n\nWhen we grow the archive_string buffer, we have to make sure it fits\nat least one maximum-sized multibyte character in the current locale\nand the null character.\n\nFixes #1298", "target": 1, "dataset": "other", "idx": 201874} {"func": "archive_string_append_from_wcs(struct archive_string *as,\n const wchar_t *w, size_t len)\n{\n\t/* We cannot use the standard wcstombs() here because it\n\t * cannot tell us how big the output buffer should be. So\n\t * I've built a loop around wcrtomb() or wctomb() that\n\t * converts a character at a time and resizes the string as\n\t * needed. We prefer wcrtomb() when it's available because\n\t * it's thread-safe. */\n\tint n, ret_val = 0;\n\tchar *p;\n\tchar *end;\n#if HAVE_WCRTOMB\n\tmbstate_t shift_state;\n\n\tmemset(&shift_state, 0, sizeof(shift_state));\n#else\n\t/* Clear the shift state before starting. */\n\twctomb(NULL, L'\\0');\n#endif\n\t/*\n\t * Allocate buffer for MBS.\n\t * We need this allocation here since it is possible that\n\t * as->s is still NULL.\n\t */\n\tif (archive_string_ensure(as, as->length + len + 1) == NULL)\n\t\treturn (-1);\n\n\tp = as->s + as->length;\n\tend = as->s + as->buffer_length - MB_CUR_MAX -1;\n\twhile (*w != L'\\0' && len > 0) {\n\t\tif (p >= end) {\n\t\t\tas->length = p - as->s;\n\t\t\tas->s[as->length] = '\\0';\n\t\t\t/* Re-allocate buffer for MBS. */\n\t\t\tif (archive_string_ensure(as,\n\t\t\t as->length + max(len * 2,\n\t\t\t (size_t)MB_CUR_MAX) + 1) == NULL)\n\t\t\t\treturn (-1);\n\t\t\tp = as->s + as->length;\n\t\t\tend = as->s + as->buffer_length - MB_CUR_MAX -1;\n\t\t}\n#if HAVE_WCRTOMB\n\t\tn = wcrtomb(p, *w++, &shift_state);\n#else\n\t\tn = wctomb(p, *w++);\n#endif\n\t\tif (n == -1) {\n\t\t\tif (errno == EILSEQ) {\n\t\t\t\t/* Skip an illegal wide char. */\n\t\t\t\t*p++ = '?';\n\t\t\t\tret_val = -1;\n\t\t\t} else {\n\t\t\t\tret_val = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else\n\t\t\tp += n;\n\t\tlen--;\n\t}\n\tas->length = p - as->s;\n\tas->s[as->length] = '\\0';\n\treturn (ret_val);\n}", "project": "libarchive", "hash": 85036731968145354958341451146284390103, "size": 64, "commit_id": "4f085eea879e2be745f4d9bf57e8513ae48157f4", "message": "Fix a possible heap-buffer-overflow in archive_string_append_from_wcs()\n\nWhen we grow the archive_string buffer, we have to make sure it fits\nat least one maximum-sized multibyte character in the current locale\nand the null character.\n\nFixes #1298", "target": 0, "dataset": "other", "idx": 325834} {"func": "void __do_SAK(struct tty_struct *tty)\n{\n#ifdef TTY_SOFT_SAK\n\ttty_hangup(tty);\n#else\n\tstruct task_struct *g, *p;\n\tstruct pid *session;\n\tint\t\ti;\n\n\tif (!tty)\n\t\treturn;\n\tsession = tty->session;\n\n\ttty_ldisc_flush(tty);\n\n\ttty_driver_flush_buffer(tty);\n\n\tread_lock(&tasklist_lock);\n\t/* Kill the entire session */\n\tdo_each_pid_task(session, PIDTYPE_SID, p) {\n\t\ttty_notice(tty, \"SAK: killed process %d (%s): by session\\n\",\n\t\t\t task_pid_nr(p), p->comm);\n\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t} while_each_pid_task(session, PIDTYPE_SID, p);\n\n\t/* Now kill any processes that happen to have the tty open */\n\tdo_each_thread(g, p) {\n\t\tif (p->signal->tty == tty) {\n\t\t\ttty_notice(tty, \"SAK: killed process %d (%s): by controlling tty\\n\",\n\t\t\t\t task_pid_nr(p), p->comm);\n\t\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t\t\tcontinue;\n\t\t}\n\t\ttask_lock(p);\n\t\ti = iterate_fd(p->files, 0, this_tty, tty);\n\t\tif (i != 0) {\n\t\t\ttty_notice(tty, \"SAK: killed process %d (%s): by fd#%d\\n\",\n\t\t\t\t task_pid_nr(p), p->comm, i - 1);\n\t\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t\t}\n\t\ttask_unlock(p);\n\t} while_each_thread(g, p);\n\tread_unlock(&tasklist_lock);\n#endif\n}", "project": "linux", "hash": 327113028686969306396725554617278047338, "size": 45, "commit_id": "c8bcd9c5be24fb9e6132e97da5a35e55a83e36b9", "message": "tty: Fix ->session locking\n\nCurrently, locking of ->session is very inconsistent; most places\nprotect it using the legacy tty mutex, but disassociate_ctty(),\n__do_SAK(), tiocspgrp() and tiocgsid() don't.\nTwo of the writers hold the ctrl_lock (because they already need it for\n->pgrp), but __proc_set_tty() doesn't do that yet.\n\nOn a PREEMPT=y system, an unprivileged user can theoretically abuse\nthis broken locking to read 4 bytes of freed memory via TIOCGSID if\ntiocgsid() is preempted long enough at the right point. (Other things\nmight also go wrong, especially if root-only ioctls are involved; I'm\nnot sure about that.)\n\nChange the locking on ->session such that:\n\n - tty_lock() is held by all writers: By making disassociate_ctty()\n hold it. This should be fine because the same lock can already be\n taken through the call to tty_vhangup_session().\n The tricky part is that we need to shorten the area covered by\n siglock to be able to take tty_lock() without ugly retry logic; as\n far as I can tell, this should be fine, since nothing in the\n signal_struct is touched in the `if (tty)` branch.\n - ctrl_lock is held by all writers: By changing __proc_set_tty() to\n hold the lock a little longer.\n - All readers that aren't holding tty_lock() hold ctrl_lock: By\n adding locking to tiocgsid() and __do_SAK(), and expanding the area\n covered by ctrl_lock in tiocspgrp().\n\nCc: stable@kernel.org\nSigned-off-by: Jann Horn \nReviewed-by: Jiri Slaby \nSigned-off-by: Greg Kroah-Hartman ", "target": 1, "dataset": "other", "idx": 201881} {"func": "void __do_SAK(struct tty_struct *tty)\n{\n#ifdef TTY_SOFT_SAK\n\ttty_hangup(tty);\n#else\n\tstruct task_struct *g, *p;\n\tstruct pid *session;\n\tint\t\ti;\n\tunsigned long flags;\n\n\tif (!tty)\n\t\treturn;\n\n\tspin_lock_irqsave(&tty->ctrl_lock, flags);\n\tsession = get_pid(tty->session);\n\tspin_unlock_irqrestore(&tty->ctrl_lock, flags);\n\n\ttty_ldisc_flush(tty);\n\n\ttty_driver_flush_buffer(tty);\n\n\tread_lock(&tasklist_lock);\n\t/* Kill the entire session */\n\tdo_each_pid_task(session, PIDTYPE_SID, p) {\n\t\ttty_notice(tty, \"SAK: killed process %d (%s): by session\\n\",\n\t\t\t task_pid_nr(p), p->comm);\n\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t} while_each_pid_task(session, PIDTYPE_SID, p);\n\n\t/* Now kill any processes that happen to have the tty open */\n\tdo_each_thread(g, p) {\n\t\tif (p->signal->tty == tty) {\n\t\t\ttty_notice(tty, \"SAK: killed process %d (%s): by controlling tty\\n\",\n\t\t\t\t task_pid_nr(p), p->comm);\n\t\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t\t\tcontinue;\n\t\t}\n\t\ttask_lock(p);\n\t\ti = iterate_fd(p->files, 0, this_tty, tty);\n\t\tif (i != 0) {\n\t\t\ttty_notice(tty, \"SAK: killed process %d (%s): by fd#%d\\n\",\n\t\t\t\t task_pid_nr(p), p->comm, i - 1);\n\t\t\tgroup_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);\n\t\t}\n\t\ttask_unlock(p);\n\t} while_each_thread(g, p);\n\tread_unlock(&tasklist_lock);\n\tput_pid(session);\n#endif\n}", "project": "linux", "hash": 232074957705892957788904660986151519370, "size": 50, "commit_id": "c8bcd9c5be24fb9e6132e97da5a35e55a83e36b9", "message": "tty: Fix ->session locking\n\nCurrently, locking of ->session is very inconsistent; most places\nprotect it using the legacy tty mutex, but disassociate_ctty(),\n__do_SAK(), tiocspgrp() and tiocgsid() don't.\nTwo of the writers hold the ctrl_lock (because they already need it for\n->pgrp), but __proc_set_tty() doesn't do that yet.\n\nOn a PREEMPT=y system, an unprivileged user can theoretically abuse\nthis broken locking to read 4 bytes of freed memory via TIOCGSID if\ntiocgsid() is preempted long enough at the right point. (Other things\nmight also go wrong, especially if root-only ioctls are involved; I'm\nnot sure about that.)\n\nChange the locking on ->session such that:\n\n - tty_lock() is held by all writers: By making disassociate_ctty()\n hold it. This should be fine because the same lock can already be\n taken through the call to tty_vhangup_session().\n The tricky part is that we need to shorten the area covered by\n siglock to be able to take tty_lock() without ugly retry logic; as\n far as I can tell, this should be fine, since nothing in the\n signal_struct is touched in the `if (tty)` branch.\n - ctrl_lock is held by all writers: By changing __proc_set_tty() to\n hold the lock a little longer.\n - All readers that aren't holding tty_lock() hold ctrl_lock: By\n adding locking to tiocgsid() and __do_SAK(), and expanding the area\n covered by ctrl_lock in tiocspgrp().\n\nCc: stable@kernel.org\nSigned-off-by: Jann Horn \nReviewed-by: Jiri Slaby \nSigned-off-by: Greg Kroah-Hartman ", "target": 0, "dataset": "other", "idx": 326074} {"func": "long uv__idna_toascii(const char* s, const char* se, char* d, char* de) {\n const char* si;\n const char* st;\n unsigned c;\n char* ds;\n int rc;\n\n ds = d;\n\n for (si = s; si < se; /* empty */) {\n st = si;\n c = uv__utf8_decode1(&si, se);\n\n if (c != '.')\n if (c != 0x3002) /* \u3002 */\n if (c != 0xFF0E) /* \uff0e */\n if (c != 0xFF61) /* \uff61 */\n continue;\n\n rc = uv__idna_toascii_label(s, st, &d, de);\n\n if (rc < 0)\n return rc;\n\n if (d < de)\n *d++ = '.';\n\n s = si;\n }\n\n if (s < se) {\n rc = uv__idna_toascii_label(s, se, &d, de);\n\n if (rc < 0)\n return rc;\n }\n\n if (d < de)\n *d++ = '\\0';\n\n return d - ds; /* Number of bytes written. */\n}", "project": "libuv", "hash": 330726136045724320865601654107082283716, "size": 42, "commit_id": "b7466e31e4bee160d82a68fca11b1f61d46debae", "message": "idna: fix OOB read in punycode decoder\n\nlibuv was vulnerable to out-of-bounds reads in the uv__idna_toascii()\nfunction which is used to convert strings to ASCII. This is called by\nthe DNS resolution function and can lead to information disclosures or\ncrashes.\n\nReported by Eric Sesterhenn in collaboration with Cure53 and ExpressVPN.\n\nReported-By: Eric Sesterhenn \nFixes: https://github.com/libuv/libuv/issues/3147\nPR-URL: https://github.com/libuv/libuv-private/pull/1\nRefs: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22918\nReviewed-By: Colin Ihrig \nReviewed-By: Richard Lau ", "target": 1, "dataset": "other", "idx": 201892} {"func": "long uv__idna_toascii(const char* s, const char* se, char* d, char* de) {\n const char* si;\n const char* st;\n unsigned c;\n char* ds;\n int rc;\n\n ds = d;\n\n si = s;\n while (si < se) {\n st = si;\n c = uv__utf8_decode1(&si, se);\n\n if (c == -1u)\n return UV_EINVAL;\n\n if (c != '.')\n if (c != 0x3002) /* \u3002 */\n if (c != 0xFF0E) /* \uff0e */\n if (c != 0xFF61) /* \uff61 */\n continue;\n\n rc = uv__idna_toascii_label(s, st, &d, de);\n\n if (rc < 0)\n return rc;\n\n if (d < de)\n *d++ = '.';\n\n s = si;\n }\n\n if (s < se) {\n rc = uv__idna_toascii_label(s, se, &d, de);\n\n if (rc < 0)\n return rc;\n }\n\n if (d < de)\n *d++ = '\\0';\n\n return d - ds; /* Number of bytes written. */\n}", "project": "libuv", "hash": 143364374050282701014374410463146753253, "size": 46, "commit_id": "b7466e31e4bee160d82a68fca11b1f61d46debae", "message": "idna: fix OOB read in punycode decoder\n\nlibuv was vulnerable to out-of-bounds reads in the uv__idna_toascii()\nfunction which is used to convert strings to ASCII. This is called by\nthe DNS resolution function and can lead to information disclosures or\ncrashes.\n\nReported by Eric Sesterhenn in collaboration with Cure53 and ExpressVPN.\n\nReported-By: Eric Sesterhenn \nFixes: https://github.com/libuv/libuv/issues/3147\nPR-URL: https://github.com/libuv/libuv-private/pull/1\nRefs: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22918\nReviewed-By: Colin Ihrig \nReviewed-By: Richard Lau ", "target": 0, "dataset": "other", "idx": 326145} {"func": "static int nf_tables_newset(struct sk_buff *skb, const struct nfnl_info *info,\n\t\t\t const struct nlattr * const nla[])\n{\n\tconst struct nfgenmsg *nfmsg = nlmsg_data(info->nlh);\n\tu32 ktype, dtype, flags, policy, gc_int, objtype;\n\tstruct netlink_ext_ack *extack = info->extack;\n\tu8 genmask = nft_genmask_next(info->net);\n\tint family = nfmsg->nfgen_family;\n\tconst struct nft_set_ops *ops;\n\tstruct nft_expr *expr = NULL;\n\tstruct net *net = info->net;\n\tstruct nft_set_desc desc;\n\tstruct nft_table *table;\n\tunsigned char *udata;\n\tstruct nft_set *set;\n\tstruct nft_ctx ctx;\n\tsize_t alloc_size;\n\tu64 timeout;\n\tchar *name;\n\tint err, i;\n\tu16 udlen;\n\tu64 size;\n\n\tif (nla[NFTA_SET_TABLE] == NULL ||\n\t nla[NFTA_SET_NAME] == NULL ||\n\t nla[NFTA_SET_KEY_LEN] == NULL ||\n\t nla[NFTA_SET_ID] == NULL)\n\t\treturn -EINVAL;\n\n\tmemset(&desc, 0, sizeof(desc));\n\n\tktype = NFT_DATA_VALUE;\n\tif (nla[NFTA_SET_KEY_TYPE] != NULL) {\n\t\tktype = ntohl(nla_get_be32(nla[NFTA_SET_KEY_TYPE]));\n\t\tif ((ktype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK)\n\t\t\treturn -EINVAL;\n\t}\n\n\tdesc.klen = ntohl(nla_get_be32(nla[NFTA_SET_KEY_LEN]));\n\tif (desc.klen == 0 || desc.klen > NFT_DATA_VALUE_MAXLEN)\n\t\treturn -EINVAL;\n\n\tflags = 0;\n\tif (nla[NFTA_SET_FLAGS] != NULL) {\n\t\tflags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));\n\t\tif (flags & ~(NFT_SET_ANONYMOUS | NFT_SET_CONSTANT |\n\t\t\t NFT_SET_INTERVAL | NFT_SET_TIMEOUT |\n\t\t\t NFT_SET_MAP | NFT_SET_EVAL |\n\t\t\t NFT_SET_OBJECT | NFT_SET_CONCAT | NFT_SET_EXPR))\n\t\t\treturn -EOPNOTSUPP;\n\t\t/* Only one of these operations is supported */\n\t\tif ((flags & (NFT_SET_MAP | NFT_SET_OBJECT)) ==\n\t\t\t (NFT_SET_MAP | NFT_SET_OBJECT))\n\t\t\treturn -EOPNOTSUPP;\n\t\tif ((flags & (NFT_SET_EVAL | NFT_SET_OBJECT)) ==\n\t\t\t (NFT_SET_EVAL | NFT_SET_OBJECT))\n\t\t\treturn -EOPNOTSUPP;\n\t}\n\n\tdtype = 0;\n\tif (nla[NFTA_SET_DATA_TYPE] != NULL) {\n\t\tif (!(flags & NFT_SET_MAP))\n\t\t\treturn -EINVAL;\n\n\t\tdtype = ntohl(nla_get_be32(nla[NFTA_SET_DATA_TYPE]));\n\t\tif ((dtype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK &&\n\t\t dtype != NFT_DATA_VERDICT)\n\t\t\treturn -EINVAL;\n\n\t\tif (dtype != NFT_DATA_VERDICT) {\n\t\t\tif (nla[NFTA_SET_DATA_LEN] == NULL)\n\t\t\t\treturn -EINVAL;\n\t\t\tdesc.dlen = ntohl(nla_get_be32(nla[NFTA_SET_DATA_LEN]));\n\t\t\tif (desc.dlen == 0 || desc.dlen > NFT_DATA_VALUE_MAXLEN)\n\t\t\t\treturn -EINVAL;\n\t\t} else\n\t\t\tdesc.dlen = sizeof(struct nft_verdict);\n\t} else if (flags & NFT_SET_MAP)\n\t\treturn -EINVAL;\n\n\tif (nla[NFTA_SET_OBJ_TYPE] != NULL) {\n\t\tif (!(flags & NFT_SET_OBJECT))\n\t\t\treturn -EINVAL;\n\n\t\tobjtype = ntohl(nla_get_be32(nla[NFTA_SET_OBJ_TYPE]));\n\t\tif (objtype == NFT_OBJECT_UNSPEC ||\n\t\t objtype > NFT_OBJECT_MAX)\n\t\t\treturn -EOPNOTSUPP;\n\t} else if (flags & NFT_SET_OBJECT)\n\t\treturn -EINVAL;\n\telse\n\t\tobjtype = NFT_OBJECT_UNSPEC;\n\n\ttimeout = 0;\n\tif (nla[NFTA_SET_TIMEOUT] != NULL) {\n\t\tif (!(flags & NFT_SET_TIMEOUT))\n\t\t\treturn -EINVAL;\n\n\t\terr = nf_msecs_to_jiffies64(nla[NFTA_SET_TIMEOUT], &timeout);\n\t\tif (err)\n\t\t\treturn err;\n\t}\n\tgc_int = 0;\n\tif (nla[NFTA_SET_GC_INTERVAL] != NULL) {\n\t\tif (!(flags & NFT_SET_TIMEOUT))\n\t\t\treturn -EINVAL;\n\t\tgc_int = ntohl(nla_get_be32(nla[NFTA_SET_GC_INTERVAL]));\n\t}\n\n\tpolicy = NFT_SET_POL_PERFORMANCE;\n\tif (nla[NFTA_SET_POLICY] != NULL)\n\t\tpolicy = ntohl(nla_get_be32(nla[NFTA_SET_POLICY]));\n\n\tif (nla[NFTA_SET_DESC] != NULL) {\n\t\terr = nf_tables_set_desc_parse(&desc, nla[NFTA_SET_DESC]);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tif (nla[NFTA_SET_EXPR] || nla[NFTA_SET_EXPRESSIONS])\n\t\tdesc.expr = true;\n\n\ttable = nft_table_lookup(net, nla[NFTA_SET_TABLE], family, genmask,\n\t\t\t\t NETLINK_CB(skb).portid);\n\tif (IS_ERR(table)) {\n\t\tNL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);\n\t\treturn PTR_ERR(table);\n\t}\n\n\tnft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);\n\n\tset = nft_set_lookup(table, nla[NFTA_SET_NAME], genmask);\n\tif (IS_ERR(set)) {\n\t\tif (PTR_ERR(set) != -ENOENT) {\n\t\t\tNL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);\n\t\t\treturn PTR_ERR(set);\n\t\t}\n\t} else {\n\t\tif (info->nlh->nlmsg_flags & NLM_F_EXCL) {\n\t\t\tNL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);\n\t\t\treturn -EEXIST;\n\t\t}\n\t\tif (info->nlh->nlmsg_flags & NLM_F_REPLACE)\n\t\t\treturn -EOPNOTSUPP;\n\n\t\treturn 0;\n\t}\n\n\tif (!(info->nlh->nlmsg_flags & NLM_F_CREATE))\n\t\treturn -ENOENT;\n\n\tops = nft_select_set_ops(&ctx, nla, &desc, policy);\n\tif (IS_ERR(ops))\n\t\treturn PTR_ERR(ops);\n\n\tudlen = 0;\n\tif (nla[NFTA_SET_USERDATA])\n\t\tudlen = nla_len(nla[NFTA_SET_USERDATA]);\n\n\tsize = 0;\n\tif (ops->privsize != NULL)\n\t\tsize = ops->privsize(nla, &desc);\n\talloc_size = sizeof(*set) + size + udlen;\n\tif (alloc_size < size)\n\t\treturn -ENOMEM;\n\tset = kvzalloc(alloc_size, GFP_KERNEL);\n\tif (!set)\n\t\treturn -ENOMEM;\n\n\tname = nla_strdup(nla[NFTA_SET_NAME], GFP_KERNEL);\n\tif (!name) {\n\t\terr = -ENOMEM;\n\t\tgoto err_set_name;\n\t}\n\n\terr = nf_tables_set_alloc_name(&ctx, set, name);\n\tkfree(name);\n\tif (err < 0)\n\t\tgoto err_set_alloc_name;\n\n\tif (nla[NFTA_SET_EXPR]) {\n\t\texpr = nft_set_elem_expr_alloc(&ctx, set, nla[NFTA_SET_EXPR]);\n\t\tif (IS_ERR(expr)) {\n\t\t\terr = PTR_ERR(expr);\n\t\t\tgoto err_set_alloc_name;\n\t\t}\n\t\tset->exprs[0] = expr;\n\t\tset->num_exprs++;\n\t} else if (nla[NFTA_SET_EXPRESSIONS]) {\n\t\tstruct nft_expr *expr;\n\t\tstruct nlattr *tmp;\n\t\tint left;\n\n\t\tif (!(flags & NFT_SET_EXPR)) {\n\t\t\terr = -EINVAL;\n\t\t\tgoto err_set_alloc_name;\n\t\t}\n\t\ti = 0;\n\t\tnla_for_each_nested(tmp, nla[NFTA_SET_EXPRESSIONS], left) {\n\t\t\tif (i == NFT_SET_EXPR_MAX) {\n\t\t\t\terr = -E2BIG;\n\t\t\t\tgoto err_set_init;\n\t\t\t}\n\t\t\tif (nla_type(tmp) != NFTA_LIST_ELEM) {\n\t\t\t\terr = -EINVAL;\n\t\t\t\tgoto err_set_init;\n\t\t\t}\n\t\t\texpr = nft_set_elem_expr_alloc(&ctx, set, tmp);\n\t\t\tif (IS_ERR(expr)) {\n\t\t\t\terr = PTR_ERR(expr);\n\t\t\t\tgoto err_set_init;\n\t\t\t}\n\t\t\tset->exprs[i++] = expr;\n\t\t\tset->num_exprs++;\n\t\t}\n\t}\n\n\tudata = NULL;\n\tif (udlen) {\n\t\tudata = set->data + size;\n\t\tnla_memcpy(udata, nla[NFTA_SET_USERDATA], udlen);\n\t}\n\n\tINIT_LIST_HEAD(&set->bindings);\n\tINIT_LIST_HEAD(&set->catchall_list);\n\tset->table = table;\n\twrite_pnet(&set->net, net);\n\tset->ops = ops;\n\tset->ktype = ktype;\n\tset->klen = desc.klen;\n\tset->dtype = dtype;\n\tset->objtype = objtype;\n\tset->dlen = desc.dlen;\n\tset->flags = flags;\n\tset->size = desc.size;\n\tset->policy = policy;\n\tset->udlen = udlen;\n\tset->udata = udata;\n\tset->timeout = timeout;\n\tset->gc_int = gc_int;\n\tset->handle = nf_tables_alloc_handle(table);\n\n\tset->field_count = desc.field_count;\n\tfor (i = 0; i < desc.field_count; i++)\n\t\tset->field_len[i] = desc.field_len[i];\n\n\terr = ops->init(set, &desc, nla);\n\tif (err < 0)\n\t\tgoto err_set_init;\n\n\terr = nft_trans_set_add(&ctx, NFT_MSG_NEWSET, set);\n\tif (err < 0)\n\t\tgoto err_set_trans;\n\n\tlist_add_tail_rcu(&set->list, &table->sets);\n\ttable->use++;\n\treturn 0;\n\nerr_set_trans:\n\tops->destroy(set);\nerr_set_init:\n\tfor (i = 0; i < set->num_exprs; i++)\n\t\tnft_expr_destroy(&ctx, set->exprs[i]);\nerr_set_alloc_name:\n\tkfree(set->name);\nerr_set_name:\n\tkvfree(set);\n\treturn err;\n}", "project": "linux", "hash": 193021357358532201027347093134489495686, "size": 269, "commit_id": "ad9f151e560b016b6ad3280b48e42fa11e1a5440", "message": "netfilter: nf_tables: initialize set before expression setup\n\nnft_set_elem_expr_alloc() needs an initialized set if expression sets on\nthe NFT_EXPR_GC flag. Move set fields initialization before expression\nsetup.\n\n[4512935.019450] ==================================================================\n[4512935.019456] BUG: KASAN: null-ptr-deref in nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019487] Read of size 8 at addr 0000000000000070 by task nft/23532\n[4512935.019494] CPU: 1 PID: 23532 Comm: nft Not tainted 5.12.0-rc4+ #48\n[...]\n[4512935.019502] Call Trace:\n[4512935.019505] dump_stack+0x89/0xb4\n[4512935.019512] ? nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019536] ? nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019560] kasan_report.cold.12+0x5f/0xd8\n[4512935.019566] ? nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019590] nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019615] nf_tables_newset+0xc7f/0x1460 [nf_tables]\n\nReported-by: syzbot+ce96ca2b1d0b37c6422d@syzkaller.appspotmail.com\nFixes: 65038428b2c6 (\"netfilter: nf_tables: allow to specify stateful expression in set definition\")\nSigned-off-by: Pablo Neira Ayuso ", "target": 1, "dataset": "other", "idx": 202069} {"func": "static int nf_tables_newset(struct sk_buff *skb, const struct nfnl_info *info,\n\t\t\t const struct nlattr * const nla[])\n{\n\tconst struct nfgenmsg *nfmsg = nlmsg_data(info->nlh);\n\tu32 ktype, dtype, flags, policy, gc_int, objtype;\n\tstruct netlink_ext_ack *extack = info->extack;\n\tu8 genmask = nft_genmask_next(info->net);\n\tint family = nfmsg->nfgen_family;\n\tconst struct nft_set_ops *ops;\n\tstruct nft_expr *expr = NULL;\n\tstruct net *net = info->net;\n\tstruct nft_set_desc desc;\n\tstruct nft_table *table;\n\tunsigned char *udata;\n\tstruct nft_set *set;\n\tstruct nft_ctx ctx;\n\tsize_t alloc_size;\n\tu64 timeout;\n\tchar *name;\n\tint err, i;\n\tu16 udlen;\n\tu64 size;\n\n\tif (nla[NFTA_SET_TABLE] == NULL ||\n\t nla[NFTA_SET_NAME] == NULL ||\n\t nla[NFTA_SET_KEY_LEN] == NULL ||\n\t nla[NFTA_SET_ID] == NULL)\n\t\treturn -EINVAL;\n\n\tmemset(&desc, 0, sizeof(desc));\n\n\tktype = NFT_DATA_VALUE;\n\tif (nla[NFTA_SET_KEY_TYPE] != NULL) {\n\t\tktype = ntohl(nla_get_be32(nla[NFTA_SET_KEY_TYPE]));\n\t\tif ((ktype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK)\n\t\t\treturn -EINVAL;\n\t}\n\n\tdesc.klen = ntohl(nla_get_be32(nla[NFTA_SET_KEY_LEN]));\n\tif (desc.klen == 0 || desc.klen > NFT_DATA_VALUE_MAXLEN)\n\t\treturn -EINVAL;\n\n\tflags = 0;\n\tif (nla[NFTA_SET_FLAGS] != NULL) {\n\t\tflags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));\n\t\tif (flags & ~(NFT_SET_ANONYMOUS | NFT_SET_CONSTANT |\n\t\t\t NFT_SET_INTERVAL | NFT_SET_TIMEOUT |\n\t\t\t NFT_SET_MAP | NFT_SET_EVAL |\n\t\t\t NFT_SET_OBJECT | NFT_SET_CONCAT | NFT_SET_EXPR))\n\t\t\treturn -EOPNOTSUPP;\n\t\t/* Only one of these operations is supported */\n\t\tif ((flags & (NFT_SET_MAP | NFT_SET_OBJECT)) ==\n\t\t\t (NFT_SET_MAP | NFT_SET_OBJECT))\n\t\t\treturn -EOPNOTSUPP;\n\t\tif ((flags & (NFT_SET_EVAL | NFT_SET_OBJECT)) ==\n\t\t\t (NFT_SET_EVAL | NFT_SET_OBJECT))\n\t\t\treturn -EOPNOTSUPP;\n\t}\n\n\tdtype = 0;\n\tif (nla[NFTA_SET_DATA_TYPE] != NULL) {\n\t\tif (!(flags & NFT_SET_MAP))\n\t\t\treturn -EINVAL;\n\n\t\tdtype = ntohl(nla_get_be32(nla[NFTA_SET_DATA_TYPE]));\n\t\tif ((dtype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK &&\n\t\t dtype != NFT_DATA_VERDICT)\n\t\t\treturn -EINVAL;\n\n\t\tif (dtype != NFT_DATA_VERDICT) {\n\t\t\tif (nla[NFTA_SET_DATA_LEN] == NULL)\n\t\t\t\treturn -EINVAL;\n\t\t\tdesc.dlen = ntohl(nla_get_be32(nla[NFTA_SET_DATA_LEN]));\n\t\t\tif (desc.dlen == 0 || desc.dlen > NFT_DATA_VALUE_MAXLEN)\n\t\t\t\treturn -EINVAL;\n\t\t} else\n\t\t\tdesc.dlen = sizeof(struct nft_verdict);\n\t} else if (flags & NFT_SET_MAP)\n\t\treturn -EINVAL;\n\n\tif (nla[NFTA_SET_OBJ_TYPE] != NULL) {\n\t\tif (!(flags & NFT_SET_OBJECT))\n\t\t\treturn -EINVAL;\n\n\t\tobjtype = ntohl(nla_get_be32(nla[NFTA_SET_OBJ_TYPE]));\n\t\tif (objtype == NFT_OBJECT_UNSPEC ||\n\t\t objtype > NFT_OBJECT_MAX)\n\t\t\treturn -EOPNOTSUPP;\n\t} else if (flags & NFT_SET_OBJECT)\n\t\treturn -EINVAL;\n\telse\n\t\tobjtype = NFT_OBJECT_UNSPEC;\n\n\ttimeout = 0;\n\tif (nla[NFTA_SET_TIMEOUT] != NULL) {\n\t\tif (!(flags & NFT_SET_TIMEOUT))\n\t\t\treturn -EINVAL;\n\n\t\terr = nf_msecs_to_jiffies64(nla[NFTA_SET_TIMEOUT], &timeout);\n\t\tif (err)\n\t\t\treturn err;\n\t}\n\tgc_int = 0;\n\tif (nla[NFTA_SET_GC_INTERVAL] != NULL) {\n\t\tif (!(flags & NFT_SET_TIMEOUT))\n\t\t\treturn -EINVAL;\n\t\tgc_int = ntohl(nla_get_be32(nla[NFTA_SET_GC_INTERVAL]));\n\t}\n\n\tpolicy = NFT_SET_POL_PERFORMANCE;\n\tif (nla[NFTA_SET_POLICY] != NULL)\n\t\tpolicy = ntohl(nla_get_be32(nla[NFTA_SET_POLICY]));\n\n\tif (nla[NFTA_SET_DESC] != NULL) {\n\t\terr = nf_tables_set_desc_parse(&desc, nla[NFTA_SET_DESC]);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tif (nla[NFTA_SET_EXPR] || nla[NFTA_SET_EXPRESSIONS])\n\t\tdesc.expr = true;\n\n\ttable = nft_table_lookup(net, nla[NFTA_SET_TABLE], family, genmask,\n\t\t\t\t NETLINK_CB(skb).portid);\n\tif (IS_ERR(table)) {\n\t\tNL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);\n\t\treturn PTR_ERR(table);\n\t}\n\n\tnft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);\n\n\tset = nft_set_lookup(table, nla[NFTA_SET_NAME], genmask);\n\tif (IS_ERR(set)) {\n\t\tif (PTR_ERR(set) != -ENOENT) {\n\t\t\tNL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);\n\t\t\treturn PTR_ERR(set);\n\t\t}\n\t} else {\n\t\tif (info->nlh->nlmsg_flags & NLM_F_EXCL) {\n\t\t\tNL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);\n\t\t\treturn -EEXIST;\n\t\t}\n\t\tif (info->nlh->nlmsg_flags & NLM_F_REPLACE)\n\t\t\treturn -EOPNOTSUPP;\n\n\t\treturn 0;\n\t}\n\n\tif (!(info->nlh->nlmsg_flags & NLM_F_CREATE))\n\t\treturn -ENOENT;\n\n\tops = nft_select_set_ops(&ctx, nla, &desc, policy);\n\tif (IS_ERR(ops))\n\t\treturn PTR_ERR(ops);\n\n\tudlen = 0;\n\tif (nla[NFTA_SET_USERDATA])\n\t\tudlen = nla_len(nla[NFTA_SET_USERDATA]);\n\n\tsize = 0;\n\tif (ops->privsize != NULL)\n\t\tsize = ops->privsize(nla, &desc);\n\talloc_size = sizeof(*set) + size + udlen;\n\tif (alloc_size < size)\n\t\treturn -ENOMEM;\n\tset = kvzalloc(alloc_size, GFP_KERNEL);\n\tif (!set)\n\t\treturn -ENOMEM;\n\n\tname = nla_strdup(nla[NFTA_SET_NAME], GFP_KERNEL);\n\tif (!name) {\n\t\terr = -ENOMEM;\n\t\tgoto err_set_name;\n\t}\n\n\terr = nf_tables_set_alloc_name(&ctx, set, name);\n\tkfree(name);\n\tif (err < 0)\n\t\tgoto err_set_name;\n\n\tudata = NULL;\n\tif (udlen) {\n\t\tudata = set->data + size;\n\t\tnla_memcpy(udata, nla[NFTA_SET_USERDATA], udlen);\n\t}\n\n\tINIT_LIST_HEAD(&set->bindings);\n\tINIT_LIST_HEAD(&set->catchall_list);\n\tset->table = table;\n\twrite_pnet(&set->net, net);\n\tset->ops = ops;\n\tset->ktype = ktype;\n\tset->klen = desc.klen;\n\tset->dtype = dtype;\n\tset->objtype = objtype;\n\tset->dlen = desc.dlen;\n\tset->flags = flags;\n\tset->size = desc.size;\n\tset->policy = policy;\n\tset->udlen = udlen;\n\tset->udata = udata;\n\tset->timeout = timeout;\n\tset->gc_int = gc_int;\n\n\tset->field_count = desc.field_count;\n\tfor (i = 0; i < desc.field_count; i++)\n\t\tset->field_len[i] = desc.field_len[i];\n\n\terr = ops->init(set, &desc, nla);\n\tif (err < 0)\n\t\tgoto err_set_init;\n\n\tif (nla[NFTA_SET_EXPR]) {\n\t\texpr = nft_set_elem_expr_alloc(&ctx, set, nla[NFTA_SET_EXPR]);\n\t\tif (IS_ERR(expr)) {\n\t\t\terr = PTR_ERR(expr);\n\t\t\tgoto err_set_expr_alloc;\n\t\t}\n\t\tset->exprs[0] = expr;\n\t\tset->num_exprs++;\n\t} else if (nla[NFTA_SET_EXPRESSIONS]) {\n\t\tstruct nft_expr *expr;\n\t\tstruct nlattr *tmp;\n\t\tint left;\n\n\t\tif (!(flags & NFT_SET_EXPR)) {\n\t\t\terr = -EINVAL;\n\t\t\tgoto err_set_expr_alloc;\n\t\t}\n\t\ti = 0;\n\t\tnla_for_each_nested(tmp, nla[NFTA_SET_EXPRESSIONS], left) {\n\t\t\tif (i == NFT_SET_EXPR_MAX) {\n\t\t\t\terr = -E2BIG;\n\t\t\t\tgoto err_set_expr_alloc;\n\t\t\t}\n\t\t\tif (nla_type(tmp) != NFTA_LIST_ELEM) {\n\t\t\t\terr = -EINVAL;\n\t\t\t\tgoto err_set_expr_alloc;\n\t\t\t}\n\t\t\texpr = nft_set_elem_expr_alloc(&ctx, set, tmp);\n\t\t\tif (IS_ERR(expr)) {\n\t\t\t\terr = PTR_ERR(expr);\n\t\t\t\tgoto err_set_expr_alloc;\n\t\t\t}\n\t\t\tset->exprs[i++] = expr;\n\t\t\tset->num_exprs++;\n\t\t}\n\t}\n\n\tset->handle = nf_tables_alloc_handle(table);\n\n\terr = nft_trans_set_add(&ctx, NFT_MSG_NEWSET, set);\n\tif (err < 0)\n\t\tgoto err_set_expr_alloc;\n\n\tlist_add_tail_rcu(&set->list, &table->sets);\n\ttable->use++;\n\treturn 0;\n\nerr_set_expr_alloc:\n\tfor (i = 0; i < set->num_exprs; i++)\n\t\tnft_expr_destroy(&ctx, set->exprs[i]);\n\n\tops->destroy(set);\nerr_set_init:\n\tkfree(set->name);\nerr_set_name:\n\tkvfree(set);\n\treturn err;\n}", "project": "linux", "hash": 70145795789126680677504544991909643805, "size": 270, "commit_id": "ad9f151e560b016b6ad3280b48e42fa11e1a5440", "message": "netfilter: nf_tables: initialize set before expression setup\n\nnft_set_elem_expr_alloc() needs an initialized set if expression sets on\nthe NFT_EXPR_GC flag. Move set fields initialization before expression\nsetup.\n\n[4512935.019450] ==================================================================\n[4512935.019456] BUG: KASAN: null-ptr-deref in nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019487] Read of size 8 at addr 0000000000000070 by task nft/23532\n[4512935.019494] CPU: 1 PID: 23532 Comm: nft Not tainted 5.12.0-rc4+ #48\n[...]\n[4512935.019502] Call Trace:\n[4512935.019505] dump_stack+0x89/0xb4\n[4512935.019512] ? nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019536] ? nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019560] kasan_report.cold.12+0x5f/0xd8\n[4512935.019566] ? nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019590] nft_set_elem_expr_alloc+0x84/0xd0 [nf_tables]\n[4512935.019615] nf_tables_newset+0xc7f/0x1460 [nf_tables]\n\nReported-by: syzbot+ce96ca2b1d0b37c6422d@syzkaller.appspotmail.com\nFixes: 65038428b2c6 (\"netfilter: nf_tables: allow to specify stateful expression in set definition\")\nSigned-off-by: Pablo Neira Ayuso ", "target": 0, "dataset": "other", "idx": 328360} {"func": "static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,\n\t\t\t\tstruct bpf_reg_state *src_reg)\n{\n\tbool src_known = tnum_subreg_is_const(src_reg->var_off);\n\tbool dst_known = tnum_subreg_is_const(dst_reg->var_off);\n\tstruct tnum var32_off = tnum_subreg(dst_reg->var_off);\n\ts32 smin_val = src_reg->smin_value;\n\tu32 umin_val = src_reg->umin_value;\n\n\t/* Assuming scalar64_min_max_or will be called so it is safe\n\t * to skip updating register for known case.\n\t */\n\tif (src_known && dst_known)\n\t\treturn;\n\n\t/* We get our maximum from the var_off, and our minimum is the\n\t * maximum of the operands' minima\n\t */\n\tdst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);\n\tdst_reg->u32_max_value = var32_off.value | var32_off.mask;\n\tif (dst_reg->s32_min_value < 0 || smin_val < 0) {\n\t\t/* Lose signed bounds when ORing negative numbers,\n\t\t * ain't nobody got time for that.\n\t\t */\n\t\tdst_reg->s32_min_value = S32_MIN;\n\t\tdst_reg->s32_max_value = S32_MAX;\n\t} else {\n\t\t/* ORing two positives gives a positive, so safe to\n\t\t * cast result into s64.\n\t\t */\n\t\tdst_reg->s32_min_value = dst_reg->umin_value;\n\t\tdst_reg->s32_max_value = dst_reg->umax_value;\n\t}\n}", "project": "linux", "hash": 165771617226406414034272893159919382683, "size": 34, "commit_id": "5b9fbeb75b6a98955f628e205ac26689bcb1383e", "message": "bpf: Fix scalar32_min_max_or bounds tracking\n\nSimon reported an issue with the current scalar32_min_max_or() implementation.\nThat is, compared to the other 32 bit subreg tracking functions, the code in\nscalar32_min_max_or() stands out that it's using the 64 bit registers instead\nof 32 bit ones. This leads to bounds tracking issues, for example:\n\n [...]\n 8: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 8: (79) r1 = *(u64 *)(r0 +0)\n R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 9: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 9: (b7) r0 = 1\n 10: R0_w=inv1 R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 10: (18) r2 = 0x600000002\n 12: R0_w=inv1 R1_w=inv(id=0) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 12: (ad) if r1 < r2 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: (95) exit\n 14: R0_w=inv1 R1_w=inv(id=0,umax_value=25769803777,var_off=(0x0; 0x7ffffffff)) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 14: (25) if r1 > 0x0 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: (95) exit\n 16: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=25769803777,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 16: (47) r1 |= 0\n 17: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=32212254719,var_off=(0x1; 0x700000000),s32_max_value=1,u32_max_value=1) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n [...]\n\nThe bound tests on the map value force the upper unsigned bound to be 25769803777\nin 64 bit (0b11000000000000000000000000000000001) and then lower one to be 1. By\nusing OR they are truncated and thus result in the range [1,1] for the 32 bit reg\ntracker. This is incorrect given the only thing we know is that the value must be\npositive and thus 2147483647 (0b1111111111111111111111111111111) at max for the\nsubregs. Fix it by using the {u,s}32_{min,max}_value vars instead. This also makes\nsense, for example, for the case where we update dst_reg->s32_{min,max}_value in\nthe else branch we need to use the newly computed dst_reg->u32_{min,max}_value as\nwe know that these are positive. Previously, in the else branch the 64 bit values\nof umin_value=1 and umax_value=32212254719 were used and latter got truncated to\nbe 1 as upper bound there. After the fix the subreg range is now correct:\n\n [...]\n 8: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 8: (79) r1 = *(u64 *)(r0 +0)\n R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 9: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 9: (b7) r0 = 1\n 10: R0_w=inv1 R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 10: (18) r2 = 0x600000002\n 12: R0_w=inv1 R1_w=inv(id=0) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 12: (ad) if r1 < r2 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: (95) exit\n 14: R0_w=inv1 R1_w=inv(id=0,umax_value=25769803777,var_off=(0x0; 0x7ffffffff)) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 14: (25) if r1 > 0x0 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: (95) exit\n 16: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=25769803777,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 16: (47) r1 |= 0\n 17: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=32212254719,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n [...]\n\nFixes: 3f50f132d840 (\"bpf: Verifier, do explicit ALU32 bounds tracking\")\nReported-by: Simon Scannell \nSigned-off-by: Daniel Borkmann \nReviewed-by: John Fastabend \nAcked-by: Alexei Starovoitov ", "target": 1, "dataset": "other", "idx": 202076} {"func": "static void scalar_min_max_or(struct bpf_reg_state *dst_reg,\n\t\t\t struct bpf_reg_state *src_reg)\n{\n\tbool src_known = tnum_is_const(src_reg->var_off);\n\tbool dst_known = tnum_is_const(dst_reg->var_off);\n\ts64 smin_val = src_reg->smin_value;\n\tu64 umin_val = src_reg->umin_value;\n\n\tif (src_known && dst_known) {\n\t\t__mark_reg_known(dst_reg, dst_reg->var_off.value |\n\t\t\t\t\t src_reg->var_off.value);\n\t\treturn;\n\t}\n\n\t/* We get our maximum from the var_off, and our minimum is the\n\t * maximum of the operands' minima\n\t */\n\tdst_reg->umin_value = max(dst_reg->umin_value, umin_val);\n\tdst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;\n\tif (dst_reg->smin_value < 0 || smin_val < 0) {\n\t\t/* Lose signed bounds when ORing negative numbers,\n\t\t * ain't nobody got time for that.\n\t\t */\n\t\tdst_reg->smin_value = S64_MIN;\n\t\tdst_reg->smax_value = S64_MAX;\n\t} else {\n\t\t/* ORing two positives gives a positive, so safe to\n\t\t * cast result into s64.\n\t\t */\n\t\tdst_reg->smin_value = dst_reg->umin_value;\n\t\tdst_reg->smax_value = dst_reg->umax_value;\n\t}\n\t/* We may learn something more from the var_off */\n\t__update_reg_bounds(dst_reg);\n}", "project": "linux", "hash": 16041466753298829583829099804318410019, "size": 35, "commit_id": "5b9fbeb75b6a98955f628e205ac26689bcb1383e", "message": "bpf: Fix scalar32_min_max_or bounds tracking\n\nSimon reported an issue with the current scalar32_min_max_or() implementation.\nThat is, compared to the other 32 bit subreg tracking functions, the code in\nscalar32_min_max_or() stands out that it's using the 64 bit registers instead\nof 32 bit ones. This leads to bounds tracking issues, for example:\n\n [...]\n 8: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 8: (79) r1 = *(u64 *)(r0 +0)\n R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 9: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 9: (b7) r0 = 1\n 10: R0_w=inv1 R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 10: (18) r2 = 0x600000002\n 12: R0_w=inv1 R1_w=inv(id=0) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 12: (ad) if r1 < r2 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: (95) exit\n 14: R0_w=inv1 R1_w=inv(id=0,umax_value=25769803777,var_off=(0x0; 0x7ffffffff)) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 14: (25) if r1 > 0x0 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: (95) exit\n 16: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=25769803777,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 16: (47) r1 |= 0\n 17: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=32212254719,var_off=(0x1; 0x700000000),s32_max_value=1,u32_max_value=1) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n [...]\n\nThe bound tests on the map value force the upper unsigned bound to be 25769803777\nin 64 bit (0b11000000000000000000000000000000001) and then lower one to be 1. By\nusing OR they are truncated and thus result in the range [1,1] for the 32 bit reg\ntracker. This is incorrect given the only thing we know is that the value must be\npositive and thus 2147483647 (0b1111111111111111111111111111111) at max for the\nsubregs. Fix it by using the {u,s}32_{min,max}_value vars instead. This also makes\nsense, for example, for the case where we update dst_reg->s32_{min,max}_value in\nthe else branch we need to use the newly computed dst_reg->u32_{min,max}_value as\nwe know that these are positive. Previously, in the else branch the 64 bit values\nof umin_value=1 and umax_value=32212254719 were used and latter got truncated to\nbe 1 as upper bound there. After the fix the subreg range is now correct:\n\n [...]\n 8: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 8: (79) r1 = *(u64 *)(r0 +0)\n R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm\n 9: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 9: (b7) r0 = 1\n 10: R0_w=inv1 R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm\n 10: (18) r2 = 0x600000002\n 12: R0_w=inv1 R1_w=inv(id=0) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 12: (ad) if r1 < r2 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 13: (95) exit\n 14: R0_w=inv1 R1_w=inv(id=0,umax_value=25769803777,var_off=(0x0; 0x7ffffffff)) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 14: (25) if r1 > 0x0 goto pc+1\n R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 15: (95) exit\n 16: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=25769803777,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n 16: (47) r1 |= 0\n 17: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=32212254719,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm\n [...]\n\nFixes: 3f50f132d840 (\"bpf: Verifier, do explicit ALU32 bounds tracking\")\nReported-by: Simon Scannell \nSigned-off-by: Daniel Borkmann \nReviewed-by: John Fastabend \nAcked-by: Alexei Starovoitov ", "target": 0, "dataset": "other", "idx": 328523} {"func": "slap_modrdn2mods(\n\tOperation\t*op,\n\tSlapReply\t*rs )\n{\n\tint\t\ta_cnt, d_cnt;\n\tLDAPRDN\t\told_rdn = NULL;\n\tLDAPRDN\t\tnew_rdn = NULL;\n\n\tassert( !BER_BVISEMPTY( &op->oq_modrdn.rs_newrdn ) );\n\n\t/* if requestDN is empty, silently reset deleteOldRDN */\n\tif ( BER_BVISEMPTY( &op->o_req_dn ) ) op->orr_deleteoldrdn = 0;\n\n\tif ( ldap_bv2rdn_x( &op->oq_modrdn.rs_newrdn, &new_rdn,\n\t\t(char **)&rs->sr_text, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx ) ) {\n\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\"%s slap_modrdn2mods: can't figure out \"\n\t\t\t\"type(s)/value(s) of newrdn\\n\",\n\t\t\top->o_log_prefix, 0, 0 );\n\t\trs->sr_err = LDAP_INVALID_DN_SYNTAX;\n\t\trs->sr_text = \"unknown type(s)/value(s) used in RDN\";\n\t\tgoto done;\n\t}\n\n\tif ( op->oq_modrdn.rs_deleteoldrdn ) {\n\t\tif ( ldap_bv2rdn_x( &op->o_req_dn, &old_rdn,\n\t\t\t(char **)&rs->sr_text, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx ) ) {\n\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\"%s slap_modrdn2mods: can't figure out \"\n\t\t\t\t\"type(s)/value(s) of oldrdn\\n\",\n\t\t\t\top->o_log_prefix, 0, 0 );\n\t\t\trs->sr_err = LDAP_OTHER;\n\t\t\trs->sr_text = \"cannot parse RDN from old DN\";\n\t\t\tgoto done;\n\t\t}\n\t}\n\trs->sr_text = NULL;\n\n\t/* Add new attribute values to the entry */\n\tfor ( a_cnt = 0; new_rdn[a_cnt]; a_cnt++ ) {\n\t\tAttributeDescription\t*desc = NULL;\n\t\tModifications \t\t*mod_tmp;\n\n\t\trs->sr_err = slap_bv2ad( &new_rdn[a_cnt]->la_attr, &desc, &rs->sr_text );\n\n\t\tif ( rs->sr_err != LDAP_SUCCESS ) {\n\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\"%s slap_modrdn2mods: %s: %s (new)\\n\",\n\t\t\t\top->o_log_prefix,\n\t\t\t\trs->sr_text,\n\t\t\t\tnew_rdn[ a_cnt ]->la_attr.bv_val );\n\t\t\tgoto done;\t\t\n\t\t}\n\n\t\tif ( !desc->ad_type->sat_equality ) {\n\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\"%s slap_modrdn2mods: %s: %s (new)\\n\",\n\t\t\t\top->o_log_prefix,\n\t\t\t\trs->sr_text,\n\t\t\t\tnew_rdn[ a_cnt ]->la_attr.bv_val );\n\t\t\trs->sr_text = \"naming attribute has no equality matching rule\";\n\t\t\trs->sr_err = LDAP_NAMING_VIOLATION;\n\t\t\tgoto done;\n\t\t}\n\n\t\t/* Apply modification */\n\t\tmod_tmp = ( Modifications * )ch_malloc( sizeof( Modifications ) );\n\t\tmod_tmp->sml_desc = desc;\n\t\tBER_BVZERO( &mod_tmp->sml_type );\n\t\tmod_tmp->sml_numvals = 1;\n\t\tmod_tmp->sml_values = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\tber_dupbv( &mod_tmp->sml_values[0], &new_rdn[a_cnt]->la_value );\n\t\tmod_tmp->sml_values[1].bv_val = NULL;\n\t\tif( desc->ad_type->sat_equality->smr_normalize) {\n\t\t\tmod_tmp->sml_nvalues = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\t\trs->sr_err = desc->ad_type->sat_equality->smr_normalize(\n\t\t\t\tSLAP_MR_EQUALITY|SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,\n\t\t\t\tdesc->ad_type->sat_syntax,\n\t\t\t\tdesc->ad_type->sat_equality,\n\t\t\t\t&mod_tmp->sml_values[0],\n\t\t\t\t&mod_tmp->sml_nvalues[0], NULL );\n\t\t\tif (rs->sr_err != LDAP_SUCCESS) {\n\t\t\t\tch_free(mod_tmp->sml_nvalues);\n\t\t\t\tch_free(mod_tmp->sml_values[0].bv_val);\n\t\t\t\tch_free(mod_tmp->sml_values);\n\t\t\t\tch_free(mod_tmp);\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tmod_tmp->sml_nvalues[1].bv_val = NULL;\n\t\t} else {\n\t\t\tmod_tmp->sml_nvalues = NULL;\n\t\t}\n\t\tmod_tmp->sml_op = SLAP_MOD_SOFTADD;\n\t\tmod_tmp->sml_flags = 0;\n\t\tmod_tmp->sml_next = op->orr_modlist;\n\t\top->orr_modlist = mod_tmp;\n\t}\n\n\t/* Remove old rdn value if required */\n\tif ( op->orr_deleteoldrdn ) {\n\t\tfor ( d_cnt = 0; old_rdn[d_cnt]; d_cnt++ ) {\n\t\t\tAttributeDescription\t*desc = NULL;\n\t\t\tModifications \t\t*mod_tmp;\n\n\t\t\trs->sr_err = slap_bv2ad( &old_rdn[d_cnt]->la_attr, &desc, &rs->sr_text );\n\t\t\tif ( rs->sr_err != LDAP_SUCCESS ) {\n\t\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\t\"%s slap_modrdn2mods: %s: %s (old)\\n\",\n\t\t\t\t\top->o_log_prefix,\n\t\t\t\t\trs->sr_text, \n\t\t\t\t\told_rdn[d_cnt]->la_attr.bv_val );\n\t\t\t\tgoto done;\t\t\n\t\t\t}\n\n\t\t\t/* Apply modification */\n\t\t\tmod_tmp = ( Modifications * )ch_malloc( sizeof( Modifications ) );\n\t\t\tmod_tmp->sml_desc = desc;\n\t\t\tBER_BVZERO( &mod_tmp->sml_type );\n\t\t\tmod_tmp->sml_numvals = 1;\n\t\t\tmod_tmp->sml_values = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\t\tber_dupbv( &mod_tmp->sml_values[0], &old_rdn[d_cnt]->la_value );\n\t\t\tmod_tmp->sml_values[1].bv_val = NULL;\n\t\t\tif( desc->ad_type->sat_equality->smr_normalize) {\n\t\t\t\tmod_tmp->sml_nvalues = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\t\t\t(void) (*desc->ad_type->sat_equality->smr_normalize)(\n\t\t\t\t\tSLAP_MR_EQUALITY|SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,\n\t\t\t\t\tdesc->ad_type->sat_syntax,\n\t\t\t\t\tdesc->ad_type->sat_equality,\n\t\t\t\t\t&mod_tmp->sml_values[0],\n\t\t\t\t\t&mod_tmp->sml_nvalues[0], NULL );\n\t\t\t\tmod_tmp->sml_nvalues[1].bv_val = NULL;\n\t\t\t} else {\n\t\t\t\tmod_tmp->sml_nvalues = NULL;\n\t\t\t}\n\t\t\tmod_tmp->sml_op = LDAP_MOD_DELETE;\n\t\t\tmod_tmp->sml_flags = 0;\n\t\t\tmod_tmp->sml_next = op->orr_modlist;\n\t\t\top->orr_modlist = mod_tmp;\n\t\t}\n\t}\n\t\ndone:\n\n\t/* LDAP v2 supporting correct attribute handling. */\n\tif ( rs->sr_err != LDAP_SUCCESS && op->orr_modlist != NULL ) {\n\t\tModifications *tmp;\n\n\t\tfor ( ; op->orr_modlist != NULL; op->orr_modlist = tmp ) {\n\t\t\ttmp = op->orr_modlist->sml_next;\n\t\t\tch_free( op->orr_modlist );\n\t\t}\n\t}\n\n\tif ( new_rdn != NULL ) {\n\t\tldap_rdnfree_x( new_rdn, op->o_tmpmemctx );\n\t}\n\tif ( old_rdn != NULL ) {\n\t\tldap_rdnfree_x( old_rdn, op->o_tmpmemctx );\n\t}\n\n\treturn rs->sr_err;\n}", "project": "openldap", "hash": 98924267316692135884880271228017176283, "size": 162, "commit_id": "4c774220a752bf8e3284984890dc0931fe73165d", "message": "ITS#9370 check for equality rule on old_rdn\n\nJust skip normalization if there's no equality rule. We accept\nDNs without equality rules already.", "target": 1, "dataset": "other", "idx": 202129} {"func": "slap_modrdn2mods(\n\tOperation\t*op,\n\tSlapReply\t*rs )\n{\n\tint\t\ta_cnt, d_cnt;\n\tLDAPRDN\t\told_rdn = NULL;\n\tLDAPRDN\t\tnew_rdn = NULL;\n\n\tassert( !BER_BVISEMPTY( &op->oq_modrdn.rs_newrdn ) );\n\n\t/* if requestDN is empty, silently reset deleteOldRDN */\n\tif ( BER_BVISEMPTY( &op->o_req_dn ) ) op->orr_deleteoldrdn = 0;\n\n\tif ( ldap_bv2rdn_x( &op->oq_modrdn.rs_newrdn, &new_rdn,\n\t\t(char **)&rs->sr_text, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx ) ) {\n\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\"%s slap_modrdn2mods: can't figure out \"\n\t\t\t\"type(s)/value(s) of newrdn\\n\",\n\t\t\top->o_log_prefix, 0, 0 );\n\t\trs->sr_err = LDAP_INVALID_DN_SYNTAX;\n\t\trs->sr_text = \"unknown type(s)/value(s) used in RDN\";\n\t\tgoto done;\n\t}\n\n\tif ( op->oq_modrdn.rs_deleteoldrdn ) {\n\t\tif ( ldap_bv2rdn_x( &op->o_req_dn, &old_rdn,\n\t\t\t(char **)&rs->sr_text, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx ) ) {\n\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\"%s slap_modrdn2mods: can't figure out \"\n\t\t\t\t\"type(s)/value(s) of oldrdn\\n\",\n\t\t\t\top->o_log_prefix, 0, 0 );\n\t\t\trs->sr_err = LDAP_OTHER;\n\t\t\trs->sr_text = \"cannot parse RDN from old DN\";\n\t\t\tgoto done;\n\t\t}\n\t}\n\trs->sr_text = NULL;\n\n\t/* Add new attribute values to the entry */\n\tfor ( a_cnt = 0; new_rdn[a_cnt]; a_cnt++ ) {\n\t\tAttributeDescription\t*desc = NULL;\n\t\tModifications \t\t*mod_tmp;\n\n\t\trs->sr_err = slap_bv2ad( &new_rdn[a_cnt]->la_attr, &desc, &rs->sr_text );\n\n\t\tif ( rs->sr_err != LDAP_SUCCESS ) {\n\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\"%s slap_modrdn2mods: %s: %s (new)\\n\",\n\t\t\t\top->o_log_prefix,\n\t\t\t\trs->sr_text,\n\t\t\t\tnew_rdn[ a_cnt ]->la_attr.bv_val );\n\t\t\tgoto done;\t\t\n\t\t}\n\n\t\tif ( !desc->ad_type->sat_equality ) {\n\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\"%s slap_modrdn2mods: %s: %s (new)\\n\",\n\t\t\t\top->o_log_prefix,\n\t\t\t\trs->sr_text,\n\t\t\t\tnew_rdn[ a_cnt ]->la_attr.bv_val );\n\t\t\trs->sr_text = \"naming attribute has no equality matching rule\";\n\t\t\trs->sr_err = LDAP_NAMING_VIOLATION;\n\t\t\tgoto done;\n\t\t}\n\n\t\t/* Apply modification */\n\t\tmod_tmp = ( Modifications * )ch_malloc( sizeof( Modifications ) );\n\t\tmod_tmp->sml_desc = desc;\n\t\tBER_BVZERO( &mod_tmp->sml_type );\n\t\tmod_tmp->sml_numvals = 1;\n\t\tmod_tmp->sml_values = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\tber_dupbv( &mod_tmp->sml_values[0], &new_rdn[a_cnt]->la_value );\n\t\tmod_tmp->sml_values[1].bv_val = NULL;\n\t\tif( desc->ad_type->sat_equality->smr_normalize) {\n\t\t\tmod_tmp->sml_nvalues = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\t\trs->sr_err = desc->ad_type->sat_equality->smr_normalize(\n\t\t\t\tSLAP_MR_EQUALITY|SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,\n\t\t\t\tdesc->ad_type->sat_syntax,\n\t\t\t\tdesc->ad_type->sat_equality,\n\t\t\t\t&mod_tmp->sml_values[0],\n\t\t\t\t&mod_tmp->sml_nvalues[0], NULL );\n\t\t\tif (rs->sr_err != LDAP_SUCCESS) {\n\t\t\t\tch_free(mod_tmp->sml_nvalues);\n\t\t\t\tch_free(mod_tmp->sml_values[0].bv_val);\n\t\t\t\tch_free(mod_tmp->sml_values);\n\t\t\t\tch_free(mod_tmp);\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tmod_tmp->sml_nvalues[1].bv_val = NULL;\n\t\t} else {\n\t\t\tmod_tmp->sml_nvalues = NULL;\n\t\t}\n\t\tmod_tmp->sml_op = SLAP_MOD_SOFTADD;\n\t\tmod_tmp->sml_flags = 0;\n\t\tmod_tmp->sml_next = op->orr_modlist;\n\t\top->orr_modlist = mod_tmp;\n\t}\n\n\t/* Remove old rdn value if required */\n\tif ( op->orr_deleteoldrdn ) {\n\t\tfor ( d_cnt = 0; old_rdn[d_cnt]; d_cnt++ ) {\n\t\t\tAttributeDescription\t*desc = NULL;\n\t\t\tModifications \t\t*mod_tmp;\n\n\t\t\trs->sr_err = slap_bv2ad( &old_rdn[d_cnt]->la_attr, &desc, &rs->sr_text );\n\t\t\tif ( rs->sr_err != LDAP_SUCCESS ) {\n\t\t\t\tDebug( LDAP_DEBUG_TRACE,\n\t\t\t\t\t\"%s slap_modrdn2mods: %s: %s (old)\\n\",\n\t\t\t\t\top->o_log_prefix,\n\t\t\t\t\trs->sr_text, \n\t\t\t\t\told_rdn[d_cnt]->la_attr.bv_val );\n\t\t\t\tgoto done;\t\t\n\t\t\t}\n\n\t\t\t/* Apply modification */\n\t\t\tmod_tmp = ( Modifications * )ch_malloc( sizeof( Modifications ) );\n\t\t\tmod_tmp->sml_desc = desc;\n\t\t\tBER_BVZERO( &mod_tmp->sml_type );\n\t\t\tmod_tmp->sml_numvals = 1;\n\t\t\tmod_tmp->sml_values = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\t\tber_dupbv( &mod_tmp->sml_values[0], &old_rdn[d_cnt]->la_value );\n\t\t\tmod_tmp->sml_values[1].bv_val = NULL;\n\t\t\tif( desc->ad_type->sat_equality && desc->ad_type->sat_equality->smr_normalize) {\n\t\t\t\tmod_tmp->sml_nvalues = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) );\n\t\t\t\t(void) (*desc->ad_type->sat_equality->smr_normalize)(\n\t\t\t\t\tSLAP_MR_EQUALITY|SLAP_MR_VALUE_OF_ASSERTION_SYNTAX,\n\t\t\t\t\tdesc->ad_type->sat_syntax,\n\t\t\t\t\tdesc->ad_type->sat_equality,\n\t\t\t\t\t&mod_tmp->sml_values[0],\n\t\t\t\t\t&mod_tmp->sml_nvalues[0], NULL );\n\t\t\t\tmod_tmp->sml_nvalues[1].bv_val = NULL;\n\t\t\t} else {\n\t\t\t\tmod_tmp->sml_nvalues = NULL;\n\t\t\t}\n\t\t\tmod_tmp->sml_op = LDAP_MOD_DELETE;\n\t\t\tmod_tmp->sml_flags = 0;\n\t\t\tmod_tmp->sml_next = op->orr_modlist;\n\t\t\top->orr_modlist = mod_tmp;\n\t\t}\n\t}\n\t\ndone:\n\n\t/* LDAP v2 supporting correct attribute handling. */\n\tif ( rs->sr_err != LDAP_SUCCESS && op->orr_modlist != NULL ) {\n\t\tModifications *tmp;\n\n\t\tfor ( ; op->orr_modlist != NULL; op->orr_modlist = tmp ) {\n\t\t\ttmp = op->orr_modlist->sml_next;\n\t\t\tch_free( op->orr_modlist );\n\t\t}\n\t}\n\n\tif ( new_rdn != NULL ) {\n\t\tldap_rdnfree_x( new_rdn, op->o_tmpmemctx );\n\t}\n\tif ( old_rdn != NULL ) {\n\t\tldap_rdnfree_x( old_rdn, op->o_tmpmemctx );\n\t}\n\n\treturn rs->sr_err;\n}", "project": "openldap", "hash": 23684533698009506860231461160337640809, "size": 162, "commit_id": "4c774220a752bf8e3284984890dc0931fe73165d", "message": "ITS#9370 check for equality rule on old_rdn\n\nJust skip normalization if there's no equality rule. We accept\nDNs without equality rules already.", "target": 0, "dataset": "other", "idx": 329989} {"func": "MagickExport Image *WaveImage(const Image *image,const double amplitude,\n const double wave_length,const PixelInterpolateMethod method,\n ExceptionInfo *exception)\n{\n#define WaveImageTag \"Wave/Image\"\n\n CacheView\n *canvas_image_view,\n *wave_view;\n\n float\n *sine_map;\n\n Image\n *canvas_image,\n *wave_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n ssize_t\n i;\n\n ssize_t\n y;\n\n /*\n Initialize wave image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n canvas_image=CloneImage(image,0,0,MagickTrue,exception);\n if (canvas_image == (Image *) NULL)\n return((Image *) NULL);\n if ((canvas_image->alpha_trait == UndefinedPixelTrait) &&\n (canvas_image->background_color.alpha != OpaqueAlpha))\n (void) SetImageAlpha(canvas_image,OpaqueAlpha,exception);\n wave_image=CloneImage(canvas_image,canvas_image->columns,(size_t)\n (canvas_image->rows+2.0*fabs(amplitude)),MagickTrue,exception);\n if (wave_image == (Image *) NULL)\n {\n canvas_image=DestroyImage(canvas_image);\n return((Image *) NULL);\n }\n if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse)\n {\n canvas_image=DestroyImage(canvas_image);\n wave_image=DestroyImage(wave_image);\n return((Image *) NULL);\n }\n /*\n Allocate sine map.\n */\n sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,\n sizeof(*sine_map));\n if (sine_map == (float *) NULL)\n {\n canvas_image=DestroyImage(canvas_image);\n wave_image=DestroyImage(wave_image);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) wave_image->columns; i++)\n sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)\n ((2.0*MagickPI*i)/wave_length));\n /*\n Wave image.\n */\n status=MagickTrue;\n progress=0;\n canvas_image_view=AcquireVirtualCacheView(canvas_image,exception);\n wave_view=AcquireAuthenticCacheView(wave_image,exception);\n (void) SetCacheViewVirtualPixelMethod(canvas_image_view,\n BackgroundVirtualPixelMethod);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(canvas_image,wave_image,wave_image->rows,1)\n#endif\n for (y=0; y < (ssize_t) wave_image->rows; y++)\n {\n const Quantum\n *magick_restrict p;\n\n Quantum\n *magick_restrict q;\n\n ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n p=GetCacheViewVirtualPixels(canvas_image_view,0,y,canvas_image->columns,1,\n exception);\n q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,\n exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) wave_image->columns; x++)\n {\n status=InterpolatePixelChannels(canvas_image,canvas_image_view,\n wave_image,method,(double) x,(double) (y-sine_map[x]),q,exception);\n if (status == MagickFalse)\n break;\n p+=GetPixelChannels(canvas_image);\n q+=GetPixelChannels(wave_image);\n }\n if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(canvas_image,WaveImageTag,progress,\n canvas_image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n wave_view=DestroyCacheView(wave_view);\n canvas_image_view=DestroyCacheView(canvas_image_view);\n canvas_image=DestroyImage(canvas_image);\n sine_map=(float *) RelinquishMagickMemory(sine_map);\n if (status == MagickFalse)\n wave_image=DestroyImage(wave_image);\n return(wave_image);\n}", "project": "ImageMagick", "hash": 109616764411189885332816110905608229061, "size": 140, "commit_id": "94174beff065cb5683d09d79e992c3ebbdead311", "message": "https://github.com/ImageMagick/ImageMagick/issues/3296", "target": 1, "dataset": "other", "idx": 202140} {"func": "MagickExport Image *WaveImage(const Image *image,const double amplitude,\n const double wave_length,const PixelInterpolateMethod method,\n ExceptionInfo *exception)\n{\n#define WaveImageTag \"Wave/Image\"\n\n CacheView\n *canvas_image_view,\n *wave_view;\n\n float\n *sine_map;\n\n Image\n *canvas_image,\n *wave_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n ssize_t\n i;\n\n ssize_t\n y;\n\n /*\n Initialize wave image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n canvas_image=CloneImage(image,0,0,MagickTrue,exception);\n if (canvas_image == (Image *) NULL)\n return((Image *) NULL);\n if ((canvas_image->alpha_trait == UndefinedPixelTrait) &&\n (canvas_image->background_color.alpha != OpaqueAlpha))\n (void) SetImageAlpha(canvas_image,OpaqueAlpha,exception);\n wave_image=CloneImage(canvas_image,canvas_image->columns,(size_t)\n (canvas_image->rows+2.0*fabs(amplitude)),MagickTrue,exception);\n if (wave_image == (Image *) NULL)\n {\n canvas_image=DestroyImage(canvas_image);\n return((Image *) NULL);\n }\n if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse)\n {\n canvas_image=DestroyImage(canvas_image);\n wave_image=DestroyImage(wave_image);\n return((Image *) NULL);\n }\n /*\n Allocate sine map.\n */\n sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,\n sizeof(*sine_map));\n if (sine_map == (float *) NULL)\n {\n canvas_image=DestroyImage(canvas_image);\n wave_image=DestroyImage(wave_image);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) wave_image->columns; i++)\n sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)\n ((2.0*MagickPI*i)*PerceptibleReciprocal(wave_length)));\n /*\n Wave image.\n */\n status=MagickTrue;\n progress=0;\n canvas_image_view=AcquireVirtualCacheView(canvas_image,exception);\n wave_view=AcquireAuthenticCacheView(wave_image,exception);\n (void) SetCacheViewVirtualPixelMethod(canvas_image_view,\n BackgroundVirtualPixelMethod);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(canvas_image,wave_image,wave_image->rows,1)\n#endif\n for (y=0; y < (ssize_t) wave_image->rows; y++)\n {\n const Quantum\n *magick_restrict p;\n\n Quantum\n *magick_restrict q;\n\n ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n p=GetCacheViewVirtualPixels(canvas_image_view,0,y,canvas_image->columns,1,\n exception);\n q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,\n exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) wave_image->columns; x++)\n {\n status=InterpolatePixelChannels(canvas_image,canvas_image_view,\n wave_image,method,(double) x,(double) (y-sine_map[x]),q,exception);\n if (status == MagickFalse)\n break;\n p+=GetPixelChannels(canvas_image);\n q+=GetPixelChannels(wave_image);\n }\n if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(canvas_image,WaveImageTag,progress,\n canvas_image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n wave_view=DestroyCacheView(wave_view);\n canvas_image_view=DestroyCacheView(canvas_image_view);\n canvas_image=DestroyImage(canvas_image);\n sine_map=(float *) RelinquishMagickMemory(sine_map);\n if (status == MagickFalse)\n wave_image=DestroyImage(wave_image);\n return(wave_image);\n}", "project": "ImageMagick", "hash": 295514983873945565860327311775528409590, "size": 140, "commit_id": "94174beff065cb5683d09d79e992c3ebbdead311", "message": "https://github.com/ImageMagick/ImageMagick/issues/3296", "target": 0, "dataset": "other", "idx": 330274} {"func": "static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,\n\t\t struct packet_type *pt, struct net_device *orig_dev)\n{\n\tstruct sock *sk;\n\tstruct packet_sock *po;\n\tstruct sockaddr_ll *sll;\n\tunion tpacket_uhdr h;\n\tu8 *skb_head = skb->data;\n\tint skb_len = skb->len;\n\tunsigned int snaplen, res;\n\tunsigned long status = TP_STATUS_USER;\n\tunsigned short macoff, netoff, hdrlen;\n\tstruct sk_buff *copy_skb = NULL;\n\tstruct timespec64 ts;\n\t__u32 ts_status;\n\tbool is_drop_n_account = false;\n\tunsigned int slot_id = 0;\n\tbool do_vnet = false;\n\n\t/* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.\n\t * We may add members to them until current aligned size without forcing\n\t * userspace to call getsockopt(..., PACKET_HDRLEN, ...).\n\t */\n\tBUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);\n\tBUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);\n\n\tif (skb->pkt_type == PACKET_LOOPBACK)\n\t\tgoto drop;\n\n\tsk = pt->af_packet_priv;\n\tpo = pkt_sk(sk);\n\n\tif (!net_eq(dev_net(dev), sock_net(sk)))\n\t\tgoto drop;\n\n\tif (dev->header_ops) {\n\t\tif (sk->sk_type != SOCK_DGRAM)\n\t\t\tskb_push(skb, skb->data - skb_mac_header(skb));\n\t\telse if (skb->pkt_type == PACKET_OUTGOING) {\n\t\t\t/* Special case: outgoing packets have ll header at head */\n\t\t\tskb_pull(skb, skb_network_offset(skb));\n\t\t}\n\t}\n\n\tsnaplen = skb->len;\n\n\tres = run_filter(skb, sk, snaplen);\n\tif (!res)\n\t\tgoto drop_n_restore;\n\n\t/* If we are flooded, just give up */\n\tif (__packet_rcv_has_room(po, skb) == ROOM_NONE) {\n\t\tatomic_inc(&po->tp_drops);\n\t\tgoto drop_n_restore;\n\t}\n\n\tif (skb->ip_summed == CHECKSUM_PARTIAL)\n\t\tstatus |= TP_STATUS_CSUMNOTREADY;\n\telse if (skb->pkt_type != PACKET_OUTGOING &&\n\t\t (skb->ip_summed == CHECKSUM_COMPLETE ||\n\t\t skb_csum_unnecessary(skb)))\n\t\tstatus |= TP_STATUS_CSUM_VALID;\n\n\tif (snaplen > res)\n\t\tsnaplen = res;\n\n\tif (sk->sk_type == SOCK_DGRAM) {\n\t\tmacoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +\n\t\t\t\t po->tp_reserve;\n\t} else {\n\t\tunsigned int maclen = skb_network_offset(skb);\n\t\tnetoff = TPACKET_ALIGN(po->tp_hdrlen +\n\t\t\t\t (maclen < 16 ? 16 : maclen)) +\n\t\t\t\t po->tp_reserve;\n\t\tif (po->has_vnet_hdr) {\n\t\t\tnetoff += sizeof(struct virtio_net_hdr);\n\t\t\tdo_vnet = true;\n\t\t}\n\t\tmacoff = netoff - maclen;\n\t}\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tif (macoff + snaplen > po->rx_ring.frame_size) {\n\t\t\tif (po->copy_thresh &&\n\t\t\t atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {\n\t\t\t\tif (skb_shared(skb)) {\n\t\t\t\t\tcopy_skb = skb_clone(skb, GFP_ATOMIC);\n\t\t\t\t} else {\n\t\t\t\t\tcopy_skb = skb_get(skb);\n\t\t\t\t\tskb_head = skb->data;\n\t\t\t\t}\n\t\t\t\tif (copy_skb)\n\t\t\t\t\tskb_set_owner_r(copy_skb, sk);\n\t\t\t}\n\t\t\tsnaplen = po->rx_ring.frame_size - macoff;\n\t\t\tif ((int)snaplen < 0) {\n\t\t\t\tsnaplen = 0;\n\t\t\t\tdo_vnet = false;\n\t\t\t}\n\t\t}\n\t} else if (unlikely(macoff + snaplen >\n\t\t\t GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {\n\t\tu32 nval;\n\n\t\tnval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;\n\t\tpr_err_once(\"tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\\n\",\n\t\t\t snaplen, nval, macoff);\n\t\tsnaplen = nval;\n\t\tif (unlikely((int)snaplen < 0)) {\n\t\t\tsnaplen = 0;\n\t\t\tmacoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;\n\t\t\tdo_vnet = false;\n\t\t}\n\t}\n\tspin_lock(&sk->sk_receive_queue.lock);\n\th.raw = packet_current_rx_frame(po, skb,\n\t\t\t\t\tTP_STATUS_KERNEL, (macoff+snaplen));\n\tif (!h.raw)\n\t\tgoto drop_n_account;\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tslot_id = po->rx_ring.head;\n\t\tif (test_bit(slot_id, po->rx_ring.rx_owner_map))\n\t\t\tgoto drop_n_account;\n\t\t__set_bit(slot_id, po->rx_ring.rx_owner_map);\n\t}\n\n\tif (do_vnet &&\n\t virtio_net_hdr_from_skb(skb, h.raw + macoff -\n\t\t\t\t sizeof(struct virtio_net_hdr),\n\t\t\t\t vio_le(), true, 0)) {\n\t\tif (po->tp_version == TPACKET_V3)\n\t\t\tprb_clear_blk_fill_status(&po->rx_ring);\n\t\tgoto drop_n_account;\n\t}\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tpacket_increment_rx_head(po, &po->rx_ring);\n\t/*\n\t * LOSING will be reported till you read the stats,\n\t * because it's COR - Clear On Read.\n\t * Anyways, moving it for V1/V2 only as V3 doesn't need this\n\t * at packet level.\n\t */\n\t\tif (atomic_read(&po->tp_drops))\n\t\t\tstatus |= TP_STATUS_LOSING;\n\t}\n\n\tpo->stats.stats1.tp_packets++;\n\tif (copy_skb) {\n\t\tstatus |= TP_STATUS_COPY;\n\t\t__skb_queue_tail(&sk->sk_receive_queue, copy_skb);\n\t}\n\tspin_unlock(&sk->sk_receive_queue.lock);\n\n\tskb_copy_bits(skb, 0, h.raw + macoff, snaplen);\n\n\tif (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))\n\t\tktime_get_real_ts64(&ts);\n\n\tstatus |= ts_status;\n\n\tswitch (po->tp_version) {\n\tcase TPACKET_V1:\n\t\th.h1->tp_len = skb->len;\n\t\th.h1->tp_snaplen = snaplen;\n\t\th.h1->tp_mac = macoff;\n\t\th.h1->tp_net = netoff;\n\t\th.h1->tp_sec = ts.tv_sec;\n\t\th.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;\n\t\thdrlen = sizeof(*h.h1);\n\t\tbreak;\n\tcase TPACKET_V2:\n\t\th.h2->tp_len = skb->len;\n\t\th.h2->tp_snaplen = snaplen;\n\t\th.h2->tp_mac = macoff;\n\t\th.h2->tp_net = netoff;\n\t\th.h2->tp_sec = ts.tv_sec;\n\t\th.h2->tp_nsec = ts.tv_nsec;\n\t\tif (skb_vlan_tag_present(skb)) {\n\t\t\th.h2->tp_vlan_tci = skb_vlan_tag_get(skb);\n\t\t\th.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);\n\t\t\tstatus |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;\n\t\t} else {\n\t\t\th.h2->tp_vlan_tci = 0;\n\t\t\th.h2->tp_vlan_tpid = 0;\n\t\t}\n\t\tmemset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));\n\t\thdrlen = sizeof(*h.h2);\n\t\tbreak;\n\tcase TPACKET_V3:\n\t\t/* tp_nxt_offset,vlan are already populated above.\n\t\t * So DONT clear those fields here\n\t\t */\n\t\th.h3->tp_status |= status;\n\t\th.h3->tp_len = skb->len;\n\t\th.h3->tp_snaplen = snaplen;\n\t\th.h3->tp_mac = macoff;\n\t\th.h3->tp_net = netoff;\n\t\th.h3->tp_sec = ts.tv_sec;\n\t\th.h3->tp_nsec = ts.tv_nsec;\n\t\tmemset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));\n\t\thdrlen = sizeof(*h.h3);\n\t\tbreak;\n\tdefault:\n\t\tBUG();\n\t}\n\n\tsll = h.raw + TPACKET_ALIGN(hdrlen);\n\tsll->sll_halen = dev_parse_header(skb, sll->sll_addr);\n\tsll->sll_family = AF_PACKET;\n\tsll->sll_hatype = dev->type;\n\tsll->sll_protocol = skb->protocol;\n\tsll->sll_pkttype = skb->pkt_type;\n\tif (unlikely(po->origdev))\n\t\tsll->sll_ifindex = orig_dev->ifindex;\n\telse\n\t\tsll->sll_ifindex = dev->ifindex;\n\n\tsmp_mb();\n\n#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tu8 *start, *end;\n\n\t\tend = (u8 *) PAGE_ALIGN((unsigned long) h.raw +\n\t\t\t\t\tmacoff + snaplen);\n\n\t\tfor (start = h.raw; start < end; start += PAGE_SIZE)\n\t\t\tflush_dcache_page(pgv_to_page(start));\n\t}\n\tsmp_wmb();\n#endif\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tspin_lock(&sk->sk_receive_queue.lock);\n\t\t__packet_set_status(po, h.raw, status);\n\t\t__clear_bit(slot_id, po->rx_ring.rx_owner_map);\n\t\tspin_unlock(&sk->sk_receive_queue.lock);\n\t\tsk->sk_data_ready(sk);\n\t} else if (po->tp_version == TPACKET_V3) {\n\t\tprb_clear_blk_fill_status(&po->rx_ring);\n\t}\n\ndrop_n_restore:\n\tif (skb_head != skb->data && skb_shared(skb)) {\n\t\tskb->data = skb_head;\n\t\tskb->len = skb_len;\n\t}\ndrop:\n\tif (!is_drop_n_account)\n\t\tconsume_skb(skb);\n\telse\n\t\tkfree_skb(skb);\n\treturn 0;\n\ndrop_n_account:\n\tspin_unlock(&sk->sk_receive_queue.lock);\n\tatomic_inc(&po->tp_drops);\n\tis_drop_n_account = true;\n\n\tsk->sk_data_ready(sk);\n\tkfree_skb(copy_skb);\n\tgoto drop_n_restore;\n}", "project": "linux", "hash": 247138033746397759600375764218281666520, "size": 264, "commit_id": "acf69c946233259ab4d64f8869d4037a198c7f06", "message": "net/packet: fix overflow in tpacket_rcv\n\nUsing tp_reserve to calculate netoff can overflow as\ntp_reserve is unsigned int and netoff is unsigned short.\n\nThis may lead to macoff receving a smaller value then\nsizeof(struct virtio_net_hdr), and if po->has_vnet_hdr\nis set, an out-of-bounds write will occur when\ncalling virtio_net_hdr_from_skb.\n\nThe bug is fixed by converting netoff to unsigned int\nand checking if it exceeds USHRT_MAX.\n\nThis addresses CVE-2020-14386\n\nFixes: 8913336a7e8d (\"packet: add PACKET_RESERVE sockopt\")\nSigned-off-by: Or Cohen \nSigned-off-by: Eric Dumazet \nSigned-off-by: Linus Torvalds ", "target": 1, "dataset": "other", "idx": 202143} {"func": "static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,\n\t\t struct packet_type *pt, struct net_device *orig_dev)\n{\n\tstruct sock *sk;\n\tstruct packet_sock *po;\n\tstruct sockaddr_ll *sll;\n\tunion tpacket_uhdr h;\n\tu8 *skb_head = skb->data;\n\tint skb_len = skb->len;\n\tunsigned int snaplen, res;\n\tunsigned long status = TP_STATUS_USER;\n\tunsigned short macoff, hdrlen;\n\tunsigned int netoff;\n\tstruct sk_buff *copy_skb = NULL;\n\tstruct timespec64 ts;\n\t__u32 ts_status;\n\tbool is_drop_n_account = false;\n\tunsigned int slot_id = 0;\n\tbool do_vnet = false;\n\n\t/* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.\n\t * We may add members to them until current aligned size without forcing\n\t * userspace to call getsockopt(..., PACKET_HDRLEN, ...).\n\t */\n\tBUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);\n\tBUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);\n\n\tif (skb->pkt_type == PACKET_LOOPBACK)\n\t\tgoto drop;\n\n\tsk = pt->af_packet_priv;\n\tpo = pkt_sk(sk);\n\n\tif (!net_eq(dev_net(dev), sock_net(sk)))\n\t\tgoto drop;\n\n\tif (dev->header_ops) {\n\t\tif (sk->sk_type != SOCK_DGRAM)\n\t\t\tskb_push(skb, skb->data - skb_mac_header(skb));\n\t\telse if (skb->pkt_type == PACKET_OUTGOING) {\n\t\t\t/* Special case: outgoing packets have ll header at head */\n\t\t\tskb_pull(skb, skb_network_offset(skb));\n\t\t}\n\t}\n\n\tsnaplen = skb->len;\n\n\tres = run_filter(skb, sk, snaplen);\n\tif (!res)\n\t\tgoto drop_n_restore;\n\n\t/* If we are flooded, just give up */\n\tif (__packet_rcv_has_room(po, skb) == ROOM_NONE) {\n\t\tatomic_inc(&po->tp_drops);\n\t\tgoto drop_n_restore;\n\t}\n\n\tif (skb->ip_summed == CHECKSUM_PARTIAL)\n\t\tstatus |= TP_STATUS_CSUMNOTREADY;\n\telse if (skb->pkt_type != PACKET_OUTGOING &&\n\t\t (skb->ip_summed == CHECKSUM_COMPLETE ||\n\t\t skb_csum_unnecessary(skb)))\n\t\tstatus |= TP_STATUS_CSUM_VALID;\n\n\tif (snaplen > res)\n\t\tsnaplen = res;\n\n\tif (sk->sk_type == SOCK_DGRAM) {\n\t\tmacoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +\n\t\t\t\t po->tp_reserve;\n\t} else {\n\t\tunsigned int maclen = skb_network_offset(skb);\n\t\tnetoff = TPACKET_ALIGN(po->tp_hdrlen +\n\t\t\t\t (maclen < 16 ? 16 : maclen)) +\n\t\t\t\t po->tp_reserve;\n\t\tif (po->has_vnet_hdr) {\n\t\t\tnetoff += sizeof(struct virtio_net_hdr);\n\t\t\tdo_vnet = true;\n\t\t}\n\t\tmacoff = netoff - maclen;\n\t}\n\tif (netoff > USHRT_MAX) {\n\t\tatomic_inc(&po->tp_drops);\n\t\tgoto drop_n_restore;\n\t}\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tif (macoff + snaplen > po->rx_ring.frame_size) {\n\t\t\tif (po->copy_thresh &&\n\t\t\t atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {\n\t\t\t\tif (skb_shared(skb)) {\n\t\t\t\t\tcopy_skb = skb_clone(skb, GFP_ATOMIC);\n\t\t\t\t} else {\n\t\t\t\t\tcopy_skb = skb_get(skb);\n\t\t\t\t\tskb_head = skb->data;\n\t\t\t\t}\n\t\t\t\tif (copy_skb)\n\t\t\t\t\tskb_set_owner_r(copy_skb, sk);\n\t\t\t}\n\t\t\tsnaplen = po->rx_ring.frame_size - macoff;\n\t\t\tif ((int)snaplen < 0) {\n\t\t\t\tsnaplen = 0;\n\t\t\t\tdo_vnet = false;\n\t\t\t}\n\t\t}\n\t} else if (unlikely(macoff + snaplen >\n\t\t\t GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {\n\t\tu32 nval;\n\n\t\tnval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;\n\t\tpr_err_once(\"tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\\n\",\n\t\t\t snaplen, nval, macoff);\n\t\tsnaplen = nval;\n\t\tif (unlikely((int)snaplen < 0)) {\n\t\t\tsnaplen = 0;\n\t\t\tmacoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;\n\t\t\tdo_vnet = false;\n\t\t}\n\t}\n\tspin_lock(&sk->sk_receive_queue.lock);\n\th.raw = packet_current_rx_frame(po, skb,\n\t\t\t\t\tTP_STATUS_KERNEL, (macoff+snaplen));\n\tif (!h.raw)\n\t\tgoto drop_n_account;\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tslot_id = po->rx_ring.head;\n\t\tif (test_bit(slot_id, po->rx_ring.rx_owner_map))\n\t\t\tgoto drop_n_account;\n\t\t__set_bit(slot_id, po->rx_ring.rx_owner_map);\n\t}\n\n\tif (do_vnet &&\n\t virtio_net_hdr_from_skb(skb, h.raw + macoff -\n\t\t\t\t sizeof(struct virtio_net_hdr),\n\t\t\t\t vio_le(), true, 0)) {\n\t\tif (po->tp_version == TPACKET_V3)\n\t\t\tprb_clear_blk_fill_status(&po->rx_ring);\n\t\tgoto drop_n_account;\n\t}\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tpacket_increment_rx_head(po, &po->rx_ring);\n\t/*\n\t * LOSING will be reported till you read the stats,\n\t * because it's COR - Clear On Read.\n\t * Anyways, moving it for V1/V2 only as V3 doesn't need this\n\t * at packet level.\n\t */\n\t\tif (atomic_read(&po->tp_drops))\n\t\t\tstatus |= TP_STATUS_LOSING;\n\t}\n\n\tpo->stats.stats1.tp_packets++;\n\tif (copy_skb) {\n\t\tstatus |= TP_STATUS_COPY;\n\t\t__skb_queue_tail(&sk->sk_receive_queue, copy_skb);\n\t}\n\tspin_unlock(&sk->sk_receive_queue.lock);\n\n\tskb_copy_bits(skb, 0, h.raw + macoff, snaplen);\n\n\tif (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))\n\t\tktime_get_real_ts64(&ts);\n\n\tstatus |= ts_status;\n\n\tswitch (po->tp_version) {\n\tcase TPACKET_V1:\n\t\th.h1->tp_len = skb->len;\n\t\th.h1->tp_snaplen = snaplen;\n\t\th.h1->tp_mac = macoff;\n\t\th.h1->tp_net = netoff;\n\t\th.h1->tp_sec = ts.tv_sec;\n\t\th.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;\n\t\thdrlen = sizeof(*h.h1);\n\t\tbreak;\n\tcase TPACKET_V2:\n\t\th.h2->tp_len = skb->len;\n\t\th.h2->tp_snaplen = snaplen;\n\t\th.h2->tp_mac = macoff;\n\t\th.h2->tp_net = netoff;\n\t\th.h2->tp_sec = ts.tv_sec;\n\t\th.h2->tp_nsec = ts.tv_nsec;\n\t\tif (skb_vlan_tag_present(skb)) {\n\t\t\th.h2->tp_vlan_tci = skb_vlan_tag_get(skb);\n\t\t\th.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);\n\t\t\tstatus |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;\n\t\t} else {\n\t\t\th.h2->tp_vlan_tci = 0;\n\t\t\th.h2->tp_vlan_tpid = 0;\n\t\t}\n\t\tmemset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));\n\t\thdrlen = sizeof(*h.h2);\n\t\tbreak;\n\tcase TPACKET_V3:\n\t\t/* tp_nxt_offset,vlan are already populated above.\n\t\t * So DONT clear those fields here\n\t\t */\n\t\th.h3->tp_status |= status;\n\t\th.h3->tp_len = skb->len;\n\t\th.h3->tp_snaplen = snaplen;\n\t\th.h3->tp_mac = macoff;\n\t\th.h3->tp_net = netoff;\n\t\th.h3->tp_sec = ts.tv_sec;\n\t\th.h3->tp_nsec = ts.tv_nsec;\n\t\tmemset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));\n\t\thdrlen = sizeof(*h.h3);\n\t\tbreak;\n\tdefault:\n\t\tBUG();\n\t}\n\n\tsll = h.raw + TPACKET_ALIGN(hdrlen);\n\tsll->sll_halen = dev_parse_header(skb, sll->sll_addr);\n\tsll->sll_family = AF_PACKET;\n\tsll->sll_hatype = dev->type;\n\tsll->sll_protocol = skb->protocol;\n\tsll->sll_pkttype = skb->pkt_type;\n\tif (unlikely(po->origdev))\n\t\tsll->sll_ifindex = orig_dev->ifindex;\n\telse\n\t\tsll->sll_ifindex = dev->ifindex;\n\n\tsmp_mb();\n\n#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tu8 *start, *end;\n\n\t\tend = (u8 *) PAGE_ALIGN((unsigned long) h.raw +\n\t\t\t\t\tmacoff + snaplen);\n\n\t\tfor (start = h.raw; start < end; start += PAGE_SIZE)\n\t\t\tflush_dcache_page(pgv_to_page(start));\n\t}\n\tsmp_wmb();\n#endif\n\n\tif (po->tp_version <= TPACKET_V2) {\n\t\tspin_lock(&sk->sk_receive_queue.lock);\n\t\t__packet_set_status(po, h.raw, status);\n\t\t__clear_bit(slot_id, po->rx_ring.rx_owner_map);\n\t\tspin_unlock(&sk->sk_receive_queue.lock);\n\t\tsk->sk_data_ready(sk);\n\t} else if (po->tp_version == TPACKET_V3) {\n\t\tprb_clear_blk_fill_status(&po->rx_ring);\n\t}\n\ndrop_n_restore:\n\tif (skb_head != skb->data && skb_shared(skb)) {\n\t\tskb->data = skb_head;\n\t\tskb->len = skb_len;\n\t}\ndrop:\n\tif (!is_drop_n_account)\n\t\tconsume_skb(skb);\n\telse\n\t\tkfree_skb(skb);\n\treturn 0;\n\ndrop_n_account:\n\tspin_unlock(&sk->sk_receive_queue.lock);\n\tatomic_inc(&po->tp_drops);\n\tis_drop_n_account = true;\n\n\tsk->sk_data_ready(sk);\n\tkfree_skb(copy_skb);\n\tgoto drop_n_restore;\n}", "project": "linux", "hash": 321520857233827511931030116735694876634, "size": 269, "commit_id": "acf69c946233259ab4d64f8869d4037a198c7f06", "message": "net/packet: fix overflow in tpacket_rcv\n\nUsing tp_reserve to calculate netoff can overflow as\ntp_reserve is unsigned int and netoff is unsigned short.\n\nThis may lead to macoff receving a smaller value then\nsizeof(struct virtio_net_hdr), and if po->has_vnet_hdr\nis set, an out-of-bounds write will occur when\ncalling virtio_net_hdr_from_skb.\n\nThe bug is fixed by converting netoff to unsigned int\nand checking if it exceeds USHRT_MAX.\n\nThis addresses CVE-2020-14386\n\nFixes: 8913336a7e8d (\"packet: add PACKET_RESERVE sockopt\")\nSigned-off-by: Or Cohen \nSigned-off-by: Eric Dumazet \nSigned-off-by: Linus Torvalds ", "target": 0, "dataset": "other", "idx": 330393} {"func": "static void set_pixel_format(VncState *vs,\n int bits_per_pixel, int depth,\n int big_endian_flag, int true_color_flag,\n int red_max, int green_max, int blue_max,\n int red_shift, int green_shift, int blue_shift)\n{\n if (!true_color_flag) {\n vnc_client_error(vs);\n return;\n }\n\n switch (bits_per_pixel) {\n case 8:\n case 16:\n case 32:\n break;\n default:\n vnc_client_error(vs);\n return;\n }\n\n vs->client_pf.rmax = red_max;\n vs->client_pf.rbits = hweight_long(red_max);\n vs->client_pf.rshift = red_shift;\n vs->client_pf.rmask = red_max << red_shift;\n vs->client_pf.gmax = green_max;\n vs->client_pf.gbits = hweight_long(green_max);\n vs->client_pf.gshift = green_shift;\n vs->client_pf.gmask = green_max << green_shift;\n vs->client_pf.bmax = blue_max;\n vs->client_pf.bbits = hweight_long(blue_max);\n vs->client_pf.bshift = blue_shift;\n vs->client_pf.bmask = blue_max << blue_shift;\n vs->client_pf.bits_per_pixel = bits_per_pixel;\n vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;\n vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;\n vs->client_be = big_endian_flag;\n\n set_pixel_conversion(vs);\n\n graphic_hw_invalidate(vs->vd->dcl.con);\n graphic_hw_update(vs->vd->dcl.con);\n}", "project": "qemu", "hash": 209274626528158267666795461424033381853, "size": 43, "commit_id": "4c65fed8bdf96780735dbdb92a8bd0d6b6526cc3", "message": "ui: vnc: avoid floating point exception\n\nWhile sending 'SetPixelFormat' messages to a VNC server,\nthe client could set the 'red-max', 'green-max' and 'blue-max'\nvalues to be zero. This leads to a floating point exception in\nwrite_png_palette while doing frame buffer updates.\n\nReported-by: Lian Yihan \nSigned-off-by: Prasad J Pandit \nReviewed-by: Gerd Hoffmann \nSigned-off-by: Peter Maydell ", "target": 1, "dataset": "other", "idx": 202144} {"func": "static void set_pixel_format(VncState *vs,\n int bits_per_pixel, int depth,\n int big_endian_flag, int true_color_flag,\n int red_max, int green_max, int blue_max,\n int red_shift, int green_shift, int blue_shift)\n{\n if (!true_color_flag) {\n vnc_client_error(vs);\n return;\n }\n\n switch (bits_per_pixel) {\n case 8:\n case 16:\n case 32:\n break;\n default:\n vnc_client_error(vs);\n return;\n }\n\n vs->client_pf.rmax = red_max ? red_max : 0xFF;\n vs->client_pf.rbits = hweight_long(red_max);\n vs->client_pf.rshift = red_shift;\n vs->client_pf.rmask = red_max << red_shift;\n vs->client_pf.gmax = green_max ? green_max : 0xFF;\n vs->client_pf.gbits = hweight_long(green_max);\n vs->client_pf.gshift = green_shift;\n vs->client_pf.gmask = green_max << green_shift;\n vs->client_pf.bmax = blue_max ? blue_max : 0xFF;\n vs->client_pf.bbits = hweight_long(blue_max);\n vs->client_pf.bshift = blue_shift;\n vs->client_pf.bmask = blue_max << blue_shift;\n vs->client_pf.bits_per_pixel = bits_per_pixel;\n vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;\n vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;\n vs->client_be = big_endian_flag;\n\n set_pixel_conversion(vs);\n\n graphic_hw_invalidate(vs->vd->dcl.con);\n graphic_hw_update(vs->vd->dcl.con);\n}", "project": "qemu", "hash": 98211384367942618164926733929775680004, "size": 43, "commit_id": "4c65fed8bdf96780735dbdb92a8bd0d6b6526cc3", "message": "ui: vnc: avoid floating point exception\n\nWhile sending 'SetPixelFormat' messages to a VNC server,\nthe client could set the 'red-max', 'green-max' and 'blue-max'\nvalues to be zero. This leads to a floating point exception in\nwrite_png_palette while doing frame buffer updates.\n\nReported-by: Lian Yihan \nSigned-off-by: Prasad J Pandit \nReviewed-by: Gerd Hoffmann \nSigned-off-by: Peter Maydell ", "target": 0, "dataset": "other", "idx": 330516} {"func": "repodata_schema2id(Repodata *data, Id *schema, int create)\n{\n int h, len, i;\n Id *sp, cid;\n Id *schematahash;\n\n if (!*schema)\n return 0;\t/* XXX: allow empty schema? */\n if ((schematahash = data->schematahash) == 0)\n {\n data->schematahash = schematahash = solv_calloc(256, sizeof(Id));\n for (i = 1; i < data->nschemata; i++)\n\t{\n\t for (sp = data->schemadata + data->schemata[i], h = 0; *sp;)\n\t h = h * 7 + *sp++;\n\t h &= 255;\n\t schematahash[h] = i;\n\t}\n data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK);\n data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK);\n }\n\n for (sp = schema, len = 0, h = 0; *sp; len++)\n h = h * 7 + *sp++;\n h &= 255;\n len++;\n\n cid = schematahash[h];\n if (cid)\n {\n if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n /* cache conflict, do a slow search */\n for (cid = 1; cid < data->nschemata; cid++)\n if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n }\n /* a new one */\n if (!create)\n return 0;\n data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK);\n data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK);\n /* add schema */\n memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id));\n data->schemata[data->nschemata] = data->schemadatalen;\n data->schemadatalen += len;\n schematahash[h] = data->nschemata;\n#if 0\nfprintf(stderr, \"schema2id: new schema\\n\");\n#endif\n return data->nschemata++;\n}", "project": "libsolv", "hash": 198011217878246148723542582906537124475, "size": 52, "commit_id": "fdb9c9c03508990e4583046b590c30d958f272da", "message": "repodata_schema2id: fix heap-buffer-overflow in memcmp\n\nWhen the length of last schema in data->schemadata is\nless than length of input schema, we got a read overflow\nin asan test.\n\nSigned-off-by: Zhipeng Xie ", "target": 1, "dataset": "other", "idx": 202305} {"func": "repodata_schema2id(Repodata *data, Id *schema, int create)\n{\n int h, len, i;\n Id *sp, cid;\n Id *schematahash;\n\n if (!*schema)\n return 0;\t/* XXX: allow empty schema? */\n if ((schematahash = data->schematahash) == 0)\n {\n data->schematahash = schematahash = solv_calloc(256, sizeof(Id));\n for (i = 1; i < data->nschemata; i++)\n\t{\n\t for (sp = data->schemadata + data->schemata[i], h = 0; *sp;)\n\t h = h * 7 + *sp++;\n\t h &= 255;\n\t schematahash[h] = i;\n\t}\n data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK);\n data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK);\n }\n\n for (sp = schema, len = 0, h = 0; *sp; len++)\n h = h * 7 + *sp++;\n h &= 255;\n len++;\n\n cid = schematahash[h];\n if (cid)\n {\n if ((data->schemata[cid] + len <= data->schemadatalen) &&\n\t\t\t !memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n /* cache conflict, do a slow search */\n for (cid = 1; cid < data->nschemata; cid++)\n if ((data->schemata[cid] + len <= data->schemadatalen) &&\n\t\t\t\t!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n }\n /* a new one */\n if (!create)\n return 0;\n data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK);\n data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK);\n /* add schema */\n memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id));\n data->schemata[data->nschemata] = data->schemadatalen;\n data->schemadatalen += len;\n schematahash[h] = data->nschemata;\n#if 0\nfprintf(stderr, \"schema2id: new schema\\n\");\n#endif\n return data->nschemata++;\n}", "project": "libsolv", "hash": 40327825865103618095291848843313728372, "size": 54, "commit_id": "fdb9c9c03508990e4583046b590c30d958f272da", "message": "repodata_schema2id: fix heap-buffer-overflow in memcmp\n\nWhen the length of last schema in data->schemadata is\nless than length of input schema, we got a read overflow\nin asan test.\n\nSigned-off-by: Zhipeng Xie ", "target": 0, "dataset": "other", "idx": 333146} {"func": "_decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) {\n // To avoid dealing with YCbCr subsampling, let libtiff handle it\n // Use a TIFFRGBAImage wrapping the tiff image, and let libtiff handle\n // all of the conversion. Metadata read from the TIFFRGBAImage could\n // be different from the metadata that the base tiff returns.\n\n INT32 strip_row;\n UINT8 *new_data;\n UINT32 rows_per_strip, row_byte_size, rows_to_read;\n int ret;\n TIFFRGBAImage img;\n char emsg[1024] = \"\";\n\n ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);\n if (ret != 1) {\n rows_per_strip = state->ysize;\n }\n TRACE((\"RowsPerStrip: %u \\n\", rows_per_strip));\n\n if (!(TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg))) {\n TRACE((\"Decode error, msg: %s\", emsg));\n state->errcode = IMAGING_CODEC_BROKEN;\n // nothing to clean up, just return\n return -1;\n }\n\n img.req_orientation = ORIENTATION_TOPLEFT;\n img.col_offset = 0;\n\n if (state->xsize != img.width || state->ysize != img.height) {\n TRACE(\n (\"Inconsistent Image Error: %d =? %d, %d =? %d\",\n state->xsize,\n img.width,\n state->ysize,\n img.height));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decodeycbcr_err;\n }\n\n /* overflow check for row byte size */\n if (INT_MAX / 4 < img.width) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n // TiffRGBAImages are 32bits/pixel.\n row_byte_size = img.width * 4;\n\n /* overflow check for realloc */\n if (INT_MAX / row_byte_size < rows_per_strip) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n state->bytes = rows_per_strip * row_byte_size;\n\n TRACE((\"StripSize: %d \\n\", state->bytes));\n\n /* realloc to fit whole strip */\n /* malloc check above */\n new_data = realloc(state->buffer, state->bytes);\n if (!new_data) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n state->buffer = new_data;\n\n for (; state->y < state->ysize; state->y += rows_per_strip) {\n img.row_offset = state->y;\n rows_to_read = min(rows_per_strip, img.height - state->y);\n\n if (TIFFRGBAImageGet(&img, (UINT32 *)state->buffer, img.width, rows_to_read) ==\n -1) {\n TRACE((\"Decode Error, y: %d\\n\", state->y));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decodeycbcr_err;\n }\n\n TRACE((\"Decoded strip for row %d \\n\", state->y));\n\n // iterate over each row in the strip and stuff data into image\n for (strip_row = 0;\n strip_row < min((INT32)rows_per_strip, state->ysize - state->y);\n strip_row++) {\n TRACE((\"Writing data into line %d ; \\n\", state->y + strip_row));\n\n // UINT8 * bbb = state->buffer + strip_row * (state->bytes /\n // rows_per_strip); TRACE((\"chars: %x %x %x %x\\n\", ((UINT8 *)bbb)[0],\n // ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));\n\n state->shuffle(\n (UINT8 *)im->image[state->y + state->yoff + strip_row] +\n state->xoff * im->pixelsize,\n state->buffer + strip_row * row_byte_size,\n state->xsize);\n }\n }\n\ndecodeycbcr_err:\n TIFFRGBAImageEnd(&img);\n if (state->errcode != 0) {\n return -1;\n }\n return 0;\n}", "project": "Pillow", "hash": 24226912125521825308253027036068382827, "size": 107, "commit_id": "3fee28eb9479bf7d59e0fa08068f9cc4a6e2f04c", "message": "Incorrect error code checking in TiffDecode.c\n\n* since Pillow 8.1.0\n* CVE-2021-25289", "target": 1, "dataset": "other", "idx": 202401} {"func": "_decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) {\n // To avoid dealing with YCbCr subsampling, let libtiff handle it\n // Use a TIFFRGBAImage wrapping the tiff image, and let libtiff handle\n // all of the conversion. Metadata read from the TIFFRGBAImage could\n // be different from the metadata that the base tiff returns.\n\n INT32 strip_row;\n UINT8 *new_data;\n UINT32 rows_per_strip, row_byte_size, rows_to_read;\n int ret;\n TIFFRGBAImage img;\n char emsg[1024] = \"\";\n\n ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);\n if (ret != 1) {\n rows_per_strip = state->ysize;\n }\n TRACE((\"RowsPerStrip: %u \\n\", rows_per_strip));\n\n if (!(TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg))) {\n TRACE((\"Decode error, msg: %s\", emsg));\n state->errcode = IMAGING_CODEC_BROKEN;\n // nothing to clean up, just return\n return -1;\n }\n\n img.req_orientation = ORIENTATION_TOPLEFT;\n img.col_offset = 0;\n\n if (state->xsize != img.width || state->ysize != img.height) {\n TRACE(\n (\"Inconsistent Image Error: %d =? %d, %d =? %d\",\n state->xsize,\n img.width,\n state->ysize,\n img.height));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decodeycbcr_err;\n }\n\n /* overflow check for row byte size */\n if (INT_MAX / 4 < img.width) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n // TiffRGBAImages are 32bits/pixel.\n row_byte_size = img.width * 4;\n\n /* overflow check for realloc */\n if (INT_MAX / row_byte_size < rows_per_strip) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n state->bytes = rows_per_strip * row_byte_size;\n\n TRACE((\"StripSize: %d \\n\", state->bytes));\n\n /* realloc to fit whole strip */\n /* malloc check above */\n new_data = realloc(state->buffer, state->bytes);\n if (!new_data) {\n state->errcode = IMAGING_CODEC_MEMORY;\n goto decodeycbcr_err;\n }\n\n state->buffer = new_data;\n\n for (; state->y < state->ysize; state->y += rows_per_strip) {\n img.row_offset = state->y;\n rows_to_read = min(rows_per_strip, img.height - state->y);\n\n if (!TIFFRGBAImageGet(&img, (UINT32 *)state->buffer, img.width, rows_to_read)) {\n TRACE((\"Decode Error, y: %d\\n\", state->y));\n state->errcode = IMAGING_CODEC_BROKEN;\n goto decodeycbcr_err;\n }\n\n TRACE((\"Decoded strip for row %d \\n\", state->y));\n\n // iterate over each row in the strip and stuff data into image\n for (strip_row = 0;\n strip_row < min((INT32)rows_per_strip, state->ysize - state->y);\n strip_row++) {\n TRACE((\"Writing data into line %d ; \\n\", state->y + strip_row));\n\n // UINT8 * bbb = state->buffer + strip_row * (state->bytes /\n // rows_per_strip); TRACE((\"chars: %x %x %x %x\\n\", ((UINT8 *)bbb)[0],\n // ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));\n\n state->shuffle(\n (UINT8 *)im->image[state->y + state->yoff + strip_row] +\n state->xoff * im->pixelsize,\n state->buffer + strip_row * row_byte_size,\n state->xsize);\n }\n }\n\ndecodeycbcr_err:\n TIFFRGBAImageEnd(&img);\n if (state->errcode != 0) {\n return -1;\n }\n return 0;\n}", "project": "Pillow", "hash": 337824209326848979984273145189268149899, "size": 106, "commit_id": "3fee28eb9479bf7d59e0fa08068f9cc4a6e2f04c", "message": "Incorrect error code checking in TiffDecode.c\n\n* since Pillow 8.1.0\n* CVE-2021-25289", "target": 0, "dataset": "other", "idx": 333841} {"func": "mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)\n{\n\tMonoImage *image = method->klass->image;\n\tMonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;\n\tMonoTableInfo *tables = image->tables;\n\tMonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];\n\tMonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];\n\tguint32 im_cols [MONO_IMPLMAP_SIZE];\n\tguint32 scope_token;\n\tconst char *import = NULL;\n\tconst char *orig_scope;\n\tconst char *new_scope;\n\tchar *error_msg;\n\tchar *full_name, *file_name;\n\tint i;\n\tMonoDl *module = NULL;\n\n\tg_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);\n\n\tif (piinfo->addr)\n\t\treturn piinfo->addr;\n\n\tif (method->klass->image->dynamic) {\n\t\tMonoReflectionMethodAux *method_aux = \n\t\t\tg_hash_table_lookup (\n\t\t\t\t((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);\n\t\tif (!method_aux)\n\t\t\treturn NULL;\n\n\t\timport = method_aux->dllentry;\n\t\torig_scope = method_aux->dll;\n\t}\n\telse {\n\t\tif (!piinfo->implmap_idx)\n\t\t\treturn NULL;\n\n\t\tmono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);\n\n\t\tpiinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];\n\t\timport = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);\n\t\tscope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);\n\t\torig_scope = mono_metadata_string_heap (image, scope_token);\n\t}\n\n\tmono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);\n\n\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\"DllImport attempting to load: '%s'.\", new_scope);\n\n\tif (exc_class) {\n\t\t*exc_class = NULL;\n\t\t*exc_arg = NULL;\n\t}\n\n\t/* we allow a special name to dlopen from the running process namespace */\n\tif (strcmp (new_scope, \"__Internal\") == 0)\n\t\tmodule = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);\n\n\t/*\n\t * Try loading the module using a variety of names\n\t */\n\tfor (i = 0; i < 4; ++i) {\n\t\tswitch (i) {\n\t\tcase 0:\n\t\t\t/* Try the original name */\n\t\t\tfile_name = g_strdup (new_scope);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\t/* Try trimming the .dll extension */\n\t\t\tif (strstr (new_scope, \".dll\") == (new_scope + strlen (new_scope) - 4)) {\n\t\t\t\tfile_name = g_strdup (new_scope);\n\t\t\t\tfile_name [strlen (new_scope) - 4] = '\\0';\n\t\t\t}\n\t\t\telse\n\t\t\t\tcontinue;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tif (strstr (new_scope, \"lib\") != new_scope) {\n\t\t\t\tfile_name = g_strdup_printf (\"lib%s\", new_scope);\n\t\t\t}\n\t\t\telse\n\t\t\t\tcontinue;\n\t\t\tbreak;\n\t\tdefault:\n#ifndef TARGET_WIN32\n\t\t\tif (!g_ascii_strcasecmp (\"user32.dll\", new_scope) ||\n\t\t\t !g_ascii_strcasecmp (\"kernel32.dll\", new_scope) ||\n\t\t\t !g_ascii_strcasecmp (\"user32\", new_scope) ||\n\t\t\t !g_ascii_strcasecmp (\"kernel\", new_scope)) {\n\t\t\t\tfile_name = g_strdup (\"libMonoSupportW.so\");\n\t\t\t} else\n#endif\n\t\t\t\t continue;\n#ifndef TARGET_WIN32\n\t\t\tbreak;\n#endif\n\t\t}\n\n\t\tif (!module) {\n\t\t\tvoid *iter = NULL;\n\t\t\twhile ((full_name = mono_dl_build_path (NULL, file_name, &iter))) {\n\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\t\"DllImport loading location: '%s'.\", full_name);\n\t\t\t\tmodule = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);\n\t\t\t\tif (!module) {\n\t\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\t\t\"DllImport error loading library: '%s'.\",\n\t\t\t\t\t\t\terror_msg);\n\t\t\t\t\tg_free (error_msg);\n\t\t\t\t}\n\t\t\t\tg_free (full_name);\n\t\t\t\tif (module)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!module) {\n\t\t\tvoid *iter = NULL;\n\t\t\twhile ((full_name = mono_dl_build_path (\".\", file_name, &iter))) {\n\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\"DllImport loading library: '%s'.\", full_name);\n\t\t\t\tmodule = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);\n\t\t\t\tif (!module) {\n\t\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\t\"DllImport error loading library '%s'.\",\n\t\t\t\t\t\terror_msg);\n\t\t\t\t\tg_free (error_msg);\n\t\t\t\t}\n\t\t\t\tg_free (full_name);\n\t\t\t\tif (module)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!module) {\n\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\"DllImport loading: '%s'.\", file_name);\n\t\t\tmodule = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);\n\t\t\tif (!module) {\n\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\t\"DllImport error loading library '%s'.\",\n\t\t\t\t\t\terror_msg);\n\t\t\t}\n\t\t}\n\n\t\tg_free (file_name);\n\n\t\tif (module)\n\t\t\tbreak;\n\t}\n\n\tif (!module) {\n\t\tmono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\"DllImport unable to load library '%s'.\",\n\t\t\t\terror_msg);\n\t\tg_free (error_msg);\n\n\t\tif (exc_class) {\n\t\t\t*exc_class = \"DllNotFoundException\";\n\t\t\t*exc_arg = new_scope;\n\t\t}\n\t\treturn NULL;\n\t}\n\n#ifdef TARGET_WIN32\n\tif (import && import [0] == '#' && isdigit (import [1])) {\n\t\tchar *end;\n\t\tlong id;\n\n\t\tid = strtol (import + 1, &end, 10);\n\t\tif (id > 0 && *end == '\\0')\n\t\t\timport++;\n\t}\n#endif\n\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\"Searching for '%s'.\", import);\n\n\tif (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {\n\t\terror_msg = mono_dl_symbol (module, import, &piinfo->addr); \n\t} else {\n\t\tchar *mangled_name = NULL, *mangled_name2 = NULL;\n\t\tint mangle_charset;\n\t\tint mangle_stdcall;\n\t\tint mangle_param_count;\n#ifdef TARGET_WIN32\n\t\tint param_count;\n#endif\n\n\t\t/*\n\t\t * Search using a variety of mangled names\n\t\t */\n\t\tfor (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {\n\t\t\tfor (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {\n\t\t\t\tgboolean need_param_count = FALSE;\n#ifdef TARGET_WIN32\n\t\t\t\tif (mangle_stdcall > 0)\n\t\t\t\t\tneed_param_count = TRUE;\n#endif\n\t\t\t\tfor (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {\n\n\t\t\t\t\tif (piinfo->addr)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tmangled_name = (char*)import;\n\t\t\t\t\tswitch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {\n\t\t\t\t\tcase PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:\n\t\t\t\t\t\t/* Try the mangled name first */\n\t\t\t\t\t\tif (mangle_charset == 0)\n\t\t\t\t\t\t\tmangled_name = g_strconcat (import, \"W\", NULL);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:\n#ifdef TARGET_WIN32\n\t\t\t\t\t\tif (mangle_charset == 0)\n\t\t\t\t\t\t\tmangled_name = g_strconcat (import, \"W\", NULL);\n#else\n\t\t\t\t\t\t/* Try the mangled name last */\n\t\t\t\t\t\tif (mangle_charset == 1)\n\t\t\t\t\t\t\tmangled_name = g_strconcat (import, \"A\", NULL);\n#endif\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t/* Try the mangled name last */\n\t\t\t\t\t\tif (mangle_charset == 1)\n\t\t\t\t\t\t\tmangled_name = g_strconcat (import, \"A\", NULL);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n#ifdef TARGET_WIN32\n\t\t\t\t\tif (mangle_param_count == 0)\n\t\t\t\t\t\tparam_count = mono_method_signature (method)->param_count * sizeof (gpointer);\n\t\t\t\t\telse\n\t\t\t\t\t\t/* Try brute force, since it would be very hard to compute the stack usage correctly */\n\t\t\t\t\t\tparam_count = mangle_param_count;\n\n\t\t\t\t\t/* Try the stdcall mangled name */\n\t\t\t\t\t/* \n\t\t\t\t\t * gcc under windows creates mangled names without the underscore, but MS.NET\n\t\t\t\t\t * doesn't support it, so we doesn't support it either.\n\t\t\t\t\t */\n\t\t\t\t\tif (mangle_stdcall == 1)\n\t\t\t\t\t\tmangled_name2 = g_strdup_printf (\"_%s@%d\", mangled_name, param_count);\n\t\t\t\t\telse\n\t\t\t\t\t\tmangled_name2 = mangled_name;\n#else\n\t\t\t\t\tmangled_name2 = mangled_name;\n#endif\n\n\t\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\t\t\t\"Probing '%s'.\", mangled_name2);\n\n\t\t\t\t\terror_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);\n\n\t\t\t\t\tif (piinfo->addr)\n\t\t\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\t\t\t\t\"Found as '%s'.\", mangled_name2);\n\n\t\t\t\t\tif (mangled_name != mangled_name2)\n\t\t\t\t\t\tg_free (mangled_name2);\n\t\t\t\t\tif (mangled_name != import)\n\t\t\t\t\t\tg_free (mangled_name);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!piinfo->addr) {\n\t\tg_free (error_msg);\n\t\tif (exc_class) {\n\t\t\t*exc_class = \"EntryPointNotFoundException\";\n\t\t\t*exc_arg = import;\n\t\t}\n\t\treturn NULL;\n\t}\n\treturn piinfo->addr;\n}", "project": "mono", "hash": 320715786743187810347874367233438679401, "size": 276, "commit_id": "8e890a3bf80a4620e417814dc14886b1bbd17625", "message": "Search for dllimported shared libs in the base directory, not cwd.\n\n* loader.c: we don't search the current directory anymore for shared\nlibraries referenced in DllImport attributes, as it has a slight\nsecurity risk. We search in the same directory where the referencing\nimage was loaded from, instead. Fixes bug# 641915.", "target": 1, "dataset": "other", "idx": 202558} {"func": "mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)\n{\n\tMonoImage *image = method->klass->image;\n\tMonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;\n\tMonoTableInfo *tables = image->tables;\n\tMonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];\n\tMonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];\n\tguint32 im_cols [MONO_IMPLMAP_SIZE];\n\tguint32 scope_token;\n\tconst char *import = NULL;\n\tconst char *orig_scope;\n\tconst char *new_scope;\n\tchar *error_msg;\n\tchar *full_name, *file_name;\n\tint i;\n\tMonoDl *module = NULL;\n\n\tg_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);\n\n\tif (piinfo->addr)\n\t\treturn piinfo->addr;\n\n\tif (method->klass->image->dynamic) {\n\t\tMonoReflectionMethodAux *method_aux = \n\t\t\tg_hash_table_lookup (\n\t\t\t\t((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);\n\t\tif (!method_aux)\n\t\t\treturn NULL;\n\n\t\timport = method_aux->dllentry;\n\t\torig_scope = method_aux->dll;\n\t}\n\telse {\n\t\tif (!piinfo->implmap_idx)\n\t\t\treturn NULL;\n\n\t\tmono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);\n\n\t\tpiinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];\n\t\timport = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);\n\t\tscope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);\n\t\torig_scope = mono_metadata_string_heap (image, scope_token);\n\t}\n\n\tmono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);\n\n\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\"DllImport attempting to load: '%s'.\", new_scope);\n\n\tif (exc_class) {\n\t\t*exc_class = NULL;\n\t\t*exc_arg = NULL;\n\t}\n\n\t/* we allow a special name to dlopen from the running process namespace */\n\tif (strcmp (new_scope, \"__Internal\") == 0)\n\t\tmodule = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);\n\n\t/*\n\t * Try loading the module using a variety of names\n\t */\n\tfor (i = 0; i < 4; ++i) {\n\t\tswitch (i) {\n\t\tcase 0:\n\t\t\t/* Try the original name */\n\t\t\tfile_name = g_strdup (new_scope);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\t/* Try trimming the .dll extension */\n\t\t\tif (strstr (new_scope, \".dll\") == (new_scope + strlen (new_scope) - 4)) {\n\t\t\t\tfile_name = g_strdup (new_scope);\n\t\t\t\tfile_name [strlen (new_scope) - 4] = '\\0';\n\t\t\t}\n\t\t\telse\n\t\t\t\tcontinue;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tif (strstr (new_scope, \"lib\") != new_scope) {\n\t\t\t\tfile_name = g_strdup_printf (\"lib%s\", new_scope);\n\t\t\t}\n\t\t\telse\n\t\t\t\tcontinue;\n\t\t\tbreak;\n\t\tdefault:\n#ifndef TARGET_WIN32\n\t\t\tif (!g_ascii_strcasecmp (\"user32.dll\", new_scope) ||\n\t\t\t !g_ascii_strcasecmp (\"kernel32.dll\", new_scope) ||\n\t\t\t !g_ascii_strcasecmp (\"user32\", new_scope) ||\n\t\t\t !g_ascii_strcasecmp (\"kernel\", new_scope)) {\n\t\t\t\tfile_name = g_strdup (\"libMonoSupportW.so\");\n\t\t\t} else\n#endif\n\t\t\t\t continue;\n#ifndef TARGET_WIN32\n\t\t\tbreak;\n#endif\n\t\t}\n\n\t\tif (!module) {\n\t\t\tvoid *iter = NULL;\n\t\t\tchar *mdirname = g_path_get_dirname (image->name);\n\t\t\twhile ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {\n\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\"DllImport loading library: '%s'.\", full_name);\n\t\t\t\tmodule = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);\n\t\t\t\tif (!module) {\n\t\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\t\"DllImport error loading library '%s'.\",\n\t\t\t\t\t\terror_msg);\n\t\t\t\t\tg_free (error_msg);\n\t\t\t\t}\n\t\t\t\tg_free (full_name);\n\t\t\t\tif (module)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tg_free (mdirname);\n\t\t}\n\n\t\tif (!module) {\n\t\t\tvoid *iter = NULL;\n\t\t\twhile ((full_name = mono_dl_build_path (NULL, file_name, &iter))) {\n\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\t\"DllImport loading location: '%s'.\", full_name);\n\t\t\t\tmodule = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);\n\t\t\t\tif (!module) {\n\t\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\t\t\"DllImport error loading library: '%s'.\",\n\t\t\t\t\t\t\terror_msg);\n\t\t\t\t\tg_free (error_msg);\n\t\t\t\t}\n\t\t\t\tg_free (full_name);\n\t\t\t\tif (module)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!module) {\n\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\"DllImport loading: '%s'.\", file_name);\n\t\t\tmodule = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);\n\t\t\tif (!module) {\n\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\t\"DllImport error loading library '%s'.\",\n\t\t\t\t\t\terror_msg);\n\t\t\t}\n\t\t}\n\n\t\tg_free (file_name);\n\n\t\tif (module)\n\t\t\tbreak;\n\t}\n\n\tif (!module) {\n\t\tmono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\"DllImport unable to load library '%s'.\",\n\t\t\t\terror_msg);\n\t\tg_free (error_msg);\n\n\t\tif (exc_class) {\n\t\t\t*exc_class = \"DllNotFoundException\";\n\t\t\t*exc_arg = new_scope;\n\t\t}\n\t\treturn NULL;\n\t}\n\n#ifdef TARGET_WIN32\n\tif (import && import [0] == '#' && isdigit (import [1])) {\n\t\tchar *end;\n\t\tlong id;\n\n\t\tid = strtol (import + 1, &end, 10);\n\t\tif (id > 0 && *end == '\\0')\n\t\t\timport++;\n\t}\n#endif\n\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\"Searching for '%s'.\", import);\n\n\tif (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {\n\t\terror_msg = mono_dl_symbol (module, import, &piinfo->addr); \n\t} else {\n\t\tchar *mangled_name = NULL, *mangled_name2 = NULL;\n\t\tint mangle_charset;\n\t\tint mangle_stdcall;\n\t\tint mangle_param_count;\n#ifdef TARGET_WIN32\n\t\tint param_count;\n#endif\n\n\t\t/*\n\t\t * Search using a variety of mangled names\n\t\t */\n\t\tfor (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {\n\t\t\tfor (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {\n\t\t\t\tgboolean need_param_count = FALSE;\n#ifdef TARGET_WIN32\n\t\t\t\tif (mangle_stdcall > 0)\n\t\t\t\t\tneed_param_count = TRUE;\n#endif\n\t\t\t\tfor (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {\n\n\t\t\t\t\tif (piinfo->addr)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tmangled_name = (char*)import;\n\t\t\t\t\tswitch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {\n\t\t\t\t\tcase PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:\n\t\t\t\t\t\t/* Try the mangled name first */\n\t\t\t\t\t\tif (mangle_charset == 0)\n\t\t\t\t\t\t\tmangled_name = g_strconcat (import, \"W\", NULL);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:\n#ifdef TARGET_WIN32\n\t\t\t\t\t\tif (mangle_charset == 0)\n\t\t\t\t\t\t\tmangled_name = g_strconcat (import, \"W\", NULL);\n#else\n\t\t\t\t\t\t/* Try the mangled name last */\n\t\t\t\t\t\tif (mangle_charset == 1)\n\t\t\t\t\t\t\tmangled_name = g_strconcat (import, \"A\", NULL);\n#endif\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t/* Try the mangled name last */\n\t\t\t\t\t\tif (mangle_charset == 1)\n\t\t\t\t\t\t\tmangled_name = g_strconcat (import, \"A\", NULL);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n#ifdef TARGET_WIN32\n\t\t\t\t\tif (mangle_param_count == 0)\n\t\t\t\t\t\tparam_count = mono_method_signature (method)->param_count * sizeof (gpointer);\n\t\t\t\t\telse\n\t\t\t\t\t\t/* Try brute force, since it would be very hard to compute the stack usage correctly */\n\t\t\t\t\t\tparam_count = mangle_param_count;\n\n\t\t\t\t\t/* Try the stdcall mangled name */\n\t\t\t\t\t/* \n\t\t\t\t\t * gcc under windows creates mangled names without the underscore, but MS.NET\n\t\t\t\t\t * doesn't support it, so we doesn't support it either.\n\t\t\t\t\t */\n\t\t\t\t\tif (mangle_stdcall == 1)\n\t\t\t\t\t\tmangled_name2 = g_strdup_printf (\"_%s@%d\", mangled_name, param_count);\n\t\t\t\t\telse\n\t\t\t\t\t\tmangled_name2 = mangled_name;\n#else\n\t\t\t\t\tmangled_name2 = mangled_name;\n#endif\n\n\t\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\t\t\t\"Probing '%s'.\", mangled_name2);\n\n\t\t\t\t\terror_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);\n\n\t\t\t\t\tif (piinfo->addr)\n\t\t\t\t\t\tmono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,\n\t\t\t\t\t\t\t\t\t\"Found as '%s'.\", mangled_name2);\n\n\t\t\t\t\tif (mangled_name != mangled_name2)\n\t\t\t\t\t\tg_free (mangled_name2);\n\t\t\t\t\tif (mangled_name != import)\n\t\t\t\t\t\tg_free (mangled_name);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!piinfo->addr) {\n\t\tg_free (error_msg);\n\t\tif (exc_class) {\n\t\t\t*exc_class = \"EntryPointNotFoundException\";\n\t\t\t*exc_arg = import;\n\t\t}\n\t\treturn NULL;\n\t}\n\treturn piinfo->addr;\n}", "project": "mono", "hash": 23336029349961999853011559792852870024, "size": 278, "commit_id": "8e890a3bf80a4620e417814dc14886b1bbd17625", "message": "Search for dllimported shared libs in the base directory, not cwd.\n\n* loader.c: we don't search the current directory anymore for shared\nlibraries referenced in DllImport attributes, as it has a slight\nsecurity risk. We search in the same directory where the referencing\nimage was loaded from, instead. Fixes bug# 641915.", "target": 0, "dataset": "other", "idx": 334474} {"func": "bool timerqueue_add(struct timerqueue_head *head, struct timerqueue_node *node)\n{\n\tstruct rb_node **p = &head->head.rb_node;\n\tstruct rb_node *parent = NULL;\n\tstruct timerqueue_node *ptr;\n\n\t/* Make sure we don't add nodes that are already added */\n\tWARN_ON_ONCE(!RB_EMPTY_NODE(&node->node));\n\n\twhile (*p) {\n\t\tparent = *p;\n\t\tptr = rb_entry(parent, struct timerqueue_node, node);\n\t\tif (node->expires < ptr->expires)\n\t\t\tp = &(*p)->rb_left;\n\t\telse\n\t\t\tp = &(*p)->rb_right;\n\t}\n\trb_link_node(&node->node, parent, p);\n\trb_insert_color(&node->node, &head->head);\n\n\tif (!head->next || node->expires < head->next->expires) {\n\t\thead->next = node;\n\t\treturn true;\n\t}\n\treturn false;\n}", "project": "tip", "hash": 295643821598703418675091892895767224857, "size": 26, "commit_id": "511885d7061eda3eb1faf3f57dcc936ff75863f1", "message": "lib/timerqueue: Rely on rbtree semantics for next timer\n\nSimplify the timerqueue code by using cached rbtrees and rely on the tree\nleftmost node semantics to get the timer with earliest expiration time.\nThis is a drop in conversion, and therefore semantics remain untouched.\n\nThe runtime overhead of cached rbtrees is be pretty much the same as the\ncurrent head->next method, noting that when removing the leftmost node,\na common operation for the timerqueue, the rb_next(leftmost) is O(1) as\nwell, so the next timer will either be the right node or its parent.\nTherefore no extra pointer chasing. Finally, the size of the struct\ntimerqueue_head remains the same.\n\nPasses several hours of rcutorture.\n\nSigned-off-by: Davidlohr Bueso \nSigned-off-by: Thomas Gleixner \nLink: https://lkml.kernel.org/r/20190724152323.bojciei3muvfxalm@linux-r8p5", "target": 1, "dataset": "other", "idx": 202574} {"func": "bool timerqueue_add(struct timerqueue_head *head, struct timerqueue_node *node)\n{\n\tstruct rb_node **p = &head->rb_root.rb_root.rb_node;\n\tstruct rb_node *parent = NULL;\n\tstruct timerqueue_node *ptr;\n\tbool leftmost = true;\n\n\t/* Make sure we don't add nodes that are already added */\n\tWARN_ON_ONCE(!RB_EMPTY_NODE(&node->node));\n\n\twhile (*p) {\n\t\tparent = *p;\n\t\tptr = rb_entry(parent, struct timerqueue_node, node);\n\t\tif (node->expires < ptr->expires) {\n\t\t\tp = &(*p)->rb_left;\n\t\t} else {\n\t\t\tp = &(*p)->rb_right;\n\t\t\tleftmost = false;\n\t\t}\n\t}\n\trb_link_node(&node->node, parent, p);\n\trb_insert_color_cached(&node->node, &head->rb_root, leftmost);\n\n\treturn leftmost;\n}", "project": "tip", "hash": 121492852338608162479188929864215178822, "size": 25, "commit_id": "511885d7061eda3eb1faf3f57dcc936ff75863f1", "message": "lib/timerqueue: Rely on rbtree semantics for next timer\n\nSimplify the timerqueue code by using cached rbtrees and rely on the tree\nleftmost node semantics to get the timer with earliest expiration time.\nThis is a drop in conversion, and therefore semantics remain untouched.\n\nThe runtime overhead of cached rbtrees is be pretty much the same as the\ncurrent head->next method, noting that when removing the leftmost node,\na common operation for the timerqueue, the rb_next(leftmost) is O(1) as\nwell, so the next timer will either be the right node or its parent.\nTherefore no extra pointer chasing. Finally, the size of the struct\ntimerqueue_head remains the same.\n\nPasses several hours of rcutorture.\n\nSigned-off-by: Davidlohr Bueso \nSigned-off-by: Thomas Gleixner \nLink: https://lkml.kernel.org/r/20190724152323.bojciei3muvfxalm@linux-r8p5", "target": 0, "dataset": "other", "idx": 335107} {"func": "dissect_dnp3_message(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)\n{\n proto_item *ti, *tdl, *tc, *hidden_item;\n proto_tree *dnp3_tree, *dl_tree, *field_tree;\n int offset = 0, temp_offset = 0;\n gboolean dl_prm;\n guint8 dl_len, dl_ctl, dl_func;\n const gchar *func_code_str;\n guint16 dl_dst, dl_src, calc_dl_crc;\n\n /* Make entries in Protocol column and Info column on summary display */\n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"DNP 3.0\");\n col_clear(pinfo->cinfo, COL_INFO);\n\n /* Skip \"0x0564\" header bytes */\n temp_offset += 2;\n\n dl_len = tvb_get_guint8(tvb, temp_offset);\n temp_offset += 1;\n\n dl_ctl = tvb_get_guint8(tvb, temp_offset);\n temp_offset += 1;\n\n dl_dst = tvb_get_letohs(tvb, temp_offset);\n temp_offset += 2;\n\n dl_src = tvb_get_letohs(tvb, temp_offset);\n\n dl_func = dl_ctl & DNP3_CTL_FUNC;\n dl_prm = dl_ctl & DNP3_CTL_PRM;\n func_code_str = val_to_str(dl_func, dl_prm ? dnp3_ctl_func_pri_vals : dnp3_ctl_func_sec_vals,\n \"Unknown function (0x%02x)\");\n\n /* Make sure source and dest are always in the info column */\n col_append_fstr(pinfo->cinfo, COL_INFO, \"from %u to %u\", dl_src, dl_dst);\n col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, \"len=%u, %s\", dl_len, func_code_str);\n\n /* create display subtree for the protocol */\n ti = proto_tree_add_item(tree, proto_dnp3, tvb, offset, -1, ENC_NA);\n dnp3_tree = proto_item_add_subtree(ti, ett_dnp3);\n\n /* Create Subtree for Data Link Layer */\n dl_tree = proto_tree_add_subtree_format(dnp3_tree, tvb, offset, DNP_HDR_LEN, ett_dnp3_dl, &tdl,\n \"Data Link Layer, Len: %u, From: %u, To: %u, \", dl_len, dl_src, dl_dst);\n if (dl_prm) {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tdl, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tdl, \"PRM, \");\n if (dl_ctl & DNP3_CTL_FCB) proto_item_append_text(tdl, \"FCB, \");\n if (dl_ctl & DNP3_CTL_FCV) proto_item_append_text(tdl, \"FCV, \");\n }\n else {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tdl, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tdl, \"PRM, \");\n if (dl_ctl & DNP3_CTL_RES) proto_item_append_text(tdl, \"RES, \");\n if (dl_ctl & DNP3_CTL_DFC) proto_item_append_text(tdl, \"DFC, \");\n }\n proto_item_append_text(tdl, \"%s\", func_code_str);\n\n /* start bytes */\n proto_tree_add_item(dl_tree, hf_dnp3_start, tvb, offset, 2, ENC_BIG_ENDIAN);\n offset += 2;\n\n /* add length field */\n proto_tree_add_item(dl_tree, hf_dnp3_len, tvb, offset, 1, ENC_BIG_ENDIAN);\n offset += 1;\n\n /* Add Control Byte Subtree */\n tc = proto_tree_add_uint_format_value(dl_tree, hf_dnp3_ctl, tvb, offset, 1, dl_ctl,\n \"0x%02x (\", dl_ctl);\n /* Add Text to Control Byte Subtree Header */\n if (dl_prm) {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tc, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tc, \"PRM, \");\n if (dl_ctl & DNP3_CTL_FCB) proto_item_append_text(tc, \"FCB, \");\n if (dl_ctl & DNP3_CTL_FCV) proto_item_append_text(tc, \"FCV, \");\n }\n else {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tc, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tc, \"PRM, \");\n if (dl_ctl & DNP3_CTL_RES) proto_item_append_text(tc, \"RES, \");\n if (dl_ctl & DNP3_CTL_DFC) proto_item_append_text(tc, \"DFC, \");\n }\n proto_item_append_text(tc, \"%s)\", func_code_str );\n field_tree = proto_item_add_subtree(tc, ett_dnp3_dl_ctl);\n\n /* Add Control Byte Subtree Items */\n if (dl_prm) {\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dir, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prm, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_fcb, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_fcv, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prifunc, tvb, offset, 1, ENC_BIG_ENDIAN);\n }\n else {\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dir, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prm, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dfc, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_secfunc, tvb, offset, 1, ENC_BIG_ENDIAN);\n }\n offset += 1;\n\n /* add destination and source addresses */\n proto_tree_add_item(dl_tree, hf_dnp3_dst, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n hidden_item = proto_tree_add_item(dl_tree, hf_dnp3_addr, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n proto_item_set_hidden(hidden_item);\n offset += 2;\n proto_tree_add_item(dl_tree, hf_dnp3_src, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n hidden_item = proto_tree_add_item(dl_tree, hf_dnp3_addr, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n proto_item_set_hidden(hidden_item);\n offset += 2;\n\n /* and header CRC */\n calc_dl_crc = calculateCRCtvb(tvb, 0, DNP_HDR_LEN - 2);\n proto_tree_add_checksum(dl_tree, tvb, offset, hf_dnp3_data_hdr_crc,\n hf_dnp3_data_hdr_crc_status, &ei_dnp3_data_hdr_crc_incorrect,\n pinfo, calc_dl_crc, ENC_LITTLE_ENDIAN, PROTO_CHECKSUM_VERIFY);\n offset += 2;\n\n /* If the DataLink function is 'Request Link Status' or 'Status of Link',\n or 'Reset Link' we don't expect any Transport or Application Layer Data\n NOTE: This code should probably check what DOES have TR or AL data */\n if ((dl_func != DL_FUNC_LINK_STAT) && (dl_func != DL_FUNC_STAT_LINK) &&\n (dl_func != DL_FUNC_RESET_LINK) && (dl_func != DL_FUNC_ACK))\n {\n proto_tree *data_tree;\n proto_item *data_ti;\n guint8 tr_ctl, tr_seq;\n gboolean tr_fir, tr_fin;\n guint8 *al_buffer, *al_buffer_ptr;\n guint8 data_len;\n int data_start = offset;\n int tl_offset;\n gboolean crc_OK = FALSE;\n tvbuff_t *next_tvb;\n guint i;\n static int * const transport_flags[] = {\n &hf_dnp3_tr_fin,\n &hf_dnp3_tr_fir,\n &hf_dnp3_tr_seq,\n NULL\n };\n\n /* get the transport layer byte */\n tr_ctl = tvb_get_guint8(tvb, offset);\n tr_seq = tr_ctl & DNP3_TR_SEQ;\n tr_fir = tr_ctl & DNP3_TR_FIR;\n tr_fin = tr_ctl & DNP3_TR_FIN;\n\n /* Add Transport Layer Tree */\n tc = proto_tree_add_bitmask(dnp3_tree, tvb, offset, hf_dnp3_tr_ctl, ett_dnp3_tr_ctl, transport_flags, ENC_BIG_ENDIAN);\n proto_item_append_text(tc, \"(\");\n if (tr_fir) proto_item_append_text(tc, \"FIR, \");\n if (tr_fin) proto_item_append_text(tc, \"FIN, \");\n proto_item_append_text(tc, \"Sequence %u)\", tr_seq);\n\n /* Add data chunk tree */\n data_tree = proto_tree_add_subtree(dnp3_tree, tvb, offset, -1, ett_dnp3_dl_data, &data_ti, \"Data Chunks\");\n\n /* extract the application layer data, validating the CRCs */\n\n /* XXX - check for dl_len <= 5 */\n data_len = dl_len - 5;\n al_buffer = (guint8 *)wmem_alloc(pinfo->pool, data_len);\n al_buffer_ptr = al_buffer;\n i = 0;\n tl_offset = 1; /* skip the initial transport layer byte when assembling chunks for the application layer tvb */\n while (data_len > 0)\n {\n guint8 chk_size;\n const guint8 *chk_ptr;\n proto_tree *chk_tree;\n proto_item *chk_len_ti;\n guint16 calc_crc, act_crc;\n\n chk_size = MIN(data_len, AL_MAX_CHUNK_SIZE);\n chk_ptr = tvb_get_ptr(tvb, offset, chk_size);\n memcpy(al_buffer_ptr, chk_ptr + tl_offset, chk_size - tl_offset);\n al_buffer_ptr += chk_size - tl_offset;\n\n chk_tree = proto_tree_add_subtree_format(data_tree, tvb, offset, chk_size + 2, ett_dnp3_dl_chunk, NULL, \"Data Chunk: %u\", i);\n proto_tree_add_item(chk_tree, hf_dnp3_data_chunk, tvb, offset, chk_size, ENC_NA);\n chk_len_ti = proto_tree_add_uint(chk_tree, hf_dnp3_data_chunk_len, tvb, offset, 0, chk_size);\n proto_item_set_generated(chk_len_ti);\n\n offset += chk_size;\n\n calc_crc = calculateCRC(chk_ptr, chk_size);\n proto_tree_add_checksum(chk_tree, tvb, offset, hf_dnp3_data_chunk_crc,\n hf_dnp3_data_chunk_crc_status, &ei_dnp3_data_chunk_crc_incorrect,\n pinfo, calc_crc, ENC_LITTLE_ENDIAN, PROTO_CHECKSUM_VERIFY);\n act_crc = tvb_get_letohs(tvb, offset);\n offset += 2;\n crc_OK = calc_crc == act_crc;\n if (!crc_OK)\n {\n /* Don't trust the rest of the data, get out of here */\n break;\n }\n data_len -= chk_size;\n i++;\n tl_offset = 0; /* copy all the data in the rest of the chunks */\n }\n proto_item_set_len(data_ti, offset - data_start);\n\n /* if crc OK, set up new tvb */\n if (crc_OK)\n {\n tvbuff_t *al_tvb;\n gboolean save_fragmented;\n\n al_tvb = tvb_new_child_real_data(tvb, al_buffer, (guint) (al_buffer_ptr-al_buffer), (gint) (al_buffer_ptr-al_buffer));\n\n /* Check for fragmented packet */\n save_fragmented = pinfo->fragmented;\n\n /* Reassemble AL fragments */\n static guint al_max_fragments = 60;\n static guint al_fragment_aging = 64; /* sequence numbers only 6 bit */\n fragment_head *frag_al = NULL;\n pinfo->fragmented = TRUE;\n if (!pinfo->fd->visited)\n {\n frag_al = fragment_add_seq_single_aging(&al_reassembly_table,\n al_tvb, 0, pinfo, tr_seq, NULL,\n tvb_reported_length(al_tvb), /* As this is a constructed tvb, all of it is ok */\n tr_fir, tr_fin,\n al_max_fragments, al_fragment_aging);\n }\n else\n {\n frag_al = fragment_get_reassembled_id(&al_reassembly_table, pinfo, tr_seq);\n }\n next_tvb = process_reassembled_data(al_tvb, 0, pinfo,\n \"Reassembled DNP 3.0 Application Layer message\", frag_al, &dnp3_frag_items,\n NULL, dnp3_tree);\n\n if (frag_al)\n {\n if (pinfo->num == frag_al->reassembled_in && pinfo->curr_layer_num == frag_al->reas_in_layer_num)\n {\n /* As a complete AL message will have cleared the info column,\n make sure source and dest are always in the info column */\n //col_append_fstr(pinfo->cinfo, COL_INFO, \"from %u to %u\", dl_src, dl_dst);\n //col_set_fence(pinfo->cinfo, COL_INFO);\n dissect_dnp3_al(next_tvb, pinfo, dnp3_tree);\n }\n else\n {\n /* Lock any column info set by the DL and TL */\n col_set_fence(pinfo->cinfo, COL_INFO);\n col_append_fstr(pinfo->cinfo, COL_INFO,\n \" (Application Layer fragment %u, reassembled in packet %u)\",\n tr_seq, frag_al->reassembled_in);\n proto_tree_add_item(dnp3_tree, hf_al_frag_data, al_tvb, 0, -1, ENC_NA);\n }\n }\n else\n {\n col_append_fstr(pinfo->cinfo, COL_INFO,\n \" (Application Layer Unreassembled fragment %u)\",\n tr_seq);\n proto_tree_add_item(dnp3_tree, hf_al_frag_data, al_tvb, 0, -1, ENC_NA);\n }\n\n pinfo->fragmented = save_fragmented;\n }\n else\n {\n /* CRC error - throw away the data. */\n next_tvb = NULL;\n }\n }\n\n /* Set the length of the message */\n proto_item_set_len(ti, offset);\n return offset;\n}", "project": "wireshark", "hash": 308851302387044557192207962363054817597, "size": 277, "commit_id": "618661b22e34a59b21117db723d8ff91e064d4ba", "message": "dnp: plug a memory leak.\n\nIf we're throwing away the data, *throw away the data* - free it, as\nwe're not using it as the backing data for a tvbuff.", "target": 1, "dataset": "other", "idx": 202609} {"func": "dissect_dnp3_message(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)\n{\n proto_item *ti, *tdl, *tc, *hidden_item;\n proto_tree *dnp3_tree, *dl_tree, *field_tree;\n int offset = 0, temp_offset = 0;\n gboolean dl_prm;\n guint8 dl_len, dl_ctl, dl_func;\n const gchar *func_code_str;\n guint16 dl_dst, dl_src, calc_dl_crc;\n\n /* Make entries in Protocol column and Info column on summary display */\n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"DNP 3.0\");\n col_clear(pinfo->cinfo, COL_INFO);\n\n /* Skip \"0x0564\" header bytes */\n temp_offset += 2;\n\n dl_len = tvb_get_guint8(tvb, temp_offset);\n temp_offset += 1;\n\n dl_ctl = tvb_get_guint8(tvb, temp_offset);\n temp_offset += 1;\n\n dl_dst = tvb_get_letohs(tvb, temp_offset);\n temp_offset += 2;\n\n dl_src = tvb_get_letohs(tvb, temp_offset);\n\n dl_func = dl_ctl & DNP3_CTL_FUNC;\n dl_prm = dl_ctl & DNP3_CTL_PRM;\n func_code_str = val_to_str(dl_func, dl_prm ? dnp3_ctl_func_pri_vals : dnp3_ctl_func_sec_vals,\n \"Unknown function (0x%02x)\");\n\n /* Make sure source and dest are always in the info column */\n col_append_fstr(pinfo->cinfo, COL_INFO, \"from %u to %u\", dl_src, dl_dst);\n col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, \"len=%u, %s\", dl_len, func_code_str);\n\n /* create display subtree for the protocol */\n ti = proto_tree_add_item(tree, proto_dnp3, tvb, offset, -1, ENC_NA);\n dnp3_tree = proto_item_add_subtree(ti, ett_dnp3);\n\n /* Create Subtree for Data Link Layer */\n dl_tree = proto_tree_add_subtree_format(dnp3_tree, tvb, offset, DNP_HDR_LEN, ett_dnp3_dl, &tdl,\n \"Data Link Layer, Len: %u, From: %u, To: %u, \", dl_len, dl_src, dl_dst);\n if (dl_prm) {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tdl, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tdl, \"PRM, \");\n if (dl_ctl & DNP3_CTL_FCB) proto_item_append_text(tdl, \"FCB, \");\n if (dl_ctl & DNP3_CTL_FCV) proto_item_append_text(tdl, \"FCV, \");\n }\n else {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tdl, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tdl, \"PRM, \");\n if (dl_ctl & DNP3_CTL_RES) proto_item_append_text(tdl, \"RES, \");\n if (dl_ctl & DNP3_CTL_DFC) proto_item_append_text(tdl, \"DFC, \");\n }\n proto_item_append_text(tdl, \"%s\", func_code_str);\n\n /* start bytes */\n proto_tree_add_item(dl_tree, hf_dnp3_start, tvb, offset, 2, ENC_BIG_ENDIAN);\n offset += 2;\n\n /* add length field */\n proto_tree_add_item(dl_tree, hf_dnp3_len, tvb, offset, 1, ENC_BIG_ENDIAN);\n offset += 1;\n\n /* Add Control Byte Subtree */\n tc = proto_tree_add_uint_format_value(dl_tree, hf_dnp3_ctl, tvb, offset, 1, dl_ctl,\n \"0x%02x (\", dl_ctl);\n /* Add Text to Control Byte Subtree Header */\n if (dl_prm) {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tc, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tc, \"PRM, \");\n if (dl_ctl & DNP3_CTL_FCB) proto_item_append_text(tc, \"FCB, \");\n if (dl_ctl & DNP3_CTL_FCV) proto_item_append_text(tc, \"FCV, \");\n }\n else {\n if (dl_ctl & DNP3_CTL_DIR) proto_item_append_text(tc, \"DIR, \");\n if (dl_ctl & DNP3_CTL_PRM) proto_item_append_text(tc, \"PRM, \");\n if (dl_ctl & DNP3_CTL_RES) proto_item_append_text(tc, \"RES, \");\n if (dl_ctl & DNP3_CTL_DFC) proto_item_append_text(tc, \"DFC, \");\n }\n proto_item_append_text(tc, \"%s)\", func_code_str );\n field_tree = proto_item_add_subtree(tc, ett_dnp3_dl_ctl);\n\n /* Add Control Byte Subtree Items */\n if (dl_prm) {\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dir, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prm, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_fcb, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_fcv, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prifunc, tvb, offset, 1, ENC_BIG_ENDIAN);\n }\n else {\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dir, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_prm, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_dfc, tvb, offset, 1, ENC_LITTLE_ENDIAN);\n proto_tree_add_item(field_tree, hf_dnp3_ctl_secfunc, tvb, offset, 1, ENC_BIG_ENDIAN);\n }\n offset += 1;\n\n /* add destination and source addresses */\n proto_tree_add_item(dl_tree, hf_dnp3_dst, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n hidden_item = proto_tree_add_item(dl_tree, hf_dnp3_addr, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n proto_item_set_hidden(hidden_item);\n offset += 2;\n proto_tree_add_item(dl_tree, hf_dnp3_src, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n hidden_item = proto_tree_add_item(dl_tree, hf_dnp3_addr, tvb, offset, 2, ENC_LITTLE_ENDIAN);\n proto_item_set_hidden(hidden_item);\n offset += 2;\n\n /* and header CRC */\n calc_dl_crc = calculateCRCtvb(tvb, 0, DNP_HDR_LEN - 2);\n proto_tree_add_checksum(dl_tree, tvb, offset, hf_dnp3_data_hdr_crc,\n hf_dnp3_data_hdr_crc_status, &ei_dnp3_data_hdr_crc_incorrect,\n pinfo, calc_dl_crc, ENC_LITTLE_ENDIAN, PROTO_CHECKSUM_VERIFY);\n offset += 2;\n\n /* If the DataLink function is 'Request Link Status' or 'Status of Link',\n or 'Reset Link' we don't expect any Transport or Application Layer Data\n NOTE: This code should probably check what DOES have TR or AL data */\n if ((dl_func != DL_FUNC_LINK_STAT) && (dl_func != DL_FUNC_STAT_LINK) &&\n (dl_func != DL_FUNC_RESET_LINK) && (dl_func != DL_FUNC_ACK))\n {\n proto_tree *data_tree;\n proto_item *data_ti;\n guint8 tr_ctl, tr_seq;\n gboolean tr_fir, tr_fin;\n guint8 *al_buffer, *al_buffer_ptr;\n guint8 data_len;\n int data_start = offset;\n int tl_offset;\n gboolean crc_OK = FALSE;\n tvbuff_t *next_tvb;\n guint i;\n static int * const transport_flags[] = {\n &hf_dnp3_tr_fin,\n &hf_dnp3_tr_fir,\n &hf_dnp3_tr_seq,\n NULL\n };\n\n /* get the transport layer byte */\n tr_ctl = tvb_get_guint8(tvb, offset);\n tr_seq = tr_ctl & DNP3_TR_SEQ;\n tr_fir = tr_ctl & DNP3_TR_FIR;\n tr_fin = tr_ctl & DNP3_TR_FIN;\n\n /* Add Transport Layer Tree */\n tc = proto_tree_add_bitmask(dnp3_tree, tvb, offset, hf_dnp3_tr_ctl, ett_dnp3_tr_ctl, transport_flags, ENC_BIG_ENDIAN);\n proto_item_append_text(tc, \"(\");\n if (tr_fir) proto_item_append_text(tc, \"FIR, \");\n if (tr_fin) proto_item_append_text(tc, \"FIN, \");\n proto_item_append_text(tc, \"Sequence %u)\", tr_seq);\n\n /* Add data chunk tree */\n data_tree = proto_tree_add_subtree(dnp3_tree, tvb, offset, -1, ett_dnp3_dl_data, &data_ti, \"Data Chunks\");\n\n /* extract the application layer data, validating the CRCs */\n\n /* XXX - check for dl_len <= 5 */\n data_len = dl_len - 5;\n al_buffer = (guint8 *)wmem_alloc(pinfo->pool, data_len);\n al_buffer_ptr = al_buffer;\n i = 0;\n tl_offset = 1; /* skip the initial transport layer byte when assembling chunks for the application layer tvb */\n while (data_len > 0)\n {\n guint8 chk_size;\n const guint8 *chk_ptr;\n proto_tree *chk_tree;\n proto_item *chk_len_ti;\n guint16 calc_crc, act_crc;\n\n chk_size = MIN(data_len, AL_MAX_CHUNK_SIZE);\n chk_ptr = tvb_get_ptr(tvb, offset, chk_size);\n memcpy(al_buffer_ptr, chk_ptr + tl_offset, chk_size - tl_offset);\n al_buffer_ptr += chk_size - tl_offset;\n\n chk_tree = proto_tree_add_subtree_format(data_tree, tvb, offset, chk_size + 2, ett_dnp3_dl_chunk, NULL, \"Data Chunk: %u\", i);\n proto_tree_add_item(chk_tree, hf_dnp3_data_chunk, tvb, offset, chk_size, ENC_NA);\n chk_len_ti = proto_tree_add_uint(chk_tree, hf_dnp3_data_chunk_len, tvb, offset, 0, chk_size);\n proto_item_set_generated(chk_len_ti);\n\n offset += chk_size;\n\n calc_crc = calculateCRC(chk_ptr, chk_size);\n proto_tree_add_checksum(chk_tree, tvb, offset, hf_dnp3_data_chunk_crc,\n hf_dnp3_data_chunk_crc_status, &ei_dnp3_data_chunk_crc_incorrect,\n pinfo, calc_crc, ENC_LITTLE_ENDIAN, PROTO_CHECKSUM_VERIFY);\n act_crc = tvb_get_letohs(tvb, offset);\n offset += 2;\n crc_OK = calc_crc == act_crc;\n if (!crc_OK)\n {\n /* Don't trust the rest of the data, get out of here */\n break;\n }\n data_len -= chk_size;\n i++;\n tl_offset = 0; /* copy all the data in the rest of the chunks */\n }\n proto_item_set_len(data_ti, offset - data_start);\n\n /* if crc OK, set up new tvb */\n if (crc_OK)\n {\n tvbuff_t *al_tvb;\n gboolean save_fragmented;\n\n al_tvb = tvb_new_child_real_data(tvb, al_buffer, (guint) (al_buffer_ptr-al_buffer), (gint) (al_buffer_ptr-al_buffer));\n\n /* Check for fragmented packet */\n save_fragmented = pinfo->fragmented;\n\n /* Reassemble AL fragments */\n static guint al_max_fragments = 60;\n static guint al_fragment_aging = 64; /* sequence numbers only 6 bit */\n fragment_head *frag_al = NULL;\n pinfo->fragmented = TRUE;\n if (!pinfo->fd->visited)\n {\n frag_al = fragment_add_seq_single_aging(&al_reassembly_table,\n al_tvb, 0, pinfo, tr_seq, NULL,\n tvb_reported_length(al_tvb), /* As this is a constructed tvb, all of it is ok */\n tr_fir, tr_fin,\n al_max_fragments, al_fragment_aging);\n }\n else\n {\n frag_al = fragment_get_reassembled_id(&al_reassembly_table, pinfo, tr_seq);\n }\n next_tvb = process_reassembled_data(al_tvb, 0, pinfo,\n \"Reassembled DNP 3.0 Application Layer message\", frag_al, &dnp3_frag_items,\n NULL, dnp3_tree);\n\n if (frag_al)\n {\n if (pinfo->num == frag_al->reassembled_in && pinfo->curr_layer_num == frag_al->reas_in_layer_num)\n {\n /* As a complete AL message will have cleared the info column,\n make sure source and dest are always in the info column */\n //col_append_fstr(pinfo->cinfo, COL_INFO, \"from %u to %u\", dl_src, dl_dst);\n //col_set_fence(pinfo->cinfo, COL_INFO);\n dissect_dnp3_al(next_tvb, pinfo, dnp3_tree);\n }\n else\n {\n /* Lock any column info set by the DL and TL */\n col_set_fence(pinfo->cinfo, COL_INFO);\n col_append_fstr(pinfo->cinfo, COL_INFO,\n \" (Application Layer fragment %u, reassembled in packet %u)\",\n tr_seq, frag_al->reassembled_in);\n proto_tree_add_item(dnp3_tree, hf_al_frag_data, al_tvb, 0, -1, ENC_NA);\n }\n }\n else\n {\n col_append_fstr(pinfo->cinfo, COL_INFO,\n \" (Application Layer Unreassembled fragment %u)\",\n tr_seq);\n proto_tree_add_item(dnp3_tree, hf_al_frag_data, al_tvb, 0, -1, ENC_NA);\n }\n\n pinfo->fragmented = save_fragmented;\n }\n else\n {\n /* CRC error - throw away the data. */\n g_free(al_buffer);\n next_tvb = NULL;\n }\n }\n\n /* Set the length of the message */\n proto_item_set_len(ti, offset);\n return offset;\n}", "project": "wireshark", "hash": 125850200117559018768311602342424911021, "size": 278, "commit_id": "618661b22e34a59b21117db723d8ff91e064d4ba", "message": "dnp: plug a memory leak.\n\nIf we're throwing away the data, *throw away the data* - free it, as\nwe're not using it as the backing data for a tvbuff.", "target": 0, "dataset": "other", "idx": 335510} {"func": "static uint16_t nvme_map_addr(NvmeCtrl *n, NvmeSg *sg, hwaddr addr, size_t len)\n{\n bool cmb = false, pmr = false;\n\n if (!len) {\n return NVME_SUCCESS;\n }\n\n trace_pci_nvme_map_addr(addr, len);\n\n if (nvme_addr_is_cmb(n, addr)) {\n cmb = true;\n } else if (nvme_addr_is_pmr(n, addr)) {\n pmr = true;\n }\n\n if (cmb || pmr) {\n if (sg->flags & NVME_SG_DMA) {\n return NVME_INVALID_USE_OF_CMB | NVME_DNR;\n }\n\n if (sg->iov.niov + 1 > IOV_MAX) {\n goto max_mappings_exceeded;\n }\n\n if (cmb) {\n return nvme_map_addr_cmb(n, &sg->iov, addr, len);\n } else {\n return nvme_map_addr_pmr(n, &sg->iov, addr, len);\n }\n }\n\n if (!(sg->flags & NVME_SG_DMA)) {\n return NVME_INVALID_USE_OF_CMB | NVME_DNR;\n }\n\n if (sg->qsg.nsg + 1 > IOV_MAX) {\n goto max_mappings_exceeded;\n }\n\n qemu_sglist_add(&sg->qsg, addr, len);\n\n return NVME_SUCCESS;\n\nmax_mappings_exceeded:\n NVME_GUEST_ERR(pci_nvme_ub_too_many_mappings,\n \"number of mappings exceed 1024\");\n return NVME_INTERNAL_DEV_ERROR | NVME_DNR;\n}", "project": "qemu", "hash": 161220796245487945523383117449990525230, "size": 49, "commit_id": "736b01642d85be832385063f278fe7cd4ffb5221", "message": "hw/nvme: fix CVE-2021-3929\n\nThis fixes CVE-2021-3929 \"locally\" by denying DMA to the iomem of the\ndevice itself. This still allows DMA to MMIO regions of other devices\n(e.g. doing P2P DMA to the controller memory buffer of another NVMe\ndevice).\n\nFixes: CVE-2021-3929\nReported-by: Qiuhao Li \nReviewed-by: Keith Busch \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Klaus Jensen ", "target": 1, "dataset": "other", "idx": 202660} {"func": "static uint16_t nvme_map_addr(NvmeCtrl *n, NvmeSg *sg, hwaddr addr, size_t len)\n{\n bool cmb = false, pmr = false;\n\n if (!len) {\n return NVME_SUCCESS;\n }\n\n trace_pci_nvme_map_addr(addr, len);\n\n if (nvme_addr_is_iomem(n, addr)) {\n return NVME_DATA_TRAS_ERROR;\n }\n\n if (nvme_addr_is_cmb(n, addr)) {\n cmb = true;\n } else if (nvme_addr_is_pmr(n, addr)) {\n pmr = true;\n }\n\n if (cmb || pmr) {\n if (sg->flags & NVME_SG_DMA) {\n return NVME_INVALID_USE_OF_CMB | NVME_DNR;\n }\n\n if (sg->iov.niov + 1 > IOV_MAX) {\n goto max_mappings_exceeded;\n }\n\n if (cmb) {\n return nvme_map_addr_cmb(n, &sg->iov, addr, len);\n } else {\n return nvme_map_addr_pmr(n, &sg->iov, addr, len);\n }\n }\n\n if (!(sg->flags & NVME_SG_DMA)) {\n return NVME_INVALID_USE_OF_CMB | NVME_DNR;\n }\n\n if (sg->qsg.nsg + 1 > IOV_MAX) {\n goto max_mappings_exceeded;\n }\n\n qemu_sglist_add(&sg->qsg, addr, len);\n\n return NVME_SUCCESS;\n\nmax_mappings_exceeded:\n NVME_GUEST_ERR(pci_nvme_ub_too_many_mappings,\n \"number of mappings exceed 1024\");\n return NVME_INTERNAL_DEV_ERROR | NVME_DNR;\n}", "project": "qemu", "hash": 171394500595149274575594149292479412061, "size": 53, "commit_id": "736b01642d85be832385063f278fe7cd4ffb5221", "message": "hw/nvme: fix CVE-2021-3929\n\nThis fixes CVE-2021-3929 \"locally\" by denying DMA to the iomem of the\ndevice itself. This still allows DMA to MMIO regions of other devices\n(e.g. doing P2P DMA to the controller memory buffer of another NVMe\ndevice).\n\nFixes: CVE-2021-3929\nReported-by: Qiuhao Li \nReviewed-by: Keith Busch \nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Klaus Jensen ", "target": 0, "dataset": "other", "idx": 336154} {"func": "int do_epoll_ctl(int epfd, int op, int fd, struct epoll_event *epds,\n\t\t bool nonblock)\n{\n\tint error;\n\tint full_check = 0;\n\tstruct fd f, tf;\n\tstruct eventpoll *ep;\n\tstruct epitem *epi;\n\tstruct eventpoll *tep = NULL;\n\n\terror = -EBADF;\n\tf = fdget(epfd);\n\tif (!f.file)\n\t\tgoto error_return;\n\n\t/* Get the \"struct file *\" for the target file */\n\ttf = fdget(fd);\n\tif (!tf.file)\n\t\tgoto error_fput;\n\n\t/* The target file descriptor must support poll */\n\terror = -EPERM;\n\tif (!file_can_poll(tf.file))\n\t\tgoto error_tgt_fput;\n\n\t/* Check if EPOLLWAKEUP is allowed */\n\tif (ep_op_has_event(op))\n\t\tep_take_care_of_epollwakeup(epds);\n\n\t/*\n\t * We have to check that the file structure underneath the file descriptor\n\t * the user passed to us _is_ an eventpoll file. And also we do not permit\n\t * adding an epoll file descriptor inside itself.\n\t */\n\terror = -EINVAL;\n\tif (f.file == tf.file || !is_file_epoll(f.file))\n\t\tgoto error_tgt_fput;\n\n\t/*\n\t * epoll adds to the wakeup queue at EPOLL_CTL_ADD time only,\n\t * so EPOLLEXCLUSIVE is not allowed for a EPOLL_CTL_MOD operation.\n\t * Also, we do not currently supported nested exclusive wakeups.\n\t */\n\tif (ep_op_has_event(op) && (epds->events & EPOLLEXCLUSIVE)) {\n\t\tif (op == EPOLL_CTL_MOD)\n\t\t\tgoto error_tgt_fput;\n\t\tif (op == EPOLL_CTL_ADD && (is_file_epoll(tf.file) ||\n\t\t\t\t(epds->events & ~EPOLLEXCLUSIVE_OK_BITS)))\n\t\t\tgoto error_tgt_fput;\n\t}\n\n\t/*\n\t * At this point it is safe to assume that the \"private_data\" contains\n\t * our own data structure.\n\t */\n\tep = f.file->private_data;\n\n\t/*\n\t * When we insert an epoll file descriptor, inside another epoll file\n\t * descriptor, there is the change of creating closed loops, which are\n\t * better be handled here, than in more critical paths. While we are\n\t * checking for loops we also determine the list of files reachable\n\t * and hang them on the tfile_check_list, so we can check that we\n\t * haven't created too many possible wakeup paths.\n\t *\n\t * We do not need to take the global 'epumutex' on EPOLL_CTL_ADD when\n\t * the epoll file descriptor is attaching directly to a wakeup source,\n\t * unless the epoll file descriptor is nested. The purpose of taking the\n\t * 'epmutex' on add is to prevent complex toplogies such as loops and\n\t * deep wakeup paths from forming in parallel through multiple\n\t * EPOLL_CTL_ADD operations.\n\t */\n\terror = epoll_mutex_lock(&ep->mtx, 0, nonblock);\n\tif (error)\n\t\tgoto error_tgt_fput;\n\tif (op == EPOLL_CTL_ADD) {\n\t\tif (!list_empty(&f.file->f_ep_links) ||\n\t\t\t\t\t\tis_file_epoll(tf.file)) {\n\t\t\tmutex_unlock(&ep->mtx);\n\t\t\terror = epoll_mutex_lock(&epmutex, 0, nonblock);\n\t\t\tif (error)\n\t\t\t\tgoto error_tgt_fput;\n\t\t\tfull_check = 1;\n\t\t\tif (is_file_epoll(tf.file)) {\n\t\t\t\terror = -ELOOP;\n\t\t\t\tif (ep_loop_check(ep, tf.file) != 0) {\n\t\t\t\t\tclear_tfile_check_list();\n\t\t\t\t\tgoto error_tgt_fput;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tget_file(tf.file);\n\t\t\t\tlist_add(&tf.file->f_tfile_llink,\n\t\t\t\t\t\t\t&tfile_check_list);\n\t\t\t}\n\t\t\terror = epoll_mutex_lock(&ep->mtx, 0, nonblock);\n\t\t\tif (error) {\nout_del:\n\t\t\t\tlist_del(&tf.file->f_tfile_llink);\n\t\t\t\tif (!is_file_epoll(tf.file))\n\t\t\t\t\tfput(tf.file);\n\t\t\t\tgoto error_tgt_fput;\n\t\t\t}\n\t\t\tif (is_file_epoll(tf.file)) {\n\t\t\t\ttep = tf.file->private_data;\n\t\t\t\terror = epoll_mutex_lock(&tep->mtx, 1, nonblock);\n\t\t\t\tif (error) {\n\t\t\t\t\tmutex_unlock(&ep->mtx);\n\t\t\t\t\tgoto out_del;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * Try to lookup the file inside our RB tree, Since we grabbed \"mtx\"\n\t * above, we can be sure to be able to use the item looked up by\n\t * ep_find() till we release the mutex.\n\t */\n\tepi = ep_find(ep, tf.file, fd);\n\n\terror = -EINVAL;\n\tswitch (op) {\n\tcase EPOLL_CTL_ADD:\n\t\tif (!epi) {\n\t\t\tepds->events |= EPOLLERR | EPOLLHUP;\n\t\t\terror = ep_insert(ep, epds, tf.file, fd, full_check);\n\t\t} else\n\t\t\terror = -EEXIST;\n\t\tif (full_check)\n\t\t\tclear_tfile_check_list();\n\t\tbreak;\n\tcase EPOLL_CTL_DEL:\n\t\tif (epi)\n\t\t\terror = ep_remove(ep, epi);\n\t\telse\n\t\t\terror = -ENOENT;\n\t\tbreak;\n\tcase EPOLL_CTL_MOD:\n\t\tif (epi) {\n\t\t\tif (!(epi->event.events & EPOLLEXCLUSIVE)) {\n\t\t\t\tepds->events |= EPOLLERR | EPOLLHUP;\n\t\t\t\terror = ep_modify(ep, epi, epds);\n\t\t\t}\n\t\t} else\n\t\t\terror = -ENOENT;\n\t\tbreak;\n\t}\n\tif (tep != NULL)\n\t\tmutex_unlock(&tep->mtx);\n\tmutex_unlock(&ep->mtx);\n\nerror_tgt_fput:\n\tif (full_check)\n\t\tmutex_unlock(&epmutex);\n\n\tfdput(tf);\nerror_fput:\n\tfdput(f);\nerror_return:\n\n\treturn error;\n}", "project": "linux", "hash": 278445563960181030958909173096615505008, "size": 162, "commit_id": "52c479697c9b73f628140dcdfcd39ea302d05482", "message": "do_epoll_ctl(): clean the failure exits up a bit\n\nSigned-off-by: Al Viro ", "target": 1, "dataset": "other", "idx": 202665} {"func": "int do_epoll_ctl(int epfd, int op, int fd, struct epoll_event *epds,\n\t\t bool nonblock)\n{\n\tint error;\n\tint full_check = 0;\n\tstruct fd f, tf;\n\tstruct eventpoll *ep;\n\tstruct epitem *epi;\n\tstruct eventpoll *tep = NULL;\n\n\terror = -EBADF;\n\tf = fdget(epfd);\n\tif (!f.file)\n\t\tgoto error_return;\n\n\t/* Get the \"struct file *\" for the target file */\n\ttf = fdget(fd);\n\tif (!tf.file)\n\t\tgoto error_fput;\n\n\t/* The target file descriptor must support poll */\n\terror = -EPERM;\n\tif (!file_can_poll(tf.file))\n\t\tgoto error_tgt_fput;\n\n\t/* Check if EPOLLWAKEUP is allowed */\n\tif (ep_op_has_event(op))\n\t\tep_take_care_of_epollwakeup(epds);\n\n\t/*\n\t * We have to check that the file structure underneath the file descriptor\n\t * the user passed to us _is_ an eventpoll file. And also we do not permit\n\t * adding an epoll file descriptor inside itself.\n\t */\n\terror = -EINVAL;\n\tif (f.file == tf.file || !is_file_epoll(f.file))\n\t\tgoto error_tgt_fput;\n\n\t/*\n\t * epoll adds to the wakeup queue at EPOLL_CTL_ADD time only,\n\t * so EPOLLEXCLUSIVE is not allowed for a EPOLL_CTL_MOD operation.\n\t * Also, we do not currently supported nested exclusive wakeups.\n\t */\n\tif (ep_op_has_event(op) && (epds->events & EPOLLEXCLUSIVE)) {\n\t\tif (op == EPOLL_CTL_MOD)\n\t\t\tgoto error_tgt_fput;\n\t\tif (op == EPOLL_CTL_ADD && (is_file_epoll(tf.file) ||\n\t\t\t\t(epds->events & ~EPOLLEXCLUSIVE_OK_BITS)))\n\t\t\tgoto error_tgt_fput;\n\t}\n\n\t/*\n\t * At this point it is safe to assume that the \"private_data\" contains\n\t * our own data structure.\n\t */\n\tep = f.file->private_data;\n\n\t/*\n\t * When we insert an epoll file descriptor, inside another epoll file\n\t * descriptor, there is the change of creating closed loops, which are\n\t * better be handled here, than in more critical paths. While we are\n\t * checking for loops we also determine the list of files reachable\n\t * and hang them on the tfile_check_list, so we can check that we\n\t * haven't created too many possible wakeup paths.\n\t *\n\t * We do not need to take the global 'epumutex' on EPOLL_CTL_ADD when\n\t * the epoll file descriptor is attaching directly to a wakeup source,\n\t * unless the epoll file descriptor is nested. The purpose of taking the\n\t * 'epmutex' on add is to prevent complex toplogies such as loops and\n\t * deep wakeup paths from forming in parallel through multiple\n\t * EPOLL_CTL_ADD operations.\n\t */\n\terror = epoll_mutex_lock(&ep->mtx, 0, nonblock);\n\tif (error)\n\t\tgoto error_tgt_fput;\n\tif (op == EPOLL_CTL_ADD) {\n\t\tif (!list_empty(&f.file->f_ep_links) ||\n\t\t\t\t\t\tis_file_epoll(tf.file)) {\n\t\t\tmutex_unlock(&ep->mtx);\n\t\t\terror = epoll_mutex_lock(&epmutex, 0, nonblock);\n\t\t\tif (error)\n\t\t\t\tgoto error_tgt_fput;\n\t\t\tfull_check = 1;\n\t\t\tif (is_file_epoll(tf.file)) {\n\t\t\t\terror = -ELOOP;\n\t\t\t\tif (ep_loop_check(ep, tf.file) != 0)\n\t\t\t\t\tgoto error_tgt_fput;\n\t\t\t} else {\n\t\t\t\tget_file(tf.file);\n\t\t\t\tlist_add(&tf.file->f_tfile_llink,\n\t\t\t\t\t\t\t&tfile_check_list);\n\t\t\t}\n\t\t\terror = epoll_mutex_lock(&ep->mtx, 0, nonblock);\n\t\t\tif (error)\n\t\t\t\tgoto error_tgt_fput;\n\t\t\tif (is_file_epoll(tf.file)) {\n\t\t\t\ttep = tf.file->private_data;\n\t\t\t\terror = epoll_mutex_lock(&tep->mtx, 1, nonblock);\n\t\t\t\tif (error) {\n\t\t\t\t\tmutex_unlock(&ep->mtx);\n\t\t\t\t\tgoto error_tgt_fput;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * Try to lookup the file inside our RB tree, Since we grabbed \"mtx\"\n\t * above, we can be sure to be able to use the item looked up by\n\t * ep_find() till we release the mutex.\n\t */\n\tepi = ep_find(ep, tf.file, fd);\n\n\terror = -EINVAL;\n\tswitch (op) {\n\tcase EPOLL_CTL_ADD:\n\t\tif (!epi) {\n\t\t\tepds->events |= EPOLLERR | EPOLLHUP;\n\t\t\terror = ep_insert(ep, epds, tf.file, fd, full_check);\n\t\t} else\n\t\t\terror = -EEXIST;\n\t\tbreak;\n\tcase EPOLL_CTL_DEL:\n\t\tif (epi)\n\t\t\terror = ep_remove(ep, epi);\n\t\telse\n\t\t\terror = -ENOENT;\n\t\tbreak;\n\tcase EPOLL_CTL_MOD:\n\t\tif (epi) {\n\t\t\tif (!(epi->event.events & EPOLLEXCLUSIVE)) {\n\t\t\t\tepds->events |= EPOLLERR | EPOLLHUP;\n\t\t\t\terror = ep_modify(ep, epi, epds);\n\t\t\t}\n\t\t} else\n\t\t\terror = -ENOENT;\n\t\tbreak;\n\t}\n\tif (tep != NULL)\n\t\tmutex_unlock(&tep->mtx);\n\tmutex_unlock(&ep->mtx);\n\nerror_tgt_fput:\n\tif (full_check) {\n\t\tclear_tfile_check_list();\n\t\tmutex_unlock(&epmutex);\n\t}\n\n\tfdput(tf);\nerror_fput:\n\tfdput(f);\nerror_return:\n\n\treturn error;\n}", "project": "linux", "hash": 291400095598389893794119152689563159831, "size": 155, "commit_id": "52c479697c9b73f628140dcdfcd39ea302d05482", "message": "do_epoll_ctl(): clean the failure exits up a bit\n\nSigned-off-by: Al Viro ", "target": 0, "dataset": "other", "idx": 336269} {"func": "read_yin_container(struct lys_module *module, struct lys_node *parent, struct lyxml_elem *yin, int options,\n struct unres_schema *unres)\n{\n struct ly_ctx *ctx = module->ctx;\n struct lyxml_elem *sub, *next, root;\n struct lys_node *node = NULL;\n struct lys_node *retval;\n struct lys_node_container *cont;\n const char *value;\n void *reallocated;\n int r;\n int c_tpdf = 0, c_must = 0, c_ftrs = 0, c_ext = 0;\n\n /* init */\n memset(&root, 0, sizeof root);\n\n cont = calloc(1, sizeof *cont);\n LY_CHECK_ERR_RETURN(!cont, LOGMEM(ctx), NULL);\n\n cont->nodetype = LYS_CONTAINER;\n cont->prev = (struct lys_node *)cont;\n retval = (struct lys_node *)cont;\n\n if (read_yin_common(module, parent, retval, LYEXT_PAR_NODE, yin,\n OPT_IDENT | OPT_MODULE | ((options & LYS_PARSE_OPT_CFG_IGNORE) ? OPT_CFG_IGNORE :\n (options & LYS_PARSE_OPT_CFG_NOINHERIT) ? OPT_CFG_PARSE : OPT_CFG_PARSE | OPT_CFG_INHERIT),\n unres)) {\n goto error;\n }\n\n LOGDBG(LY_LDGYIN, \"parsing %s statement \\\"%s\\\"\", yin->name, retval->name);\n\n /* insert the node into the schema tree */\n if (lys_node_addchild(parent, lys_main_module(module), retval, options)) {\n goto error;\n }\n\n /* process container's specific children */\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ext, retval->ext_size, \"extensions\", \"container\", error);\n c_ext++;\n } else if (!strcmp(sub->name, \"presence\")) {\n if (cont->presence) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n GETVAL(ctx, value, sub, \"value\");\n cont->presence = lydict_insert(ctx, value, strlen(value));\n\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_PRESENCE, 0, unres)) {\n goto error;\n }\n lyxml_free(ctx, sub);\n } else if (!strcmp(sub->name, \"when\")) {\n if (cont->when) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n\n cont->when = read_yin_when(module, sub, unres);\n if (!cont->when) {\n lyxml_free(ctx, sub);\n goto error;\n }\n lyxml_free(ctx, sub);\n\n /* data statements */\n } else if (!strcmp(sub->name, \"container\") ||\n !strcmp(sub->name, \"leaf-list\") ||\n !strcmp(sub->name, \"leaf\") ||\n !strcmp(sub->name, \"list\") ||\n !strcmp(sub->name, \"choice\") ||\n !strcmp(sub->name, \"uses\") ||\n !strcmp(sub->name, \"grouping\") ||\n !strcmp(sub->name, \"anyxml\") ||\n !strcmp(sub->name, \"anydata\") ||\n !strcmp(sub->name, \"action\") ||\n !strcmp(sub->name, \"notification\")) {\n lyxml_unlink_elem(ctx, sub, 2);\n lyxml_add_child(ctx, &root, sub);\n\n /* array counters */\n } else if (!strcmp(sub->name, \"typedef\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_tpdf, cont->tpdf_size, \"typedefs\", \"container\", error);\n c_tpdf++;\n } else if (!strcmp(sub->name, \"must\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_must, cont->must_size, \"musts\", \"container\", error);\n c_must++;\n } else if (!strcmp(sub->name, \"if-feature\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ftrs, retval->iffeature_size, \"if-features\", \"container\", error);\n c_ftrs++;\n } else {\n LOGVAL(ctx, LYE_INSTMT, LY_VLOG_LYS, retval, sub->name);\n goto error;\n }\n }\n\n /* middle part - process nodes with cardinality of 0..n except the data nodes */\n if (c_tpdf) {\n cont->tpdf = calloc(c_tpdf, sizeof *cont->tpdf);\n LY_CHECK_ERR_GOTO(!cont->tpdf, LOGMEM(ctx), error);\n }\n if (c_must) {\n cont->must = calloc(c_must, sizeof *cont->must);\n LY_CHECK_ERR_GOTO(!cont->must, LOGMEM(ctx), error);\n }\n if (c_ftrs) {\n cont->iffeature = calloc(c_ftrs, sizeof *cont->iffeature);\n LY_CHECK_ERR_GOTO(!cont->iffeature, LOGMEM(ctx), error);\n }\n if (c_ext) {\n /* some extensions may be already present from the substatements */\n reallocated = realloc(retval->ext, (c_ext + retval->ext_size) * sizeof *retval->ext);\n LY_CHECK_ERR_GOTO(!reallocated, LOGMEM(ctx), error);\n retval->ext = reallocated;\n\n /* init memory */\n memset(&retval->ext[retval->ext_size], 0, c_ext * sizeof *retval->ext);\n }\n\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n r = lyp_yin_fill_ext(retval, LYEXT_PAR_NODE, 0, 0, module, sub, &retval->ext, &retval->ext_size, unres);\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"typedef\")) {\n r = fill_yin_typedef(module, retval, sub, &cont->tpdf[cont->tpdf_size], unres);\n cont->tpdf_size++;\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"must\")) {\n r = fill_yin_must(module, sub, &cont->must[cont->must_size], unres);\n cont->must_size++;\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"if-feature\")) {\n r = fill_yin_iffeature(retval, 0, sub, &cont->iffeature[cont->iffeature_size], unres);\n cont->iffeature_size++;\n if (r) {\n goto error;\n }\n }\n }\n\n lyp_reduce_ext_list(&retval->ext, retval->ext_size, c_ext + retval->ext_size);\n\n /* last part - process data nodes */\n LY_TREE_FOR_SAFE(root.child, next, sub) {\n if (!strcmp(sub->name, \"container\")) {\n node = read_yin_container(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"leaf-list\")) {\n node = read_yin_leaflist(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"leaf\")) {\n node = read_yin_leaf(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"list\")) {\n node = read_yin_list(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"choice\")) {\n node = read_yin_choice(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"uses\")) {\n node = read_yin_uses(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"grouping\")) {\n node = read_yin_grouping(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"anyxml\")) {\n node = read_yin_anydata(module, retval, sub, LYS_ANYXML, options, unres);\n } else if (!strcmp(sub->name, \"anydata\")) {\n node = read_yin_anydata(module, retval, sub, LYS_ANYDATA, options, unres);\n } else if (!strcmp(sub->name, \"action\")) {\n node = read_yin_rpc_action(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"notification\")) {\n node = read_yin_notif(module, retval, sub, options, unres);\n }\n if (!node) {\n goto error;\n }\n\n lyxml_free(ctx, sub);\n }\n\n /* check XPath dependencies */\n if (!(ctx->models.flags & LY_CTX_TRUSTED) && (cont->when || cont->must)) {\n if (options & LYS_PARSE_OPT_INGRP) {\n if (lyxp_node_check_syntax(retval)) {\n goto error;\n }\n } else {\n if (unres_schema_add_node(module, unres, retval, UNRES_XPATH, NULL) == -1) {\n goto error;\n }\n }\n }\n\n for (r = 0; r < retval->ext_size; ++r) {\n /* set flag, which represent LYEXT_OPT_VALID */\n if (retval->ext[r]->flags & LYEXT_OPT_VALID) {\n retval->flags |= LYS_VALID_EXT;\n if (retval->ext[r]->flags & LYEXT_OPT_VALID_SUBTREE) {\n retval->flags |= LYS_VALID_EXT_SUBTREE;\n break;\n }\n }\n }\n\n return retval;\n\nerror:\n lys_node_free(ctx, retval, NULL, 0);\n while (root.child) {\n lyxml_free(ctx, root.child);\n }\n return NULL;\n}", "project": "libyang", "hash": 55868768057507781729927570308714603647, "size": 217, "commit_id": "a3917d95d516e3de267d3cfa5d4d3715a90e8777", "message": "yin parser BUGFIX invalid memory access\n\n... in case there were some unresolved\nextensions.\nFixes #1454\nFixes #1455", "target": 1, "dataset": "other", "idx": 202684} {"func": "read_yin_container(struct lys_module *module, struct lys_node *parent, struct lyxml_elem *yin, int options,\n struct unres_schema *unres)\n{\n struct ly_ctx *ctx = module->ctx;\n struct lyxml_elem *sub, *next, root;\n struct lys_node *node = NULL;\n struct lys_node *retval;\n struct lys_node_container *cont;\n const char *value;\n void *reallocated;\n int r;\n int c_tpdf = 0, c_must = 0, c_ftrs = 0, c_ext = 0;\n\n /* init */\n memset(&root, 0, sizeof root);\n\n cont = calloc(1, sizeof *cont);\n LY_CHECK_ERR_RETURN(!cont, LOGMEM(ctx), NULL);\n\n cont->nodetype = LYS_CONTAINER;\n cont->prev = (struct lys_node *)cont;\n retval = (struct lys_node *)cont;\n\n if (read_yin_common(module, parent, retval, LYEXT_PAR_NODE, yin,\n OPT_IDENT | OPT_MODULE | ((options & LYS_PARSE_OPT_CFG_IGNORE) ? OPT_CFG_IGNORE :\n (options & LYS_PARSE_OPT_CFG_NOINHERIT) ? OPT_CFG_PARSE : OPT_CFG_PARSE | OPT_CFG_INHERIT),\n unres)) {\n goto error;\n }\n\n LOGDBG(LY_LDGYIN, \"parsing %s statement \\\"%s\\\"\", yin->name, retval->name);\n\n /* insert the node into the schema tree */\n if (lys_node_addchild(parent, lys_main_module(module), retval, options)) {\n goto error;\n }\n\n /* process container's specific children */\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ext, retval->ext_size, \"extensions\", \"container\", error);\n c_ext++;\n } else if (!strcmp(sub->name, \"presence\")) {\n if (cont->presence) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n GETVAL(ctx, value, sub, \"value\");\n cont->presence = lydict_insert(ctx, value, strlen(value));\n\n if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_PRESENCE, 0, unres)) {\n goto error;\n }\n lyxml_free(ctx, sub);\n } else if (!strcmp(sub->name, \"when\")) {\n if (cont->when) {\n LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name);\n goto error;\n }\n\n cont->when = read_yin_when(module, sub, unres);\n if (!cont->when) {\n lyxml_free(ctx, sub);\n goto error;\n }\n lyxml_free(ctx, sub);\n\n /* data statements */\n } else if (!strcmp(sub->name, \"container\") ||\n !strcmp(sub->name, \"leaf-list\") ||\n !strcmp(sub->name, \"leaf\") ||\n !strcmp(sub->name, \"list\") ||\n !strcmp(sub->name, \"choice\") ||\n !strcmp(sub->name, \"uses\") ||\n !strcmp(sub->name, \"grouping\") ||\n !strcmp(sub->name, \"anyxml\") ||\n !strcmp(sub->name, \"anydata\") ||\n !strcmp(sub->name, \"action\") ||\n !strcmp(sub->name, \"notification\")) {\n lyxml_unlink_elem(ctx, sub, 2);\n lyxml_add_child(ctx, &root, sub);\n\n /* array counters */\n } else if (!strcmp(sub->name, \"typedef\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_tpdf, cont->tpdf_size, \"typedefs\", \"container\", error);\n c_tpdf++;\n } else if (!strcmp(sub->name, \"must\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_must, cont->must_size, \"musts\", \"container\", error);\n c_must++;\n } else if (!strcmp(sub->name, \"if-feature\")) {\n YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ftrs, retval->iffeature_size, \"if-features\", \"container\", error);\n c_ftrs++;\n } else {\n LOGVAL(ctx, LYE_INSTMT, LY_VLOG_LYS, retval, sub->name);\n goto error;\n }\n }\n\n /* middle part - process nodes with cardinality of 0..n except the data nodes */\n if (c_tpdf) {\n cont->tpdf = calloc(c_tpdf, sizeof *cont->tpdf);\n LY_CHECK_ERR_GOTO(!cont->tpdf, LOGMEM(ctx), error);\n }\n if (c_must) {\n cont->must = calloc(c_must, sizeof *cont->must);\n LY_CHECK_ERR_GOTO(!cont->must, LOGMEM(ctx), error);\n }\n if (c_ftrs) {\n cont->iffeature = calloc(c_ftrs, sizeof *cont->iffeature);\n LY_CHECK_ERR_GOTO(!cont->iffeature, LOGMEM(ctx), error);\n }\n if (c_ext) {\n /* some extensions may be already present from the substatements */\n reallocated = realloc(retval->ext, (c_ext + retval->ext_size) * sizeof *retval->ext);\n LY_CHECK_ERR_GOTO(!reallocated, LOGMEM(ctx), error);\n retval->ext = reallocated;\n\n /* init memory */\n memset(&retval->ext[retval->ext_size], 0, c_ext * sizeof *retval->ext);\n }\n\n LY_TREE_FOR_SAFE(yin->child, next, sub) {\n if (strcmp(sub->ns->value, LY_NSYIN)) {\n /* extension */\n r = lyp_yin_fill_ext(retval, LYEXT_PAR_NODE, 0, 0, module, sub, &retval->ext, &retval->ext_size, unres);\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"typedef\")) {\n r = fill_yin_typedef(module, retval, sub, &cont->tpdf[cont->tpdf_size], unres);\n cont->tpdf_size++;\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"must\")) {\n r = fill_yin_must(module, sub, &cont->must[cont->must_size], unres);\n cont->must_size++;\n if (r) {\n goto error;\n }\n } else if (!strcmp(sub->name, \"if-feature\")) {\n r = fill_yin_iffeature(retval, 0, sub, &cont->iffeature[cont->iffeature_size], unres);\n cont->iffeature_size++;\n if (r) {\n goto error;\n }\n }\n }\n\n lyp_reduce_ext_list(&retval->ext, retval->ext_size, c_ext + retval->ext_size);\n\n /* last part - process data nodes */\n LY_TREE_FOR_SAFE(root.child, next, sub) {\n if (!strcmp(sub->name, \"container\")) {\n node = read_yin_container(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"leaf-list\")) {\n node = read_yin_leaflist(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"leaf\")) {\n node = read_yin_leaf(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"list\")) {\n node = read_yin_list(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"choice\")) {\n node = read_yin_choice(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"uses\")) {\n node = read_yin_uses(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"grouping\")) {\n node = read_yin_grouping(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"anyxml\")) {\n node = read_yin_anydata(module, retval, sub, LYS_ANYXML, options, unres);\n } else if (!strcmp(sub->name, \"anydata\")) {\n node = read_yin_anydata(module, retval, sub, LYS_ANYDATA, options, unres);\n } else if (!strcmp(sub->name, \"action\")) {\n node = read_yin_rpc_action(module, retval, sub, options, unres);\n } else if (!strcmp(sub->name, \"notification\")) {\n node = read_yin_notif(module, retval, sub, options, unres);\n }\n if (!node) {\n goto error;\n }\n\n lyxml_free(ctx, sub);\n }\n\n /* check XPath dependencies */\n if (!(ctx->models.flags & LY_CTX_TRUSTED) && (cont->when || cont->must)) {\n if (options & LYS_PARSE_OPT_INGRP) {\n if (lyxp_node_check_syntax(retval)) {\n goto error;\n }\n } else {\n if (unres_schema_add_node(module, unres, retval, UNRES_XPATH, NULL) == -1) {\n goto error;\n }\n }\n }\n\n for (r = 0; r < retval->ext_size; ++r) {\n /* extension instance may not yet be resolved */\n if (retval->ext[r] && (retval->ext[r]->flags & LYEXT_OPT_VALID)) {\n /* set flag, which represent LYEXT_OPT_VALID */\n retval->flags |= LYS_VALID_EXT;\n if (retval->ext[r]->flags & LYEXT_OPT_VALID_SUBTREE) {\n retval->flags |= LYS_VALID_EXT_SUBTREE;\n break;\n }\n }\n }\n\n return retval;\n\nerror:\n lys_node_free(ctx, retval, NULL, 0);\n while (root.child) {\n lyxml_free(ctx, root.child);\n }\n return NULL;\n}", "project": "libyang", "hash": 336173865557448454715868745869729551732, "size": 218, "commit_id": "a3917d95d516e3de267d3cfa5d4d3715a90e8777", "message": "yin parser BUGFIX invalid memory access\n\n... in case there were some unresolved\nextensions.\nFixes #1454\nFixes #1455", "target": 0, "dataset": "other", "idx": 336786} {"func": "rb_str_justify(int argc, VALUE *argv, VALUE str, char jflag)\n{\n rb_encoding *enc;\n VALUE w;\n long width, len, flen = 1, fclen = 1;\n VALUE res;\n char *p;\n const char *f = \" \";\n long n, llen, rlen;\n volatile VALUE pad;\n int singlebyte = 1, cr;\n\n rb_scan_args(argc, argv, \"11\", &w, &pad);\n enc = STR_ENC_GET(str);\n width = NUM2LONG(w);\n if (argc == 2) {\n\tStringValue(pad);\n\tenc = rb_enc_check(str, pad);\n\tf = RSTRING_PTR(pad);\n\tflen = RSTRING_LEN(pad);\n\tfclen = str_strlen(pad, enc);\n\tsinglebyte = single_byte_optimizable(pad);\n\tif (flen == 0 || fclen == 0) {\n\t rb_raise(rb_eArgError, \"zero width padding\");\n\t}\n }\n len = str_strlen(str, enc);\n if (width < 0 || len >= width) return rb_str_dup(str);\n n = width - len;\n llen = (jflag == 'l') ? 0 : ((jflag == 'r') ? n : n/2);\n rlen = n - llen;\n cr = ENC_CODERANGE(str);\n res = rb_str_new5(str, 0, RSTRING_LEN(str)+n*flen/fclen+2);\n p = RSTRING_PTR(res);\n while (llen) {\n\tif (flen <= 1) {\n\t *p++ = *f;\n\t llen--;\n\t}\n\telse if (llen > fclen) {\n\t memcpy(p,f,flen);\n\t p += flen;\n\t llen -= fclen;\n\t}\n\telse {\n\t char *fp = str_nth(f, f+flen, llen, enc, singlebyte);\n\t n = fp - f;\n\t memcpy(p,f,n);\n\t p+=n;\n\t break;\n\t}\n }\n memcpy(p, RSTRING_PTR(str), RSTRING_LEN(str));\n p+=RSTRING_LEN(str);\n while (rlen) {\n\tif (flen <= 1) {\n\t *p++ = *f;\n\t rlen--;\n\t}\n\telse if (rlen > fclen) {\n\t memcpy(p,f,flen);\n\t p += flen;\n\t rlen -= fclen;\n\t}\n\telse {\n\t char *fp = str_nth(f, f+flen, rlen, enc, singlebyte);\n\t n = fp - f;\n\t memcpy(p,f,n);\n\t p+=n;\n\t break;\n\t}\n }\n *p = '\\0';\n STR_SET_LEN(res, p-RSTRING_PTR(res));\n OBJ_INFECT(res, str);\n if (!NIL_P(pad)) OBJ_INFECT(res, pad);\n rb_enc_associate(res, enc);\n if (argc == 2)\n\tcr = ENC_CODERANGE_AND(cr, ENC_CODERANGE(pad));\n if (cr != ENC_CODERANGE_BROKEN)\n\tENC_CODERANGE_SET(res, cr);\n return res;\n}", "project": "ruby", "hash": 26901884064724764290314463604500539542, "size": 83, "commit_id": "1c2ef610358af33f9ded3086aa2d70aac03dcac5", "message": "* string.c (rb_str_justify): CVE-2009-4124.\n Fixes a bug reported by \n Emmanouel Kellinis , KPMG London;\n Patch by nobu.\n\n\ngit-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@26038 b2dd03c8-39d4-4d8f-98ff-823fe69b080e", "target": 1, "dataset": "other", "idx": 202689} {"func": "rb_str_justify(int argc, VALUE *argv, VALUE str, char jflag)\n{\n rb_encoding *enc;\n VALUE w;\n long width, len, flen = 1, fclen = 1;\n VALUE res;\n char *p;\n const char *f = \" \";\n long n, size, llen, rlen, llen2 = 0, rlen2 = 0;\n volatile VALUE pad;\n int singlebyte = 1, cr;\n\n rb_scan_args(argc, argv, \"11\", &w, &pad);\n enc = STR_ENC_GET(str);\n width = NUM2LONG(w);\n if (argc == 2) {\n\tStringValue(pad);\n\tenc = rb_enc_check(str, pad);\n\tf = RSTRING_PTR(pad);\n\tflen = RSTRING_LEN(pad);\n\tfclen = str_strlen(pad, enc);\n\tsinglebyte = single_byte_optimizable(pad);\n\tif (flen == 0 || fclen == 0) {\n\t rb_raise(rb_eArgError, \"zero width padding\");\n\t}\n }\n len = str_strlen(str, enc);\n if (width < 0 || len >= width) return rb_str_dup(str);\n n = width - len;\n llen = (jflag == 'l') ? 0 : ((jflag == 'r') ? n : n/2);\n rlen = n - llen;\n cr = ENC_CODERANGE(str);\n if (flen > 1) {\n llen2 = str_offset(f, f + flen, llen % fclen, enc, singlebyte);\n rlen2 = str_offset(f, f + flen, rlen % fclen, enc, singlebyte);\n }\n size = RSTRING_LEN(str);\n if ((len = llen / fclen + rlen / fclen) >= LONG_MAX / flen ||\n (len *= flen) >= LONG_MAX - llen2 - rlen2 ||\n (len += llen2 + rlen2) >= LONG_MAX - size) {\n rb_raise(rb_eArgError, \"argument too big\");\n }\n len += size;\n res = rb_str_new5(str, 0, len);\n p = RSTRING_PTR(res);\n if (flen <= 1) {\n memset(p, *f, llen);\n p += llen;\n }\n else {\n while (llen > fclen) {\n\t memcpy(p,f,flen);\n\t p += flen;\n\t llen -= fclen;\n\t}\n if (llen > 0) {\n memcpy(p, f, llen2);\n p += llen2;\n\t}\n }\n memcpy(p, RSTRING_PTR(str), size);\n p += size;\n if (flen <= 1) {\n memset(p, *f, rlen);\n p += rlen;\n }\n else {\n while (rlen > fclen) {\n\t memcpy(p,f,flen);\n\t p += flen;\n\t rlen -= fclen;\n\t}\n if (rlen > 0) {\n memcpy(p, f, rlen2);\n p += rlen2;\n\t}\n }\n *p = '\\0';\n STR_SET_LEN(res, p-RSTRING_PTR(res));\n OBJ_INFECT(res, str);\n if (!NIL_P(pad)) OBJ_INFECT(res, pad);\n rb_enc_associate(res, enc);\n if (argc == 2)\n\tcr = ENC_CODERANGE_AND(cr, ENC_CODERANGE(pad));\n if (cr != ENC_CODERANGE_BROKEN)\n\tENC_CODERANGE_SET(res, cr);\n return res;\n}", "project": "ruby", "hash": 78565306356934170507378775330432968749, "size": 88, "commit_id": "1c2ef610358af33f9ded3086aa2d70aac03dcac5", "message": "* string.c (rb_str_justify): CVE-2009-4124.\n Fixes a bug reported by \n Emmanouel Kellinis , KPMG London;\n Patch by nobu.\n\n\ngit-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@26038 b2dd03c8-39d4-4d8f-98ff-823fe69b080e", "target": 0, "dataset": "other", "idx": 337027} {"func": "static int cmd_handle_untagged (IMAP_DATA* idata)\n{\n char* s;\n char* pn;\n unsigned int count;\n\n s = imap_next_word (idata->buf);\n pn = imap_next_word (s);\n\n if ((idata->state >= IMAP_SELECTED) && isdigit ((unsigned char) *s))\n {\n pn = s;\n s = imap_next_word (s);\n\n /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the\n * connection, so update that one.\n */\n if (ascii_strncasecmp (\"EXISTS\", s, 6) == 0)\n {\n dprint (2, (debugfile, \"Handling EXISTS\\n\"));\n\n /* new mail arrived */\n mutt_atoui (pn, &count);\n\n if ( !(idata->reopen & IMAP_EXPUNGE_PENDING) &&\n\t count < idata->max_msn)\n {\n /* Notes 6.0.3 has a tendency to report fewer messages exist than\n * it should. */\n\tdprint (1, (debugfile, \"Message count is out of sync\"));\n\treturn 0;\n }\n /* at least the InterChange server sends EXISTS messages freely,\n * even when there is no new mail */\n else if (count == idata->max_msn)\n\tdprint (3, (debugfile,\n \"cmd_handle_untagged: superfluous EXISTS message.\\n\"));\n else\n {\n\tif (!(idata->reopen & IMAP_EXPUNGE_PENDING))\n {\n dprint (2, (debugfile,\n \"cmd_handle_untagged: New mail in %s - %d messages total.\\n\",\n idata->mailbox, count));\n\t idata->reopen |= IMAP_NEWMAIL_PENDING;\n }\n\tidata->newMailCount = count;\n }\n }\n /* pn vs. s: need initial seqno */\n else if (ascii_strncasecmp (\"EXPUNGE\", s, 7) == 0)\n cmd_parse_expunge (idata, pn);\n else if (ascii_strncasecmp (\"FETCH\", s, 5) == 0)\n cmd_parse_fetch (idata, pn);\n }\n else if (ascii_strncasecmp (\"CAPABILITY\", s, 10) == 0)\n cmd_parse_capability (idata, s);\n else if (!ascii_strncasecmp (\"OK [CAPABILITY\", s, 14))\n cmd_parse_capability (idata, pn);\n else if (!ascii_strncasecmp (\"OK [CAPABILITY\", pn, 14))\n cmd_parse_capability (idata, imap_next_word (pn));\n else if (ascii_strncasecmp (\"LIST\", s, 4) == 0)\n cmd_parse_list (idata, s);\n else if (ascii_strncasecmp (\"LSUB\", s, 4) == 0)\n cmd_parse_lsub (idata, s);\n else if (ascii_strncasecmp (\"MYRIGHTS\", s, 8) == 0)\n cmd_parse_myrights (idata, s);\n else if (ascii_strncasecmp (\"SEARCH\", s, 6) == 0)\n cmd_parse_search (idata, s);\n else if (ascii_strncasecmp (\"STATUS\", s, 6) == 0)\n cmd_parse_status (idata, s);\n else if (ascii_strncasecmp (\"ENABLED\", s, 7) == 0)\n cmd_parse_enabled (idata, s);\n else if (ascii_strncasecmp (\"BYE\", s, 3) == 0)\n {\n dprint (2, (debugfile, \"Handling BYE\\n\"));\n\n /* check if we're logging out */\n if (idata->status == IMAP_BYE)\n return 0;\n\n /* server shut down our connection */\n s += 3;\n SKIPWS (s);\n mutt_error (\"%s\", s);\n mutt_sleep (2);\n cmd_handle_fatal (idata);\n\n return -1;\n }\n else if (option (OPTIMAPSERVERNOISE) && (ascii_strncasecmp (\"NO\", s, 2) == 0))\n {\n dprint (2, (debugfile, \"Handling untagged NO\\n\"));\n\n /* Display the warning message from the server */\n mutt_error (\"%s\", s+3);\n mutt_sleep (2);\n }\n\n return 0;\n}", "project": "mutt", "hash": 50423773011428319367692617777736025326, "size": 101, "commit_id": "9347b5c01dc52682cb6be11539d9b7ebceae4416", "message": "Handle NO response without message properly", "target": 1, "dataset": "other", "idx": 202733} {"func": "static int cmd_handle_untagged (IMAP_DATA* idata)\n{\n char* s;\n char* pn;\n unsigned int count;\n\n s = imap_next_word (idata->buf);\n pn = imap_next_word (s);\n\n if ((idata->state >= IMAP_SELECTED) && isdigit ((unsigned char) *s))\n {\n pn = s;\n s = imap_next_word (s);\n\n /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the\n * connection, so update that one.\n */\n if (ascii_strncasecmp (\"EXISTS\", s, 6) == 0)\n {\n dprint (2, (debugfile, \"Handling EXISTS\\n\"));\n\n /* new mail arrived */\n mutt_atoui (pn, &count);\n\n if ( !(idata->reopen & IMAP_EXPUNGE_PENDING) &&\n\t count < idata->max_msn)\n {\n /* Notes 6.0.3 has a tendency to report fewer messages exist than\n * it should. */\n\tdprint (1, (debugfile, \"Message count is out of sync\"));\n\treturn 0;\n }\n /* at least the InterChange server sends EXISTS messages freely,\n * even when there is no new mail */\n else if (count == idata->max_msn)\n\tdprint (3, (debugfile,\n \"cmd_handle_untagged: superfluous EXISTS message.\\n\"));\n else\n {\n\tif (!(idata->reopen & IMAP_EXPUNGE_PENDING))\n {\n dprint (2, (debugfile,\n \"cmd_handle_untagged: New mail in %s - %d messages total.\\n\",\n idata->mailbox, count));\n\t idata->reopen |= IMAP_NEWMAIL_PENDING;\n }\n\tidata->newMailCount = count;\n }\n }\n /* pn vs. s: need initial seqno */\n else if (ascii_strncasecmp (\"EXPUNGE\", s, 7) == 0)\n cmd_parse_expunge (idata, pn);\n else if (ascii_strncasecmp (\"FETCH\", s, 5) == 0)\n cmd_parse_fetch (idata, pn);\n }\n else if (ascii_strncasecmp (\"CAPABILITY\", s, 10) == 0)\n cmd_parse_capability (idata, s);\n else if (!ascii_strncasecmp (\"OK [CAPABILITY\", s, 14))\n cmd_parse_capability (idata, pn);\n else if (!ascii_strncasecmp (\"OK [CAPABILITY\", pn, 14))\n cmd_parse_capability (idata, imap_next_word (pn));\n else if (ascii_strncasecmp (\"LIST\", s, 4) == 0)\n cmd_parse_list (idata, s);\n else if (ascii_strncasecmp (\"LSUB\", s, 4) == 0)\n cmd_parse_lsub (idata, s);\n else if (ascii_strncasecmp (\"MYRIGHTS\", s, 8) == 0)\n cmd_parse_myrights (idata, s);\n else if (ascii_strncasecmp (\"SEARCH\", s, 6) == 0)\n cmd_parse_search (idata, s);\n else if (ascii_strncasecmp (\"STATUS\", s, 6) == 0)\n cmd_parse_status (idata, s);\n else if (ascii_strncasecmp (\"ENABLED\", s, 7) == 0)\n cmd_parse_enabled (idata, s);\n else if (ascii_strncasecmp (\"BYE\", s, 3) == 0)\n {\n dprint (2, (debugfile, \"Handling BYE\\n\"));\n\n /* check if we're logging out */\n if (idata->status == IMAP_BYE)\n return 0;\n\n /* server shut down our connection */\n s += 3;\n SKIPWS (s);\n mutt_error (\"%s\", s);\n mutt_sleep (2);\n cmd_handle_fatal (idata);\n\n return -1;\n }\n else if (option (OPTIMAPSERVERNOISE) && (ascii_strncasecmp (\"NO\", s, 2) == 0))\n {\n dprint (2, (debugfile, \"Handling untagged NO\\n\"));\n\n /* Display the warning message from the server */\n mutt_error (\"%s\", s+2);\n mutt_sleep (2);\n }\n\n return 0;\n}", "project": "mutt", "hash": 87163458428751244929158289758255212737, "size": 101, "commit_id": "9347b5c01dc52682cb6be11539d9b7ebceae4416", "message": "Handle NO response without message properly", "target": 0, "dataset": "other", "idx": 338014} {"func": "static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method,\n ExceptionInfo *exception)\n{\n ExceptionInfo\n *sans_exception;\n\n Image\n *prev_image,\n *dup_image,\n *bgnd_image,\n *optimized_image;\n\n RectangleInfo\n try_bounds,\n bgnd_bounds,\n dup_bounds,\n *bounds;\n\n MagickBooleanType\n add_frames,\n try_cleared,\n cleared;\n\n DisposeType\n *disposals;\n\n register const Image\n *curr;\n\n register ssize_t\n i;\n\n assert(image != (const Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n assert(method == OptimizeLayer ||\n method == OptimizeImageLayer ||\n method == OptimizePlusLayer);\n /*\n Are we allowed to add/remove frames from animation?\n */\n add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse;\n /*\n Ensure all the images are the same size.\n */\n curr=GetFirstImageInList(image);\n for (; curr != (Image *) NULL; curr=GetNextImageInList(curr))\n {\n if ((curr->columns != image->columns) || (curr->rows != image->rows))\n ThrowImageException(OptionError,\"ImagesAreNotTheSameSize\");\n\n if ((curr->page.x != 0) || (curr->page.y != 0) ||\n (curr->page.width != image->page.width) ||\n (curr->page.height != image->page.height))\n ThrowImageException(OptionError,\"ImagePagesAreNotCoalesced\");\n }\n /*\n Allocate memory (times 2 if we allow the use of frame duplications)\n */\n curr=GetFirstImageInList(image);\n bounds=(RectangleInfo *) AcquireQuantumMemory((size_t)\n GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)*\n sizeof(*bounds));\n if (bounds == (RectangleInfo *) NULL)\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n disposals=(DisposeType *) AcquireQuantumMemory((size_t)\n GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)*\n sizeof(*disposals));\n if (disposals == (DisposeType *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n /*\n Initialise Previous Image as fully transparent\n */\n prev_image=CloneImage(curr,curr->columns,curr->rows,MagickTrue,exception);\n if (prev_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n return((Image *) NULL);\n }\n prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */\n prev_image->page.x=0;\n prev_image->page.y=0;\n prev_image->dispose=NoneDispose;\n prev_image->background_color.alpha_trait=BlendPixelTrait;\n prev_image->background_color.alpha=(MagickRealType) TransparentAlpha;\n (void) SetImageBackgroundColor(prev_image,exception);\n /*\n Figure out the area of overlay of the first frame\n No pixel could be cleared as all pixels are already cleared.\n */\n#if DEBUG_OPT_FRAME\n i=0;\n (void) FormatLocaleFile(stderr,\"frame %.20g :-\\n\",(double) i);\n#endif\n disposals[0]=NoneDispose;\n bounds[0]=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"overlay: %.20gx%.20g%+.20g%+.20g\\n\\n\",\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y );\n#endif\n /*\n Compute the bounding box of changes for each pair of images.\n */\n i=1;\n bgnd_image=(Image *) NULL;\n dup_image=(Image *) NULL;\n dup_bounds.width=0;\n dup_bounds.height=0;\n dup_bounds.x=0;\n dup_bounds.y=0;\n curr=GetNextImageInList(curr);\n for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr))\n {\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"frame %.20g :-\\n\",(double) i);\n#endif\n /*\n Assume none disposal is the best\n */\n bounds[i]=CompareImagesBounds(curr->previous,curr,CompareAnyLayer,exception);\n cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception);\n disposals[i-1]=NoneDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"overlay: %.20gx%.20g%+.20g%+.20g%s%s\\n\",\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y,\n bounds[i].x < 0?\" (unchanged)\":\"\",\n cleared?\" (pixels cleared)\":\"\");\n#endif\n if ( bounds[i].x < 0 ) {\n /*\n Image frame is exactly the same as the previous frame!\n If not adding frames leave it to be cropped down to a null image.\n Otherwise mark previous image for deleted, transfering its crop bounds\n to the current image.\n */\n if ( add_frames && i>=2 ) {\n disposals[i-1]=DelDispose;\n disposals[i]=NoneDispose;\n bounds[i]=bounds[i-1];\n i++;\n continue;\n }\n }\n else\n {\n /*\n Compare a none disposal against a previous disposal\n */\n try_bounds=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"test_prev: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels were cleared)\":\"\");\n#endif\n if ( (!try_cleared && cleared ) ||\n try_bounds.width * try_bounds.height\n < bounds[i].width * bounds[i].height )\n {\n cleared=try_cleared;\n bounds[i]=try_bounds;\n disposals[i-1]=PreviousDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"previous: accepted\\n\");\n } else {\n (void) FormatLocaleFile(stderr,\"previous: rejected\\n\");\n#endif\n }\n\n /*\n If we are allowed lets try a complex frame duplication.\n It is useless if the previous image already clears pixels correctly.\n This method will always clear all the pixels that need to be cleared.\n */\n dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */\n if ( add_frames )\n {\n dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception);\n if (dup_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n prev_image=DestroyImage(prev_image);\n return((Image *) NULL);\n }\n dup_image->background_color.alpha_trait=BlendPixelTrait;\n dup_bounds=CompareImagesBounds(dup_image,curr,CompareClearLayer,exception);\n ClearBounds(dup_image,&dup_bounds,exception);\n try_bounds=CompareImagesBounds(dup_image,curr,CompareAnyLayer,exception);\n if ( cleared ||\n dup_bounds.width*dup_bounds.height\n +try_bounds.width*try_bounds.height\n < bounds[i].width * bounds[i].height )\n {\n cleared=MagickFalse;\n bounds[i]=try_bounds;\n disposals[i-1]=DupDispose;\n /* to be finalised later, if found to be optimial */\n }\n else\n dup_bounds.width=dup_bounds.height=0;\n }\n /*\n Now compare against a simple background disposal\n */\n bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception);\n if (bgnd_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n prev_image=DestroyImage(prev_image);\n if ( dup_image != (Image *) NULL)\n dup_image=DestroyImage(dup_image);\n return((Image *) NULL);\n }\n bgnd_image->background_color.alpha_trait=BlendPixelTrait;\n bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */\n ClearBounds(bgnd_image,&bgnd_bounds,exception);\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"background: %s\\n\",\n try_cleared?\"(pixels cleared)\":\"\");\n#endif\n if ( try_cleared )\n {\n /*\n Straight background disposal failed to clear pixels needed!\n Lets try expanding the disposal area of the previous frame, to\n include the pixels that are cleared. This guaranteed\n to work, though may not be the most optimized solution.\n */\n try_bounds=CompareImagesBounds(curr->previous,curr,CompareClearLayer,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"expand_clear: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_bounds.x<0?\" (no expand nessary)\":\"\");\n#endif\n if ( bgnd_bounds.x < 0 )\n bgnd_bounds = try_bounds;\n else\n {\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"expand_bgnd: %.20gx%.20g%+.20g%+.20g\\n\",\n (double) bgnd_bounds.width,(double) bgnd_bounds.height,\n (double) bgnd_bounds.x,(double) bgnd_bounds.y );\n#endif\n if ( try_bounds.x < bgnd_bounds.x )\n {\n bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x;\n if ( bgnd_bounds.width < try_bounds.width )\n bgnd_bounds.width = try_bounds.width;\n bgnd_bounds.x = try_bounds.x;\n }\n else\n {\n try_bounds.width += try_bounds.x - bgnd_bounds.x;\n if ( bgnd_bounds.width < try_bounds.width )\n bgnd_bounds.width = try_bounds.width;\n }\n if ( try_bounds.y < bgnd_bounds.y )\n {\n bgnd_bounds.height += bgnd_bounds.y - try_bounds.y;\n if ( bgnd_bounds.height < try_bounds.height )\n bgnd_bounds.height = try_bounds.height;\n bgnd_bounds.y = try_bounds.y;\n }\n else\n {\n try_bounds.height += try_bounds.y - bgnd_bounds.y;\n if ( bgnd_bounds.height < try_bounds.height )\n bgnd_bounds.height = try_bounds.height;\n }\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \" to : %.20gx%.20g%+.20g%+.20g\\n\",\n (double) bgnd_bounds.width,(double) bgnd_bounds.height,\n (double) bgnd_bounds.x,(double) bgnd_bounds.y );\n#endif\n }\n ClearBounds(bgnd_image,&bgnd_bounds,exception);\n#if DEBUG_OPT_FRAME\n/* Something strange is happening with a specific animation\n * CompareAnyLayers (normal method) and CompareClearLayers returns the whole\n * image, which is not posibly correct! As verified by previous tests.\n * Something changed beyond the bgnd_bounds clearing. But without being able\n * to see, or writet he image at this point it is hard to tell what is wrong!\n * Only CompareOverlay seemed to return something sensible.\n */\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareClearLayer,exception);\n (void) FormatLocaleFile(stderr, \"expand_ctst: %.20gx%.20g%+.20g%+.20g\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y );\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n (void) FormatLocaleFile(stderr, \"expand_any : %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels cleared)\":\"\");\n#endif\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareOverlayLayer,exception);\n#if DEBUG_OPT_FRAME\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n (void) FormatLocaleFile(stderr, \"expand_test: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels cleared)\":\"\");\n#endif\n }\n /*\n Test if this background dispose is smaller than any of the\n other methods we tryed before this (including duplicated frame)\n */\n if ( cleared ||\n bgnd_bounds.width*bgnd_bounds.height\n +try_bounds.width*try_bounds.height\n < bounds[i-1].width*bounds[i-1].height\n +dup_bounds.width*dup_bounds.height\n +bounds[i].width*bounds[i].height )\n {\n cleared=MagickFalse;\n bounds[i-1]=bgnd_bounds;\n bounds[i]=try_bounds;\n if ( disposals[i-1] == DupDispose )\n dup_image=DestroyImage(dup_image);\n disposals[i-1]=BackgroundDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"expand_bgnd: accepted\\n\");\n } else {\n (void) FormatLocaleFile(stderr,\"expand_bgnd: reject\\n\");\n#endif\n }\n }\n /*\n Finalise choice of dispose, set new prev_image,\n and junk any extra images as appropriate,\n */\n if ( disposals[i-1] == DupDispose )\n {\n if (bgnd_image != (Image *) NULL)\n bgnd_image=DestroyImage(bgnd_image);\n prev_image=DestroyImage(prev_image);\n prev_image=dup_image, dup_image=(Image *) NULL;\n bounds[i+1]=bounds[i];\n bounds[i]=dup_bounds;\n disposals[i-1]=DupDispose;\n disposals[i]=BackgroundDispose;\n i++;\n }\n else\n {\n if ( dup_image != (Image *) NULL)\n dup_image=DestroyImage(dup_image);\n if ( disposals[i-1] != PreviousDispose )\n prev_image=DestroyImage(prev_image);\n if ( disposals[i-1] == BackgroundDispose )\n prev_image=bgnd_image, bgnd_image=(Image *) NULL;\n if (bgnd_image != (Image *) NULL)\n bgnd_image=DestroyImage(bgnd_image);\n if ( disposals[i-1] == NoneDispose )\n {\n prev_image=ReferenceImage(curr->previous);\n if (prev_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n return((Image *) NULL);\n }\n }\n\n }\n assert(prev_image != (Image *) NULL);\n disposals[i]=disposals[i-1];\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"final %.20g : %s %.20gx%.20g%+.20g%+.20g\\n\",\n (double) i-1,\n CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]),\n (double) bounds[i-1].width,(double) bounds[i-1].height,\n (double) bounds[i-1].x,(double) bounds[i-1].y );\n#endif\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"interum %.20g : %s %.20gx%.20g%+.20g%+.20g\\n\",\n (double) i,\n CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]),\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y );\n (void) FormatLocaleFile(stderr,\"\\n\");\n#endif\n i++;\n }\n prev_image=DestroyImage(prev_image);\n /*\n Optimize all images in sequence.\n */\n sans_exception=AcquireExceptionInfo();\n i=0;\n curr=GetFirstImageInList(image);\n optimized_image=NewImageList();\n while ( curr != (const Image *) NULL )\n {\n prev_image=CloneImage(curr,0,0,MagickTrue,exception);\n if (prev_image == (Image *) NULL)\n break;\n prev_image->background_color.alpha_trait=BlendPixelTrait;\n if ( disposals[i] == DelDispose ) {\n size_t time = 0;\n while ( disposals[i] == DelDispose ) {\n time += curr->delay*1000/curr->ticks_per_second;\n curr=GetNextImageInList(curr);\n i++;\n }\n time += curr->delay*1000/curr->ticks_per_second;\n prev_image->ticks_per_second = 100L;\n prev_image->delay = time*prev_image->ticks_per_second/1000;\n }\n bgnd_image=CropImage(prev_image,&bounds[i],sans_exception);\n prev_image=DestroyImage(prev_image);\n if (bgnd_image == (Image *) NULL)\n break;\n bgnd_image->dispose=disposals[i];\n if ( disposals[i] == DupDispose ) {\n bgnd_image->delay=0;\n bgnd_image->dispose=NoneDispose;\n }\n else\n curr=GetNextImageInList(curr);\n AppendImageToList(&optimized_image,bgnd_image);\n i++;\n }\n sans_exception=DestroyExceptionInfo(sans_exception);\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n if (curr != (Image *) NULL)\n {\n optimized_image=DestroyImageList(optimized_image);\n return((Image *) NULL);\n }\n return(GetFirstImageInList(optimized_image));\n}", "project": "ImageMagick", "hash": 140795675133758458513138893585385241253, "size": 449, "commit_id": "ef59bd764f88d893f1219fee8ba696a5d3f8c1c4", "message": "There is a Division by Zero in function OptimizeLayerFrames (#2743)\n\nin file MagickCore/layer.c. cur->ticks_per_seconds can be zero\r\nwith a crafted input argument *image. This is similar to\r\nCVE-2019-13454.", "target": 1, "dataset": "other", "idx": 202739} {"func": "static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method,\n ExceptionInfo *exception)\n{\n ExceptionInfo\n *sans_exception;\n\n Image\n *prev_image,\n *dup_image,\n *bgnd_image,\n *optimized_image;\n\n RectangleInfo\n try_bounds,\n bgnd_bounds,\n dup_bounds,\n *bounds;\n\n MagickBooleanType\n add_frames,\n try_cleared,\n cleared;\n\n DisposeType\n *disposals;\n\n register const Image\n *curr;\n\n register ssize_t\n i;\n\n assert(image != (const Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n assert(method == OptimizeLayer ||\n method == OptimizeImageLayer ||\n method == OptimizePlusLayer);\n /*\n Are we allowed to add/remove frames from animation?\n */\n add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse;\n /*\n Ensure all the images are the same size.\n */\n curr=GetFirstImageInList(image);\n for (; curr != (Image *) NULL; curr=GetNextImageInList(curr))\n {\n if ((curr->columns != image->columns) || (curr->rows != image->rows))\n ThrowImageException(OptionError,\"ImagesAreNotTheSameSize\");\n\n if ((curr->page.x != 0) || (curr->page.y != 0) ||\n (curr->page.width != image->page.width) ||\n (curr->page.height != image->page.height))\n ThrowImageException(OptionError,\"ImagePagesAreNotCoalesced\");\n }\n /*\n Allocate memory (times 2 if we allow the use of frame duplications)\n */\n curr=GetFirstImageInList(image);\n bounds=(RectangleInfo *) AcquireQuantumMemory((size_t)\n GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)*\n sizeof(*bounds));\n if (bounds == (RectangleInfo *) NULL)\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n disposals=(DisposeType *) AcquireQuantumMemory((size_t)\n GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)*\n sizeof(*disposals));\n if (disposals == (DisposeType *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n /*\n Initialise Previous Image as fully transparent\n */\n prev_image=CloneImage(curr,curr->columns,curr->rows,MagickTrue,exception);\n if (prev_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n return((Image *) NULL);\n }\n prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */\n prev_image->page.x=0;\n prev_image->page.y=0;\n prev_image->dispose=NoneDispose;\n prev_image->background_color.alpha_trait=BlendPixelTrait;\n prev_image->background_color.alpha=(MagickRealType) TransparentAlpha;\n (void) SetImageBackgroundColor(prev_image,exception);\n /*\n Figure out the area of overlay of the first frame\n No pixel could be cleared as all pixels are already cleared.\n */\n#if DEBUG_OPT_FRAME\n i=0;\n (void) FormatLocaleFile(stderr,\"frame %.20g :-\\n\",(double) i);\n#endif\n disposals[0]=NoneDispose;\n bounds[0]=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"overlay: %.20gx%.20g%+.20g%+.20g\\n\\n\",\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y );\n#endif\n /*\n Compute the bounding box of changes for each pair of images.\n */\n i=1;\n bgnd_image=(Image *) NULL;\n dup_image=(Image *) NULL;\n dup_bounds.width=0;\n dup_bounds.height=0;\n dup_bounds.x=0;\n dup_bounds.y=0;\n curr=GetNextImageInList(curr);\n for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr))\n {\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"frame %.20g :-\\n\",(double) i);\n#endif\n /*\n Assume none disposal is the best\n */\n bounds[i]=CompareImagesBounds(curr->previous,curr,CompareAnyLayer,exception);\n cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception);\n disposals[i-1]=NoneDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"overlay: %.20gx%.20g%+.20g%+.20g%s%s\\n\",\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y,\n bounds[i].x < 0?\" (unchanged)\":\"\",\n cleared?\" (pixels cleared)\":\"\");\n#endif\n if ( bounds[i].x < 0 ) {\n /*\n Image frame is exactly the same as the previous frame!\n If not adding frames leave it to be cropped down to a null image.\n Otherwise mark previous image for deleted, transfering its crop bounds\n to the current image.\n */\n if ( add_frames && i>=2 ) {\n disposals[i-1]=DelDispose;\n disposals[i]=NoneDispose;\n bounds[i]=bounds[i-1];\n i++;\n continue;\n }\n }\n else\n {\n /*\n Compare a none disposal against a previous disposal\n */\n try_bounds=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"test_prev: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels were cleared)\":\"\");\n#endif\n if ( (!try_cleared && cleared ) ||\n try_bounds.width * try_bounds.height\n < bounds[i].width * bounds[i].height )\n {\n cleared=try_cleared;\n bounds[i]=try_bounds;\n disposals[i-1]=PreviousDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"previous: accepted\\n\");\n } else {\n (void) FormatLocaleFile(stderr,\"previous: rejected\\n\");\n#endif\n }\n\n /*\n If we are allowed lets try a complex frame duplication.\n It is useless if the previous image already clears pixels correctly.\n This method will always clear all the pixels that need to be cleared.\n */\n dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */\n if ( add_frames )\n {\n dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception);\n if (dup_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n prev_image=DestroyImage(prev_image);\n return((Image *) NULL);\n }\n dup_image->background_color.alpha_trait=BlendPixelTrait;\n dup_bounds=CompareImagesBounds(dup_image,curr,CompareClearLayer,exception);\n ClearBounds(dup_image,&dup_bounds,exception);\n try_bounds=CompareImagesBounds(dup_image,curr,CompareAnyLayer,exception);\n if ( cleared ||\n dup_bounds.width*dup_bounds.height\n +try_bounds.width*try_bounds.height\n < bounds[i].width * bounds[i].height )\n {\n cleared=MagickFalse;\n bounds[i]=try_bounds;\n disposals[i-1]=DupDispose;\n /* to be finalised later, if found to be optimial */\n }\n else\n dup_bounds.width=dup_bounds.height=0;\n }\n /*\n Now compare against a simple background disposal\n */\n bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception);\n if (bgnd_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n prev_image=DestroyImage(prev_image);\n if ( dup_image != (Image *) NULL)\n dup_image=DestroyImage(dup_image);\n return((Image *) NULL);\n }\n bgnd_image->background_color.alpha_trait=BlendPixelTrait;\n bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */\n ClearBounds(bgnd_image,&bgnd_bounds,exception);\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"background: %s\\n\",\n try_cleared?\"(pixels cleared)\":\"\");\n#endif\n if ( try_cleared )\n {\n /*\n Straight background disposal failed to clear pixels needed!\n Lets try expanding the disposal area of the previous frame, to\n include the pixels that are cleared. This guaranteed\n to work, though may not be the most optimized solution.\n */\n try_bounds=CompareImagesBounds(curr->previous,curr,CompareClearLayer,exception);\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"expand_clear: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_bounds.x<0?\" (no expand nessary)\":\"\");\n#endif\n if ( bgnd_bounds.x < 0 )\n bgnd_bounds = try_bounds;\n else\n {\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"expand_bgnd: %.20gx%.20g%+.20g%+.20g\\n\",\n (double) bgnd_bounds.width,(double) bgnd_bounds.height,\n (double) bgnd_bounds.x,(double) bgnd_bounds.y );\n#endif\n if ( try_bounds.x < bgnd_bounds.x )\n {\n bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x;\n if ( bgnd_bounds.width < try_bounds.width )\n bgnd_bounds.width = try_bounds.width;\n bgnd_bounds.x = try_bounds.x;\n }\n else\n {\n try_bounds.width += try_bounds.x - bgnd_bounds.x;\n if ( bgnd_bounds.width < try_bounds.width )\n bgnd_bounds.width = try_bounds.width;\n }\n if ( try_bounds.y < bgnd_bounds.y )\n {\n bgnd_bounds.height += bgnd_bounds.y - try_bounds.y;\n if ( bgnd_bounds.height < try_bounds.height )\n bgnd_bounds.height = try_bounds.height;\n bgnd_bounds.y = try_bounds.y;\n }\n else\n {\n try_bounds.height += try_bounds.y - bgnd_bounds.y;\n if ( bgnd_bounds.height < try_bounds.height )\n bgnd_bounds.height = try_bounds.height;\n }\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \" to : %.20gx%.20g%+.20g%+.20g\\n\",\n (double) bgnd_bounds.width,(double) bgnd_bounds.height,\n (double) bgnd_bounds.x,(double) bgnd_bounds.y );\n#endif\n }\n ClearBounds(bgnd_image,&bgnd_bounds,exception);\n#if DEBUG_OPT_FRAME\n/* Something strange is happening with a specific animation\n * CompareAnyLayers (normal method) and CompareClearLayers returns the whole\n * image, which is not posibly correct! As verified by previous tests.\n * Something changed beyond the bgnd_bounds clearing. But without being able\n * to see, or writet he image at this point it is hard to tell what is wrong!\n * Only CompareOverlay seemed to return something sensible.\n */\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareClearLayer,exception);\n (void) FormatLocaleFile(stderr, \"expand_ctst: %.20gx%.20g%+.20g%+.20g\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y );\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception);\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n (void) FormatLocaleFile(stderr, \"expand_any : %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels cleared)\":\"\");\n#endif\n try_bounds=CompareImagesBounds(bgnd_image,curr,CompareOverlayLayer,exception);\n#if DEBUG_OPT_FRAME\n try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception);\n (void) FormatLocaleFile(stderr, \"expand_test: %.20gx%.20g%+.20g%+.20g%s\\n\",\n (double) try_bounds.width,(double) try_bounds.height,\n (double) try_bounds.x,(double) try_bounds.y,\n try_cleared?\" (pixels cleared)\":\"\");\n#endif\n }\n /*\n Test if this background dispose is smaller than any of the\n other methods we tryed before this (including duplicated frame)\n */\n if ( cleared ||\n bgnd_bounds.width*bgnd_bounds.height\n +try_bounds.width*try_bounds.height\n < bounds[i-1].width*bounds[i-1].height\n +dup_bounds.width*dup_bounds.height\n +bounds[i].width*bounds[i].height )\n {\n cleared=MagickFalse;\n bounds[i-1]=bgnd_bounds;\n bounds[i]=try_bounds;\n if ( disposals[i-1] == DupDispose )\n dup_image=DestroyImage(dup_image);\n disposals[i-1]=BackgroundDispose;\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr,\"expand_bgnd: accepted\\n\");\n } else {\n (void) FormatLocaleFile(stderr,\"expand_bgnd: reject\\n\");\n#endif\n }\n }\n /*\n Finalise choice of dispose, set new prev_image,\n and junk any extra images as appropriate,\n */\n if ( disposals[i-1] == DupDispose )\n {\n if (bgnd_image != (Image *) NULL)\n bgnd_image=DestroyImage(bgnd_image);\n prev_image=DestroyImage(prev_image);\n prev_image=dup_image, dup_image=(Image *) NULL;\n bounds[i+1]=bounds[i];\n bounds[i]=dup_bounds;\n disposals[i-1]=DupDispose;\n disposals[i]=BackgroundDispose;\n i++;\n }\n else\n {\n if ( dup_image != (Image *) NULL)\n dup_image=DestroyImage(dup_image);\n if ( disposals[i-1] != PreviousDispose )\n prev_image=DestroyImage(prev_image);\n if ( disposals[i-1] == BackgroundDispose )\n prev_image=bgnd_image, bgnd_image=(Image *) NULL;\n if (bgnd_image != (Image *) NULL)\n bgnd_image=DestroyImage(bgnd_image);\n if ( disposals[i-1] == NoneDispose )\n {\n prev_image=ReferenceImage(curr->previous);\n if (prev_image == (Image *) NULL)\n {\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n return((Image *) NULL);\n }\n }\n\n }\n assert(prev_image != (Image *) NULL);\n disposals[i]=disposals[i-1];\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"final %.20g : %s %.20gx%.20g%+.20g%+.20g\\n\",\n (double) i-1,\n CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]),\n (double) bounds[i-1].width,(double) bounds[i-1].height,\n (double) bounds[i-1].x,(double) bounds[i-1].y );\n#endif\n#if DEBUG_OPT_FRAME\n (void) FormatLocaleFile(stderr, \"interum %.20g : %s %.20gx%.20g%+.20g%+.20g\\n\",\n (double) i,\n CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]),\n (double) bounds[i].width,(double) bounds[i].height,\n (double) bounds[i].x,(double) bounds[i].y );\n (void) FormatLocaleFile(stderr,\"\\n\");\n#endif\n i++;\n }\n prev_image=DestroyImage(prev_image);\n /*\n Optimize all images in sequence.\n */\n sans_exception=AcquireExceptionInfo();\n i=0;\n curr=GetFirstImageInList(image);\n optimized_image=NewImageList();\n while ( curr != (const Image *) NULL )\n {\n prev_image=CloneImage(curr,0,0,MagickTrue,exception);\n if (prev_image == (Image *) NULL)\n break;\n prev_image->background_color.alpha_trait=BlendPixelTrait;\n if ( disposals[i] == DelDispose ) {\n size_t time = 0;\n while ( disposals[i] == DelDispose ) {\n time +=(size_t) (curr->delay*1000*\n PerceptibleReciprocal((double) curr->ticks_per_second));\n curr=GetNextImageInList(curr);\n i++;\n }\n time += (size_t)(curr->delay*1000*\n PerceptibleReciprocal((double) curr->ticks_per_second));\n prev_image->ticks_per_second = 100L;\n prev_image->delay = time*prev_image->ticks_per_second/1000;\n }\n bgnd_image=CropImage(prev_image,&bounds[i],sans_exception);\n prev_image=DestroyImage(prev_image);\n if (bgnd_image == (Image *) NULL)\n break;\n bgnd_image->dispose=disposals[i];\n if ( disposals[i] == DupDispose ) {\n bgnd_image->delay=0;\n bgnd_image->dispose=NoneDispose;\n }\n else\n curr=GetNextImageInList(curr);\n AppendImageToList(&optimized_image,bgnd_image);\n i++;\n }\n sans_exception=DestroyExceptionInfo(sans_exception);\n bounds=(RectangleInfo *) RelinquishMagickMemory(bounds);\n disposals=(DisposeType *) RelinquishMagickMemory(disposals);\n if (curr != (Image *) NULL)\n {\n optimized_image=DestroyImageList(optimized_image);\n return((Image *) NULL);\n }\n return(GetFirstImageInList(optimized_image));\n}", "project": "ImageMagick", "hash": 137819104896390903763862580984210764323, "size": 451, "commit_id": "ef59bd764f88d893f1219fee8ba696a5d3f8c1c4", "message": "There is a Division by Zero in function OptimizeLayerFrames (#2743)\n\nin file MagickCore/layer.c. cur->ticks_per_seconds can be zero\r\nwith a crafted input argument *image. This is similar to\r\nCVE-2019-13454.", "target": 0, "dataset": "other", "idx": 338501} {"func": "static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)\n{\n\tstruct io_buffer *buf;\n\tu64 addr = pbuf->addr;\n\tint i, bid = pbuf->bid;\n\n\tfor (i = 0; i < pbuf->nbufs; i++) {\n\t\tbuf = kmalloc(sizeof(*buf), GFP_KERNEL);\n\t\tif (!buf)\n\t\t\tbreak;\n\n\t\tbuf->addr = addr;\n\t\tbuf->len = pbuf->len;\n\t\tbuf->bid = bid;\n\t\taddr += pbuf->len;\n\t\tbid++;\n\t\tif (!*head) {\n\t\t\tINIT_LIST_HEAD(&buf->list);\n\t\t\t*head = buf;\n\t\t} else {\n\t\t\tlist_add_tail(&buf->list, &(*head)->list);\n\t\t}\n\t}\n\n\treturn i ? i : -ENOMEM;\n}", "project": "linux", "hash": 97053759323757789573775019463585321454, "size": 26, "commit_id": "d1f82808877bb10d3deee7cf3374a4eb3fb582db", "message": "io_uring: truncate lengths larger than MAX_RW_COUNT on provide buffers\n\nRead and write operations are capped to MAX_RW_COUNT. Some read ops rely on\nthat limit, and that is not guaranteed by the IORING_OP_PROVIDE_BUFFERS.\n\nTruncate those lengths when doing io_add_buffers, so buffer addresses still\nuse the uncapped length.\n\nAlso, take the chance and change struct io_buffer len member to __u32, so\nit matches struct io_provide_buffer len member.\n\nThis fixes CVE-2021-3491, also reported as ZDI-CAN-13546.\n\nFixes: ddf0322db79c (\"io_uring: add IORING_OP_PROVIDE_BUFFERS\")\nReported-by: Billy Jheng Bing-Jhong (@st424204)\nSigned-off-by: Thadeu Lima de Souza Cascardo \nSigned-off-by: Jens Axboe ", "target": 1, "dataset": "other", "idx": 202741} {"func": "static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)\n{\n\tstruct io_buffer *buf;\n\tu64 addr = pbuf->addr;\n\tint i, bid = pbuf->bid;\n\n\tfor (i = 0; i < pbuf->nbufs; i++) {\n\t\tbuf = kmalloc(sizeof(*buf), GFP_KERNEL);\n\t\tif (!buf)\n\t\t\tbreak;\n\n\t\tbuf->addr = addr;\n\t\tbuf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);\n\t\tbuf->bid = bid;\n\t\taddr += pbuf->len;\n\t\tbid++;\n\t\tif (!*head) {\n\t\t\tINIT_LIST_HEAD(&buf->list);\n\t\t\t*head = buf;\n\t\t} else {\n\t\t\tlist_add_tail(&buf->list, &(*head)->list);\n\t\t}\n\t}\n\n\treturn i ? i : -ENOMEM;\n}", "project": "linux", "hash": 66027508180468263129870084716869579887, "size": 26, "commit_id": "d1f82808877bb10d3deee7cf3374a4eb3fb582db", "message": "io_uring: truncate lengths larger than MAX_RW_COUNT on provide buffers\n\nRead and write operations are capped to MAX_RW_COUNT. Some read ops rely on\nthat limit, and that is not guaranteed by the IORING_OP_PROVIDE_BUFFERS.\n\nTruncate those lengths when doing io_add_buffers, so buffer addresses still\nuse the uncapped length.\n\nAlso, take the chance and change struct io_buffer len member to __u32, so\nit matches struct io_provide_buffer len member.\n\nThis fixes CVE-2021-3491, also reported as ZDI-CAN-13546.\n\nFixes: ddf0322db79c (\"io_uring: add IORING_OP_PROVIDE_BUFFERS\")\nReported-by: Billy Jheng Bing-Jhong (@st424204)\nSigned-off-by: Thadeu Lima de Souza Cascardo \nSigned-off-by: Jens Axboe ", "target": 0, "dataset": "other", "idx": 338639} {"func": "static int ib_prctl_set(struct task_struct *task, unsigned long ctrl)\n{\n\tswitch (ctrl) {\n\tcase PR_SPEC_ENABLE:\n\t\tif (spectre_v2_user_ibpb == SPECTRE_V2_USER_NONE &&\n\t\t spectre_v2_user_stibp == SPECTRE_V2_USER_NONE)\n\t\t\treturn 0;\n\t\t/*\n\t\t * Indirect branch speculation is always disabled in strict\n\t\t * mode.\n\t\t */\n\t\tif (spectre_v2_user_ibpb == SPECTRE_V2_USER_STRICT ||\n\t\t spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT ||\n\t\t spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT_PREFERRED)\n\t\t\treturn -EPERM;\n\t\ttask_clear_spec_ib_disable(task);\n\t\ttask_update_spec_tif(task);\n\t\tbreak;\n\tcase PR_SPEC_DISABLE:\n\tcase PR_SPEC_FORCE_DISABLE:\n\t\t/*\n\t\t * Indirect branch speculation is always allowed when\n\t\t * mitigation is force disabled.\n\t\t */\n\t\tif (spectre_v2_user_ibpb == SPECTRE_V2_USER_NONE &&\n\t\t spectre_v2_user_stibp == SPECTRE_V2_USER_NONE)\n\t\t\treturn -EPERM;\n\t\tif (spectre_v2_user_ibpb == SPECTRE_V2_USER_STRICT ||\n\t\t spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT ||\n\t\t spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT_PREFERRED)\n\t\t\treturn 0;\n\t\ttask_set_spec_ib_disable(task);\n\t\tif (ctrl == PR_SPEC_FORCE_DISABLE)\n\t\t\ttask_set_spec_ib_force_disable(task);\n\t\ttask_update_spec_tif(task);\n\t\tbreak;\n\tdefault:\n\t\treturn -ERANGE;\n\t}\n\treturn 0;\n}", "project": "linux", "hash": 132412332318217215818390687833972356536, "size": 41, "commit_id": "4d8df8cbb9156b0a0ab3f802b80cb5db57acc0bf", "message": "x86/speculation: PR_SPEC_FORCE_DISABLE enforcement for indirect branches.\n\nCurrently, it is possible to enable indirect branch speculation even after\nit was force-disabled using the PR_SPEC_FORCE_DISABLE option. Moreover, the\nPR_GET_SPECULATION_CTRL command gives afterwards an incorrect result\n(force-disabled when it is in fact enabled). This also is inconsistent\nvs. STIBP and the documention which cleary states that\nPR_SPEC_FORCE_DISABLE cannot be undone.\n\nFix this by actually enforcing force-disabled indirect branch\nspeculation. PR_SPEC_ENABLE called after PR_SPEC_FORCE_DISABLE now fails\nwith -EPERM as described in the documentation.\n\nFixes: 9137bb27e60e (\"x86/speculation: Add prctl() control for indirect branch speculation\")\nSigned-off-by: Anthony Steinhauser \nSigned-off-by: Thomas Gleixner \nCc: stable@vger.kernel.org", "target": 1, "dataset": "other", "idx": 202751} {"func": "static int ib_prctl_set(struct task_struct *task, unsigned long ctrl)\n{\n\tswitch (ctrl) {\n\tcase PR_SPEC_ENABLE:\n\t\tif (spectre_v2_user_ibpb == SPECTRE_V2_USER_NONE &&\n\t\t spectre_v2_user_stibp == SPECTRE_V2_USER_NONE)\n\t\t\treturn 0;\n\t\t/*\n\t\t * Indirect branch speculation is always disabled in strict\n\t\t * mode. It can neither be enabled if it was force-disabled\n\t\t * by a previous prctl call.\n\n\t\t */\n\t\tif (spectre_v2_user_ibpb == SPECTRE_V2_USER_STRICT ||\n\t\t spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT ||\n\t\t spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT_PREFERRED ||\n\t\t task_spec_ib_force_disable(task))\n\t\t\treturn -EPERM;\n\t\ttask_clear_spec_ib_disable(task);\n\t\ttask_update_spec_tif(task);\n\t\tbreak;\n\tcase PR_SPEC_DISABLE:\n\tcase PR_SPEC_FORCE_DISABLE:\n\t\t/*\n\t\t * Indirect branch speculation is always allowed when\n\t\t * mitigation is force disabled.\n\t\t */\n\t\tif (spectre_v2_user_ibpb == SPECTRE_V2_USER_NONE &&\n\t\t spectre_v2_user_stibp == SPECTRE_V2_USER_NONE)\n\t\t\treturn -EPERM;\n\t\tif (spectre_v2_user_ibpb == SPECTRE_V2_USER_STRICT ||\n\t\t spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT ||\n\t\t spectre_v2_user_stibp == SPECTRE_V2_USER_STRICT_PREFERRED)\n\t\t\treturn 0;\n\t\ttask_set_spec_ib_disable(task);\n\t\tif (ctrl == PR_SPEC_FORCE_DISABLE)\n\t\t\ttask_set_spec_ib_force_disable(task);\n\t\ttask_update_spec_tif(task);\n\t\tbreak;\n\tdefault:\n\t\treturn -ERANGE;\n\t}\n\treturn 0;\n}", "project": "linux", "hash": 11919961636460426634217932345711759228, "size": 44, "commit_id": "4d8df8cbb9156b0a0ab3f802b80cb5db57acc0bf", "message": "x86/speculation: PR_SPEC_FORCE_DISABLE enforcement for indirect branches.\n\nCurrently, it is possible to enable indirect branch speculation even after\nit was force-disabled using the PR_SPEC_FORCE_DISABLE option. Moreover, the\nPR_GET_SPECULATION_CTRL command gives afterwards an incorrect result\n(force-disabled when it is in fact enabled). This also is inconsistent\nvs. STIBP and the documention which cleary states that\nPR_SPEC_FORCE_DISABLE cannot be undone.\n\nFix this by actually enforcing force-disabled indirect branch\nspeculation. PR_SPEC_ENABLE called after PR_SPEC_FORCE_DISABLE now fails\nwith -EPERM as described in the documentation.\n\nFixes: 9137bb27e60e (\"x86/speculation: Add prctl() control for indirect branch speculation\")\nSigned-off-by: Anthony Steinhauser \nSigned-off-by: Thomas Gleixner \nCc: stable@vger.kernel.org", "target": 0, "dataset": "other", "idx": 338780} {"func": "static int fuse_do_getattr(struct inode *inode, struct kstat *stat,\n\t\t\t struct file *file)\n{\n\tint err;\n\tstruct fuse_getattr_in inarg;\n\tstruct fuse_attr_out outarg;\n\tstruct fuse_mount *fm = get_fuse_mount(inode);\n\tFUSE_ARGS(args);\n\tu64 attr_version;\n\n\tattr_version = fuse_get_attr_version(fm->fc);\n\n\tmemset(&inarg, 0, sizeof(inarg));\n\tmemset(&outarg, 0, sizeof(outarg));\n\t/* Directories have separate file-handle space */\n\tif (file && S_ISREG(inode->i_mode)) {\n\t\tstruct fuse_file *ff = file->private_data;\n\n\t\tinarg.getattr_flags |= FUSE_GETATTR_FH;\n\t\tinarg.fh = ff->fh;\n\t}\n\targs.opcode = FUSE_GETATTR;\n\targs.nodeid = get_node_id(inode);\n\targs.in_numargs = 1;\n\targs.in_args[0].size = sizeof(inarg);\n\targs.in_args[0].value = &inarg;\n\targs.out_numargs = 1;\n\targs.out_args[0].size = sizeof(outarg);\n\targs.out_args[0].value = &outarg;\n\terr = fuse_simple_request(fm, &args);\n\tif (!err) {\n\t\tif (fuse_invalid_attr(&outarg.attr) ||\n\t\t (inode->i_mode ^ outarg.attr.mode) & S_IFMT) {\n\t\t\tmake_bad_inode(inode);\n\t\t\terr = -EIO;\n\t\t} else {\n\t\t\tfuse_change_attributes(inode, &outarg.attr,\n\t\t\t\t\t attr_timeout(&outarg),\n\t\t\t\t\t attr_version);\n\t\t\tif (stat)\n\t\t\t\tfuse_fillattr(inode, &outarg.attr, stat);\n\t\t}\n\t}\n\treturn err;\n}", "project": "linux", "hash": 66305836614615397501498682867266125877, "size": 45, "commit_id": "5d069dbe8aaf2a197142558b6fb2978189ba3454", "message": "fuse: fix bad inode\n\nJan Kara's analysis of the syzbot report (edited):\n\n The reproducer opens a directory on FUSE filesystem, it then attaches\n dnotify mark to the open directory. After that a fuse_do_getattr() call\n finds that attributes returned by the server are inconsistent, and calls\n make_bad_inode() which, among other things does:\n\n inode->i_mode = S_IFREG;\n\n This then confuses dnotify which doesn't tear down its structures\n properly and eventually crashes.\n\nAvoid calling make_bad_inode() on a live inode: switch to a private flag on\nthe fuse inode. Also add the test to ops which the bad_inode_ops would\nhave caught.\n\nThis bug goes back to the initial merge of fuse in 2.6.14...\n\nReported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com\nSigned-off-by: Miklos Szeredi \nTested-by: Jan Kara \nCc: ", "target": 1, "dataset": "other", "idx": 202842} {"func": "static int fuse_do_getattr(struct inode *inode, struct kstat *stat,\n\t\t\t struct file *file)\n{\n\tint err;\n\tstruct fuse_getattr_in inarg;\n\tstruct fuse_attr_out outarg;\n\tstruct fuse_mount *fm = get_fuse_mount(inode);\n\tFUSE_ARGS(args);\n\tu64 attr_version;\n\n\tattr_version = fuse_get_attr_version(fm->fc);\n\n\tmemset(&inarg, 0, sizeof(inarg));\n\tmemset(&outarg, 0, sizeof(outarg));\n\t/* Directories have separate file-handle space */\n\tif (file && S_ISREG(inode->i_mode)) {\n\t\tstruct fuse_file *ff = file->private_data;\n\n\t\tinarg.getattr_flags |= FUSE_GETATTR_FH;\n\t\tinarg.fh = ff->fh;\n\t}\n\targs.opcode = FUSE_GETATTR;\n\targs.nodeid = get_node_id(inode);\n\targs.in_numargs = 1;\n\targs.in_args[0].size = sizeof(inarg);\n\targs.in_args[0].value = &inarg;\n\targs.out_numargs = 1;\n\targs.out_args[0].size = sizeof(outarg);\n\targs.out_args[0].value = &outarg;\n\terr = fuse_simple_request(fm, &args);\n\tif (!err) {\n\t\tif (fuse_invalid_attr(&outarg.attr) ||\n\t\t (inode->i_mode ^ outarg.attr.mode) & S_IFMT) {\n\t\t\tfuse_make_bad(inode);\n\t\t\terr = -EIO;\n\t\t} else {\n\t\t\tfuse_change_attributes(inode, &outarg.attr,\n\t\t\t\t\t attr_timeout(&outarg),\n\t\t\t\t\t attr_version);\n\t\t\tif (stat)\n\t\t\t\tfuse_fillattr(inode, &outarg.attr, stat);\n\t\t}\n\t}\n\treturn err;\n}", "project": "linux", "hash": 207137391981469494967408362501142420848, "size": 45, "commit_id": "5d069dbe8aaf2a197142558b6fb2978189ba3454", "message": "fuse: fix bad inode\n\nJan Kara's analysis of the syzbot report (edited):\n\n The reproducer opens a directory on FUSE filesystem, it then attaches\n dnotify mark to the open directory. After that a fuse_do_getattr() call\n finds that attributes returned by the server are inconsistent, and calls\n make_bad_inode() which, among other things does:\n\n inode->i_mode = S_IFREG;\n\n This then confuses dnotify which doesn't tear down its structures\n properly and eventually crashes.\n\nAvoid calling make_bad_inode() on a live inode: switch to a private flag on\nthe fuse inode. Also add the test to ops which the bad_inode_ops would\nhave caught.\n\nThis bug goes back to the initial merge of fuse in 2.6.14...\n\nReported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com\nSigned-off-by: Miklos Szeredi \nTested-by: Jan Kara \nCc: ", "target": 0, "dataset": "other", "idx": 342120} {"func": "jbig2_decode_symbol_dict(Jbig2Ctx *ctx,\n Jbig2Segment *segment,\n const Jbig2SymbolDictParams *params, const byte *data, size_t size, Jbig2ArithCx *GB_stats, Jbig2ArithCx *GR_stats)\n{\n Jbig2SymbolDict *SDNEWSYMS = NULL;\n Jbig2SymbolDict *SDEXSYMS = NULL;\n uint32_t HCHEIGHT;\n uint32_t NSYMSDECODED;\n uint32_t SYMWIDTH, TOTWIDTH;\n uint32_t HCFIRSTSYM;\n uint32_t *SDNEWSYMWIDTHS = NULL;\n int SBSYMCODELEN = 0;\n Jbig2WordStream *ws = NULL;\n Jbig2HuffmanState *hs = NULL;\n Jbig2HuffmanTable *SDHUFFRDX = NULL;\n Jbig2HuffmanTable *SBHUFFRSIZE = NULL;\n Jbig2ArithState *as = NULL;\n Jbig2ArithIntCtx *IADH = NULL;\n Jbig2ArithIntCtx *IADW = NULL;\n Jbig2ArithIntCtx *IAEX = NULL;\n Jbig2ArithIntCtx *IAAI = NULL;\n Jbig2ArithIaidCtx *IAID = NULL;\n Jbig2ArithIntCtx *IARDX = NULL;\n Jbig2ArithIntCtx *IARDY = NULL;\n int code = 0;\n Jbig2SymbolDict **refagg_dicts = NULL;\n int n_refagg_dicts = 1;\n\n Jbig2TextRegionParams *tparams = NULL;\n\n /* 6.5.5 (3) */\n HCHEIGHT = 0;\n NSYMSDECODED = 0;\n\n ws = jbig2_word_stream_buf_new(ctx, data, size);\n if (ws == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate ws in jbig2_decode_symbol_dict\");\n return NULL;\n }\n\n as = jbig2_arith_new(ctx, ws);\n if (as == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate as in jbig2_decode_symbol_dict\");\n jbig2_word_stream_buf_free(ctx, ws);\n return NULL;\n }\n\n if (!params->SDHUFF) {\n IADH = jbig2_arith_int_ctx_new(ctx);\n IADW = jbig2_arith_int_ctx_new(ctx);\n IAEX = jbig2_arith_int_ctx_new(ctx);\n IAAI = jbig2_arith_int_ctx_new(ctx);\n if ((IADH == NULL) || (IADW == NULL) || (IAEX == NULL) || (IAAI == NULL)) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate storage for symbol bitmap\");\n goto cleanup1;\n }\n if (params->SDREFAGG) {\n int64_t tmp = params->SDNUMINSYMS + params->SDNUMNEWSYMS;\n\n for (SBSYMCODELEN = 0; ((int64_t) 1 << SBSYMCODELEN) < tmp; SBSYMCODELEN++);\n IAID = jbig2_arith_iaid_ctx_new(ctx, SBSYMCODELEN);\n IARDX = jbig2_arith_int_ctx_new(ctx);\n IARDY = jbig2_arith_int_ctx_new(ctx);\n if ((IAID == NULL) || (IARDX == NULL) || (IARDY == NULL)) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate storage for symbol bitmap\");\n goto cleanup2;\n }\n }\n } else {\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"huffman coded symbol dictionary\");\n hs = jbig2_huffman_new(ctx, ws);\n SDHUFFRDX = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O);\n SBHUFFRSIZE = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_A);\n if ((hs == NULL) || (SDHUFFRDX == NULL) || (SBHUFFRSIZE == NULL)) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate storage for symbol bitmap\");\n goto cleanup2;\n }\n if (!params->SDREFAGG) {\n SDNEWSYMWIDTHS = jbig2_new(ctx, uint32_t, params->SDNUMNEWSYMS);\n if (SDNEWSYMWIDTHS == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"could not allocate storage for (%u) symbol widths\", params->SDNUMNEWSYMS);\n goto cleanup2;\n }\n }\n }\n\n SDNEWSYMS = jbig2_sd_new(ctx, params->SDNUMNEWSYMS);\n if (SDNEWSYMS == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"could not allocate storage for (%u) new symbols\", params->SDNUMNEWSYMS);\n goto cleanup2;\n }\n\n /* 6.5.5 (4a) */\n while (NSYMSDECODED < params->SDNUMNEWSYMS) {\n int32_t HCDH, DW;\n\n /* 6.5.6 */\n if (params->SDHUFF) {\n HCDH = jbig2_huffman_get(hs, params->SDHUFFDH, &code);\n } else {\n code = jbig2_arith_int_decode(IADH, as, &HCDH);\n }\n\n if (code != 0) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"error or OOB decoding height class delta (%d)\\n\", code);\n }\n\n if (!params->SDHUFF && jbig2_arith_has_reached_marker(as)) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"prevent DOS while decoding height classes\");\n goto cleanup2;\n }\n\n /* 6.5.5 (4b) */\n HCHEIGHT = HCHEIGHT + HCDH;\n SYMWIDTH = 0;\n TOTWIDTH = 0;\n HCFIRSTSYM = NSYMSDECODED;\n\n if ((int32_t) HCHEIGHT < 0) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Invalid HCHEIGHT value\");\n goto cleanup2;\n }\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"HCHEIGHT = %d\", HCHEIGHT);\n#endif\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"decoding height class %d with %d syms decoded\", HCHEIGHT, NSYMSDECODED);\n\n for (;;) {\n /* 6.5.7 */\n if (params->SDHUFF) {\n DW = jbig2_huffman_get(hs, params->SDHUFFDW, &code);\n } else {\n code = jbig2_arith_int_decode(IADW, as, &DW);\n }\n if (code < 0)\n goto cleanup4;\n\n /* 6.5.5 (4c.i) */\n if (code == 1) {\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \" OOB signals end of height class %d\", HCHEIGHT);\n break;\n }\n\n /* check for broken symbol table */\n if (NSYMSDECODED >= params->SDNUMNEWSYMS) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"No OOB signalling end of height class %d\", HCHEIGHT);\n goto cleanup4;\n }\n\n SYMWIDTH = SYMWIDTH + DW;\n TOTWIDTH = TOTWIDTH + SYMWIDTH;\n if ((int32_t) SYMWIDTH < 0) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Invalid SYMWIDTH value (%d) at symbol %d\", SYMWIDTH, NSYMSDECODED + 1);\n goto cleanup4;\n }\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"SYMWIDTH = %d TOTWIDTH = %d\", SYMWIDTH, TOTWIDTH);\n#endif\n /* 6.5.5 (4c.ii) */\n if (!params->SDHUFF || params->SDREFAGG) {\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"SDHUFF = %d; SDREFAGG = %d\", params->SDHUFF, params->SDREFAGG);\n#endif\n /* 6.5.8 */\n if (!params->SDREFAGG) {\n Jbig2GenericRegionParams region_params;\n int sdat_bytes;\n Jbig2Image *image;\n\n /* Table 16 */\n region_params.MMR = 0;\n region_params.GBTEMPLATE = params->SDTEMPLATE;\n region_params.TPGDON = 0;\n region_params.USESKIP = 0;\n sdat_bytes = params->SDTEMPLATE == 0 ? 8 : 2;\n memcpy(region_params.gbat, params->sdat, sdat_bytes);\n\n image = jbig2_image_new(ctx, SYMWIDTH, HCHEIGHT);\n if (image == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to allocate image in jbig2_decode_symbol_dict\");\n goto cleanup4;\n }\n\n code = jbig2_decode_generic_region(ctx, segment, ®ion_params, as, image, GB_stats);\n if (code < 0) {\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n\n SDNEWSYMS->glyphs[NSYMSDECODED] = image;\n } else {\n /* 6.5.8.2 refinement/aggregate symbol */\n uint32_t REFAGGNINST;\n\n if (params->SDHUFF) {\n REFAGGNINST = jbig2_huffman_get(hs, params->SDHUFFAGGINST, &code);\n } else {\n code = jbig2_arith_int_decode(IAAI, as, (int32_t *) & REFAGGNINST);\n }\n if (code || (int32_t) REFAGGNINST <= 0) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"invalid number of symbols or OOB in aggregate glyph\");\n goto cleanup4;\n }\n\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"aggregate symbol coding (%d instances)\", REFAGGNINST);\n\n if (REFAGGNINST > 1) {\n Jbig2Image *image;\n uint32_t i;\n\n if (tparams == NULL) {\n /* First time through, we need to initialise the */\n /* various tables for Huffman or adaptive encoding */\n /* as well as the text region parameters structure */\n refagg_dicts = jbig2_new(ctx, Jbig2SymbolDict *, n_refagg_dicts);\n if (refagg_dicts == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory allocating dictionary array\");\n goto cleanup4;\n }\n refagg_dicts[0] = jbig2_sd_new(ctx, params->SDNUMINSYMS + params->SDNUMNEWSYMS);\n if (refagg_dicts[0] == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory allocating symbol dictionary\");\n jbig2_free(ctx->allocator, refagg_dicts);\n goto cleanup4;\n }\n for (i = 0; i < params->SDNUMINSYMS; i++) {\n refagg_dicts[0]->glyphs[i] = jbig2_image_clone(ctx, params->SDINSYMS->glyphs[i]);\n }\n\n tparams = jbig2_new(ctx, Jbig2TextRegionParams, 1);\n if (tparams == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory creating text region params\");\n goto cleanup4;\n }\n if (!params->SDHUFF) {\n /* Values from Table 17, section 6.5.8.2 (2) */\n tparams->IADT = jbig2_arith_int_ctx_new(ctx);\n tparams->IAFS = jbig2_arith_int_ctx_new(ctx);\n tparams->IADS = jbig2_arith_int_ctx_new(ctx);\n tparams->IAIT = jbig2_arith_int_ctx_new(ctx);\n /* Table 31 */\n for (SBSYMCODELEN = 0; (1 << SBSYMCODELEN) < (int)(params->SDNUMINSYMS + params->SDNUMNEWSYMS); SBSYMCODELEN++);\n tparams->IAID = jbig2_arith_iaid_ctx_new(ctx, SBSYMCODELEN);\n tparams->IARI = jbig2_arith_int_ctx_new(ctx);\n tparams->IARDW = jbig2_arith_int_ctx_new(ctx);\n tparams->IARDH = jbig2_arith_int_ctx_new(ctx);\n tparams->IARDX = jbig2_arith_int_ctx_new(ctx);\n tparams->IARDY = jbig2_arith_int_ctx_new(ctx);\n } else {\n tparams->SBHUFFFS = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_F); /* Table B.6 */\n tparams->SBHUFFDS = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_H); /* Table B.8 */\n tparams->SBHUFFDT = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_K); /* Table B.11 */\n tparams->SBHUFFRDW = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O); /* Table B.15 */\n tparams->SBHUFFRDH = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O); /* Table B.15 */\n tparams->SBHUFFRDX = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O); /* Table B.15 */\n tparams->SBHUFFRDY = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O); /* Table B.15 */\n }\n tparams->SBHUFF = params->SDHUFF;\n tparams->SBREFINE = 1;\n tparams->SBSTRIPS = 1;\n tparams->SBDEFPIXEL = 0;\n tparams->SBCOMBOP = JBIG2_COMPOSE_OR;\n tparams->TRANSPOSED = 0;\n tparams->REFCORNER = JBIG2_CORNER_TOPLEFT;\n tparams->SBDSOFFSET = 0;\n tparams->SBRTEMPLATE = params->SDRTEMPLATE;\n }\n tparams->SBNUMINSTANCES = REFAGGNINST;\n\n image = jbig2_image_new(ctx, SYMWIDTH, HCHEIGHT);\n if (image == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory creating symbol image\");\n goto cleanup4;\n }\n\n /* multiple symbols are handled as a text region */\n jbig2_decode_text_region(ctx, segment, tparams, (const Jbig2SymbolDict * const *)refagg_dicts,\n n_refagg_dicts, image, data, size, GR_stats, as, ws);\n\n SDNEWSYMS->glyphs[NSYMSDECODED] = image;\n refagg_dicts[0]->glyphs[params->SDNUMINSYMS + NSYMSDECODED] = jbig2_image_clone(ctx, SDNEWSYMS->glyphs[NSYMSDECODED]);\n } else {\n /* 6.5.8.2.2 */\n /* bool SBHUFF = params->SDHUFF; */\n Jbig2RefinementRegionParams rparams;\n Jbig2Image *image;\n uint32_t ID;\n int32_t RDX, RDY;\n int BMSIZE = 0;\n uint32_t ninsyms = params->SDNUMINSYMS;\n int code1 = 0;\n int code2 = 0;\n int code3 = 0;\n int code4 = 0;\n\n /* 6.5.8.2.2 (2, 3, 4, 5) */\n if (params->SDHUFF) {\n ID = jbig2_huffman_get_bits(hs, SBSYMCODELEN, &code4);\n RDX = jbig2_huffman_get(hs, SDHUFFRDX, &code1);\n RDY = jbig2_huffman_get(hs, SDHUFFRDX, &code2);\n BMSIZE = jbig2_huffman_get(hs, SBHUFFRSIZE, &code3);\n jbig2_huffman_skip(hs);\n } else {\n code1 = jbig2_arith_iaid_decode(IAID, as, (int32_t *) & ID);\n code2 = jbig2_arith_int_decode(IARDX, as, &RDX);\n code3 = jbig2_arith_int_decode(IARDY, as, &RDY);\n }\n\n if ((code1 < 0) || (code2 < 0) || (code3 < 0) || (code4 < 0)) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to decode data\");\n goto cleanup4;\n }\n\n if (ID >= ninsyms + NSYMSDECODED) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"refinement references unknown symbol %d\", ID);\n goto cleanup4;\n }\n\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number,\n \"symbol is a refinement of id %d with the \" \"refinement applied at (%d,%d)\", ID, RDX, RDY);\n\n image = jbig2_image_new(ctx, SYMWIDTH, HCHEIGHT);\n if (image == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory creating symbol image\");\n goto cleanup4;\n }\n\n /* Table 18 */\n rparams.GRTEMPLATE = params->SDRTEMPLATE;\n rparams.reference = (ID < ninsyms) ? params->SDINSYMS->glyphs[ID] : SDNEWSYMS->glyphs[ID - ninsyms];\n /* SumatraPDF: fail on missing glyphs */\n if (rparams.reference == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"missing glyph %d/%d!\", ID, ninsyms);\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n rparams.DX = RDX;\n rparams.DY = RDY;\n rparams.TPGRON = 0;\n memcpy(rparams.grat, params->sdrat, 4);\n code = jbig2_decode_refinement_region(ctx, segment, &rparams, as, image, GR_stats);\n if (code < 0)\n goto cleanup4;\n\n SDNEWSYMS->glyphs[NSYMSDECODED] = image;\n\n /* 6.5.8.2.2 (7) */\n if (params->SDHUFF) {\n if (BMSIZE == 0)\n BMSIZE = image->height * image->stride;\n jbig2_huffman_advance(hs, BMSIZE);\n }\n }\n }\n\n#ifdef OUTPUT_PBM\n {\n char name[64];\n FILE *out;\n\n snprintf(name, 64, \"sd.%04d.%04d.pbm\", segment->number, NSYMSDECODED);\n out = fopen(name, \"wb\");\n jbig2_image_write_pbm(SDNEWSYMS->glyphs[NSYMSDECODED], out);\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"writing out glyph as '%s' ...\", name);\n fclose(out);\n }\n#endif\n\n }\n\n /* 6.5.5 (4c.iii) */\n if (params->SDHUFF && !params->SDREFAGG) {\n SDNEWSYMWIDTHS[NSYMSDECODED] = SYMWIDTH;\n }\n\n /* 6.5.5 (4c.iv) */\n NSYMSDECODED = NSYMSDECODED + 1;\n\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"decoded symbol %u of %u (%ux%u)\", NSYMSDECODED, params->SDNUMNEWSYMS, SYMWIDTH, HCHEIGHT);\n\n } /* end height class decode loop */\n\n /* 6.5.5 (4d) */\n if (params->SDHUFF && !params->SDREFAGG) {\n /* 6.5.9 */\n Jbig2Image *image;\n uint32_t BMSIZE = jbig2_huffman_get(hs, params->SDHUFFBMSIZE, &code);\n uint32_t j;\n int x;\n\n if (code) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"error decoding size of collective bitmap!\");\n goto cleanup4;\n }\n\n /* skip any bits before the next byte boundary */\n jbig2_huffman_skip(hs);\n\n image = jbig2_image_new(ctx, TOTWIDTH, HCHEIGHT);\n if (image == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"could not allocate collective bitmap image!\");\n goto cleanup4;\n }\n\n if (BMSIZE == 0) {\n /* if BMSIZE == 0 bitmap is uncompressed */\n const byte *src = data + jbig2_huffman_offset(hs);\n const int stride = (image->width >> 3) + ((image->width & 7) ? 1 : 0);\n byte *dst = image->data;\n\n /* SumatraPDF: prevent read access violation */\n if (size - jbig2_huffman_offset(hs) < image->height * stride) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"not enough data for decoding (%d/%d)\", image->height * stride,\n size - jbig2_huffman_offset(hs));\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n\n BMSIZE = image->height * stride;\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number,\n \"reading %dx%d uncompressed bitmap\" \" for %d symbols (%d bytes)\", image->width, image->height, NSYMSDECODED - HCFIRSTSYM, BMSIZE);\n\n for (j = 0; j < image->height; j++) {\n memcpy(dst, src, stride);\n dst += image->stride;\n src += stride;\n }\n } else {\n Jbig2GenericRegionParams rparams;\n\n /* SumatraPDF: prevent read access violation */\n if (size - jbig2_huffman_offset(hs) < BMSIZE) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"not enough data for decoding (%d/%d)\", BMSIZE, size - jbig2_huffman_offset(hs));\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number,\n \"reading %dx%d collective bitmap for %d symbols (%d bytes)\", image->width, image->height, NSYMSDECODED - HCFIRSTSYM, BMSIZE);\n\n rparams.MMR = 1;\n code = jbig2_decode_generic_mmr(ctx, segment, &rparams, data + jbig2_huffman_offset(hs), BMSIZE, image);\n if (code) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"error decoding MMR bitmap image!\");\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n }\n\n /* advance past the data we've just read */\n jbig2_huffman_advance(hs, BMSIZE);\n\n /* copy the collective bitmap into the symbol dictionary */\n x = 0;\n for (j = HCFIRSTSYM; j < NSYMSDECODED; j++) {\n Jbig2Image *glyph;\n\n glyph = jbig2_image_new(ctx, SDNEWSYMWIDTHS[j], HCHEIGHT);\n if (glyph == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to copy the collective bitmap into symbol dictionary\");\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n jbig2_image_compose(ctx, glyph, image, -x, 0, JBIG2_COMPOSE_REPLACE);\n x += SDNEWSYMWIDTHS[j];\n SDNEWSYMS->glyphs[j] = glyph;\n }\n jbig2_image_release(ctx, image);\n }\n\n } /* end of symbol decode loop */\n\n /* 6.5.10 */\n SDEXSYMS = jbig2_sd_new(ctx, params->SDNUMEXSYMS);\n if (SDEXSYMS == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to allocate symbols exported from symbols dictionary\");\n goto cleanup4;\n } else {\n uint32_t i = 0;\n uint32_t j = 0;\n uint32_t k;\n int exflag = 0;\n uint32_t limit = params->SDNUMINSYMS + params->SDNUMNEWSYMS;\n uint32_t exrunlength;\n int zerolength = 0;\n\n while (i < limit) {\n if (params->SDHUFF)\n exrunlength = jbig2_huffman_get(hs, SBHUFFRSIZE, &code);\n else\n code = jbig2_arith_int_decode(IAEX, as, (int32_t *)&exrunlength);\n /* prevent infinite loop */\n zerolength = exrunlength > 0 ? 0 : zerolength + 1;\n if (code || (exrunlength > limit - i) || (zerolength > 4) || (exflag && (exrunlength + j > params->SDNUMEXSYMS))) {\n if (code)\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to decode exrunlength for exported symbols\");\n else if (exrunlength <= 0)\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"runlength too small in export symbol table (%d <= 0)\\n\", exrunlength);\n else\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number,\n \"runlength too large in export symbol table (%d > %d - %d)\\n\", exrunlength, params->SDNUMEXSYMS, j);\n /* skip to the cleanup code and return SDEXSYMS = NULL */\n jbig2_sd_release(ctx, SDEXSYMS);\n SDEXSYMS = NULL;\n break;\n }\n for (k = 0; k < exrunlength; k++) {\n if (exflag) {\n SDEXSYMS->glyphs[j++] = (i < params->SDNUMINSYMS) ?\n jbig2_image_clone(ctx, params->SDINSYMS->glyphs[i]) : jbig2_image_clone(ctx, SDNEWSYMS->glyphs[i - params->SDNUMINSYMS]);\n }\n i++;\n }\n exflag = !exflag;\n }\n }\n\ncleanup4:\n if (tparams != NULL) {\n if (!params->SDHUFF) {\n jbig2_arith_int_ctx_free(ctx, tparams->IADT);\n jbig2_arith_int_ctx_free(ctx, tparams->IAFS);\n jbig2_arith_int_ctx_free(ctx, tparams->IADS);\n jbig2_arith_int_ctx_free(ctx, tparams->IAIT);\n jbig2_arith_iaid_ctx_free(ctx, tparams->IAID);\n jbig2_arith_int_ctx_free(ctx, tparams->IARI);\n jbig2_arith_int_ctx_free(ctx, tparams->IARDW);\n jbig2_arith_int_ctx_free(ctx, tparams->IARDH);\n jbig2_arith_int_ctx_free(ctx, tparams->IARDX);\n jbig2_arith_int_ctx_free(ctx, tparams->IARDY);\n } else {\n jbig2_release_huffman_table(ctx, tparams->SBHUFFFS);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFDS);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFDT);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFRDX);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFRDY);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFRDW);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFRDH);\n }\n jbig2_free(ctx->allocator, tparams);\n }\n if (refagg_dicts != NULL) {\n jbig2_sd_release(ctx, refagg_dicts[0]);\n jbig2_free(ctx->allocator, refagg_dicts);\n }\n\ncleanup2:\n jbig2_sd_release(ctx, SDNEWSYMS);\n if (params->SDHUFF && !params->SDREFAGG) {\n jbig2_free(ctx->allocator, SDNEWSYMWIDTHS);\n }\n jbig2_release_huffman_table(ctx, SDHUFFRDX);\n jbig2_release_huffman_table(ctx, SBHUFFRSIZE);\n jbig2_huffman_free(ctx, hs);\n jbig2_arith_iaid_ctx_free(ctx, IAID);\n jbig2_arith_int_ctx_free(ctx, IARDX);\n jbig2_arith_int_ctx_free(ctx, IARDY);\n\ncleanup1:\n jbig2_word_stream_buf_free(ctx, ws);\n jbig2_free(ctx->allocator, as);\n jbig2_arith_int_ctx_free(ctx, IADH);\n jbig2_arith_int_ctx_free(ctx, IADW);\n jbig2_arith_int_ctx_free(ctx, IAEX);\n jbig2_arith_int_ctx_free(ctx, IAAI);\n\n return SDEXSYMS;\n}", "project": "ghostpdl", "hash": 151781195134694545420505614324781028208, "size": 568, "commit_id": "b184e783702246e154294326d03d9abda669fcfa", "message": "Bug 697703: Prevent integer overflow vulnerability.\n\nAdd extra check for the offset being greater than the size\nof the image and hence reading off the end of the buffer.\n\nThank you to Dai Ge for finding this issue and suggesting a patch.", "target": 1, "dataset": "other", "idx": 202890} {"func": "jbig2_decode_symbol_dict(Jbig2Ctx *ctx,\n Jbig2Segment *segment,\n const Jbig2SymbolDictParams *params, const byte *data, size_t size, Jbig2ArithCx *GB_stats, Jbig2ArithCx *GR_stats)\n{\n Jbig2SymbolDict *SDNEWSYMS = NULL;\n Jbig2SymbolDict *SDEXSYMS = NULL;\n uint32_t HCHEIGHT;\n uint32_t NSYMSDECODED;\n uint32_t SYMWIDTH, TOTWIDTH;\n uint32_t HCFIRSTSYM;\n uint32_t *SDNEWSYMWIDTHS = NULL;\n int SBSYMCODELEN = 0;\n Jbig2WordStream *ws = NULL;\n Jbig2HuffmanState *hs = NULL;\n Jbig2HuffmanTable *SDHUFFRDX = NULL;\n Jbig2HuffmanTable *SBHUFFRSIZE = NULL;\n Jbig2ArithState *as = NULL;\n Jbig2ArithIntCtx *IADH = NULL;\n Jbig2ArithIntCtx *IADW = NULL;\n Jbig2ArithIntCtx *IAEX = NULL;\n Jbig2ArithIntCtx *IAAI = NULL;\n Jbig2ArithIaidCtx *IAID = NULL;\n Jbig2ArithIntCtx *IARDX = NULL;\n Jbig2ArithIntCtx *IARDY = NULL;\n int code = 0;\n Jbig2SymbolDict **refagg_dicts = NULL;\n int n_refagg_dicts = 1;\n\n Jbig2TextRegionParams *tparams = NULL;\n\n /* 6.5.5 (3) */\n HCHEIGHT = 0;\n NSYMSDECODED = 0;\n\n ws = jbig2_word_stream_buf_new(ctx, data, size);\n if (ws == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate ws in jbig2_decode_symbol_dict\");\n return NULL;\n }\n\n as = jbig2_arith_new(ctx, ws);\n if (as == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate as in jbig2_decode_symbol_dict\");\n jbig2_word_stream_buf_free(ctx, ws);\n return NULL;\n }\n\n if (!params->SDHUFF) {\n IADH = jbig2_arith_int_ctx_new(ctx);\n IADW = jbig2_arith_int_ctx_new(ctx);\n IAEX = jbig2_arith_int_ctx_new(ctx);\n IAAI = jbig2_arith_int_ctx_new(ctx);\n if ((IADH == NULL) || (IADW == NULL) || (IAEX == NULL) || (IAAI == NULL)) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate storage for symbol bitmap\");\n goto cleanup1;\n }\n if (params->SDREFAGG) {\n int64_t tmp = params->SDNUMINSYMS + params->SDNUMNEWSYMS;\n\n for (SBSYMCODELEN = 0; ((int64_t) 1 << SBSYMCODELEN) < tmp; SBSYMCODELEN++);\n IAID = jbig2_arith_iaid_ctx_new(ctx, SBSYMCODELEN);\n IARDX = jbig2_arith_int_ctx_new(ctx);\n IARDY = jbig2_arith_int_ctx_new(ctx);\n if ((IAID == NULL) || (IARDX == NULL) || (IARDY == NULL)) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate storage for symbol bitmap\");\n goto cleanup2;\n }\n }\n } else {\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"huffman coded symbol dictionary\");\n hs = jbig2_huffman_new(ctx, ws);\n SDHUFFRDX = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O);\n SBHUFFRSIZE = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_A);\n if ((hs == NULL) || (SDHUFFRDX == NULL) || (SBHUFFRSIZE == NULL)) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"failed to allocate storage for symbol bitmap\");\n goto cleanup2;\n }\n if (!params->SDREFAGG) {\n SDNEWSYMWIDTHS = jbig2_new(ctx, uint32_t, params->SDNUMNEWSYMS);\n if (SDNEWSYMWIDTHS == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"could not allocate storage for (%u) symbol widths\", params->SDNUMNEWSYMS);\n goto cleanup2;\n }\n }\n }\n\n SDNEWSYMS = jbig2_sd_new(ctx, params->SDNUMNEWSYMS);\n if (SDNEWSYMS == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"could not allocate storage for (%u) new symbols\", params->SDNUMNEWSYMS);\n goto cleanup2;\n }\n\n /* 6.5.5 (4a) */\n while (NSYMSDECODED < params->SDNUMNEWSYMS) {\n int32_t HCDH, DW;\n\n /* 6.5.6 */\n if (params->SDHUFF) {\n HCDH = jbig2_huffman_get(hs, params->SDHUFFDH, &code);\n } else {\n code = jbig2_arith_int_decode(IADH, as, &HCDH);\n }\n\n if (code != 0) {\n jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, \"error or OOB decoding height class delta (%d)\\n\", code);\n }\n\n if (!params->SDHUFF && jbig2_arith_has_reached_marker(as)) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"prevent DOS while decoding height classes\");\n goto cleanup2;\n }\n\n /* 6.5.5 (4b) */\n HCHEIGHT = HCHEIGHT + HCDH;\n SYMWIDTH = 0;\n TOTWIDTH = 0;\n HCFIRSTSYM = NSYMSDECODED;\n\n if ((int32_t) HCHEIGHT < 0) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Invalid HCHEIGHT value\");\n goto cleanup2;\n }\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"HCHEIGHT = %d\", HCHEIGHT);\n#endif\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"decoding height class %d with %d syms decoded\", HCHEIGHT, NSYMSDECODED);\n\n for (;;) {\n /* 6.5.7 */\n if (params->SDHUFF) {\n DW = jbig2_huffman_get(hs, params->SDHUFFDW, &code);\n } else {\n code = jbig2_arith_int_decode(IADW, as, &DW);\n }\n if (code < 0)\n goto cleanup4;\n\n /* 6.5.5 (4c.i) */\n if (code == 1) {\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \" OOB signals end of height class %d\", HCHEIGHT);\n break;\n }\n\n /* check for broken symbol table */\n if (NSYMSDECODED >= params->SDNUMNEWSYMS) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"No OOB signalling end of height class %d\", HCHEIGHT);\n goto cleanup4;\n }\n\n SYMWIDTH = SYMWIDTH + DW;\n TOTWIDTH = TOTWIDTH + SYMWIDTH;\n if ((int32_t) SYMWIDTH < 0) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Invalid SYMWIDTH value (%d) at symbol %d\", SYMWIDTH, NSYMSDECODED + 1);\n goto cleanup4;\n }\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"SYMWIDTH = %d TOTWIDTH = %d\", SYMWIDTH, TOTWIDTH);\n#endif\n /* 6.5.5 (4c.ii) */\n if (!params->SDHUFF || params->SDREFAGG) {\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"SDHUFF = %d; SDREFAGG = %d\", params->SDHUFF, params->SDREFAGG);\n#endif\n /* 6.5.8 */\n if (!params->SDREFAGG) {\n Jbig2GenericRegionParams region_params;\n int sdat_bytes;\n Jbig2Image *image;\n\n /* Table 16 */\n region_params.MMR = 0;\n region_params.GBTEMPLATE = params->SDTEMPLATE;\n region_params.TPGDON = 0;\n region_params.USESKIP = 0;\n sdat_bytes = params->SDTEMPLATE == 0 ? 8 : 2;\n memcpy(region_params.gbat, params->sdat, sdat_bytes);\n\n image = jbig2_image_new(ctx, SYMWIDTH, HCHEIGHT);\n if (image == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to allocate image in jbig2_decode_symbol_dict\");\n goto cleanup4;\n }\n\n code = jbig2_decode_generic_region(ctx, segment, ®ion_params, as, image, GB_stats);\n if (code < 0) {\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n\n SDNEWSYMS->glyphs[NSYMSDECODED] = image;\n } else {\n /* 6.5.8.2 refinement/aggregate symbol */\n uint32_t REFAGGNINST;\n\n if (params->SDHUFF) {\n REFAGGNINST = jbig2_huffman_get(hs, params->SDHUFFAGGINST, &code);\n } else {\n code = jbig2_arith_int_decode(IAAI, as, (int32_t *) & REFAGGNINST);\n }\n if (code || (int32_t) REFAGGNINST <= 0) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"invalid number of symbols or OOB in aggregate glyph\");\n goto cleanup4;\n }\n\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"aggregate symbol coding (%d instances)\", REFAGGNINST);\n\n if (REFAGGNINST > 1) {\n Jbig2Image *image;\n uint32_t i;\n\n if (tparams == NULL) {\n /* First time through, we need to initialise the */\n /* various tables for Huffman or adaptive encoding */\n /* as well as the text region parameters structure */\n refagg_dicts = jbig2_new(ctx, Jbig2SymbolDict *, n_refagg_dicts);\n if (refagg_dicts == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory allocating dictionary array\");\n goto cleanup4;\n }\n refagg_dicts[0] = jbig2_sd_new(ctx, params->SDNUMINSYMS + params->SDNUMNEWSYMS);\n if (refagg_dicts[0] == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory allocating symbol dictionary\");\n jbig2_free(ctx->allocator, refagg_dicts);\n goto cleanup4;\n }\n for (i = 0; i < params->SDNUMINSYMS; i++) {\n refagg_dicts[0]->glyphs[i] = jbig2_image_clone(ctx, params->SDINSYMS->glyphs[i]);\n }\n\n tparams = jbig2_new(ctx, Jbig2TextRegionParams, 1);\n if (tparams == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory creating text region params\");\n goto cleanup4;\n }\n if (!params->SDHUFF) {\n /* Values from Table 17, section 6.5.8.2 (2) */\n tparams->IADT = jbig2_arith_int_ctx_new(ctx);\n tparams->IAFS = jbig2_arith_int_ctx_new(ctx);\n tparams->IADS = jbig2_arith_int_ctx_new(ctx);\n tparams->IAIT = jbig2_arith_int_ctx_new(ctx);\n /* Table 31 */\n for (SBSYMCODELEN = 0; (1 << SBSYMCODELEN) < (int)(params->SDNUMINSYMS + params->SDNUMNEWSYMS); SBSYMCODELEN++);\n tparams->IAID = jbig2_arith_iaid_ctx_new(ctx, SBSYMCODELEN);\n tparams->IARI = jbig2_arith_int_ctx_new(ctx);\n tparams->IARDW = jbig2_arith_int_ctx_new(ctx);\n tparams->IARDH = jbig2_arith_int_ctx_new(ctx);\n tparams->IARDX = jbig2_arith_int_ctx_new(ctx);\n tparams->IARDY = jbig2_arith_int_ctx_new(ctx);\n } else {\n tparams->SBHUFFFS = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_F); /* Table B.6 */\n tparams->SBHUFFDS = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_H); /* Table B.8 */\n tparams->SBHUFFDT = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_K); /* Table B.11 */\n tparams->SBHUFFRDW = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O); /* Table B.15 */\n tparams->SBHUFFRDH = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O); /* Table B.15 */\n tparams->SBHUFFRDX = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O); /* Table B.15 */\n tparams->SBHUFFRDY = jbig2_build_huffman_table(ctx, &jbig2_huffman_params_O); /* Table B.15 */\n }\n tparams->SBHUFF = params->SDHUFF;\n tparams->SBREFINE = 1;\n tparams->SBSTRIPS = 1;\n tparams->SBDEFPIXEL = 0;\n tparams->SBCOMBOP = JBIG2_COMPOSE_OR;\n tparams->TRANSPOSED = 0;\n tparams->REFCORNER = JBIG2_CORNER_TOPLEFT;\n tparams->SBDSOFFSET = 0;\n tparams->SBRTEMPLATE = params->SDRTEMPLATE;\n }\n tparams->SBNUMINSTANCES = REFAGGNINST;\n\n image = jbig2_image_new(ctx, SYMWIDTH, HCHEIGHT);\n if (image == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory creating symbol image\");\n goto cleanup4;\n }\n\n /* multiple symbols are handled as a text region */\n jbig2_decode_text_region(ctx, segment, tparams, (const Jbig2SymbolDict * const *)refagg_dicts,\n n_refagg_dicts, image, data, size, GR_stats, as, ws);\n\n SDNEWSYMS->glyphs[NSYMSDECODED] = image;\n refagg_dicts[0]->glyphs[params->SDNUMINSYMS + NSYMSDECODED] = jbig2_image_clone(ctx, SDNEWSYMS->glyphs[NSYMSDECODED]);\n } else {\n /* 6.5.8.2.2 */\n /* bool SBHUFF = params->SDHUFF; */\n Jbig2RefinementRegionParams rparams;\n Jbig2Image *image;\n uint32_t ID;\n int32_t RDX, RDY;\n int BMSIZE = 0;\n uint32_t ninsyms = params->SDNUMINSYMS;\n int code1 = 0;\n int code2 = 0;\n int code3 = 0;\n int code4 = 0;\n\n /* 6.5.8.2.2 (2, 3, 4, 5) */\n if (params->SDHUFF) {\n ID = jbig2_huffman_get_bits(hs, SBSYMCODELEN, &code4);\n RDX = jbig2_huffman_get(hs, SDHUFFRDX, &code1);\n RDY = jbig2_huffman_get(hs, SDHUFFRDX, &code2);\n BMSIZE = jbig2_huffman_get(hs, SBHUFFRSIZE, &code3);\n jbig2_huffman_skip(hs);\n } else {\n code1 = jbig2_arith_iaid_decode(IAID, as, (int32_t *) & ID);\n code2 = jbig2_arith_int_decode(IARDX, as, &RDX);\n code3 = jbig2_arith_int_decode(IARDY, as, &RDY);\n }\n\n if ((code1 < 0) || (code2 < 0) || (code3 < 0) || (code4 < 0)) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to decode data\");\n goto cleanup4;\n }\n\n if (ID >= ninsyms + NSYMSDECODED) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"refinement references unknown symbol %d\", ID);\n goto cleanup4;\n }\n\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number,\n \"symbol is a refinement of id %d with the \" \"refinement applied at (%d,%d)\", ID, RDX, RDY);\n\n image = jbig2_image_new(ctx, SYMWIDTH, HCHEIGHT);\n if (image == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"Out of memory creating symbol image\");\n goto cleanup4;\n }\n\n /* Table 18 */\n rparams.GRTEMPLATE = params->SDRTEMPLATE;\n rparams.reference = (ID < ninsyms) ? params->SDINSYMS->glyphs[ID] : SDNEWSYMS->glyphs[ID - ninsyms];\n /* SumatraPDF: fail on missing glyphs */\n if (rparams.reference == NULL) {\n code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"missing glyph %d/%d!\", ID, ninsyms);\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n rparams.DX = RDX;\n rparams.DY = RDY;\n rparams.TPGRON = 0;\n memcpy(rparams.grat, params->sdrat, 4);\n code = jbig2_decode_refinement_region(ctx, segment, &rparams, as, image, GR_stats);\n if (code < 0)\n goto cleanup4;\n\n SDNEWSYMS->glyphs[NSYMSDECODED] = image;\n\n /* 6.5.8.2.2 (7) */\n if (params->SDHUFF) {\n if (BMSIZE == 0)\n BMSIZE = image->height * image->stride;\n jbig2_huffman_advance(hs, BMSIZE);\n }\n }\n }\n\n#ifdef OUTPUT_PBM\n {\n char name[64];\n FILE *out;\n\n snprintf(name, 64, \"sd.%04d.%04d.pbm\", segment->number, NSYMSDECODED);\n out = fopen(name, \"wb\");\n jbig2_image_write_pbm(SDNEWSYMS->glyphs[NSYMSDECODED], out);\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"writing out glyph as '%s' ...\", name);\n fclose(out);\n }\n#endif\n\n }\n\n /* 6.5.5 (4c.iii) */\n if (params->SDHUFF && !params->SDREFAGG) {\n SDNEWSYMWIDTHS[NSYMSDECODED] = SYMWIDTH;\n }\n\n /* 6.5.5 (4c.iv) */\n NSYMSDECODED = NSYMSDECODED + 1;\n\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, \"decoded symbol %u of %u (%ux%u)\", NSYMSDECODED, params->SDNUMNEWSYMS, SYMWIDTH, HCHEIGHT);\n\n } /* end height class decode loop */\n\n /* 6.5.5 (4d) */\n if (params->SDHUFF && !params->SDREFAGG) {\n /* 6.5.9 */\n Jbig2Image *image;\n uint32_t BMSIZE = jbig2_huffman_get(hs, params->SDHUFFBMSIZE, &code);\n uint32_t j;\n int x;\n\n if (code) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"error decoding size of collective bitmap!\");\n goto cleanup4;\n }\n\n /* skip any bits before the next byte boundary */\n jbig2_huffman_skip(hs);\n\n image = jbig2_image_new(ctx, TOTWIDTH, HCHEIGHT);\n if (image == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"could not allocate collective bitmap image!\");\n goto cleanup4;\n }\n\n if (BMSIZE == 0) {\n /* if BMSIZE == 0 bitmap is uncompressed */\n const byte *src = data + jbig2_huffman_offset(hs);\n const int stride = (image->width >> 3) + ((image->width & 7) ? 1 : 0);\n byte *dst = image->data;\n\n /* SumatraPDF: prevent read access violation */\n if ((size - jbig2_huffman_offset(hs) < image->height * stride) || (size < jbig2_huffman_offset(hs))) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"not enough data for decoding (%d/%d)\", image->height * stride,\n size - jbig2_huffman_offset(hs));\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n\n BMSIZE = image->height * stride;\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number,\n \"reading %dx%d uncompressed bitmap\" \" for %d symbols (%d bytes)\", image->width, image->height, NSYMSDECODED - HCFIRSTSYM, BMSIZE);\n\n for (j = 0; j < image->height; j++) {\n memcpy(dst, src, stride);\n dst += image->stride;\n src += stride;\n }\n } else {\n Jbig2GenericRegionParams rparams;\n\n /* SumatraPDF: prevent read access violation */\n if (size - jbig2_huffman_offset(hs) < BMSIZE) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"not enough data for decoding (%d/%d)\", BMSIZE, size - jbig2_huffman_offset(hs));\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number,\n \"reading %dx%d collective bitmap for %d symbols (%d bytes)\", image->width, image->height, NSYMSDECODED - HCFIRSTSYM, BMSIZE);\n\n rparams.MMR = 1;\n code = jbig2_decode_generic_mmr(ctx, segment, &rparams, data + jbig2_huffman_offset(hs), BMSIZE, image);\n if (code) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"error decoding MMR bitmap image!\");\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n }\n\n /* advance past the data we've just read */\n jbig2_huffman_advance(hs, BMSIZE);\n\n /* copy the collective bitmap into the symbol dictionary */\n x = 0;\n for (j = HCFIRSTSYM; j < NSYMSDECODED; j++) {\n Jbig2Image *glyph;\n\n glyph = jbig2_image_new(ctx, SDNEWSYMWIDTHS[j], HCHEIGHT);\n if (glyph == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to copy the collective bitmap into symbol dictionary\");\n jbig2_image_release(ctx, image);\n goto cleanup4;\n }\n jbig2_image_compose(ctx, glyph, image, -x, 0, JBIG2_COMPOSE_REPLACE);\n x += SDNEWSYMWIDTHS[j];\n SDNEWSYMS->glyphs[j] = glyph;\n }\n jbig2_image_release(ctx, image);\n }\n\n } /* end of symbol decode loop */\n\n /* 6.5.10 */\n SDEXSYMS = jbig2_sd_new(ctx, params->SDNUMEXSYMS);\n if (SDEXSYMS == NULL) {\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to allocate symbols exported from symbols dictionary\");\n goto cleanup4;\n } else {\n uint32_t i = 0;\n uint32_t j = 0;\n uint32_t k;\n int exflag = 0;\n uint32_t limit = params->SDNUMINSYMS + params->SDNUMNEWSYMS;\n uint32_t exrunlength;\n int zerolength = 0;\n\n while (i < limit) {\n if (params->SDHUFF)\n exrunlength = jbig2_huffman_get(hs, SBHUFFRSIZE, &code);\n else\n code = jbig2_arith_int_decode(IAEX, as, (int32_t *)&exrunlength);\n /* prevent infinite loop */\n zerolength = exrunlength > 0 ? 0 : zerolength + 1;\n if (code || (exrunlength > limit - i) || (zerolength > 4) || (exflag && (exrunlength + j > params->SDNUMEXSYMS))) {\n if (code)\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"failed to decode exrunlength for exported symbols\");\n else if (exrunlength <= 0)\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, \"runlength too small in export symbol table (%d <= 0)\\n\", exrunlength);\n else\n jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number,\n \"runlength too large in export symbol table (%d > %d - %d)\\n\", exrunlength, params->SDNUMEXSYMS, j);\n /* skip to the cleanup code and return SDEXSYMS = NULL */\n jbig2_sd_release(ctx, SDEXSYMS);\n SDEXSYMS = NULL;\n break;\n }\n for (k = 0; k < exrunlength; k++) {\n if (exflag) {\n SDEXSYMS->glyphs[j++] = (i < params->SDNUMINSYMS) ?\n jbig2_image_clone(ctx, params->SDINSYMS->glyphs[i]) : jbig2_image_clone(ctx, SDNEWSYMS->glyphs[i - params->SDNUMINSYMS]);\n }\n i++;\n }\n exflag = !exflag;\n }\n }\n\ncleanup4:\n if (tparams != NULL) {\n if (!params->SDHUFF) {\n jbig2_arith_int_ctx_free(ctx, tparams->IADT);\n jbig2_arith_int_ctx_free(ctx, tparams->IAFS);\n jbig2_arith_int_ctx_free(ctx, tparams->IADS);\n jbig2_arith_int_ctx_free(ctx, tparams->IAIT);\n jbig2_arith_iaid_ctx_free(ctx, tparams->IAID);\n jbig2_arith_int_ctx_free(ctx, tparams->IARI);\n jbig2_arith_int_ctx_free(ctx, tparams->IARDW);\n jbig2_arith_int_ctx_free(ctx, tparams->IARDH);\n jbig2_arith_int_ctx_free(ctx, tparams->IARDX);\n jbig2_arith_int_ctx_free(ctx, tparams->IARDY);\n } else {\n jbig2_release_huffman_table(ctx, tparams->SBHUFFFS);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFDS);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFDT);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFRDX);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFRDY);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFRDW);\n jbig2_release_huffman_table(ctx, tparams->SBHUFFRDH);\n }\n jbig2_free(ctx->allocator, tparams);\n }\n if (refagg_dicts != NULL) {\n jbig2_sd_release(ctx, refagg_dicts[0]);\n jbig2_free(ctx->allocator, refagg_dicts);\n }\n\ncleanup2:\n jbig2_sd_release(ctx, SDNEWSYMS);\n if (params->SDHUFF && !params->SDREFAGG) {\n jbig2_free(ctx->allocator, SDNEWSYMWIDTHS);\n }\n jbig2_release_huffman_table(ctx, SDHUFFRDX);\n jbig2_release_huffman_table(ctx, SBHUFFRSIZE);\n jbig2_huffman_free(ctx, hs);\n jbig2_arith_iaid_ctx_free(ctx, IAID);\n jbig2_arith_int_ctx_free(ctx, IARDX);\n jbig2_arith_int_ctx_free(ctx, IARDY);\n\ncleanup1:\n jbig2_word_stream_buf_free(ctx, ws);\n jbig2_free(ctx->allocator, as);\n jbig2_arith_int_ctx_free(ctx, IADH);\n jbig2_arith_int_ctx_free(ctx, IADW);\n jbig2_arith_int_ctx_free(ctx, IAEX);\n jbig2_arith_int_ctx_free(ctx, IAAI);\n\n return SDEXSYMS;\n}", "project": "ghostpdl", "hash": 263544315846066824825119697673339734069, "size": 568, "commit_id": "b184e783702246e154294326d03d9abda669fcfa", "message": "Bug 697703: Prevent integer overflow vulnerability.\n\nAdd extra check for the offset being greater than the size\nof the image and hence reading off the end of the buffer.\n\nThank you to Dai Ge for finding this issue and suggesting a patch.", "target": 0, "dataset": "other", "idx": 343184} {"func": "static struct kvm_vcpu_hv_synic *synic_get(struct kvm *kvm, u32 vpidx)\n{\n\tstruct kvm_vcpu *vcpu;\n\tstruct kvm_vcpu_hv_synic *synic;\n\n\tvcpu = get_vcpu_by_vpidx(kvm, vpidx);\n\tif (!vcpu)\n\t\treturn NULL;\n\tsynic = to_hv_synic(vcpu);\n\treturn (synic->active) ? synic : NULL;\n}", "project": "linux", "hash": 276482777374283635842814384243075236447, "size": 11, "commit_id": "919f4ebc598701670e80e31573a58f1f2d2bf918", "message": "KVM: x86: hyper-v: Fix Hyper-V context null-ptr-deref\n\nReported by syzkaller:\n\n KASAN: null-ptr-deref in range [0x0000000000000140-0x0000000000000147]\n CPU: 1 PID: 8370 Comm: syz-executor859 Not tainted 5.11.0-syzkaller #0\n RIP: 0010:synic_get arch/x86/kvm/hyperv.c:165 [inline]\n RIP: 0010:kvm_hv_set_sint_gsi arch/x86/kvm/hyperv.c:475 [inline]\n RIP: 0010:kvm_hv_irq_routing_update+0x230/0x460 arch/x86/kvm/hyperv.c:498\n Call Trace:\n kvm_set_irq_routing+0x69b/0x940 arch/x86/kvm/../../../virt/kvm/irqchip.c:223\n kvm_vm_ioctl+0x12d0/0x2800 arch/x86/kvm/../../../virt/kvm/kvm_main.c:3959\n vfs_ioctl fs/ioctl.c:48 [inline]\n __do_sys_ioctl fs/ioctl.c:753 [inline]\n __se_sys_ioctl fs/ioctl.c:739 [inline]\n __x64_sys_ioctl+0x193/0x200 fs/ioctl.c:739\n do_syscall_64+0x2d/0x70 arch/x86/entry/common.c:46\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nHyper-V context is lazily allocated until Hyper-V specific MSRs are accessed\nor SynIC is enabled. However, the syzkaller testcase sets irq routing table\ndirectly w/o enabling SynIC. This results in null-ptr-deref when accessing\nSynIC Hyper-V context. This patch fixes it.\n\nsyzkaller source: https://syzkaller.appspot.com/x/repro.c?x=163342ccd00000\n\nReported-by: syzbot+6987f3b2dbd9eda95f12@syzkaller.appspotmail.com\nFixes: 8f014550dfb1 (\"KVM: x86: hyper-v: Make Hyper-V emulation enablement conditional\")\nSigned-off-by: Wanpeng Li \nMessage-Id: <1614326399-5762-1-git-send-email-wanpengli@tencent.com>\nSigned-off-by: Paolo Bonzini ", "target": 1, "dataset": "other", "idx": 202898} {"func": "static struct kvm_vcpu_hv_synic *synic_get(struct kvm *kvm, u32 vpidx)\n{\n\tstruct kvm_vcpu *vcpu;\n\tstruct kvm_vcpu_hv_synic *synic;\n\n\tvcpu = get_vcpu_by_vpidx(kvm, vpidx);\n\tif (!vcpu || !to_hv_vcpu(vcpu))\n\t\treturn NULL;\n\tsynic = to_hv_synic(vcpu);\n\treturn (synic->active) ? synic : NULL;\n}", "project": "linux", "hash": 141367306392052616744625319702569801368, "size": 11, "commit_id": "919f4ebc598701670e80e31573a58f1f2d2bf918", "message": "KVM: x86: hyper-v: Fix Hyper-V context null-ptr-deref\n\nReported by syzkaller:\n\n KASAN: null-ptr-deref in range [0x0000000000000140-0x0000000000000147]\n CPU: 1 PID: 8370 Comm: syz-executor859 Not tainted 5.11.0-syzkaller #0\n RIP: 0010:synic_get arch/x86/kvm/hyperv.c:165 [inline]\n RIP: 0010:kvm_hv_set_sint_gsi arch/x86/kvm/hyperv.c:475 [inline]\n RIP: 0010:kvm_hv_irq_routing_update+0x230/0x460 arch/x86/kvm/hyperv.c:498\n Call Trace:\n kvm_set_irq_routing+0x69b/0x940 arch/x86/kvm/../../../virt/kvm/irqchip.c:223\n kvm_vm_ioctl+0x12d0/0x2800 arch/x86/kvm/../../../virt/kvm/kvm_main.c:3959\n vfs_ioctl fs/ioctl.c:48 [inline]\n __do_sys_ioctl fs/ioctl.c:753 [inline]\n __se_sys_ioctl fs/ioctl.c:739 [inline]\n __x64_sys_ioctl+0x193/0x200 fs/ioctl.c:739\n do_syscall_64+0x2d/0x70 arch/x86/entry/common.c:46\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nHyper-V context is lazily allocated until Hyper-V specific MSRs are accessed\nor SynIC is enabled. However, the syzkaller testcase sets irq routing table\ndirectly w/o enabling SynIC. This results in null-ptr-deref when accessing\nSynIC Hyper-V context. This patch fixes it.\n\nsyzkaller source: https://syzkaller.appspot.com/x/repro.c?x=163342ccd00000\n\nReported-by: syzbot+6987f3b2dbd9eda95f12@syzkaller.appspotmail.com\nFixes: 8f014550dfb1 (\"KVM: x86: hyper-v: Make Hyper-V emulation enablement conditional\")\nSigned-off-by: Wanpeng Li \nMessage-Id: <1614326399-5762-1-git-send-email-wanpengli@tencent.com>\nSigned-off-by: Paolo Bonzini ", "target": 0, "dataset": "other", "idx": 343525} {"func": "int ssh_buffer_add_data(struct ssh_buffer_struct *buffer, const void *data, uint32_t len)\n{\n buffer_verify(buffer);\n\n if (data == NULL) {\n return -1;\n }\n\n if (buffer->used + len < len) {\n return -1;\n }\n\n if (buffer->allocated < (buffer->used + len)) {\n if(buffer->pos > 0)\n buffer_shift(buffer);\n if (realloc_buffer(buffer, buffer->used + len) < 0) {\n return -1;\n }\n }\n\n memcpy(buffer->data+buffer->used, data, len);\n buffer->used+=len;\n buffer_verify(buffer);\n return 0;\n}", "project": "libssh-mirror", "hash": 245892501454401043574922830759233496776, "size": 25, "commit_id": "10b3ebbe61a7031a3dae97f05834442220447181", "message": "buffer: Reformat ssh_buffer_add_data()\n\nSigned-off-by: Andreas Schneider \nReviewed-by: Anderson Toshiyuki Sasaki \nReviewed-by: Jakub Jelen ", "target": 1, "dataset": "other", "idx": 203616} {"func": "void *ssh_buffer_allocate(struct ssh_buffer_struct *buffer, uint32_t len)\n{\n void *ptr;\n buffer_verify(buffer);\n\n if (buffer->used + len < len) {\n return NULL;\n }\n\n if (buffer->allocated < (buffer->used + len)) {\n if (buffer->pos > 0) {\n buffer_shift(buffer);\n }\n\n if (realloc_buffer(buffer, buffer->used + len) < 0) {\n return NULL;\n }\n }\n\n ptr = buffer->data + buffer->used;\n buffer->used+=len;\n buffer_verify(buffer);\n\n return ptr;\n}", "project": "libssh-mirror", "hash": 213736684976097276551610086730047123660, "size": 25, "commit_id": "10b3ebbe61a7031a3dae97f05834442220447181", "message": "buffer: Reformat ssh_buffer_add_data()\n\nSigned-off-by: Andreas Schneider \nReviewed-by: Anderson Toshiyuki Sasaki \nReviewed-by: Jakub Jelen ", "target": 0, "dataset": "other", "idx": 345161} {"func": "static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)\n{\n struct usbdevfs_urb *urb;\n AsyncURB *aurb;\n int ret, value, index;\n\n /* \n * Process certain standard device requests.\n * These are infrequent and are processed synchronously.\n */\n value = le16_to_cpu(s->ctrl.req.wValue);\n index = le16_to_cpu(s->ctrl.req.wIndex);\n\n dprintf(\"husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\\n\",\n s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index, \n s->ctrl.len);\n\n if (s->ctrl.req.bRequestType == 0) {\n switch (s->ctrl.req.bRequest) {\n case USB_REQ_SET_ADDRESS:\n return usb_host_set_address(s, value);\n\n case USB_REQ_SET_CONFIGURATION:\n return usb_host_set_config(s, value & 0xff);\n }\n }\n\n if (s->ctrl.req.bRequestType == 1 &&\n s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE)\n return usb_host_set_interface(s, index, value);\n\n /* The rest are asynchronous */\n\n aurb = async_alloc();\n aurb->hdev = s;\n aurb->packet = p;\n\n /* \n * Setup ctrl transfer.\n *\n * s->ctrl is layed out such that data buffer immediately follows\n * 'req' struct which is exactly what usbdevfs expects.\n */ \n urb = &aurb->urb;\n\n urb->type = USBDEVFS_URB_TYPE_CONTROL;\n urb->endpoint = p->devep;\n\n urb->buffer = &s->ctrl.req;\n urb->buffer_length = 8 + s->ctrl.len;\n\n urb->usercontext = s;\n\n ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);\n\n dprintf(\"husb: submit ctrl. len %u aurb %p\\n\", urb->buffer_length, aurb);\n\n if (ret < 0) {\n dprintf(\"husb: submit failed. errno %d\\n\", errno);\n async_free(aurb);\n\n switch(errno) {\n case ETIMEDOUT:\n return USB_RET_NAK;\n case EPIPE:\n default:\n return USB_RET_STALL;\n }\n }\n\n usb_defer_packet(p, async_cancel, aurb);\n return USB_RET_ASYNC;\n}", "project": "qemu", "hash": 312416163750000928776897162836846138475, "size": 73, "commit_id": "babd03fde68093482528010a5435c14ce9128e3f", "message": "usb-linux.c: fix buffer overflow\n\nIn usb-linux.c:usb_host_handle_control, we pass a 1024-byte buffer and\nlength to the kernel. However, the length was provided by the caller\nof dev->handle_packet, and is not checked, so the kernel might provide\ntoo much data and overflow our buffer.\n\nFor example, hw/usb-uhci.c could set the length to 2047.\nhw/usb-ohci.c looks like it might go up to 4096 or 8192.\n\nThis causes a qemu crash, as reported here:\n http://www.mail-archive.com/kvm@vger.kernel.org/msg18447.html\n\nThis patch increases the usb-linux.c buffer size to 2048 to fix the\nspecific device reported, and adds a check to avoid the overflow in\nany case.\n\nSigned-off-by: Jim Paris \nSigned-off-by: Anthony Liguori ", "target": 1, "dataset": "other", "idx": 203887} {"func": "static int usb_host_handle_control(USBHostDevice *s, USBPacket *p)\n{\n struct usbdevfs_urb *urb;\n AsyncURB *aurb;\n int ret, value, index;\n int buffer_len;\n\n /* \n * Process certain standard device requests.\n * These are infrequent and are processed synchronously.\n */\n value = le16_to_cpu(s->ctrl.req.wValue);\n index = le16_to_cpu(s->ctrl.req.wIndex);\n\n dprintf(\"husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\\n\",\n s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index, \n s->ctrl.len);\n\n if (s->ctrl.req.bRequestType == 0) {\n switch (s->ctrl.req.bRequest) {\n case USB_REQ_SET_ADDRESS:\n return usb_host_set_address(s, value);\n\n case USB_REQ_SET_CONFIGURATION:\n return usb_host_set_config(s, value & 0xff);\n }\n }\n\n if (s->ctrl.req.bRequestType == 1 &&\n s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE)\n return usb_host_set_interface(s, index, value);\n\n /* The rest are asynchronous */\n\n buffer_len = 8 + s->ctrl.len;\n if (buffer_len > sizeof(s->ctrl.buffer)) {\n\t fprintf(stderr, \"husb: ctrl buffer too small (%u > %lu)\\n\",\n\t\t buffer_len, sizeof(s->ctrl.buffer));\n\t return USB_RET_STALL;\n }\n\n aurb = async_alloc();\n aurb->hdev = s;\n aurb->packet = p;\n\n /* \n * Setup ctrl transfer.\n *\n * s->ctrl is layed out such that data buffer immediately follows\n * 'req' struct which is exactly what usbdevfs expects.\n */ \n urb = &aurb->urb;\n\n urb->type = USBDEVFS_URB_TYPE_CONTROL;\n urb->endpoint = p->devep;\n\n urb->buffer = &s->ctrl.req;\n urb->buffer_length = buffer_len;\n\n urb->usercontext = s;\n\n ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb);\n\n dprintf(\"husb: submit ctrl. len %u aurb %p\\n\", urb->buffer_length, aurb);\n\n if (ret < 0) {\n dprintf(\"husb: submit failed. errno %d\\n\", errno);\n async_free(aurb);\n\n switch(errno) {\n case ETIMEDOUT:\n return USB_RET_NAK;\n case EPIPE:\n default:\n return USB_RET_STALL;\n }\n }\n\n usb_defer_packet(p, async_cancel, aurb);\n return USB_RET_ASYNC;\n}", "project": "qemu", "hash": 135771876040172573855391231658010318081, "size": 81, "commit_id": "babd03fde68093482528010a5435c14ce9128e3f", "message": "usb-linux.c: fix buffer overflow\n\nIn usb-linux.c:usb_host_handle_control, we pass a 1024-byte buffer and\nlength to the kernel. However, the length was provided by the caller\nof dev->handle_packet, and is not checked, so the kernel might provide\ntoo much data and overflow our buffer.\n\nFor example, hw/usb-uhci.c could set the length to 2047.\nhw/usb-ohci.c looks like it might go up to 4096 or 8192.\n\nThis causes a qemu crash, as reported here:\n http://www.mail-archive.com/kvm@vger.kernel.org/msg18447.html\n\nThis patch increases the usb-linux.c buffer size to 2048 to fix the\nspecific device reported, and adds a check to avoid the overflow in\nany case.\n\nSigned-off-by: Jim Paris \nSigned-off-by: Anthony Liguori ", "target": 0, "dataset": "other", "idx": 346299} {"func": "evbuffer_add(struct evbuffer *buf, const void *data_in, size_t datlen)\n{\n\tstruct evbuffer_chain *chain, *tmp;\n\tconst unsigned char *data = data_in;\n\tsize_t remain, to_alloc;\n\tint result = -1;\n\n\tEVBUFFER_LOCK(buf);\n\n\tif (buf->freeze_end) {\n\t\tgoto done;\n\t}\n\n\tchain = buf->last;\n\n\t/* If there are no chains allocated for this buffer, allocate one\n\t * big enough to hold all the data. */\n\tif (chain == NULL) {\n\t\tchain = evbuffer_chain_new(datlen);\n\t\tif (!chain)\n\t\t\tgoto done;\n\t\tevbuffer_chain_insert(buf, chain);\n\t}\n\n\tif ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {\n\t\tremain = (size_t)(chain->buffer_len - chain->misalign - chain->off);\n\t\tif (remain >= datlen) {\n\t\t\t/* there's enough space to hold all the data in the\n\t\t\t * current last chain */\n\t\t\tmemcpy(chain->buffer + chain->misalign + chain->off,\n\t\t\t data, datlen);\n\t\t\tchain->off += datlen;\n\t\t\tbuf->total_len += datlen;\n\t\t\tbuf->n_add_for_cb += datlen;\n\t\t\tgoto out;\n\t\t} else if (!CHAIN_PINNED(chain) &&\n\t\t evbuffer_chain_should_realign(chain, datlen)) {\n\t\t\t/* we can fit the data into the misalignment */\n\t\t\tevbuffer_chain_align(chain);\n\n\t\t\tmemcpy(chain->buffer + chain->off, data, datlen);\n\t\t\tchain->off += datlen;\n\t\t\tbuf->total_len += datlen;\n\t\t\tbuf->n_add_for_cb += datlen;\n\t\t\tgoto out;\n\t\t}\n\t} else {\n\t\t/* we cannot write any data to the last chain */\n\t\tremain = 0;\n\t}\n\n\t/* we need to add another chain */\n\tto_alloc = chain->buffer_len;\n\tif (to_alloc <= EVBUFFER_CHAIN_MAX_AUTO_SIZE/2)\n\t\tto_alloc <<= 1;\n\tif (datlen > to_alloc)\n\t\tto_alloc = datlen;\n\ttmp = evbuffer_chain_new(to_alloc);\n\tif (tmp == NULL)\n\t\tgoto done;\n\n\tif (remain) {\n\t\tmemcpy(chain->buffer + chain->misalign + chain->off,\n\t\t data, remain);\n\t\tchain->off += remain;\n\t\tbuf->total_len += remain;\n\t\tbuf->n_add_for_cb += remain;\n\t}\n\n\tdata += remain;\n\tdatlen -= remain;\n\n\tmemcpy(tmp->buffer, data, datlen);\n\ttmp->off = datlen;\n\tevbuffer_chain_insert(buf, tmp);\n\tbuf->n_add_for_cb += datlen;\n\nout:\n\tevbuffer_invoke_callbacks(buf);\n\tresult = 0;\ndone:\n\tEVBUFFER_UNLOCK(buf);\n\treturn result;\n}", "project": "libevent", "hash": 22227894411124508117434949505991372637, "size": 84, "commit_id": "20d6d4458bee5d88bda1511c225c25b2d3198d6c", "message": "Fix CVE-2014-6272 in Libevent 2.0\n\nFor this fix, we need to make sure that passing too-large inputs to\nthe evbuffer functions can't make us do bad things with the heap.\n\nAlso, lower the maximum chunk size to the lower of off_t, size_t maximum.\n\nThis is necessary since otherwise we could get into an infinite loop\nif we make a chunk that 'misalign' cannot index into.", "target": 1, "dataset": "other", "idx": 203893} {"func": "evbuffer_add(struct evbuffer *buf, const void *data_in, size_t datlen)\n{\n\tstruct evbuffer_chain *chain, *tmp;\n\tconst unsigned char *data = data_in;\n\tsize_t remain, to_alloc;\n\tint result = -1;\n\n\tEVBUFFER_LOCK(buf);\n\n\tif (buf->freeze_end) {\n\t\tgoto done;\n\t}\n\t/* Prevent buf->total_len overflow */\n\tif (datlen > EV_SIZE_MAX - buf->total_len) {\n\t\tgoto done;\n\t}\n\n\tchain = buf->last;\n\n\t/* If there are no chains allocated for this buffer, allocate one\n\t * big enough to hold all the data. */\n\tif (chain == NULL) {\n\t\tchain = evbuffer_chain_new(datlen);\n\t\tif (!chain)\n\t\t\tgoto done;\n\t\tevbuffer_chain_insert(buf, chain);\n\t}\n\n\tif ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {\n\t\t/* Always true for mutable buffers */\n\t\tEVUTIL_ASSERT(chain->misalign >= 0 &&\n\t\t (ev_uint64_t)chain->misalign <= EVBUFFER_CHAIN_MAX);\n\t\tremain = chain->buffer_len - (size_t)chain->misalign - chain->off;\n\t\tif (remain >= datlen) {\n\t\t\t/* there's enough space to hold all the data in the\n\t\t\t * current last chain */\n\t\t\tmemcpy(chain->buffer + chain->misalign + chain->off,\n\t\t\t data, datlen);\n\t\t\tchain->off += datlen;\n\t\t\tbuf->total_len += datlen;\n\t\t\tbuf->n_add_for_cb += datlen;\n\t\t\tgoto out;\n\t\t} else if (!CHAIN_PINNED(chain) &&\n\t\t evbuffer_chain_should_realign(chain, datlen)) {\n\t\t\t/* we can fit the data into the misalignment */\n\t\t\tevbuffer_chain_align(chain);\n\n\t\t\tmemcpy(chain->buffer + chain->off, data, datlen);\n\t\t\tchain->off += datlen;\n\t\t\tbuf->total_len += datlen;\n\t\t\tbuf->n_add_for_cb += datlen;\n\t\t\tgoto out;\n\t\t}\n\t} else {\n\t\t/* we cannot write any data to the last chain */\n\t\tremain = 0;\n\t}\n\n\t/* we need to add another chain */\n\tto_alloc = chain->buffer_len;\n\tif (to_alloc <= EVBUFFER_CHAIN_MAX_AUTO_SIZE/2)\n\t\tto_alloc <<= 1;\n\tif (datlen > to_alloc)\n\t\tto_alloc = datlen;\n\ttmp = evbuffer_chain_new(to_alloc);\n\tif (tmp == NULL)\n\t\tgoto done;\n\n\tif (remain) {\n\t\tmemcpy(chain->buffer + chain->misalign + chain->off,\n\t\t data, remain);\n\t\tchain->off += remain;\n\t\tbuf->total_len += remain;\n\t\tbuf->n_add_for_cb += remain;\n\t}\n\n\tdata += remain;\n\tdatlen -= remain;\n\n\tmemcpy(tmp->buffer, data, datlen);\n\ttmp->off = datlen;\n\tevbuffer_chain_insert(buf, tmp);\n\tbuf->n_add_for_cb += datlen;\n\nout:\n\tevbuffer_invoke_callbacks(buf);\n\tresult = 0;\ndone:\n\tEVBUFFER_UNLOCK(buf);\n\treturn result;\n}", "project": "libevent", "hash": 52044498904590272412051991226803272284, "size": 91, "commit_id": "20d6d4458bee5d88bda1511c225c25b2d3198d6c", "message": "Fix CVE-2014-6272 in Libevent 2.0\n\nFor this fix, we need to make sure that passing too-large inputs to\nthe evbuffer functions can't make us do bad things with the heap.\n\nAlso, lower the maximum chunk size to the lower of off_t, size_t maximum.\n\nThis is necessary since otherwise we could get into an infinite loop\nif we make a chunk that 'misalign' cannot index into.", "target": 0, "dataset": "other", "idx": 346340} {"func": "p11_rpc_buffer_get_byte_array (p11_buffer *buf,\n size_t *offset,\n const unsigned char **data,\n size_t *length)\n{\n\tsize_t off = *offset;\n\tuint32_t len;\n\tif (!p11_rpc_buffer_get_uint32 (buf, &off, &len))\n\t\treturn false;\n\tif (len == 0xffffffff) {\n\t\t*offset = off;\n\t\tif (data)\n\t\t\t*data = NULL;\n\t\tif (length)\n\t\t\t*length = 0;\n\t\treturn true;\n\t} else if (len >= 0x7fffffff) {\n\t\tp11_buffer_fail (buf);\n\t\treturn false;\n\t}\n\n\tif (buf->len < len || *offset > buf->len - len) {\n\t\tp11_buffer_fail (buf);\n\t\treturn false;\n\t}\n\n\tif (data)\n\t\t*data = (unsigned char *)buf->data + off;\n\tif (length)\n\t\t*length = len;\n\t*offset = off + len;\n\n\treturn true;\n}", "project": "p11-kit", "hash": 81431764540984656735179160726380243041, "size": 34, "commit_id": "69d751ca9df9ac101adfb1e5aa7e83e3358106ba", "message": "Fix bounds check in p11_rpc_buffer_get_byte_array\n\nThis bounds check should be using off, not *offset, because it has been\nadvanced four bytes from reading a uint32 earlier in the function.\nAdditionally, the pointer that is returned is computed using off, not\n*offset.", "target": 1, "dataset": "other", "idx": 204031} {"func": "p11_rpc_buffer_get_byte_array (p11_buffer *buf,\n size_t *offset,\n const unsigned char **data,\n size_t *length)\n{\n\tsize_t off = *offset;\n\tuint32_t len;\n\tif (!p11_rpc_buffer_get_uint32 (buf, &off, &len))\n\t\treturn false;\n\tif (len == 0xffffffff) {\n\t\t*offset = off;\n\t\tif (data)\n\t\t\t*data = NULL;\n\t\tif (length)\n\t\t\t*length = 0;\n\t\treturn true;\n\t} else if (len >= 0x7fffffff) {\n\t\tp11_buffer_fail (buf);\n\t\treturn false;\n\t}\n\n\tif (buf->len < len || off > buf->len - len) {\n\t\tp11_buffer_fail (buf);\n\t\treturn false;\n\t}\n\n\tif (data)\n\t\t*data = (unsigned char *)buf->data + off;\n\tif (length)\n\t\t*length = len;\n\t*offset = off + len;\n\n\treturn true;\n}", "project": "p11-kit", "hash": 69269050861741048277937073880239113087, "size": 34, "commit_id": "69d751ca9df9ac101adfb1e5aa7e83e3358106ba", "message": "Fix bounds check in p11_rpc_buffer_get_byte_array\n\nThis bounds check should be using off, not *offset, because it has been\nadvanced four bytes from reading a uint32 earlier in the function.\nAdditionally, the pointer that is returned is computed using off, not\n*offset.", "target": 0, "dataset": "other", "idx": 349479} {"func": "pixReadFromTiffStream(TIFF *tif)\n{\nchar *text;\nl_uint8 *linebuf, *data, *rowptr;\nl_uint16 spp, bps, photometry, tiffcomp, orientation, sample_fmt;\nl_uint16 *redmap, *greenmap, *bluemap;\nl_int32 d, wpl, bpl, comptype, i, j, k, ncolors, rval, gval, bval, aval;\nl_int32 xres, yres, tiffbpl, packedbpl, halfsize;\nl_uint32 w, h, tiffword, read_oriented;\nl_uint32 *line, *ppixel, *tiffdata, *pixdata;\nPIX *pix, *pix1;\nPIXCMAP *cmap;\n\n PROCNAME(\"pixReadFromTiffStream\");\n\n if (!tif)\n return (PIX *)ERROR_PTR(\"tif not defined\", procName, NULL);\n\n read_oriented = 0;\n\n /* Only accept uint image data:\n * SAMPLEFORMAT_UINT = 1;\n * SAMPLEFORMAT_INT = 2;\n * SAMPLEFORMAT_IEEEFP = 3;\n * SAMPLEFORMAT_VOID = 4; */\n TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLEFORMAT, &sample_fmt);\n if (sample_fmt != SAMPLEFORMAT_UINT) {\n L_ERROR(\"sample format = %d is not uint\\n\", procName, sample_fmt);\n return NULL;\n }\n\n /* Can't read tiff in tiled format. For what is involved, see, e.g:\n * https://www.cs.rochester.edu/~nelson/courses/vision/\\\n * resources/tiff/libtiff.html#Tiles\n * A tiled tiff can be converted to a normal (strip) tif:\n * tiffcp -s */\n if (TIFFIsTiled(tif)) {\n L_ERROR(\"tiled format is not supported\\n\", procName);\n return NULL;\n }\n\n /* Old style jpeg is not supported. We tried supporting 8 bpp.\n * TIFFReadScanline() fails on this format, so we used RGBA\n * reading, which generates a 4 spp image, and pulled out the\n * red component. However, there were problems with double-frees\n * in cleanup. For RGB, tiffbpl is exactly half the size that\n * you would expect for the raster data in a scanline, which\n * is 3 * w. */\n TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &tiffcomp);\n if (tiffcomp == COMPRESSION_OJPEG) {\n L_ERROR(\"old style jpeg format is not supported\\n\", procName);\n return NULL;\n }\n\n /* Use default fields for bps and spp */\n TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bps);\n TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &spp);\n if (bps != 1 && bps != 2 && bps != 4 && bps != 8 && bps != 16) {\n L_ERROR(\"invalid bps = %d\\n\", procName, bps);\n return NULL;\n }\n if (spp == 2 && bps != 8) {\n L_WARNING(\"for 2 spp, only handle 8 bps\\n\", procName);\n return NULL;\n }\n if (spp == 1)\n d = bps;\n else if (spp == 2) /* gray plus alpha */\n d = 32; /* will convert to RGBA */\n else if (spp == 3 || spp == 4)\n d = 32;\n else\n return (PIX *)ERROR_PTR(\"spp not in set {1,2,3,4}\", procName, NULL);\n\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);\n if (w > MaxTiffWidth) {\n L_ERROR(\"width = %d pixels; too large\\n\", procName, w);\n return NULL;\n }\n if (h > MaxTiffHeight) {\n L_ERROR(\"height = %d pixels; too large\\n\", procName, h);\n return NULL;\n }\n\n /* The relation between the size of a byte buffer required to hold\n a raster of image pixels (packedbpl) and the size of the tiff\n buffer (tiffbuf) is either 1:1 or approximately 2:1, depending\n on how the data is stored and subsampled. Allow some slop\n when validating the relation between buffer size and the image\n parameters w, spp and bps. */\n tiffbpl = TIFFScanlineSize(tif);\n packedbpl = (bps * spp * w + 7) / 8;\n halfsize = L_ABS(2 * tiffbpl - packedbpl) <= 8;\n#if 0\n if (halfsize)\n L_INFO(\"packedbpl = %d is approx. twice tiffbpl = %d\\n\", procName,\n packedbpl, tiffbpl);\n#endif\n if (tiffbpl != packedbpl && !halfsize) {\n L_ERROR(\"invalid tiffbpl: tiffbpl = %d, packedbpl = %d, \"\n \"bps = %d, spp = %d, w = %d\\n\",\n procName, tiffbpl, packedbpl, bps, spp, w);\n return NULL;\n }\n\n if ((pix = pixCreate(w, h, d)) == NULL)\n return (PIX *)ERROR_PTR(\"pix not made\", procName, NULL);\n pixSetInputFormat(pix, IFF_TIFF);\n data = (l_uint8 *)pixGetData(pix);\n wpl = pixGetWpl(pix);\n bpl = 4 * wpl;\n\n if (spp == 1) {\n linebuf = (l_uint8 *)LEPT_CALLOC(tiffbpl + 1, sizeof(l_uint8));\n for (i = 0; i < h; i++) {\n if (TIFFReadScanline(tif, linebuf, i, 0) < 0) {\n LEPT_FREE(linebuf);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"line read fail\", procName, NULL);\n }\n memcpy(data, linebuf, tiffbpl);\n data += bpl;\n }\n if (bps <= 8)\n pixEndianByteSwap(pix);\n else /* bps == 16 */\n pixEndianTwoByteSwap(pix);\n LEPT_FREE(linebuf);\n } else if (spp == 2 && bps == 8) { /* gray plus alpha */\n L_INFO(\"gray+alpha is not supported; converting to RGBA\\n\", procName);\n pixSetSpp(pix, 4);\n linebuf = (l_uint8 *)LEPT_CALLOC(tiffbpl + 1, sizeof(l_uint8));\n pixdata = pixGetData(pix);\n for (i = 0; i < h; i++) {\n if (TIFFReadScanline(tif, linebuf, i, 0) < 0) {\n LEPT_FREE(linebuf);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"line read fail\", procName, NULL);\n }\n rowptr = linebuf;\n ppixel = pixdata + i * wpl;\n for (j = k = 0; j < w; j++) {\n /* Copy gray value into r, g and b */\n SET_DATA_BYTE(ppixel, COLOR_RED, rowptr[k]);\n SET_DATA_BYTE(ppixel, COLOR_GREEN, rowptr[k]);\n SET_DATA_BYTE(ppixel, COLOR_BLUE, rowptr[k++]);\n SET_DATA_BYTE(ppixel, L_ALPHA_CHANNEL, rowptr[k++]);\n ppixel++;\n }\n }\n LEPT_FREE(linebuf);\n } else { /* rgb and rgba */\n if ((tiffdata = (l_uint32 *)LEPT_CALLOC((size_t)w * h,\n sizeof(l_uint32))) == NULL) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"calloc fail for tiffdata\", procName, NULL);\n }\n /* TIFFReadRGBAImageOriented() converts to 8 bps */\n if (!TIFFReadRGBAImageOriented(tif, w, h, tiffdata,\n ORIENTATION_TOPLEFT, 0)) {\n LEPT_FREE(tiffdata);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"failed to read tiffdata\", procName, NULL);\n } else {\n read_oriented = 1;\n }\n\n if (spp == 4) pixSetSpp(pix, 4);\n line = pixGetData(pix);\n for (i = 0; i < h; i++, line += wpl) {\n for (j = 0, ppixel = line; j < w; j++) {\n /* TIFFGet* are macros */\n tiffword = tiffdata[i * w + j];\n rval = TIFFGetR(tiffword);\n gval = TIFFGetG(tiffword);\n bval = TIFFGetB(tiffword);\n if (spp == 3) {\n composeRGBPixel(rval, gval, bval, ppixel);\n } else { /* spp == 4 */\n aval = TIFFGetA(tiffword);\n composeRGBAPixel(rval, gval, bval, aval, ppixel);\n }\n ppixel++;\n }\n }\n LEPT_FREE(tiffdata);\n }\n\n if (getTiffStreamResolution(tif, &xres, &yres) == 0) {\n pixSetXRes(pix, xres);\n pixSetYRes(pix, yres);\n }\n\n /* Find and save the compression type */\n comptype = getTiffCompressedFormat(tiffcomp);\n pixSetInputFormat(pix, comptype);\n\n if (TIFFGetField(tif, TIFFTAG_COLORMAP, &redmap, &greenmap, &bluemap)) {\n /* Save the colormap as a pix cmap. Because the\n * tiff colormap components are 16 bit unsigned,\n * and go from black (0) to white (0xffff), the\n * the pix cmap takes the most significant byte. */\n if (bps > 8) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"colormap size > 256\", procName, NULL);\n }\n if ((cmap = pixcmapCreate(bps)) == NULL) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"colormap not made\", procName, NULL);\n }\n ncolors = 1 << bps;\n for (i = 0; i < ncolors; i++)\n pixcmapAddColor(cmap, redmap[i] >> 8, greenmap[i] >> 8,\n bluemap[i] >> 8);\n if (pixSetColormap(pix, cmap)) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"invalid colormap\", procName, NULL);\n }\n\n /* Remove the colormap for 1 bpp. */\n if (bps == 1) {\n pix1 = pixRemoveColormap(pix, REMOVE_CMAP_BASED_ON_SRC);\n pixDestroy(&pix);\n pix = pix1;\n }\n } else { /* No colormap: check photometry and invert if necessary */\n if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometry)) {\n /* Guess default photometry setting. Assume min_is_white\n * if compressed 1 bpp; min_is_black otherwise. */\n if (tiffcomp == COMPRESSION_CCITTFAX3 ||\n tiffcomp == COMPRESSION_CCITTFAX4 ||\n tiffcomp == COMPRESSION_CCITTRLE ||\n tiffcomp == COMPRESSION_CCITTRLEW) {\n photometry = PHOTOMETRIC_MINISWHITE;\n } else {\n photometry = PHOTOMETRIC_MINISBLACK;\n }\n }\n if ((d == 1 && photometry == PHOTOMETRIC_MINISBLACK) ||\n (d == 8 && photometry == PHOTOMETRIC_MINISWHITE))\n pixInvert(pix, pix);\n }\n\n if (TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation)) {\n if (orientation >= 1 && orientation <= 8) {\n struct tiff_transform *transform = (read_oriented) ?\n &tiff_partial_orientation_transforms[orientation - 1] :\n &tiff_orientation_transforms[orientation - 1];\n if (transform->vflip) pixFlipTB(pix, pix);\n if (transform->hflip) pixFlipLR(pix, pix);\n if (transform->rotate) {\n PIX *oldpix = pix;\n pix = pixRotate90(oldpix, transform->rotate);\n pixDestroy(&oldpix);\n }\n }\n }\n\n text = NULL;\n TIFFGetField(tif, TIFFTAG_IMAGEDESCRIPTION, &text);\n if (text) pixSetText(pix, text);\n return pix;\n}", "project": "leptonica", "hash": 132046392038694907222335403052712221680, "size": 264, "commit_id": "5ba34b1fe741d69d43a6c8cf767756997eadd87c", "message": "Issue 23654 in oss-fuzz: Heap-buffer-overflow in pixReadFromTiffStream\n * Increase scanline buffer for reading gray+alpha and converting to RGBA", "target": 1, "dataset": "other", "idx": 204059} {"func": "pixReadFromTiffStream(TIFF *tif)\n{\nchar *text;\nl_uint8 *linebuf, *data, *rowptr;\nl_uint16 spp, bps, photometry, tiffcomp, orientation, sample_fmt;\nl_uint16 *redmap, *greenmap, *bluemap;\nl_int32 d, wpl, bpl, comptype, i, j, k, ncolors, rval, gval, bval, aval;\nl_int32 xres, yres, tiffbpl, packedbpl, halfsize;\nl_uint32 w, h, tiffword, read_oriented;\nl_uint32 *line, *ppixel, *tiffdata, *pixdata;\nPIX *pix, *pix1;\nPIXCMAP *cmap;\n\n PROCNAME(\"pixReadFromTiffStream\");\n\n if (!tif)\n return (PIX *)ERROR_PTR(\"tif not defined\", procName, NULL);\n\n read_oriented = 0;\n\n /* Only accept uint image data:\n * SAMPLEFORMAT_UINT = 1;\n * SAMPLEFORMAT_INT = 2;\n * SAMPLEFORMAT_IEEEFP = 3;\n * SAMPLEFORMAT_VOID = 4; */\n TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLEFORMAT, &sample_fmt);\n if (sample_fmt != SAMPLEFORMAT_UINT) {\n L_ERROR(\"sample format = %d is not uint\\n\", procName, sample_fmt);\n return NULL;\n }\n\n /* Can't read tiff in tiled format. For what is involved, see, e.g:\n * https://www.cs.rochester.edu/~nelson/courses/vision/\\\n * resources/tiff/libtiff.html#Tiles\n * A tiled tiff can be converted to a normal (strip) tif:\n * tiffcp -s */\n if (TIFFIsTiled(tif)) {\n L_ERROR(\"tiled format is not supported\\n\", procName);\n return NULL;\n }\n\n /* Old style jpeg is not supported. We tried supporting 8 bpp.\n * TIFFReadScanline() fails on this format, so we used RGBA\n * reading, which generates a 4 spp image, and pulled out the\n * red component. However, there were problems with double-frees\n * in cleanup. For RGB, tiffbpl is exactly half the size that\n * you would expect for the raster data in a scanline, which\n * is 3 * w. */\n TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &tiffcomp);\n if (tiffcomp == COMPRESSION_OJPEG) {\n L_ERROR(\"old style jpeg format is not supported\\n\", procName);\n return NULL;\n }\n\n /* Use default fields for bps and spp */\n TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bps);\n TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &spp);\n if (bps != 1 && bps != 2 && bps != 4 && bps != 8 && bps != 16) {\n L_ERROR(\"invalid bps = %d\\n\", procName, bps);\n return NULL;\n }\n if (spp == 2 && bps != 8) {\n L_WARNING(\"for 2 spp, only handle 8 bps\\n\", procName);\n return NULL;\n }\n if (spp == 1)\n d = bps;\n else if (spp == 2) /* gray plus alpha */\n d = 32; /* will convert to RGBA */\n else if (spp == 3 || spp == 4)\n d = 32;\n else\n return (PIX *)ERROR_PTR(\"spp not in set {1,2,3,4}\", procName, NULL);\n\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);\n if (w > MaxTiffWidth) {\n L_ERROR(\"width = %d pixels; too large\\n\", procName, w);\n return NULL;\n }\n if (h > MaxTiffHeight) {\n L_ERROR(\"height = %d pixels; too large\\n\", procName, h);\n return NULL;\n }\n\n /* The relation between the size of a byte buffer required to hold\n a raster of image pixels (packedbpl) and the size of the tiff\n buffer (tiffbuf) is either 1:1 or approximately 2:1, depending\n on how the data is stored and subsampled. Allow some slop\n when validating the relation between buffer size and the image\n parameters w, spp and bps. */\n tiffbpl = TIFFScanlineSize(tif);\n packedbpl = (bps * spp * w + 7) / 8;\n halfsize = L_ABS(2 * tiffbpl - packedbpl) <= 8;\n#if 0\n if (halfsize)\n L_INFO(\"packedbpl = %d is approx. twice tiffbpl = %d\\n\", procName,\n packedbpl, tiffbpl);\n#endif\n if (tiffbpl != packedbpl && !halfsize) {\n L_ERROR(\"invalid tiffbpl: tiffbpl = %d, packedbpl = %d, \"\n \"bps = %d, spp = %d, w = %d\\n\",\n procName, tiffbpl, packedbpl, bps, spp, w);\n return NULL;\n }\n\n if ((pix = pixCreate(w, h, d)) == NULL)\n return (PIX *)ERROR_PTR(\"pix not made\", procName, NULL);\n pixSetInputFormat(pix, IFF_TIFF);\n data = (l_uint8 *)pixGetData(pix);\n wpl = pixGetWpl(pix);\n bpl = 4 * wpl;\n\n if (spp == 1) {\n linebuf = (l_uint8 *)LEPT_CALLOC(tiffbpl + 1, sizeof(l_uint8));\n for (i = 0; i < h; i++) {\n if (TIFFReadScanline(tif, linebuf, i, 0) < 0) {\n LEPT_FREE(linebuf);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"line read fail\", procName, NULL);\n }\n memcpy(data, linebuf, tiffbpl);\n data += bpl;\n }\n if (bps <= 8)\n pixEndianByteSwap(pix);\n else /* bps == 16 */\n pixEndianTwoByteSwap(pix);\n LEPT_FREE(linebuf);\n } else if (spp == 2 && bps == 8) { /* gray plus alpha */\n L_INFO(\"gray+alpha is not supported; converting to RGBA\\n\", procName);\n pixSetSpp(pix, 4);\n linebuf = (l_uint8 *)LEPT_CALLOC(2 * tiffbpl + 1, sizeof(l_uint8));\n pixdata = pixGetData(pix);\n for (i = 0; i < h; i++) {\n if (TIFFReadScanline(tif, linebuf, i, 0) < 0) {\n LEPT_FREE(linebuf);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"line read fail\", procName, NULL);\n }\n rowptr = linebuf;\n ppixel = pixdata + i * wpl;\n for (j = k = 0; j < w; j++) {\n /* Copy gray value into r, g and b */\n SET_DATA_BYTE(ppixel, COLOR_RED, rowptr[k]);\n SET_DATA_BYTE(ppixel, COLOR_GREEN, rowptr[k]);\n SET_DATA_BYTE(ppixel, COLOR_BLUE, rowptr[k++]);\n SET_DATA_BYTE(ppixel, L_ALPHA_CHANNEL, rowptr[k++]);\n ppixel++;\n }\n }\n LEPT_FREE(linebuf);\n } else { /* rgb and rgba */\n if ((tiffdata = (l_uint32 *)LEPT_CALLOC((size_t)w * h,\n sizeof(l_uint32))) == NULL) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"calloc fail for tiffdata\", procName, NULL);\n }\n /* TIFFReadRGBAImageOriented() converts to 8 bps */\n if (!TIFFReadRGBAImageOriented(tif, w, h, tiffdata,\n ORIENTATION_TOPLEFT, 0)) {\n LEPT_FREE(tiffdata);\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"failed to read tiffdata\", procName, NULL);\n } else {\n read_oriented = 1;\n }\n\n if (spp == 4) pixSetSpp(pix, 4);\n line = pixGetData(pix);\n for (i = 0; i < h; i++, line += wpl) {\n for (j = 0, ppixel = line; j < w; j++) {\n /* TIFFGet* are macros */\n tiffword = tiffdata[i * w + j];\n rval = TIFFGetR(tiffword);\n gval = TIFFGetG(tiffword);\n bval = TIFFGetB(tiffword);\n if (spp == 3) {\n composeRGBPixel(rval, gval, bval, ppixel);\n } else { /* spp == 4 */\n aval = TIFFGetA(tiffword);\n composeRGBAPixel(rval, gval, bval, aval, ppixel);\n }\n ppixel++;\n }\n }\n LEPT_FREE(tiffdata);\n }\n\n if (getTiffStreamResolution(tif, &xres, &yres) == 0) {\n pixSetXRes(pix, xres);\n pixSetYRes(pix, yres);\n }\n\n /* Find and save the compression type */\n comptype = getTiffCompressedFormat(tiffcomp);\n pixSetInputFormat(pix, comptype);\n\n if (TIFFGetField(tif, TIFFTAG_COLORMAP, &redmap, &greenmap, &bluemap)) {\n /* Save the colormap as a pix cmap. Because the\n * tiff colormap components are 16 bit unsigned,\n * and go from black (0) to white (0xffff), the\n * the pix cmap takes the most significant byte. */\n if (bps > 8) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"colormap size > 256\", procName, NULL);\n }\n if ((cmap = pixcmapCreate(bps)) == NULL) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"colormap not made\", procName, NULL);\n }\n ncolors = 1 << bps;\n for (i = 0; i < ncolors; i++)\n pixcmapAddColor(cmap, redmap[i] >> 8, greenmap[i] >> 8,\n bluemap[i] >> 8);\n if (pixSetColormap(pix, cmap)) {\n pixDestroy(&pix);\n return (PIX *)ERROR_PTR(\"invalid colormap\", procName, NULL);\n }\n\n /* Remove the colormap for 1 bpp. */\n if (bps == 1) {\n pix1 = pixRemoveColormap(pix, REMOVE_CMAP_BASED_ON_SRC);\n pixDestroy(&pix);\n pix = pix1;\n }\n } else { /* No colormap: check photometry and invert if necessary */\n if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometry)) {\n /* Guess default photometry setting. Assume min_is_white\n * if compressed 1 bpp; min_is_black otherwise. */\n if (tiffcomp == COMPRESSION_CCITTFAX3 ||\n tiffcomp == COMPRESSION_CCITTFAX4 ||\n tiffcomp == COMPRESSION_CCITTRLE ||\n tiffcomp == COMPRESSION_CCITTRLEW) {\n photometry = PHOTOMETRIC_MINISWHITE;\n } else {\n photometry = PHOTOMETRIC_MINISBLACK;\n }\n }\n if ((d == 1 && photometry == PHOTOMETRIC_MINISBLACK) ||\n (d == 8 && photometry == PHOTOMETRIC_MINISWHITE))\n pixInvert(pix, pix);\n }\n\n if (TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation)) {\n if (orientation >= 1 && orientation <= 8) {\n struct tiff_transform *transform = (read_oriented) ?\n &tiff_partial_orientation_transforms[orientation - 1] :\n &tiff_orientation_transforms[orientation - 1];\n if (transform->vflip) pixFlipTB(pix, pix);\n if (transform->hflip) pixFlipLR(pix, pix);\n if (transform->rotate) {\n PIX *oldpix = pix;\n pix = pixRotate90(oldpix, transform->rotate);\n pixDestroy(&oldpix);\n }\n }\n }\n\n text = NULL;\n TIFFGetField(tif, TIFFTAG_IMAGEDESCRIPTION, &text);\n if (text) pixSetText(pix, text);\n return pix;\n}", "project": "leptonica", "hash": 288150895440705810941702661710210262875, "size": 264, "commit_id": "5ba34b1fe741d69d43a6c8cf767756997eadd87c", "message": "Issue 23654 in oss-fuzz: Heap-buffer-overflow in pixReadFromTiffStream\n * Increase scanline buffer for reading gray+alpha and converting to RGBA", "target": 0, "dataset": "other", "idx": 350367} {"func": "int input_set_keycode(struct input_dev *dev,\n\t\t const struct input_keymap_entry *ke)\n{\n\tunsigned long flags;\n\tunsigned int old_keycode;\n\tint retval;\n\n\tif (ke->keycode > KEY_MAX)\n\t\treturn -EINVAL;\n\n\tspin_lock_irqsave(&dev->event_lock, flags);\n\n\tretval = dev->setkeycode(dev, ke, &old_keycode);\n\tif (retval)\n\t\tgoto out;\n\n\t/* Make sure KEY_RESERVED did not get enabled. */\n\t__clear_bit(KEY_RESERVED, dev->keybit);\n\n\t/*\n\t * Simulate keyup event if keycode is not present\n\t * in the keymap anymore\n\t */\n\tif (test_bit(EV_KEY, dev->evbit) &&\n\t !is_event_supported(old_keycode, dev->keybit, KEY_MAX) &&\n\t __test_and_clear_bit(old_keycode, dev->key)) {\n\t\tstruct input_value vals[] = {\n\t\t\t{ EV_KEY, old_keycode, 0 },\n\t\t\tinput_value_sync\n\t\t};\n\n\t\tinput_pass_values(dev, vals, ARRAY_SIZE(vals));\n\t}\n\n out:\n\tspin_unlock_irqrestore(&dev->event_lock, flags);\n\n\treturn retval;\n}", "project": "linux", "hash": 337446137803997904056500807170028096296, "size": 39, "commit_id": "cb222aed03d798fc074be55e59d9a112338ee784", "message": "Input: add safety guards to input_set_keycode()\n\nIf we happen to have a garbage in input device's keycode table with values\ntoo big we'll end up doing clear_bit() with offset way outside of our\nbitmaps, damaging other objects within an input device or even outside of\nit. Let's add sanity checks to the returned old keycodes.\n\nReported-by: syzbot+c769968809f9359b07aa@syzkaller.appspotmail.com\nReported-by: syzbot+76f3a30e88d256644c78@syzkaller.appspotmail.com\nLink: https://lore.kernel.org/r/20191207212757.GA245964@dtor-ws\nSigned-off-by: Dmitry Torokhov ", "target": 1, "dataset": "other", "idx": 204147} {"func": "int input_set_keycode(struct input_dev *dev,\n\t\t const struct input_keymap_entry *ke)\n{\n\tunsigned long flags;\n\tunsigned int old_keycode;\n\tint retval;\n\n\tif (ke->keycode > KEY_MAX)\n\t\treturn -EINVAL;\n\n\tspin_lock_irqsave(&dev->event_lock, flags);\n\n\tretval = dev->setkeycode(dev, ke, &old_keycode);\n\tif (retval)\n\t\tgoto out;\n\n\t/* Make sure KEY_RESERVED did not get enabled. */\n\t__clear_bit(KEY_RESERVED, dev->keybit);\n\n\t/*\n\t * Simulate keyup event if keycode is not present\n\t * in the keymap anymore\n\t */\n\tif (old_keycode > KEY_MAX) {\n\t\tdev_warn(dev->dev.parent ?: &dev->dev,\n\t\t\t \"%s: got too big old keycode %#x\\n\",\n\t\t\t __func__, old_keycode);\n\t} else if (test_bit(EV_KEY, dev->evbit) &&\n\t\t !is_event_supported(old_keycode, dev->keybit, KEY_MAX) &&\n\t\t __test_and_clear_bit(old_keycode, dev->key)) {\n\t\tstruct input_value vals[] = {\n\t\t\t{ EV_KEY, old_keycode, 0 },\n\t\t\tinput_value_sync\n\t\t};\n\n\t\tinput_pass_values(dev, vals, ARRAY_SIZE(vals));\n\t}\n\n out:\n\tspin_unlock_irqrestore(&dev->event_lock, flags);\n\n\treturn retval;\n}", "project": "linux", "hash": 250661356441538656426884342920937476021, "size": 43, "commit_id": "cb222aed03d798fc074be55e59d9a112338ee784", "message": "Input: add safety guards to input_set_keycode()\n\nIf we happen to have a garbage in input device's keycode table with values\ntoo big we'll end up doing clear_bit() with offset way outside of our\nbitmaps, damaging other objects within an input device or even outside of\nit. Let's add sanity checks to the returned old keycodes.\n\nReported-by: syzbot+c769968809f9359b07aa@syzkaller.appspotmail.com\nReported-by: syzbot+76f3a30e88d256644c78@syzkaller.appspotmail.com\nLink: https://lore.kernel.org/r/20191207212757.GA245964@dtor-ws\nSigned-off-by: Dmitry Torokhov ", "target": 0, "dataset": "other", "idx": 353362} {"func": "static int kvm_s390_get_cmma(struct kvm *kvm, struct kvm_s390_cmma_log *args,\n\t\t\t u8 *res, unsigned long bufsize)\n{\n\tunsigned long mem_end, cur_gfn, next_gfn, hva, pgstev;\n\tstruct kvm_memslots *slots = kvm_memslots(kvm);\n\tstruct kvm_memory_slot *ms;\n\n\tcur_gfn = kvm_s390_next_dirty_cmma(slots, args->start_gfn);\n\tms = gfn_to_memslot(kvm, cur_gfn);\n\targs->count = 0;\n\targs->start_gfn = cur_gfn;\n\tif (!ms)\n\t\treturn 0;\n\tnext_gfn = kvm_s390_next_dirty_cmma(slots, cur_gfn + 1);\n\tmem_end = slots->memslots[0].base_gfn + slots->memslots[0].npages;\n\n\twhile (args->count < bufsize) {\n\t\thva = gfn_to_hva(kvm, cur_gfn);\n\t\tif (kvm_is_error_hva(hva))\n\t\t\treturn 0;\n\t\t/* Decrement only if we actually flipped the bit to 0 */\n\t\tif (test_and_clear_bit(cur_gfn - ms->base_gfn, kvm_second_dirty_bitmap(ms)))\n\t\t\tatomic64_dec(&kvm->arch.cmma_dirty_pages);\n\t\tif (get_pgste(kvm->mm, hva, &pgstev) < 0)\n\t\t\tpgstev = 0;\n\t\t/* Save the value */\n\t\tres[args->count++] = (pgstev >> 24) & 0x43;\n\t\t/* If the next bit is too far away, stop. */\n\t\tif (next_gfn > cur_gfn + KVM_S390_MAX_BIT_DISTANCE)\n\t\t\treturn 0;\n\t\t/* If we reached the previous \"next\", find the next one */\n\t\tif (cur_gfn == next_gfn)\n\t\t\tnext_gfn = kvm_s390_next_dirty_cmma(slots, cur_gfn + 1);\n\t\t/* Reached the end of memory or of the buffer, stop */\n\t\tif ((next_gfn >= mem_end) ||\n\t\t (next_gfn - args->start_gfn >= bufsize))\n\t\t\treturn 0;\n\t\tcur_gfn++;\n\t\t/* Reached the end of the current memslot, take the next one. */\n\t\tif (cur_gfn - ms->base_gfn >= ms->npages) {\n\t\t\tms = gfn_to_memslot(kvm, cur_gfn);\n\t\t\tif (!ms)\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 0;\n}", "project": "linux", "hash": 69648874825348699945429887721025870530, "size": 47, "commit_id": "0774a964ef561b7170d8d1b1bfe6f88002b6d219", "message": "KVM: Fix out of range accesses to memslots\n\nReset the LRU slot if it becomes invalid when deleting a memslot to fix\nan out-of-bounds/use-after-free access when searching through memslots.\n\nExplicitly check for there being no used slots in search_memslots(), and\nin the caller of s390's approximation variant.\n\nFixes: 36947254e5f9 (\"KVM: Dynamically size memslot array based on number of used slots\")\nReported-by: Qian Cai \nCc: Peter Xu \nSigned-off-by: Sean Christopherson \nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger \nSigned-off-by: Paolo Bonzini ", "target": 1, "dataset": "other", "idx": 204189} {"func": "static int kvm_s390_get_cmma(struct kvm *kvm, struct kvm_s390_cmma_log *args,\n\t\t\t u8 *res, unsigned long bufsize)\n{\n\tunsigned long mem_end, cur_gfn, next_gfn, hva, pgstev;\n\tstruct kvm_memslots *slots = kvm_memslots(kvm);\n\tstruct kvm_memory_slot *ms;\n\n\tif (unlikely(!slots->used_slots))\n\t\treturn 0;\n\n\tcur_gfn = kvm_s390_next_dirty_cmma(slots, args->start_gfn);\n\tms = gfn_to_memslot(kvm, cur_gfn);\n\targs->count = 0;\n\targs->start_gfn = cur_gfn;\n\tif (!ms)\n\t\treturn 0;\n\tnext_gfn = kvm_s390_next_dirty_cmma(slots, cur_gfn + 1);\n\tmem_end = slots->memslots[0].base_gfn + slots->memslots[0].npages;\n\n\twhile (args->count < bufsize) {\n\t\thva = gfn_to_hva(kvm, cur_gfn);\n\t\tif (kvm_is_error_hva(hva))\n\t\t\treturn 0;\n\t\t/* Decrement only if we actually flipped the bit to 0 */\n\t\tif (test_and_clear_bit(cur_gfn - ms->base_gfn, kvm_second_dirty_bitmap(ms)))\n\t\t\tatomic64_dec(&kvm->arch.cmma_dirty_pages);\n\t\tif (get_pgste(kvm->mm, hva, &pgstev) < 0)\n\t\t\tpgstev = 0;\n\t\t/* Save the value */\n\t\tres[args->count++] = (pgstev >> 24) & 0x43;\n\t\t/* If the next bit is too far away, stop. */\n\t\tif (next_gfn > cur_gfn + KVM_S390_MAX_BIT_DISTANCE)\n\t\t\treturn 0;\n\t\t/* If we reached the previous \"next\", find the next one */\n\t\tif (cur_gfn == next_gfn)\n\t\t\tnext_gfn = kvm_s390_next_dirty_cmma(slots, cur_gfn + 1);\n\t\t/* Reached the end of memory or of the buffer, stop */\n\t\tif ((next_gfn >= mem_end) ||\n\t\t (next_gfn - args->start_gfn >= bufsize))\n\t\t\treturn 0;\n\t\tcur_gfn++;\n\t\t/* Reached the end of the current memslot, take the next one. */\n\t\tif (cur_gfn - ms->base_gfn >= ms->npages) {\n\t\t\tms = gfn_to_memslot(kvm, cur_gfn);\n\t\t\tif (!ms)\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 0;\n}", "project": "linux", "hash": 13699562725589835050195546967713430426, "size": 50, "commit_id": "0774a964ef561b7170d8d1b1bfe6f88002b6d219", "message": "KVM: Fix out of range accesses to memslots\n\nReset the LRU slot if it becomes invalid when deleting a memslot to fix\nan out-of-bounds/use-after-free access when searching through memslots.\n\nExplicitly check for there being no used slots in search_memslots(), and\nin the caller of s390's approximation variant.\n\nFixes: 36947254e5f9 (\"KVM: Dynamically size memslot array based on number of used slots\")\nReported-by: Qian Cai \nCc: Peter Xu \nSigned-off-by: Sean Christopherson \nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger \nSigned-off-by: Paolo Bonzini ", "target": 0, "dataset": "other", "idx": 354690} {"func": "static inline void kvm_memslot_delete(struct kvm_memslots *slots,\n\t\t\t\t struct kvm_memory_slot *memslot)\n{\n\tstruct kvm_memory_slot *mslots = slots->memslots;\n\tint i;\n\n\tif (WARN_ON(slots->id_to_index[memslot->id] == -1))\n\t\treturn;\n\n\tslots->used_slots--;\n\n\tfor (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {\n\t\tmslots[i] = mslots[i + 1];\n\t\tslots->id_to_index[mslots[i].id] = i;\n\t}\n\tmslots[i] = *memslot;\n\tslots->id_to_index[memslot->id] = -1;\n}", "project": "linux", "hash": 222311292455674309157254629171646173763, "size": 18, "commit_id": "0774a964ef561b7170d8d1b1bfe6f88002b6d219", "message": "KVM: Fix out of range accesses to memslots\n\nReset the LRU slot if it becomes invalid when deleting a memslot to fix\nan out-of-bounds/use-after-free access when searching through memslots.\n\nExplicitly check for there being no used slots in search_memslots(), and\nin the caller of s390's approximation variant.\n\nFixes: 36947254e5f9 (\"KVM: Dynamically size memslot array based on number of used slots\")\nReported-by: Qian Cai \nCc: Peter Xu \nSigned-off-by: Sean Christopherson \nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger \nSigned-off-by: Paolo Bonzini ", "target": 1, "dataset": "other", "idx": 204190} {"func": "static inline void kvm_memslot_delete(struct kvm_memslots *slots,\n\t\t\t\t struct kvm_memory_slot *memslot)\n{\n\tstruct kvm_memory_slot *mslots = slots->memslots;\n\tint i;\n\n\tif (WARN_ON(slots->id_to_index[memslot->id] == -1))\n\t\treturn;\n\n\tslots->used_slots--;\n\n\tif (atomic_read(&slots->lru_slot) >= slots->used_slots)\n\t\tatomic_set(&slots->lru_slot, 0);\n\n\tfor (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {\n\t\tmslots[i] = mslots[i + 1];\n\t\tslots->id_to_index[mslots[i].id] = i;\n\t}\n\tmslots[i] = *memslot;\n\tslots->id_to_index[memslot->id] = -1;\n}", "project": "linux", "hash": 281781368969257104938303693558751249981, "size": 21, "commit_id": "0774a964ef561b7170d8d1b1bfe6f88002b6d219", "message": "KVM: Fix out of range accesses to memslots\n\nReset the LRU slot if it becomes invalid when deleting a memslot to fix\nan out-of-bounds/use-after-free access when searching through memslots.\n\nExplicitly check for there being no used slots in search_memslots(), and\nin the caller of s390's approximation variant.\n\nFixes: 36947254e5f9 (\"KVM: Dynamically size memslot array based on number of used slots\")\nReported-by: Qian Cai \nCc: Peter Xu \nSigned-off-by: Sean Christopherson \nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger \nSigned-off-by: Paolo Bonzini ", "target": 0, "dataset": "other", "idx": 354527} {"func": "search_memslots(struct kvm_memslots *slots, gfn_t gfn)\n{\n\tint start = 0, end = slots->used_slots;\n\tint slot = atomic_read(&slots->lru_slot);\n\tstruct kvm_memory_slot *memslots = slots->memslots;\n\n\tif (gfn >= memslots[slot].base_gfn &&\n\t gfn < memslots[slot].base_gfn + memslots[slot].npages)\n\t\treturn &memslots[slot];\n\n\twhile (start < end) {\n\t\tslot = start + (end - start) / 2;\n\n\t\tif (gfn >= memslots[slot].base_gfn)\n\t\t\tend = slot;\n\t\telse\n\t\t\tstart = slot + 1;\n\t}\n\n\tif (gfn >= memslots[start].base_gfn &&\n\t gfn < memslots[start].base_gfn + memslots[start].npages) {\n\t\tatomic_set(&slots->lru_slot, start);\n\t\treturn &memslots[start];\n\t}\n\n\treturn NULL;\n}", "project": "linux", "hash": 30729153982995968815676335862978537577, "size": 27, "commit_id": "0774a964ef561b7170d8d1b1bfe6f88002b6d219", "message": "KVM: Fix out of range accesses to memslots\n\nReset the LRU slot if it becomes invalid when deleting a memslot to fix\nan out-of-bounds/use-after-free access when searching through memslots.\n\nExplicitly check for there being no used slots in search_memslots(), and\nin the caller of s390's approximation variant.\n\nFixes: 36947254e5f9 (\"KVM: Dynamically size memslot array based on number of used slots\")\nReported-by: Qian Cai \nCc: Peter Xu \nSigned-off-by: Sean Christopherson \nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger \nSigned-off-by: Paolo Bonzini ", "target": 1, "dataset": "other", "idx": 204191} {"func": "search_memslots(struct kvm_memslots *slots, gfn_t gfn)\n{\n\tint start = 0, end = slots->used_slots;\n\tint slot = atomic_read(&slots->lru_slot);\n\tstruct kvm_memory_slot *memslots = slots->memslots;\n\n\tif (unlikely(!slots->used_slots))\n\t\treturn NULL;\n\n\tif (gfn >= memslots[slot].base_gfn &&\n\t gfn < memslots[slot].base_gfn + memslots[slot].npages)\n\t\treturn &memslots[slot];\n\n\twhile (start < end) {\n\t\tslot = start + (end - start) / 2;\n\n\t\tif (gfn >= memslots[slot].base_gfn)\n\t\t\tend = slot;\n\t\telse\n\t\t\tstart = slot + 1;\n\t}\n\n\tif (gfn >= memslots[start].base_gfn &&\n\t gfn < memslots[start].base_gfn + memslots[start].npages) {\n\t\tatomic_set(&slots->lru_slot, start);\n\t\treturn &memslots[start];\n\t}\n\n\treturn NULL;\n}", "project": "linux", "hash": 235844977515726339339926851382064351419, "size": 30, "commit_id": "0774a964ef561b7170d8d1b1bfe6f88002b6d219", "message": "KVM: Fix out of range accesses to memslots\n\nReset the LRU slot if it becomes invalid when deleting a memslot to fix\nan out-of-bounds/use-after-free access when searching through memslots.\n\nExplicitly check for there being no used slots in search_memslots(), and\nin the caller of s390's approximation variant.\n\nFixes: 36947254e5f9 (\"KVM: Dynamically size memslot array based on number of used slots\")\nReported-by: Qian Cai \nCc: Peter Xu \nSigned-off-by: Sean Christopherson \nMessage-Id: <20200320205546.2396-2-sean.j.christopherson@intel.com>\nAcked-by: Christian Borntraeger \nSigned-off-by: Paolo Bonzini ", "target": 0, "dataset": "other", "idx": 354422} {"func": "static int do_mount(const char *mnt, char **typep, mode_t rootmode,\n\t\t int fd, const char *opts, const char *dev, char **sourcep,\n\t\t char **mnt_optsp)\n{\n\tint res;\n\tint flags = MS_NOSUID | MS_NODEV;\n\tchar *optbuf;\n\tchar *mnt_opts = NULL;\n\tconst char *s;\n\tchar *d;\n\tchar *fsname = NULL;\n\tchar *subtype = NULL;\n\tchar *source = NULL;\n\tchar *type = NULL;\n\tint blkdev = 0;\n\n\toptbuf = (char *) malloc(strlen(opts) + 128);\n\tif (!optbuf) {\n\t\tfprintf(stderr, \"%s: failed to allocate memory\\n\", progname);\n\t\treturn -1;\n\t}\n\n\tfor (s = opts, d = optbuf; *s;) {\n\t\tunsigned len;\n\t\tconst char *fsname_str = \"fsname=\";\n\t\tconst char *subtype_str = \"subtype=\";\n\t\tbool escape_ok = begins_with(s, fsname_str) ||\n\t\t\t\t begins_with(s, subtype_str);\n\t\tfor (len = 0; s[len]; len++) {\n\t\t\tif (escape_ok && s[len] == '\\\\' && s[len + 1])\n\t\t\t\tlen++;\n\t\t\telse if (s[len] == ',')\n\t\t\t\tbreak;\n\t\t}\n\t\tif (begins_with(s, fsname_str)) {\n\t\t\tif (!get_string_opt(s, len, fsname_str, &fsname))\n\t\t\t\tgoto err;\n\t\t} else if (begins_with(s, subtype_str)) {\n\t\t\tif (!get_string_opt(s, len, subtype_str, &subtype))\n\t\t\t\tgoto err;\n\t\t} else if (opt_eq(s, len, \"blkdev\")) {\n\t\t\tif (getuid() != 0) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\"%s: option blkdev is privileged\\n\",\n\t\t\t\t\tprogname);\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tblkdev = 1;\n\t\t} else if (opt_eq(s, len, \"auto_unmount\")) {\n\t\t\tauto_unmount = 1;\n\t\t} else if (!begins_with(s, \"fd=\") &&\n\t\t\t !begins_with(s, \"rootmode=\") &&\n\t\t\t !begins_with(s, \"user_id=\") &&\n\t\t\t !begins_with(s, \"group_id=\")) {\n\t\t\tint on;\n\t\t\tint flag;\n\t\t\tint skip_option = 0;\n\t\t\tif (opt_eq(s, len, \"large_read\")) {\n\t\t\t\tstruct utsname utsname;\n\t\t\t\tunsigned kmaj, kmin;\n\t\t\t\tres = uname(&utsname);\n\t\t\t\tif (res == 0 &&\n\t\t\t\t sscanf(utsname.release, \"%u.%u\",\n\t\t\t\t\t &kmaj, &kmin) == 2 &&\n\t\t\t\t (kmaj > 2 || (kmaj == 2 && kmin > 4))) {\n\t\t\t\t\tfprintf(stderr, \"%s: note: 'large_read' mount option is deprecated for %i.%i kernels\\n\", progname, kmaj, kmin);\n\t\t\t\t\tskip_option = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (getuid() != 0 && !user_allow_other &&\n\t\t\t (opt_eq(s, len, \"allow_other\") ||\n\t\t\t opt_eq(s, len, \"allow_root\"))) {\n\t\t\t\tfprintf(stderr, \"%s: option %.*s only allowed if 'user_allow_other' is set in %s\\n\", progname, len, s, FUSE_CONF);\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tif (!skip_option) {\n\t\t\t\tif (find_mount_flag(s, len, &on, &flag)) {\n\t\t\t\t\tif (on)\n\t\t\t\t\t\tflags |= flag;\n\t\t\t\t\telse\n\t\t\t\t\t\tflags &= ~flag;\n\t\t\t\t} else {\n\t\t\t\t\tmemcpy(d, s, len);\n\t\t\t\t\td += len;\n\t\t\t\t\t*d++ = ',';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ts += len;\n\t\tif (*s)\n\t\t\ts++;\n\t}\n\t*d = '\\0';\n\tres = get_mnt_opts(flags, optbuf, &mnt_opts);\n\tif (res == -1)\n\t\tgoto err;\n\n\tsprintf(d, \"fd=%i,rootmode=%o,user_id=%u,group_id=%u\",\n\t\tfd, rootmode, getuid(), getgid());\n\n\tsource = malloc((fsname ? strlen(fsname) : 0) +\n\t\t\t(subtype ? strlen(subtype) : 0) + strlen(dev) + 32);\n\n\ttype = malloc((subtype ? strlen(subtype) : 0) + 32);\n\tif (!type || !source) {\n\t\tfprintf(stderr, \"%s: failed to allocate memory\\n\", progname);\n\t\tgoto err;\n\t}\n\n\tif (subtype)\n\t\tsprintf(type, \"%s.%s\", blkdev ? \"fuseblk\" : \"fuse\", subtype);\n\telse\n\t\tstrcpy(type, blkdev ? \"fuseblk\" : \"fuse\");\n\n\tif (fsname)\n\t\tstrcpy(source, fsname);\n\telse\n\t\tstrcpy(source, subtype ? subtype : dev);\n\n\tres = mount_notrunc(source, mnt, type, flags, optbuf);\n\tif (res == -1 && errno == ENODEV && subtype) {\n\t\t/* Probably missing subtype support */\n\t\tstrcpy(type, blkdev ? \"fuseblk\" : \"fuse\");\n\t\tif (fsname) {\n\t\t\tif (!blkdev)\n\t\t\t\tsprintf(source, \"%s#%s\", subtype, fsname);\n\t\t} else {\n\t\t\tstrcpy(source, type);\n\t\t}\n\n\t\tres = mount_notrunc(source, mnt, type, flags, optbuf);\n\t}\n\tif (res == -1 && errno == EINVAL) {\n\t\t/* It could be an old version not supporting group_id */\n\t\tsprintf(d, \"fd=%i,rootmode=%o,user_id=%u\",\n\t\t\tfd, rootmode, getuid());\n\t\tres = mount_notrunc(source, mnt, type, flags, optbuf);\n\t}\n\tif (res == -1) {\n\t\tint errno_save = errno;\n\t\tif (blkdev && errno == ENODEV && !fuse_mnt_check_fuseblk())\n\t\t\tfprintf(stderr, \"%s: 'fuseblk' support missing\\n\",\n\t\t\t\tprogname);\n\t\telse\n\t\t\tfprintf(stderr, \"%s: mount failed: %s\\n\", progname,\n\t\t\t\tstrerror(errno_save));\n\t\tgoto err;\n\t}\n\t*sourcep = source;\n\t*typep = type;\n\t*mnt_optsp = mnt_opts;\n\tfree(fsname);\n\tfree(optbuf);\n\n\treturn 0;\n\nerr:\n\tfree(fsname);\n\tfree(subtype);\n\tfree(source);\n\tfree(type);\n\tfree(mnt_opts);\n\tfree(optbuf);\n\treturn -1;\n}", "project": "libfuse", "hash": 28697076378881475463957753142520709775, "size": 165, "commit_id": "5018a0c016495155ee598b7e0167b43d5d902414", "message": "fusermount: refuse unknown options\n\nBlacklists are notoriously fragile; especially if the kernel wishes to add\nsome security-critical mount option at a later date, all existing systems\nwith older versions of fusermount installed will suddenly have a security\nproblem.\nAdditionally, if the kernel's option parsing became a tiny bit laxer, the\nblacklist could probably be bypassed.\n\nWhitelist known-harmless flags instead, even if it's slightly more\ninconvenient.", "target": 1, "dataset": "other", "idx": 204216} {"func": "static int do_mount(const char *mnt, char **typep, mode_t rootmode,\n\t\t int fd, const char *opts, const char *dev, char **sourcep,\n\t\t char **mnt_optsp)\n{\n\tint res;\n\tint flags = MS_NOSUID | MS_NODEV;\n\tchar *optbuf;\n\tchar *mnt_opts = NULL;\n\tconst char *s;\n\tchar *d;\n\tchar *fsname = NULL;\n\tchar *subtype = NULL;\n\tchar *source = NULL;\n\tchar *type = NULL;\n\tint blkdev = 0;\n\n\toptbuf = (char *) malloc(strlen(opts) + 128);\n\tif (!optbuf) {\n\t\tfprintf(stderr, \"%s: failed to allocate memory\\n\", progname);\n\t\treturn -1;\n\t}\n\n\tfor (s = opts, d = optbuf; *s;) {\n\t\tunsigned len;\n\t\tconst char *fsname_str = \"fsname=\";\n\t\tconst char *subtype_str = \"subtype=\";\n\t\tbool escape_ok = begins_with(s, fsname_str) ||\n\t\t\t\t begins_with(s, subtype_str);\n\t\tfor (len = 0; s[len]; len++) {\n\t\t\tif (escape_ok && s[len] == '\\\\' && s[len + 1])\n\t\t\t\tlen++;\n\t\t\telse if (s[len] == ',')\n\t\t\t\tbreak;\n\t\t}\n\t\tif (begins_with(s, fsname_str)) {\n\t\t\tif (!get_string_opt(s, len, fsname_str, &fsname))\n\t\t\t\tgoto err;\n\t\t} else if (begins_with(s, subtype_str)) {\n\t\t\tif (!get_string_opt(s, len, subtype_str, &subtype))\n\t\t\t\tgoto err;\n\t\t} else if (opt_eq(s, len, \"blkdev\")) {\n\t\t\tif (getuid() != 0) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\"%s: option blkdev is privileged\\n\",\n\t\t\t\t\tprogname);\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tblkdev = 1;\n\t\t} else if (opt_eq(s, len, \"auto_unmount\")) {\n\t\t\tauto_unmount = 1;\n\t\t} else if (!begins_with(s, \"fd=\") &&\n\t\t\t !begins_with(s, \"rootmode=\") &&\n\t\t\t !begins_with(s, \"user_id=\") &&\n\t\t\t !begins_with(s, \"group_id=\")) {\n\t\t\tint on;\n\t\t\tint flag;\n\t\t\tint skip_option = 0;\n\t\t\tif (opt_eq(s, len, \"large_read\")) {\n\t\t\t\tstruct utsname utsname;\n\t\t\t\tunsigned kmaj, kmin;\n\t\t\t\tres = uname(&utsname);\n\t\t\t\tif (res == 0 &&\n\t\t\t\t sscanf(utsname.release, \"%u.%u\",\n\t\t\t\t\t &kmaj, &kmin) == 2 &&\n\t\t\t\t (kmaj > 2 || (kmaj == 2 && kmin > 4))) {\n\t\t\t\t\tfprintf(stderr, \"%s: note: 'large_read' mount option is deprecated for %i.%i kernels\\n\", progname, kmaj, kmin);\n\t\t\t\t\tskip_option = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (getuid() != 0 && !user_allow_other &&\n\t\t\t (opt_eq(s, len, \"allow_other\") ||\n\t\t\t opt_eq(s, len, \"allow_root\"))) {\n\t\t\t\tfprintf(stderr, \"%s: option %.*s only allowed if 'user_allow_other' is set in %s\\n\", progname, len, s, FUSE_CONF);\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tif (!skip_option) {\n\t\t\t\tif (find_mount_flag(s, len, &on, &flag)) {\n\t\t\t\t\tif (on)\n\t\t\t\t\t\tflags |= flag;\n\t\t\t\t\telse\n\t\t\t\t\t\tflags &= ~flag;\n\t\t\t\t} else if (opt_eq(s, len, \"default_permissions\") ||\n\t\t\t\t\t opt_eq(s, len, \"allow_other\") ||\n\t\t\t\t\t begins_with(s, \"max_read=\") ||\n\t\t\t\t\t begins_with(s, \"blksize=\")) {\n\t\t\t\t\tmemcpy(d, s, len);\n\t\t\t\t\td += len;\n\t\t\t\t\t*d++ = ',';\n\t\t\t\t} else {\n\t\t\t\t\tfprintf(stderr, \"%s: unknown option '%.*s'\\n\", progname, len, s);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ts += len;\n\t\tif (*s)\n\t\t\ts++;\n\t}\n\t*d = '\\0';\n\tres = get_mnt_opts(flags, optbuf, &mnt_opts);\n\tif (res == -1)\n\t\tgoto err;\n\n\tsprintf(d, \"fd=%i,rootmode=%o,user_id=%u,group_id=%u\",\n\t\tfd, rootmode, getuid(), getgid());\n\n\tsource = malloc((fsname ? strlen(fsname) : 0) +\n\t\t\t(subtype ? strlen(subtype) : 0) + strlen(dev) + 32);\n\n\ttype = malloc((subtype ? strlen(subtype) : 0) + 32);\n\tif (!type || !source) {\n\t\tfprintf(stderr, \"%s: failed to allocate memory\\n\", progname);\n\t\tgoto err;\n\t}\n\n\tif (subtype)\n\t\tsprintf(type, \"%s.%s\", blkdev ? \"fuseblk\" : \"fuse\", subtype);\n\telse\n\t\tstrcpy(type, blkdev ? \"fuseblk\" : \"fuse\");\n\n\tif (fsname)\n\t\tstrcpy(source, fsname);\n\telse\n\t\tstrcpy(source, subtype ? subtype : dev);\n\n\tres = mount_notrunc(source, mnt, type, flags, optbuf);\n\tif (res == -1 && errno == ENODEV && subtype) {\n\t\t/* Probably missing subtype support */\n\t\tstrcpy(type, blkdev ? \"fuseblk\" : \"fuse\");\n\t\tif (fsname) {\n\t\t\tif (!blkdev)\n\t\t\t\tsprintf(source, \"%s#%s\", subtype, fsname);\n\t\t} else {\n\t\t\tstrcpy(source, type);\n\t\t}\n\n\t\tres = mount_notrunc(source, mnt, type, flags, optbuf);\n\t}\n\tif (res == -1 && errno == EINVAL) {\n\t\t/* It could be an old version not supporting group_id */\n\t\tsprintf(d, \"fd=%i,rootmode=%o,user_id=%u\",\n\t\t\tfd, rootmode, getuid());\n\t\tres = mount_notrunc(source, mnt, type, flags, optbuf);\n\t}\n\tif (res == -1) {\n\t\tint errno_save = errno;\n\t\tif (blkdev && errno == ENODEV && !fuse_mnt_check_fuseblk())\n\t\t\tfprintf(stderr, \"%s: 'fuseblk' support missing\\n\",\n\t\t\t\tprogname);\n\t\telse\n\t\t\tfprintf(stderr, \"%s: mount failed: %s\\n\", progname,\n\t\t\t\tstrerror(errno_save));\n\t\tgoto err;\n\t}\n\t*sourcep = source;\n\t*typep = type;\n\t*mnt_optsp = mnt_opts;\n\tfree(fsname);\n\tfree(optbuf);\n\n\treturn 0;\n\nerr:\n\tfree(fsname);\n\tfree(subtype);\n\tfree(source);\n\tfree(type);\n\tfree(mnt_opts);\n\tfree(optbuf);\n\treturn -1;\n}", "project": "libfuse", "hash": 91910532426858602413944803061438595958, "size": 171, "commit_id": "5018a0c016495155ee598b7e0167b43d5d902414", "message": "fusermount: refuse unknown options\n\nBlacklists are notoriously fragile; especially if the kernel wishes to add\nsome security-critical mount option at a later date, all existing systems\nwith older versions of fusermount installed will suddenly have a security\nproblem.\nAdditionally, if the kernel's option parsing became a tiny bit laxer, the\nblacklist could probably be bypassed.\n\nWhitelist known-harmless flags instead, even if it's slightly more\ninconvenient.", "target": 0, "dataset": "other", "idx": 355497} {"func": "xz_decomp(xz_statep state)\n{\n int ret;\n unsigned had;\n unsigned long crc, len;\n lzma_stream *strm = &(state->strm);\n\n lzma_action action = LZMA_RUN;\n\n /* fill output buffer up to end of deflate stream */\n had = strm->avail_out;\n do {\n /* get more input for inflate() */\n if (strm->avail_in == 0 && xz_avail(state) == -1)\n return -1;\n if (strm->avail_in == 0) {\n xz_error(state, LZMA_DATA_ERROR, \"unexpected end of file\");\n return -1;\n }\n if (state->eof)\n action = LZMA_FINISH;\n\n /* decompress and handle errors */\n#ifdef HAVE_ZLIB_H\n if (state->how == GZIP) {\n state->zstrm.avail_in = (uInt) state->strm.avail_in;\n state->zstrm.next_in = (Bytef *) state->strm.next_in;\n state->zstrm.avail_out = (uInt) state->strm.avail_out;\n state->zstrm.next_out = (Bytef *) state->strm.next_out;\n ret = inflate(&state->zstrm, Z_NO_FLUSH);\n if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {\n xz_error(state, Z_STREAM_ERROR,\n \"internal error: inflate stream corrupt\");\n return -1;\n }\n if (ret == Z_MEM_ERROR)\n ret = LZMA_MEM_ERROR;\n if (ret == Z_DATA_ERROR)\n ret = LZMA_DATA_ERROR;\n if (ret == Z_STREAM_END)\n ret = LZMA_STREAM_END;\n state->strm.avail_in = state->zstrm.avail_in;\n state->strm.next_in = state->zstrm.next_in;\n state->strm.avail_out = state->zstrm.avail_out;\n state->strm.next_out = state->zstrm.next_out;\n } else /* state->how == LZMA */\n#endif\n ret = lzma_code(strm, action);\n if (ret == LZMA_MEM_ERROR) {\n xz_error(state, LZMA_MEM_ERROR, \"out of memory\");\n return -1;\n }\n if (ret == LZMA_DATA_ERROR) {\n xz_error(state, LZMA_DATA_ERROR, \"compressed data error\");\n return -1;\n }\n } while (strm->avail_out && ret != LZMA_STREAM_END);\n\n /* update available output and crc check value */\n state->have = had - strm->avail_out;\n state->next = strm->next_out - state->have;\n#ifdef HAVE_ZLIB_H\n state->zstrm.adler =\n crc32(state->zstrm.adler, state->next, state->have);\n#endif\n\n if (ret == LZMA_STREAM_END) {\n#ifdef HAVE_ZLIB_H\n if (state->how == GZIP) {\n if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) {\n xz_error(state, LZMA_DATA_ERROR, \"unexpected end of file\");\n return -1;\n }\n if (crc != state->zstrm.adler) {\n xz_error(state, LZMA_DATA_ERROR, \"incorrect data check\");\n return -1;\n }\n if (len != (state->zstrm.total_out & 0xffffffffL)) {\n xz_error(state, LZMA_DATA_ERROR, \"incorrect length check\");\n return -1;\n }\n state->strm.avail_in = 0;\n state->strm.next_in = NULL;\n state->strm.avail_out = 0;\n state->strm.next_out = NULL;\n } else\n#endif\n if (strm->avail_in != 0 || !state->eof) {\n xz_error(state, LZMA_DATA_ERROR, \"trailing garbage\");\n return -1;\n }\n state->how = LOOK; /* ready for next stream, once have is 0 (leave\n * state->direct unchanged to remember how) */\n }\n\n /* good decompression */\n return 0;\n}", "project": "libxml2", "hash": 325103388462275924711924070031298132490, "size": 98, "commit_id": "f0709e3ca8f8947f2d91ed34e92e38a4c23eae63", "message": "CVE-2015-8035 Fix XZ compression support loop\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=757466\nDoS when parsing specially crafted XML document if XZ support\nis compiled in (which wasn't the case for 2.9.2 and master since\nNov 2013, fixed in next commit !)", "target": 1, "dataset": "other", "idx": 204281} {"func": "xz_decomp(xz_statep state)\n{\n int ret;\n unsigned had;\n unsigned long crc, len;\n lzma_stream *strm = &(state->strm);\n\n lzma_action action = LZMA_RUN;\n\n /* fill output buffer up to end of deflate stream */\n had = strm->avail_out;\n do {\n /* get more input for inflate() */\n if (strm->avail_in == 0 && xz_avail(state) == -1)\n return -1;\n if (strm->avail_in == 0) {\n xz_error(state, LZMA_DATA_ERROR, \"unexpected end of file\");\n return -1;\n }\n if (state->eof)\n action = LZMA_FINISH;\n\n /* decompress and handle errors */\n#ifdef HAVE_ZLIB_H\n if (state->how == GZIP) {\n state->zstrm.avail_in = (uInt) state->strm.avail_in;\n state->zstrm.next_in = (Bytef *) state->strm.next_in;\n state->zstrm.avail_out = (uInt) state->strm.avail_out;\n state->zstrm.next_out = (Bytef *) state->strm.next_out;\n ret = inflate(&state->zstrm, Z_NO_FLUSH);\n if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {\n xz_error(state, Z_STREAM_ERROR,\n \"internal error: inflate stream corrupt\");\n return -1;\n }\n if (ret == Z_MEM_ERROR)\n ret = LZMA_MEM_ERROR;\n if (ret == Z_DATA_ERROR)\n ret = LZMA_DATA_ERROR;\n if (ret == Z_STREAM_END)\n ret = LZMA_STREAM_END;\n state->strm.avail_in = state->zstrm.avail_in;\n state->strm.next_in = state->zstrm.next_in;\n state->strm.avail_out = state->zstrm.avail_out;\n state->strm.next_out = state->zstrm.next_out;\n } else /* state->how == LZMA */\n#endif\n ret = lzma_code(strm, action);\n if (ret == LZMA_MEM_ERROR) {\n xz_error(state, LZMA_MEM_ERROR, \"out of memory\");\n return -1;\n }\n if (ret == LZMA_DATA_ERROR) {\n xz_error(state, LZMA_DATA_ERROR, \"compressed data error\");\n return -1;\n }\n if (ret == LZMA_PROG_ERROR) {\n xz_error(state, LZMA_PROG_ERROR, \"compression error\");\n return -1;\n }\n } while (strm->avail_out && ret != LZMA_STREAM_END);\n\n /* update available output and crc check value */\n state->have = had - strm->avail_out;\n state->next = strm->next_out - state->have;\n#ifdef HAVE_ZLIB_H\n state->zstrm.adler =\n crc32(state->zstrm.adler, state->next, state->have);\n#endif\n\n if (ret == LZMA_STREAM_END) {\n#ifdef HAVE_ZLIB_H\n if (state->how == GZIP) {\n if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) {\n xz_error(state, LZMA_DATA_ERROR, \"unexpected end of file\");\n return -1;\n }\n if (crc != state->zstrm.adler) {\n xz_error(state, LZMA_DATA_ERROR, \"incorrect data check\");\n return -1;\n }\n if (len != (state->zstrm.total_out & 0xffffffffL)) {\n xz_error(state, LZMA_DATA_ERROR, \"incorrect length check\");\n return -1;\n }\n state->strm.avail_in = 0;\n state->strm.next_in = NULL;\n state->strm.avail_out = 0;\n state->strm.next_out = NULL;\n } else\n#endif\n if (strm->avail_in != 0 || !state->eof) {\n xz_error(state, LZMA_DATA_ERROR, \"trailing garbage\");\n return -1;\n }\n state->how = LOOK; /* ready for next stream, once have is 0 (leave\n * state->direct unchanged to remember how) */\n }\n\n /* good decompression */\n return 0;\n}", "project": "libxml2", "hash": 282138316863849492396180930649832436502, "size": 102, "commit_id": "f0709e3ca8f8947f2d91ed34e92e38a4c23eae63", "message": "CVE-2015-8035 Fix XZ compression support loop\n\nFor https://bugzilla.gnome.org/show_bug.cgi?id=757466\nDoS when parsing specially crafted XML document if XZ support\nis compiled in (which wasn't the case for 2.9.2 and master since\nNov 2013, fixed in next commit !)", "target": 0, "dataset": "other", "idx": 356273} {"func": "static int selectExpander(Walker *pWalker, Select *p){\n Parse *pParse = pWalker->pParse;\n int i, j, k;\n SrcList *pTabList;\n ExprList *pEList;\n struct SrcList_item *pFrom;\n sqlite3 *db = pParse->db;\n Expr *pE, *pRight, *pExpr;\n u16 selFlags = p->selFlags;\n u32 elistFlags = 0;\n\n p->selFlags |= SF_Expanded;\n if( db->mallocFailed ){\n return WRC_Abort;\n }\n assert( p->pSrc!=0 );\n if( (selFlags & SF_Expanded)!=0 ){\n return WRC_Prune;\n }\n if( pWalker->eCode ){\n /* Renumber selId because it has been copied from a view */\n p->selId = ++pParse->nSelect;\n }\n pTabList = p->pSrc;\n pEList = p->pEList;\n sqlite3WithPush(pParse, p->pWith, 0);\n\n /* Make sure cursor numbers have been assigned to all entries in\n ** the FROM clause of the SELECT statement.\n */\n sqlite3SrcListAssignCursors(pParse, pTabList);\n\n /* Look up every table named in the FROM clause of the select. If\n ** an entry of the FROM clause is a subquery instead of a table or view,\n ** then create a transient table structure to describe the subquery.\n */\n for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){\n Table *pTab;\n assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );\n if( pFrom->fg.isRecursive ) continue;\n assert( pFrom->pTab==0 );\n#ifndef SQLITE_OMIT_CTE\n if( withExpand(pWalker, pFrom) ) return WRC_Abort;\n if( pFrom->pTab ) {} else\n#endif\n if( pFrom->zName==0 ){\n#ifndef SQLITE_OMIT_SUBQUERY\n Select *pSel = pFrom->pSelect;\n /* A sub-query in the FROM clause of a SELECT */\n assert( pSel!=0 );\n assert( pFrom->pTab==0 );\n if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;\n if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;\n#endif\n }else{\n /* An ordinary table or view name in the FROM clause */\n assert( pFrom->pTab==0 );\n pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);\n if( pTab==0 ) return WRC_Abort;\n if( pTab->nTabRef>=0xffff ){\n sqlite3ErrorMsg(pParse, \"too many references to \\\"%s\\\": max 65535\",\n pTab->zName);\n pFrom->pTab = 0;\n return WRC_Abort;\n }\n pTab->nTabRef++;\n if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){\n return WRC_Abort;\n }\n#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)\n if( IsVirtual(pTab) || pTab->pSelect ){\n i16 nCol;\n u8 eCodeOrig = pWalker->eCode;\n if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;\n assert( pFrom->pSelect==0 );\n if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){\n sqlite3ErrorMsg(pParse, \"access to view \\\"%s\\\" prohibited\",\n pTab->zName);\n }\n pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);\n nCol = pTab->nCol;\n pTab->nCol = -1;\n pWalker->eCode = 1; /* Turn on Select.selId renumbering */\n sqlite3WalkSelect(pWalker, pFrom->pSelect);\n pWalker->eCode = eCodeOrig;\n pTab->nCol = nCol;\n }\n#endif\n }\n\n /* Locate the index named by the INDEXED BY clause, if any. */\n if( sqlite3IndexedByLookup(pParse, pFrom) ){\n return WRC_Abort;\n }\n }\n\n /* Process NATURAL keywords, and ON and USING clauses of joins.\n */\n if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){\n return WRC_Abort;\n }\n\n /* For every \"*\" that occurs in the column list, insert the names of\n ** all columns in all tables. And for every TABLE.* insert the names\n ** of all columns in TABLE. The parser inserted a special expression\n ** with the TK_ASTERISK operator for each \"*\" that it found in the column\n ** list. The following code just has to locate the TK_ASTERISK\n ** expressions and expand each one to the list of all columns in\n ** all tables.\n **\n ** The first loop just checks to see if there are any \"*\" operators\n ** that need expanding.\n */\n for(k=0; knExpr; k++){\n pE = pEList->a[k].pExpr;\n if( pE->op==TK_ASTERISK ) break;\n assert( pE->op!=TK_DOT || pE->pRight!=0 );\n assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );\n if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;\n elistFlags |= pE->flags;\n }\n if( knExpr ){\n /*\n ** If we get here it means the result set contains one or more \"*\"\n ** operators that need to be expanded. Loop through each expression\n ** in the result set and expand them one by one.\n */\n struct ExprList_item *a = pEList->a;\n ExprList *pNew = 0;\n int flags = pParse->db->flags;\n int longNames = (flags & SQLITE_FullColNames)!=0\n && (flags & SQLITE_ShortColNames)==0;\n\n for(k=0; knExpr; k++){\n pE = a[k].pExpr;\n elistFlags |= pE->flags;\n pRight = pE->pRight;\n assert( pE->op!=TK_DOT || pRight!=0 );\n if( pE->op!=TK_ASTERISK\n && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)\n ){\n /* This particular expression does not need to be expanded.\n */\n pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);\n if( pNew ){\n pNew->a[pNew->nExpr-1].zName = a[k].zName;\n pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;\n a[k].zName = 0;\n a[k].zSpan = 0;\n }\n a[k].pExpr = 0;\n }else{\n /* This expression is a \"*\" or a \"TABLE.*\" and needs to be\n ** expanded. */\n int tableSeen = 0; /* Set to 1 when TABLE matches */\n char *zTName = 0; /* text of name of TABLE */\n if( pE->op==TK_DOT ){\n assert( pE->pLeft!=0 );\n assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );\n zTName = pE->pLeft->u.zToken;\n }\n for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){\n Table *pTab = pFrom->pTab;\n Select *pSub = pFrom->pSelect;\n char *zTabName = pFrom->zAlias;\n const char *zSchemaName = 0;\n int iDb;\n if( zTabName==0 ){\n zTabName = pTab->zName;\n }\n if( db->mallocFailed ) break;\n if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){\n pSub = 0;\n if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){\n continue;\n }\n iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : \"*\";\n }\n for(j=0; jnCol; j++){\n char *zName = pTab->aCol[j].zName;\n char *zColname; /* The computed column name */\n char *zToFree; /* Malloced string that needs to be freed */\n Token sColname; /* Computed column name as a token */\n\n assert( zName );\n if( zTName && pSub\n && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0\n ){\n continue;\n }\n\n /* If a column is marked as 'hidden', omit it from the expanded\n ** result-set list unless the SELECT has the SF_IncludeHidden\n ** bit set.\n */\n if( (p->selFlags & SF_IncludeHidden)==0\n && IsHiddenColumn(&pTab->aCol[j]) \n ){\n continue;\n }\n tableSeen = 1;\n\n if( i>0 && zTName==0 ){\n if( (pFrom->fg.jointype & JT_NATURAL)!=0\n && tableAndColumnIndex(pTabList, i, zName, 0, 0)\n ){\n /* In a NATURAL join, omit the join columns from the \n ** table to the right of the join */\n continue;\n }\n if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){\n /* In a join with a USING clause, omit columns in the\n ** using clause from the table on the right. */\n continue;\n }\n }\n pRight = sqlite3Expr(db, TK_ID, zName);\n zColname = zName;\n zToFree = 0;\n if( longNames || pTabList->nSrc>1 ){\n Expr *pLeft;\n pLeft = sqlite3Expr(db, TK_ID, zTabName);\n pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);\n if( zSchemaName ){\n pLeft = sqlite3Expr(db, TK_ID, zSchemaName);\n pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);\n }\n if( longNames ){\n zColname = sqlite3MPrintf(db, \"%s.%s\", zTabName, zName);\n zToFree = zColname;\n }\n }else{\n pExpr = pRight;\n }\n pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);\n sqlite3TokenInit(&sColname, zColname);\n sqlite3ExprListSetName(pParse, pNew, &sColname, 0);\n if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){\n struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];\n if( pSub ){\n pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);\n testcase( pX->zSpan==0 );\n }else{\n pX->zSpan = sqlite3MPrintf(db, \"%s.%s.%s\",\n zSchemaName, zTabName, zColname);\n testcase( pX->zSpan==0 );\n }\n pX->bSpanIsTab = 1;\n }\n sqlite3DbFree(db, zToFree);\n }\n }\n if( !tableSeen ){\n if( zTName ){\n sqlite3ErrorMsg(pParse, \"no such table: %s\", zTName);\n }else{\n sqlite3ErrorMsg(pParse, \"no tables specified\");\n }\n }\n }\n }\n sqlite3ExprListDelete(db, pEList);\n p->pEList = pNew;\n }\n if( p->pEList ){\n if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n sqlite3ErrorMsg(pParse, \"too many columns in result set\");\n return WRC_Abort;\n }\n if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){\n p->selFlags |= SF_ComplexResult;\n }\n }\n return WRC_Continue;\n}", "project": "sqlite", "hash": 306812494712022841209499043837047336891, "size": 276, "commit_id": "a6c1a71cde082e09750465d5675699062922e387", "message": "Do not attempt to unwind the WITH stack in the Parse object following an error. This fixes a separate case to [de6e6d68].\n\nFossilOrigin-Name: d29edef93451cc67a5d69c1cce1b1832d9ca8fff1f600afdd51338b74d077b92", "target": 1, "dataset": "other", "idx": 204285} {"func": "static int selectExpander(Walker *pWalker, Select *p){\n Parse *pParse = pWalker->pParse;\n int i, j, k;\n SrcList *pTabList;\n ExprList *pEList;\n struct SrcList_item *pFrom;\n sqlite3 *db = pParse->db;\n Expr *pE, *pRight, *pExpr;\n u16 selFlags = p->selFlags;\n u32 elistFlags = 0;\n\n p->selFlags |= SF_Expanded;\n if( db->mallocFailed ){\n return WRC_Abort;\n }\n assert( p->pSrc!=0 );\n if( (selFlags & SF_Expanded)!=0 ){\n return WRC_Prune;\n }\n if( pWalker->eCode ){\n /* Renumber selId because it has been copied from a view */\n p->selId = ++pParse->nSelect;\n }\n pTabList = p->pSrc;\n pEList = p->pEList;\n sqlite3WithPush(pParse, p->pWith, 0);\n\n /* Make sure cursor numbers have been assigned to all entries in\n ** the FROM clause of the SELECT statement.\n */\n sqlite3SrcListAssignCursors(pParse, pTabList);\n\n /* Look up every table named in the FROM clause of the select. If\n ** an entry of the FROM clause is a subquery instead of a table or view,\n ** then create a transient table structure to describe the subquery.\n */\n for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){\n Table *pTab;\n assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );\n if( pFrom->fg.isRecursive ) continue;\n assert( pFrom->pTab==0 );\n#ifndef SQLITE_OMIT_CTE\n if( withExpand(pWalker, pFrom) ) return WRC_Abort;\n if( pFrom->pTab ) {} else\n#endif\n if( pFrom->zName==0 ){\n#ifndef SQLITE_OMIT_SUBQUERY\n Select *pSel = pFrom->pSelect;\n /* A sub-query in the FROM clause of a SELECT */\n assert( pSel!=0 );\n assert( pFrom->pTab==0 );\n if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;\n if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;\n#endif\n }else{\n /* An ordinary table or view name in the FROM clause */\n assert( pFrom->pTab==0 );\n pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);\n if( pTab==0 ) return WRC_Abort;\n if( pTab->nTabRef>=0xffff ){\n sqlite3ErrorMsg(pParse, \"too many references to \\\"%s\\\": max 65535\",\n pTab->zName);\n pFrom->pTab = 0;\n return WRC_Abort;\n }\n pTab->nTabRef++;\n if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){\n return WRC_Abort;\n }\n#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)\n if( IsVirtual(pTab) || pTab->pSelect ){\n i16 nCol;\n u8 eCodeOrig = pWalker->eCode;\n if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;\n assert( pFrom->pSelect==0 );\n if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){\n sqlite3ErrorMsg(pParse, \"access to view \\\"%s\\\" prohibited\",\n pTab->zName);\n }\n pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);\n nCol = pTab->nCol;\n pTab->nCol = -1;\n pWalker->eCode = 1; /* Turn on Select.selId renumbering */\n sqlite3WalkSelect(pWalker, pFrom->pSelect);\n pWalker->eCode = eCodeOrig;\n pTab->nCol = nCol;\n }\n#endif\n }\n\n /* Locate the index named by the INDEXED BY clause, if any. */\n if( sqlite3IndexedByLookup(pParse, pFrom) ){\n return WRC_Abort;\n }\n }\n\n /* Process NATURAL keywords, and ON and USING clauses of joins.\n */\n if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){\n return WRC_Abort;\n }\n\n /* For every \"*\" that occurs in the column list, insert the names of\n ** all columns in all tables. And for every TABLE.* insert the names\n ** of all columns in TABLE. The parser inserted a special expression\n ** with the TK_ASTERISK operator for each \"*\" that it found in the column\n ** list. The following code just has to locate the TK_ASTERISK\n ** expressions and expand each one to the list of all columns in\n ** all tables.\n **\n ** The first loop just checks to see if there are any \"*\" operators\n ** that need expanding.\n */\n for(k=0; knExpr; k++){\n pE = pEList->a[k].pExpr;\n if( pE->op==TK_ASTERISK ) break;\n assert( pE->op!=TK_DOT || pE->pRight!=0 );\n assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );\n if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;\n elistFlags |= pE->flags;\n }\n if( knExpr ){\n /*\n ** If we get here it means the result set contains one or more \"*\"\n ** operators that need to be expanded. Loop through each expression\n ** in the result set and expand them one by one.\n */\n struct ExprList_item *a = pEList->a;\n ExprList *pNew = 0;\n int flags = pParse->db->flags;\n int longNames = (flags & SQLITE_FullColNames)!=0\n && (flags & SQLITE_ShortColNames)==0;\n\n for(k=0; knExpr; k++){\n pE = a[k].pExpr;\n elistFlags |= pE->flags;\n pRight = pE->pRight;\n assert( pE->op!=TK_DOT || pRight!=0 );\n if( pE->op!=TK_ASTERISK\n && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)\n ){\n /* This particular expression does not need to be expanded.\n */\n pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);\n if( pNew ){\n pNew->a[pNew->nExpr-1].zName = a[k].zName;\n pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;\n a[k].zName = 0;\n a[k].zSpan = 0;\n }\n a[k].pExpr = 0;\n }else{\n /* This expression is a \"*\" or a \"TABLE.*\" and needs to be\n ** expanded. */\n int tableSeen = 0; /* Set to 1 when TABLE matches */\n char *zTName = 0; /* text of name of TABLE */\n if( pE->op==TK_DOT ){\n assert( pE->pLeft!=0 );\n assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );\n zTName = pE->pLeft->u.zToken;\n }\n for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){\n Table *pTab = pFrom->pTab;\n Select *pSub = pFrom->pSelect;\n char *zTabName = pFrom->zAlias;\n const char *zSchemaName = 0;\n int iDb;\n if( zTabName==0 ){\n zTabName = pTab->zName;\n }\n if( db->mallocFailed ) break;\n if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){\n pSub = 0;\n if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){\n continue;\n }\n iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : \"*\";\n }\n for(j=0; jnCol; j++){\n char *zName = pTab->aCol[j].zName;\n char *zColname; /* The computed column name */\n char *zToFree; /* Malloced string that needs to be freed */\n Token sColname; /* Computed column name as a token */\n\n assert( zName );\n if( zTName && pSub\n && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0\n ){\n continue;\n }\n\n /* If a column is marked as 'hidden', omit it from the expanded\n ** result-set list unless the SELECT has the SF_IncludeHidden\n ** bit set.\n */\n if( (p->selFlags & SF_IncludeHidden)==0\n && IsHiddenColumn(&pTab->aCol[j]) \n ){\n continue;\n }\n tableSeen = 1;\n\n if( i>0 && zTName==0 ){\n if( (pFrom->fg.jointype & JT_NATURAL)!=0\n && tableAndColumnIndex(pTabList, i, zName, 0, 0)\n ){\n /* In a NATURAL join, omit the join columns from the \n ** table to the right of the join */\n continue;\n }\n if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){\n /* In a join with a USING clause, omit columns in the\n ** using clause from the table on the right. */\n continue;\n }\n }\n pRight = sqlite3Expr(db, TK_ID, zName);\n zColname = zName;\n zToFree = 0;\n if( longNames || pTabList->nSrc>1 ){\n Expr *pLeft;\n pLeft = sqlite3Expr(db, TK_ID, zTabName);\n pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);\n if( zSchemaName ){\n pLeft = sqlite3Expr(db, TK_ID, zSchemaName);\n pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);\n }\n if( longNames ){\n zColname = sqlite3MPrintf(db, \"%s.%s\", zTabName, zName);\n zToFree = zColname;\n }\n }else{\n pExpr = pRight;\n }\n pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);\n sqlite3TokenInit(&sColname, zColname);\n sqlite3ExprListSetName(pParse, pNew, &sColname, 0);\n if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){\n struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];\n if( pSub ){\n pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);\n testcase( pX->zSpan==0 );\n }else{\n pX->zSpan = sqlite3MPrintf(db, \"%s.%s.%s\",\n zSchemaName, zTabName, zColname);\n testcase( pX->zSpan==0 );\n }\n pX->bSpanIsTab = 1;\n }\n sqlite3DbFree(db, zToFree);\n }\n }\n if( !tableSeen ){\n if( zTName ){\n sqlite3ErrorMsg(pParse, \"no such table: %s\", zTName);\n }else{\n sqlite3ErrorMsg(pParse, \"no tables specified\");\n }\n }\n }\n }\n sqlite3ExprListDelete(db, pEList);\n p->pEList = pNew;\n }\n if( p->pEList ){\n if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n sqlite3ErrorMsg(pParse, \"too many columns in result set\");\n return WRC_Abort;\n }\n if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){\n p->selFlags |= SF_ComplexResult;\n }\n }\n return WRC_Continue;\n}", "project": "sqlite", "hash": 27082898212798908738611756384964673964, "size": 276, "commit_id": "a6c1a71cde082e09750465d5675699062922e387", "message": "Do not attempt to unwind the WITH stack in the Parse object following an error. This fixes a separate case to [de6e6d68].\n\nFossilOrigin-Name: d29edef93451cc67a5d69c1cce1b1832d9ca8fff1f600afdd51338b74d077b92", "target": 0, "dataset": "other", "idx": 356309} {"func": "sudoers_policy_deserialize_info(void *v)\n{\n struct sudoers_open_info *info = v;\n char * const *cur;\n const char *p, *errstr, *groups = NULL;\n const char *remhost = NULL;\n int flags = 0;\n debug_decl(sudoers_policy_deserialize_info, SUDOERS_DEBUG_PLUGIN);\n\n#define MATCHES(s, v)\t\\\n (strncmp((s), (v), sizeof(v) - 1) == 0)\n\n#define INVALID(v) do {\t\\\n sudo_warn(U_(\"invalid %.*s set by sudo front-end\"), \\\n\t(int)(sizeof(v) - 2), (v)); \\\n} while (0)\n\n#define CHECK(s, v) do {\t\\\n if ((s)[sizeof(v) - 1] == '\\0') { \\\n\tINVALID(v); \\\n\tgoto bad; \\\n } \\\n} while (0)\n\n if (sudo_gettime_real(&sudo_user.submit_time) == -1) {\n\tsudo_warn(\"%s\", U_(\"unable to get time of day\"));\n\tgoto bad;\n }\n\n /* Parse sudo.conf plugin args. */\n if (info->plugin_args != NULL) {\n\tfor (cur = info->plugin_args; *cur != NULL; cur++) {\n\t if (MATCHES(*cur, \"error_recovery=\")) {\n\t\tint val = sudo_strtobool(*cur + sizeof(\"error_recovery=\") - 1);\n\t\tif (val == -1) {\n\t\t INVALID(\"error_recovery=\");\t/* Not a fatal error. */\n\t\t} else {\n\t\t sudoers_recovery = val;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_file=\")) {\n\t\tCHECK(*cur, \"sudoers_file=\");\n\t\tsudoers_file = *cur + sizeof(\"sudoers_file=\") - 1;\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_uid=\")) {\n\t\tp = *cur + sizeof(\"sudoers_uid=\") - 1;\n\t\tsudoers_uid = (uid_t) sudo_strtoid(p, &errstr);\n\t\tif (errstr != NULL) {\n\t\t sudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\t goto bad;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_gid=\")) {\n\t\tp = *cur + sizeof(\"sudoers_gid=\") - 1;\n\t\tsudoers_gid = (gid_t) sudo_strtoid(p, &errstr);\n\t\tif (errstr != NULL) {\n\t\t sudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\t goto bad;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_mode=\")) {\n\t\tp = *cur + sizeof(\"sudoers_mode=\") - 1;\n\t\tsudoers_mode = sudo_strtomode(p, &errstr);\n\t\tif (errstr != NULL) {\n\t\t sudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\t goto bad;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"ldap_conf=\")) {\n\t\tCHECK(*cur, \"ldap_conf=\");\n\t\tpath_ldap_conf = *cur + sizeof(\"ldap_conf=\") - 1;\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"ldap_secret=\")) {\n\t\tCHECK(*cur, \"ldap_secret=\");\n\t\tpath_ldap_secret = *cur + sizeof(\"ldap_secret=\") - 1;\n\t\tcontinue;\n\t }\n\t}\n }\n\n /* Parse command line settings. */\n user_closefrom = -1;\n for (cur = info->settings; *cur != NULL; cur++) {\n\tif (MATCHES(*cur, \"closefrom=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"closefrom=\") - 1;\n\t user_closefrom = sudo_strtonum(p, 3, INT_MAX, &errstr);\n\t if (user_closefrom == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cmnd_chroot=\")) {\n\t CHECK(*cur, \"cmnd_chroot=\");\n\t user_runchroot = *cur + sizeof(\"cmnd_chroot=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cmnd_cwd=\")) {\n\t CHECK(*cur, \"cmnd_cwd=\");\n\t user_runcwd = *cur + sizeof(\"cmnd_cwd=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"runas_user=\")) {\n\t CHECK(*cur, \"runas_user=\");\n\t sudo_user.runas_user = *cur + sizeof(\"runas_user=\") - 1;\n\t SET(sudo_user.flags, RUNAS_USER_SPECIFIED);\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"runas_group=\")) {\n\t CHECK(*cur, \"runas_group=\");\n\t sudo_user.runas_group = *cur + sizeof(\"runas_group=\") - 1;\n\t SET(sudo_user.flags, RUNAS_GROUP_SPECIFIED);\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"prompt=\")) {\n\t /* Allow epmpty prompt. */\n\t user_prompt = *cur + sizeof(\"prompt=\") - 1;\n\t def_passprompt_override = true;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"set_home=\")) {\n\t if (parse_bool(*cur, sizeof(\"set_home\") - 1, &flags,\n\t\tMODE_RESET_HOME) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"preserve_environment=\")) {\n\t if (parse_bool(*cur, sizeof(\"preserve_environment\") - 1, &flags,\n\t\tMODE_PRESERVE_ENV) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"run_shell=\")) {\n\t if (parse_bool(*cur, sizeof(\"run_shell\") -1, &flags,\n\t\tMODE_SHELL) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"login_shell=\")) {\n\t if (parse_bool(*cur, sizeof(\"login_shell\") - 1, &flags,\n\t\tMODE_LOGIN_SHELL) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"implied_shell=\")) {\n\t if (parse_bool(*cur, sizeof(\"implied_shell\") - 1, &flags,\n\t\tMODE_IMPLIED_SHELL) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"preserve_groups=\")) {\n\t if (parse_bool(*cur, sizeof(\"preserve_groups\") - 1, &flags,\n\t\tMODE_PRESERVE_GROUPS) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"ignore_ticket=\")) {\n\t if (parse_bool(*cur, sizeof(\"ignore_ticket\") -1, &flags,\n\t\tMODE_IGNORE_TICKET) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"noninteractive=\")) {\n\t if (parse_bool(*cur, sizeof(\"noninteractive\") - 1, &flags,\n\t\tMODE_NONINTERACTIVE) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"sudoedit=\")) {\n\t if (parse_bool(*cur, sizeof(\"sudoedit\") - 1, &flags,\n\t\tMODE_EDIT) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"login_class=\")) {\n\t CHECK(*cur, \"login_class=\");\n\t login_class = *cur + sizeof(\"login_class=\") - 1;\n\t def_use_loginclass = true;\n\t continue;\n\t}\n#ifdef HAVE_PRIV_SET\n\tif (MATCHES(*cur, \"runas_privs=\")) {\n\t CHECK(*cur, \"runas_privs=\");\n\t def_privs = *cur + sizeof(\"runas_privs=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"runas_limitprivs=\")) {\n\t CHECK(*cur, \"runas_limitprivs=\");\n\t def_limitprivs = *cur + sizeof(\"runas_limitprivs=\") - 1;\n\t continue;\n\t}\n#endif /* HAVE_PRIV_SET */\n#ifdef HAVE_SELINUX\n\tif (MATCHES(*cur, \"selinux_role=\")) {\n\t CHECK(*cur, \"selinux_role=\");\n\t user_role = *cur + sizeof(\"selinux_role=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"selinux_type=\")) {\n\t CHECK(*cur, \"selinux_type=\");\n\t user_type = *cur + sizeof(\"selinux_type=\") - 1;\n\t continue;\n\t}\n#endif /* HAVE_SELINUX */\n#ifdef HAVE_BSD_AUTH_H\n\tif (MATCHES(*cur, \"bsdauth_type=\")) {\n\t CHECK(*cur, \"login_style=\");\n\t login_style = *cur + sizeof(\"bsdauth_type=\") - 1;\n\t continue;\n\t}\n#endif /* HAVE_BSD_AUTH_H */\n\tif (MATCHES(*cur, \"network_addrs=\")) {\n\t interfaces_string = *cur + sizeof(\"network_addrs=\") - 1;\n\t if (!set_interfaces(interfaces_string)) {\n\t\tsudo_warn(\"%s\", U_(\"unable to parse network address list\"));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"max_groups=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"max_groups=\") - 1;\n\t sudo_user.max_groups = sudo_strtonum(p, 1, INT_MAX, &errstr);\n\t if (sudo_user.max_groups == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"remote_host=\")) {\n\t CHECK(*cur, \"remote_host=\");\n\t remhost = *cur + sizeof(\"remote_host=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"timeout=\")) {\n\t p = *cur + sizeof(\"timeout=\") - 1;\n\t user_timeout = parse_timeout(p);\n\t if (user_timeout == -1) {\n\t\tif (errno == ERANGE)\n\t\t sudo_warnx(U_(\"%s: %s\"), p, U_(\"timeout value too large\"));\n\t\telse\n\t\t sudo_warnx(U_(\"%s: %s\"), p, U_(\"invalid timeout value\"));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n#ifdef ENABLE_SUDO_PLUGIN_API\n\tif (MATCHES(*cur, \"plugin_dir=\")) {\n\t CHECK(*cur, \"plugin_dir=\");\n\t path_plugin_dir = *cur + sizeof(\"plugin_dir=\") - 1;\n\t continue;\n\t}\n#endif\n }\n\n user_gid = (gid_t)-1;\n user_sid = (pid_t)-1;\n user_uid = (gid_t)-1;\n user_umask = (mode_t)-1;\n for (cur = info->user_info; *cur != NULL; cur++) {\n\tif (MATCHES(*cur, \"user=\")) {\n\t CHECK(*cur, \"user=\");\n\t if ((user_name = strdup(*cur + sizeof(\"user=\") - 1)) == NULL)\n\t\tgoto oom;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"uid=\")) {\n\t p = *cur + sizeof(\"uid=\") - 1;\n\t user_uid = (uid_t) sudo_strtoid(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"gid=\")) {\n\t p = *cur + sizeof(\"gid=\") - 1;\n\t user_gid = (gid_t) sudo_strtoid(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"groups=\")) {\n\t CHECK(*cur, \"groups=\");\n\t groups = *cur + sizeof(\"groups=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cwd=\")) {\n\t CHECK(*cur, \"cwd=\");\n\t if ((user_cwd = strdup(*cur + sizeof(\"cwd=\") - 1)) == NULL)\n\t\tgoto oom;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"tty=\")) {\n\t CHECK(*cur, \"tty=\");\n\t if ((user_ttypath = strdup(*cur + sizeof(\"tty=\") - 1)) == NULL)\n\t\tgoto oom;\n\t user_tty = user_ttypath;\n\t if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)\n\t\tuser_tty += sizeof(_PATH_DEV) - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"host=\")) {\n\t CHECK(*cur, \"host=\");\n\t if ((user_host = strdup(*cur + sizeof(\"host=\") - 1)) == NULL)\n\t\tgoto oom;\n\t if ((p = strchr(user_host, '.')) != NULL) {\n\t\tuser_shost = strndup(user_host, (size_t)(p - user_host));\n\t\tif (user_shost == NULL)\n\t\t goto oom;\n\t } else {\n\t\tuser_shost = user_host;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"lines=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"lines=\") - 1;\n\t sudo_user.lines = sudo_strtonum(p, 1, INT_MAX, &errstr);\n\t if (sudo_user.lines == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cols=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"cols=\") - 1;\n\t sudo_user.cols = sudo_strtonum(p, 1, INT_MAX, &errstr);\n\t if (sudo_user.cols == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"sid=\")) {\n\t p = *cur + sizeof(\"sid=\") - 1;\n\t user_sid = (pid_t) sudo_strtoid(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"umask=\")) {\n\t p = *cur + sizeof(\"umask=\") - 1;\n\t sudo_user.umask = sudo_strtomode(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n }\n\n /* User name, user-ID, group-ID and host name must be specified. */\n if (user_name == NULL) {\n\tsudo_warnx(\"%s\", U_(\"user name not set by sudo front-end\"));\n\tgoto bad;\n }\n if (user_uid == (uid_t)-1) {\n\tsudo_warnx(\"%s\", U_(\"user-ID not set by sudo front-end\"));\n\tgoto bad;\n }\n if (user_gid == (gid_t)-1) {\n\tsudo_warnx(\"%s\", U_(\"group-ID not set by sudo front-end\"));\n\tgoto bad;\n }\n if (user_host == NULL) {\n\tsudo_warnx(\"%s\", U_(\"host name not set by sudo front-end\"));\n\tgoto bad;\n }\n\n if ((user_runhost = strdup(remhost ? remhost : user_host)) == NULL)\n\tgoto oom;\n if ((p = strchr(user_runhost, '.')) != NULL) {\n\tuser_srunhost = strndup(user_runhost, (size_t)(p - user_runhost));\n\tif (user_srunhost == NULL)\n\t goto oom;\n } else {\n\tuser_srunhost = user_runhost;\n }\n if (user_cwd == NULL) {\n\tif ((user_cwd = strdup(\"unknown\")) == NULL)\n\t goto oom;\n }\n if (user_runcwd == NULL) {\n\tif ((user_runcwd = strdup(user_cwd)) == NULL)\n\t goto oom;\n }\n if (user_tty == NULL) {\n\tif ((user_tty = strdup(\"unknown\")) == NULL)\n\t goto oom;\n\t/* user_ttypath remains NULL */\n }\n\n if (groups != NULL) {\n\t/* sudo_parse_gids() will print a warning on error. */\n\tuser_ngids = sudo_parse_gids(groups, &user_gid, &user_gids);\n\tif (user_ngids == -1)\n\t goto bad;\n }\n\n /* umask is only set in user_info[] for API 1.10 and above. */\n if (user_umask == (mode_t)-1) {\n\tuser_umask = umask(0);\n\tumask(user_umask);\n }\n\n /* Always reset the environment for a login shell. */\n if (ISSET(flags, MODE_LOGIN_SHELL))\n\tdef_env_reset = true;\n\n /* Some systems support fexecve() which we use for digest matches. */\n cmnd_fd = -1;\n\n /* Dump settings and user info (XXX - plugin args) */\n for (cur = info->settings; *cur != NULL; cur++)\n\tsudo_debug_printf(SUDO_DEBUG_INFO, \"settings: %s\", *cur);\n for (cur = info->user_info; *cur != NULL; cur++)\n\tsudo_debug_printf(SUDO_DEBUG_INFO, \"user_info: %s\", *cur);\n\n#undef MATCHES\n#undef INVALID\n#undef CHECK\n debug_return_int(flags);\n\noom:\n sudo_warnx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\nbad:\n debug_return_int(MODE_ERROR);\n}", "project": "sudo", "hash": 83391947378302188199193223394572343502, "size": 441, "commit_id": "c4d384082fdbc8406cf19e08d05db4cded920a55", "message": "Add sudoedit flag checks in plugin that are consistent with front-end.\nDon't assume the sudo front-end is sending reasonable mode flags.\nThese checks need to be kept consistent between the sudo front-end\nand the sudoers plugin.", "target": 1, "dataset": "other", "idx": 204323} {"func": "sudoers_policy_deserialize_info(void *v)\n{\n const int edit_mask = MODE_EDIT|MODE_IGNORE_TICKET|MODE_NONINTERACTIVE;\n struct sudoers_open_info *info = v;\n const char *p, *errstr, *groups = NULL;\n const char *remhost = NULL;\n char * const *cur;\n int flags = 0;\n debug_decl(sudoers_policy_deserialize_info, SUDOERS_DEBUG_PLUGIN);\n\n#define MATCHES(s, v)\t\\\n (strncmp((s), (v), sizeof(v) - 1) == 0)\n\n#define INVALID(v) do {\t\\\n sudo_warn(U_(\"invalid %.*s set by sudo front-end\"), \\\n\t(int)(sizeof(v) - 2), (v)); \\\n} while (0)\n\n#define CHECK(s, v) do {\t\\\n if ((s)[sizeof(v) - 1] == '\\0') { \\\n\tINVALID(v); \\\n\tgoto bad; \\\n } \\\n} while (0)\n\n if (sudo_gettime_real(&sudo_user.submit_time) == -1) {\n\tsudo_warn(\"%s\", U_(\"unable to get time of day\"));\n\tgoto bad;\n }\n\n /* Parse sudo.conf plugin args. */\n if (info->plugin_args != NULL) {\n\tfor (cur = info->plugin_args; *cur != NULL; cur++) {\n\t if (MATCHES(*cur, \"error_recovery=\")) {\n\t\tint val = sudo_strtobool(*cur + sizeof(\"error_recovery=\") - 1);\n\t\tif (val == -1) {\n\t\t INVALID(\"error_recovery=\");\t/* Not a fatal error. */\n\t\t} else {\n\t\t sudoers_recovery = val;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_file=\")) {\n\t\tCHECK(*cur, \"sudoers_file=\");\n\t\tsudoers_file = *cur + sizeof(\"sudoers_file=\") - 1;\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_uid=\")) {\n\t\tp = *cur + sizeof(\"sudoers_uid=\") - 1;\n\t\tsudoers_uid = (uid_t) sudo_strtoid(p, &errstr);\n\t\tif (errstr != NULL) {\n\t\t sudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\t goto bad;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_gid=\")) {\n\t\tp = *cur + sizeof(\"sudoers_gid=\") - 1;\n\t\tsudoers_gid = (gid_t) sudo_strtoid(p, &errstr);\n\t\tif (errstr != NULL) {\n\t\t sudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\t goto bad;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"sudoers_mode=\")) {\n\t\tp = *cur + sizeof(\"sudoers_mode=\") - 1;\n\t\tsudoers_mode = sudo_strtomode(p, &errstr);\n\t\tif (errstr != NULL) {\n\t\t sudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\t goto bad;\n\t\t}\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"ldap_conf=\")) {\n\t\tCHECK(*cur, \"ldap_conf=\");\n\t\tpath_ldap_conf = *cur + sizeof(\"ldap_conf=\") - 1;\n\t\tcontinue;\n\t }\n\t if (MATCHES(*cur, \"ldap_secret=\")) {\n\t\tCHECK(*cur, \"ldap_secret=\");\n\t\tpath_ldap_secret = *cur + sizeof(\"ldap_secret=\") - 1;\n\t\tcontinue;\n\t }\n\t}\n }\n\n /* Parse command line settings. */\n user_closefrom = -1;\n for (cur = info->settings; *cur != NULL; cur++) {\n\tif (MATCHES(*cur, \"closefrom=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"closefrom=\") - 1;\n\t user_closefrom = sudo_strtonum(p, 3, INT_MAX, &errstr);\n\t if (user_closefrom == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cmnd_chroot=\")) {\n\t CHECK(*cur, \"cmnd_chroot=\");\n\t user_runchroot = *cur + sizeof(\"cmnd_chroot=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cmnd_cwd=\")) {\n\t CHECK(*cur, \"cmnd_cwd=\");\n\t user_runcwd = *cur + sizeof(\"cmnd_cwd=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"runas_user=\")) {\n\t CHECK(*cur, \"runas_user=\");\n\t sudo_user.runas_user = *cur + sizeof(\"runas_user=\") - 1;\n\t SET(sudo_user.flags, RUNAS_USER_SPECIFIED);\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"runas_group=\")) {\n\t CHECK(*cur, \"runas_group=\");\n\t sudo_user.runas_group = *cur + sizeof(\"runas_group=\") - 1;\n\t SET(sudo_user.flags, RUNAS_GROUP_SPECIFIED);\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"prompt=\")) {\n\t /* Allow epmpty prompt. */\n\t user_prompt = *cur + sizeof(\"prompt=\") - 1;\n\t def_passprompt_override = true;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"set_home=\")) {\n\t if (parse_bool(*cur, sizeof(\"set_home\") - 1, &flags,\n\t\tMODE_RESET_HOME) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"preserve_environment=\")) {\n\t if (parse_bool(*cur, sizeof(\"preserve_environment\") - 1, &flags,\n\t\tMODE_PRESERVE_ENV) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"run_shell=\")) {\n\t if (parse_bool(*cur, sizeof(\"run_shell\") -1, &flags,\n\t\tMODE_SHELL) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"login_shell=\")) {\n\t if (parse_bool(*cur, sizeof(\"login_shell\") - 1, &flags,\n\t\tMODE_LOGIN_SHELL) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"implied_shell=\")) {\n\t if (parse_bool(*cur, sizeof(\"implied_shell\") - 1, &flags,\n\t\tMODE_IMPLIED_SHELL) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"preserve_groups=\")) {\n\t if (parse_bool(*cur, sizeof(\"preserve_groups\") - 1, &flags,\n\t\tMODE_PRESERVE_GROUPS) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"ignore_ticket=\")) {\n\t if (parse_bool(*cur, sizeof(\"ignore_ticket\") -1, &flags,\n\t\tMODE_IGNORE_TICKET) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"noninteractive=\")) {\n\t if (parse_bool(*cur, sizeof(\"noninteractive\") - 1, &flags,\n\t\tMODE_NONINTERACTIVE) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"sudoedit=\")) {\n\t if (parse_bool(*cur, sizeof(\"sudoedit\") - 1, &flags,\n\t\tMODE_EDIT) == -1)\n\t\tgoto bad;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"login_class=\")) {\n\t CHECK(*cur, \"login_class=\");\n\t login_class = *cur + sizeof(\"login_class=\") - 1;\n\t def_use_loginclass = true;\n\t continue;\n\t}\n#ifdef HAVE_PRIV_SET\n\tif (MATCHES(*cur, \"runas_privs=\")) {\n\t CHECK(*cur, \"runas_privs=\");\n\t def_privs = *cur + sizeof(\"runas_privs=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"runas_limitprivs=\")) {\n\t CHECK(*cur, \"runas_limitprivs=\");\n\t def_limitprivs = *cur + sizeof(\"runas_limitprivs=\") - 1;\n\t continue;\n\t}\n#endif /* HAVE_PRIV_SET */\n#ifdef HAVE_SELINUX\n\tif (MATCHES(*cur, \"selinux_role=\")) {\n\t CHECK(*cur, \"selinux_role=\");\n\t user_role = *cur + sizeof(\"selinux_role=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"selinux_type=\")) {\n\t CHECK(*cur, \"selinux_type=\");\n\t user_type = *cur + sizeof(\"selinux_type=\") - 1;\n\t continue;\n\t}\n#endif /* HAVE_SELINUX */\n#ifdef HAVE_BSD_AUTH_H\n\tif (MATCHES(*cur, \"bsdauth_type=\")) {\n\t CHECK(*cur, \"login_style=\");\n\t login_style = *cur + sizeof(\"bsdauth_type=\") - 1;\n\t continue;\n\t}\n#endif /* HAVE_BSD_AUTH_H */\n\tif (MATCHES(*cur, \"network_addrs=\")) {\n\t interfaces_string = *cur + sizeof(\"network_addrs=\") - 1;\n\t if (!set_interfaces(interfaces_string)) {\n\t\tsudo_warn(\"%s\", U_(\"unable to parse network address list\"));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"max_groups=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"max_groups=\") - 1;\n\t sudo_user.max_groups = sudo_strtonum(p, 1, INT_MAX, &errstr);\n\t if (sudo_user.max_groups == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"remote_host=\")) {\n\t CHECK(*cur, \"remote_host=\");\n\t remhost = *cur + sizeof(\"remote_host=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"timeout=\")) {\n\t p = *cur + sizeof(\"timeout=\") - 1;\n\t user_timeout = parse_timeout(p);\n\t if (user_timeout == -1) {\n\t\tif (errno == ERANGE)\n\t\t sudo_warnx(U_(\"%s: %s\"), p, U_(\"timeout value too large\"));\n\t\telse\n\t\t sudo_warnx(U_(\"%s: %s\"), p, U_(\"invalid timeout value\"));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n#ifdef ENABLE_SUDO_PLUGIN_API\n\tif (MATCHES(*cur, \"plugin_dir=\")) {\n\t CHECK(*cur, \"plugin_dir=\");\n\t path_plugin_dir = *cur + sizeof(\"plugin_dir=\") - 1;\n\t continue;\n\t}\n#endif\n }\n\n /* Sudo front-end should restrict mode flags for sudoedit. */\n if (ISSET(flags, MODE_EDIT) && (flags & edit_mask) != flags) {\n\tsudo_warnx(U_(\"invalid mode flags from sudo front end: 0x%x\"), flags);\n\tgoto bad;\n }\n\n user_gid = (gid_t)-1;\n user_sid = (pid_t)-1;\n user_uid = (gid_t)-1;\n user_umask = (mode_t)-1;\n for (cur = info->user_info; *cur != NULL; cur++) {\n\tif (MATCHES(*cur, \"user=\")) {\n\t CHECK(*cur, \"user=\");\n\t if ((user_name = strdup(*cur + sizeof(\"user=\") - 1)) == NULL)\n\t\tgoto oom;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"uid=\")) {\n\t p = *cur + sizeof(\"uid=\") - 1;\n\t user_uid = (uid_t) sudo_strtoid(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"gid=\")) {\n\t p = *cur + sizeof(\"gid=\") - 1;\n\t user_gid = (gid_t) sudo_strtoid(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"groups=\")) {\n\t CHECK(*cur, \"groups=\");\n\t groups = *cur + sizeof(\"groups=\") - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cwd=\")) {\n\t CHECK(*cur, \"cwd=\");\n\t if ((user_cwd = strdup(*cur + sizeof(\"cwd=\") - 1)) == NULL)\n\t\tgoto oom;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"tty=\")) {\n\t CHECK(*cur, \"tty=\");\n\t if ((user_ttypath = strdup(*cur + sizeof(\"tty=\") - 1)) == NULL)\n\t\tgoto oom;\n\t user_tty = user_ttypath;\n\t if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)\n\t\tuser_tty += sizeof(_PATH_DEV) - 1;\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"host=\")) {\n\t CHECK(*cur, \"host=\");\n\t if ((user_host = strdup(*cur + sizeof(\"host=\") - 1)) == NULL)\n\t\tgoto oom;\n\t if ((p = strchr(user_host, '.')) != NULL) {\n\t\tuser_shost = strndup(user_host, (size_t)(p - user_host));\n\t\tif (user_shost == NULL)\n\t\t goto oom;\n\t } else {\n\t\tuser_shost = user_host;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"lines=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"lines=\") - 1;\n\t sudo_user.lines = sudo_strtonum(p, 1, INT_MAX, &errstr);\n\t if (sudo_user.lines == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"cols=\")) {\n\t errno = 0;\n\t p = *cur + sizeof(\"cols=\") - 1;\n\t sudo_user.cols = sudo_strtonum(p, 1, INT_MAX, &errstr);\n\t if (sudo_user.cols == 0) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"sid=\")) {\n\t p = *cur + sizeof(\"sid=\") - 1;\n\t user_sid = (pid_t) sudo_strtoid(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n\tif (MATCHES(*cur, \"umask=\")) {\n\t p = *cur + sizeof(\"umask=\") - 1;\n\t sudo_user.umask = sudo_strtomode(p, &errstr);\n\t if (errstr != NULL) {\n\t\tsudo_warnx(U_(\"%s: %s\"), *cur, U_(errstr));\n\t\tgoto bad;\n\t }\n\t continue;\n\t}\n }\n\n /* User name, user-ID, group-ID and host name must be specified. */\n if (user_name == NULL) {\n\tsudo_warnx(\"%s\", U_(\"user name not set by sudo front-end\"));\n\tgoto bad;\n }\n if (user_uid == (uid_t)-1) {\n\tsudo_warnx(\"%s\", U_(\"user-ID not set by sudo front-end\"));\n\tgoto bad;\n }\n if (user_gid == (gid_t)-1) {\n\tsudo_warnx(\"%s\", U_(\"group-ID not set by sudo front-end\"));\n\tgoto bad;\n }\n if (user_host == NULL) {\n\tsudo_warnx(\"%s\", U_(\"host name not set by sudo front-end\"));\n\tgoto bad;\n }\n\n if ((user_runhost = strdup(remhost ? remhost : user_host)) == NULL)\n\tgoto oom;\n if ((p = strchr(user_runhost, '.')) != NULL) {\n\tuser_srunhost = strndup(user_runhost, (size_t)(p - user_runhost));\n\tif (user_srunhost == NULL)\n\t goto oom;\n } else {\n\tuser_srunhost = user_runhost;\n }\n if (user_cwd == NULL) {\n\tif ((user_cwd = strdup(\"unknown\")) == NULL)\n\t goto oom;\n }\n if (user_runcwd == NULL) {\n\tif ((user_runcwd = strdup(user_cwd)) == NULL)\n\t goto oom;\n }\n if (user_tty == NULL) {\n\tif ((user_tty = strdup(\"unknown\")) == NULL)\n\t goto oom;\n\t/* user_ttypath remains NULL */\n }\n\n if (groups != NULL) {\n\t/* sudo_parse_gids() will print a warning on error. */\n\tuser_ngids = sudo_parse_gids(groups, &user_gid, &user_gids);\n\tif (user_ngids == -1)\n\t goto bad;\n }\n\n /* umask is only set in user_info[] for API 1.10 and above. */\n if (user_umask == (mode_t)-1) {\n\tuser_umask = umask(0);\n\tumask(user_umask);\n }\n\n /* Always reset the environment for a login shell. */\n if (ISSET(flags, MODE_LOGIN_SHELL))\n\tdef_env_reset = true;\n\n /* Some systems support fexecve() which we use for digest matches. */\n cmnd_fd = -1;\n\n /* Dump settings and user info (XXX - plugin args) */\n for (cur = info->settings; *cur != NULL; cur++)\n\tsudo_debug_printf(SUDO_DEBUG_INFO, \"settings: %s\", *cur);\n for (cur = info->user_info; *cur != NULL; cur++)\n\tsudo_debug_printf(SUDO_DEBUG_INFO, \"user_info: %s\", *cur);\n\n#undef MATCHES\n#undef INVALID\n#undef CHECK\n debug_return_int(flags);\n\noom:\n sudo_warnx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\nbad:\n debug_return_int(MODE_ERROR);\n}", "project": "sudo", "hash": 50210916584704883102461860878208331377, "size": 448, "commit_id": "c4d384082fdbc8406cf19e08d05db4cded920a55", "message": "Add sudoedit flag checks in plugin that are consistent with front-end.\nDon't assume the sudo front-end is sending reasonable mode flags.\nThese checks need to be kept consistent between the sudo front-end\nand the sudoers plugin.", "target": 0, "dataset": "other", "idx": 356720} {"func": "int imap_open_connection(struct ImapAccountData *adata)\n{\n if (mutt_socket_open(adata->conn) < 0)\n return -1;\n\n adata->state = IMAP_CONNECTED;\n\n if (imap_cmd_step(adata) != IMAP_RES_OK)\n {\n imap_close_connection(adata);\n return -1;\n }\n\n if (mutt_istr_startswith(adata->buf, \"* OK\"))\n {\n if (!mutt_istr_startswith(adata->buf, \"* OK [CAPABILITY\") && check_capabilities(adata))\n {\n goto bail;\n }\n#ifdef USE_SSL\n /* Attempt STARTTLS if available and desired. */\n if ((adata->conn->ssf == 0) && (C_SslForceTls || (adata->capabilities & IMAP_CAP_STARTTLS)))\n {\n enum QuadOption ans;\n\n if (C_SslForceTls)\n ans = MUTT_YES;\n else if ((ans = query_quadoption(C_SslStarttls,\n _(\"Secure connection with TLS?\"))) == MUTT_ABORT)\n {\n goto err_close_conn;\n }\n if (ans == MUTT_YES)\n {\n enum ImapExecResult rc = imap_exec(adata, \"STARTTLS\", IMAP_CMD_SINGLE);\n // Clear any data after the STARTTLS acknowledgement\n mutt_socket_empty(adata->conn);\n\n if (rc == IMAP_EXEC_FATAL)\n goto bail;\n if (rc != IMAP_EXEC_ERROR)\n {\n if (mutt_ssl_starttls(adata->conn))\n {\n mutt_error(_(\"Could not negotiate TLS connection\"));\n goto err_close_conn;\n }\n else\n {\n /* RFC2595 demands we recheck CAPABILITY after TLS completes. */\n if (imap_exec(adata, \"CAPABILITY\", IMAP_CMD_NO_FLAGS))\n goto bail;\n }\n }\n }\n }\n\n if (C_SslForceTls && (adata->conn->ssf == 0))\n {\n mutt_error(_(\"Encrypted connection unavailable\"));\n goto err_close_conn;\n }\n#endif\n }\n else if (mutt_istr_startswith(adata->buf, \"* PREAUTH\"))\n {\n#ifdef USE_SSL\n /* Unless using a secure $tunnel, an unencrypted PREAUTH response may be a\n * MITM attack. The only way to stop \"STARTTLS\" MITM attacks is via\n * $ssl_force_tls: an attacker can easily spoof \"* OK\" and strip the\n * STARTTLS capability. So consult $ssl_force_tls, not $ssl_starttls, to\n * decide whether to abort. Note that if using $tunnel and\n * $tunnel_is_secure, adata->conn->ssf will be set to 1. */\n if ((adata->conn->ssf == 0) && C_SslForceTls)\n {\n mutt_error(_(\"Encrypted connection unavailable\"));\n goto err_close_conn;\n }\n#endif\n\n adata->state = IMAP_AUTHENTICATED;\n if (check_capabilities(adata) != 0)\n goto bail;\n FREE(&adata->capstr);\n }\n else\n {\n imap_error(\"imap_open_connection()\", adata->buf);\n goto bail;\n }\n\n return 0;\n\n#ifdef USE_SSL\nerr_close_conn:\n imap_close_connection(adata);\n#endif\nbail:\n FREE(&adata->capstr);\n return -1;\n}", "project": "neomutt", "hash": 116037772614219807053318355003276943446, "size": 101, "commit_id": "9c36717a3e2af1f2c1b7242035455ec8112b4b06", "message": "imap: close connection on all failures\n\nThanks to Gabriel Salles-Loustau for spotting the problem.\n\nCo-authored-by: Kevin McCarthy ", "target": 1, "dataset": "other", "idx": 204337} {"func": "int imap_open_connection(struct ImapAccountData *adata)\n{\n if (mutt_socket_open(adata->conn) < 0)\n return -1;\n\n adata->state = IMAP_CONNECTED;\n\n if (imap_cmd_step(adata) != IMAP_RES_OK)\n {\n imap_close_connection(adata);\n return -1;\n }\n\n if (mutt_istr_startswith(adata->buf, \"* OK\"))\n {\n if (!mutt_istr_startswith(adata->buf, \"* OK [CAPABILITY\") && check_capabilities(adata))\n {\n goto bail;\n }\n#ifdef USE_SSL\n /* Attempt STARTTLS if available and desired. */\n if ((adata->conn->ssf == 0) && (C_SslForceTls || (adata->capabilities & IMAP_CAP_STARTTLS)))\n {\n enum QuadOption ans;\n\n if (C_SslForceTls)\n ans = MUTT_YES;\n else if ((ans = query_quadoption(C_SslStarttls,\n _(\"Secure connection with TLS?\"))) == MUTT_ABORT)\n {\n goto bail;\n }\n if (ans == MUTT_YES)\n {\n enum ImapExecResult rc = imap_exec(adata, \"STARTTLS\", IMAP_CMD_SINGLE);\n // Clear any data after the STARTTLS acknowledgement\n mutt_socket_empty(adata->conn);\n\n if (rc == IMAP_EXEC_FATAL)\n goto bail;\n if (rc != IMAP_EXEC_ERROR)\n {\n if (mutt_ssl_starttls(adata->conn))\n {\n mutt_error(_(\"Could not negotiate TLS connection\"));\n goto bail;\n }\n else\n {\n /* RFC2595 demands we recheck CAPABILITY after TLS completes. */\n if (imap_exec(adata, \"CAPABILITY\", IMAP_CMD_NO_FLAGS))\n goto bail;\n }\n }\n }\n }\n\n if (C_SslForceTls && (adata->conn->ssf == 0))\n {\n mutt_error(_(\"Encrypted connection unavailable\"));\n goto bail;\n }\n#endif\n }\n else if (mutt_istr_startswith(adata->buf, \"* PREAUTH\"))\n {\n#ifdef USE_SSL\n /* Unless using a secure $tunnel, an unencrypted PREAUTH response may be a\n * MITM attack. The only way to stop \"STARTTLS\" MITM attacks is via\n * $ssl_force_tls: an attacker can easily spoof \"* OK\" and strip the\n * STARTTLS capability. So consult $ssl_force_tls, not $ssl_starttls, to\n * decide whether to abort. Note that if using $tunnel and\n * $tunnel_is_secure, adata->conn->ssf will be set to 1. */\n if ((adata->conn->ssf == 0) && C_SslForceTls)\n {\n mutt_error(_(\"Encrypted connection unavailable\"));\n goto bail;\n }\n#endif\n\n adata->state = IMAP_AUTHENTICATED;\n if (check_capabilities(adata) != 0)\n goto bail;\n FREE(&adata->capstr);\n }\n else\n {\n imap_error(\"imap_open_connection()\", adata->buf);\n goto bail;\n }\n\n return 0;\n\nbail:\n imap_close_connection(adata);\n FREE(&adata->capstr);\n return -1;\n}", "project": "neomutt", "hash": 72296476132372139826321996354956312569, "size": 98, "commit_id": "9c36717a3e2af1f2c1b7242035455ec8112b4b06", "message": "imap: close connection on all failures\n\nThanks to Gabriel Salles-Loustau for spotting the problem.\n\nCo-authored-by: Kevin McCarthy ", "target": 0, "dataset": "other", "idx": 357032} {"func": "static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,\n opj_tcd_t * p_tile_coder,\n OPJ_BYTE * p_data,\n OPJ_UINT32 * p_data_written,\n OPJ_UINT32 total_data_size,\n const opj_stream_private_t *p_stream,\n opj_event_mgr_t * p_manager\n )\n{\n opj_codestream_info_t *l_cstr_info = 00;\n OPJ_UINT32 l_remaining_data;\n opj_tcd_marker_info_t* marker_info = NULL;\n\n /* preconditions */\n assert(p_j2k != 00);\n assert(p_manager != 00);\n assert(p_stream != 00);\n\n OPJ_UNUSED(p_stream);\n\n if (total_data_size < 4) {\n opj_event_msg(p_manager, EVT_ERROR,\n \"Not enough bytes in output buffer to write SOD marker\\n\");\n return OPJ_FALSE;\n }\n\n opj_write_bytes(p_data, J2K_MS_SOD,\n 2); /* SOD */\n\n /* make room for the EOF marker */\n l_remaining_data = total_data_size - 4;\n\n /* update tile coder */\n p_tile_coder->tp_num =\n p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ;\n p_tile_coder->cur_tp_num =\n p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;\n\n /* INDEX >> */\n /* TODO mergeV2: check this part which use cstr_info */\n /*l_cstr_info = p_j2k->cstr_info;\n if (l_cstr_info) {\n if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) {\n //TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1;\n l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number;\n }\n else {*/\n /*\n TODO\n if\n (cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream))\n {\n cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream);\n }*/\n /*}*/\n /* UniPG>> */\n#ifdef USE_JPWL\n /* update markers struct */\n /*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2);\n */\n assert(0 && \"TODO\");\n#endif /* USE_JPWL */\n /* <m_specific_param.m_encoder.m_current_tile_part_number == 0) {\n p_tile_coder->tcd_image->tiles->packno = 0;\n#ifdef deadcode\n if (l_cstr_info) {\n l_cstr_info->packno = 0;\n }\n#endif\n }\n\n *p_data_written = 0;\n\n if (p_j2k->m_specific_param.m_encoder.m_PLT) {\n marker_info = opj_tcd_marker_info_create(\n p_j2k->m_specific_param.m_encoder.m_PLT);\n if (marker_info == NULL) {\n opj_event_msg(p_manager, EVT_ERROR,\n \"Cannot encode tile: opj_tcd_marker_info_create() failed\\n\");\n return OPJ_FALSE;\n }\n }\n\n assert(l_remaining_data >\n p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT);\n l_remaining_data -= p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT;\n\n if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number,\n p_data + 2,\n p_data_written, l_remaining_data, l_cstr_info,\n marker_info,\n p_manager)) {\n opj_event_msg(p_manager, EVT_ERROR, \"Cannot encode tile\\n\");\n opj_tcd_marker_info_destroy(marker_info);\n return OPJ_FALSE;\n }\n\n /* For SOD */\n *p_data_written += 2;\n\n if (p_j2k->m_specific_param.m_encoder.m_PLT) {\n OPJ_UINT32 l_data_written_PLT = 0;\n OPJ_BYTE* p_PLT_buffer = (OPJ_BYTE*)opj_malloc(\n p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT);\n if (!p_PLT_buffer) {\n opj_event_msg(p_manager, EVT_ERROR, \"Cannot allocate memory\\n\");\n opj_tcd_marker_info_destroy(marker_info);\n return OPJ_FALSE;\n }\n if (!opj_j2k_write_plt_in_memory(p_j2k,\n marker_info,\n p_PLT_buffer,\n &l_data_written_PLT,\n p_manager)) {\n opj_tcd_marker_info_destroy(marker_info);\n opj_free(p_PLT_buffer);\n return OPJ_FALSE;\n }\n\n assert(l_data_written_PLT <=\n p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT);\n\n /* Move PLT marker(s) before SOD */\n memmove(p_data + l_data_written_PLT, p_data, *p_data_written);\n memcpy(p_data, p_PLT_buffer, l_data_written_PLT);\n opj_free(p_PLT_buffer);\n *p_data_written += l_data_written_PLT;\n }\n\n opj_tcd_marker_info_destroy(marker_info);\n\n return OPJ_TRUE;\n}", "project": "openjpeg", "hash": 2596444094136185670542568690370435768, "size": 137, "commit_id": "73fdf28342e4594019af26eb6a347a34eceb6296", "message": "opj_j2k_write_sod(): avoid potential heap buffer overflow (fixes #1299) (probably master only)", "target": 1, "dataset": "other", "idx": 204345} {"func": "static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,\n opj_tcd_t * p_tile_coder,\n OPJ_BYTE * p_data,\n OPJ_UINT32 * p_data_written,\n OPJ_UINT32 total_data_size,\n const opj_stream_private_t *p_stream,\n opj_event_mgr_t * p_manager\n )\n{\n opj_codestream_info_t *l_cstr_info = 00;\n OPJ_UINT32 l_remaining_data;\n opj_tcd_marker_info_t* marker_info = NULL;\n\n /* preconditions */\n assert(p_j2k != 00);\n assert(p_manager != 00);\n assert(p_stream != 00);\n\n OPJ_UNUSED(p_stream);\n\n if (total_data_size < 4) {\n opj_event_msg(p_manager, EVT_ERROR,\n \"Not enough bytes in output buffer to write SOD marker\\n\");\n return OPJ_FALSE;\n }\n\n opj_write_bytes(p_data, J2K_MS_SOD,\n 2); /* SOD */\n\n /* make room for the EOF marker */\n l_remaining_data = total_data_size - 4;\n\n /* update tile coder */\n p_tile_coder->tp_num =\n p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ;\n p_tile_coder->cur_tp_num =\n p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;\n\n /* INDEX >> */\n /* TODO mergeV2: check this part which use cstr_info */\n /*l_cstr_info = p_j2k->cstr_info;\n if (l_cstr_info) {\n if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) {\n //TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1;\n l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number;\n }\n else {*/\n /*\n TODO\n if\n (cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream))\n {\n cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream);\n }*/\n /*}*/\n /* UniPG>> */\n#ifdef USE_JPWL\n /* update markers struct */\n /*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2);\n */\n assert(0 && \"TODO\");\n#endif /* USE_JPWL */\n /* <m_specific_param.m_encoder.m_current_tile_part_number == 0) {\n p_tile_coder->tcd_image->tiles->packno = 0;\n#ifdef deadcode\n if (l_cstr_info) {\n l_cstr_info->packno = 0;\n }\n#endif\n }\n\n *p_data_written = 0;\n\n if (p_j2k->m_specific_param.m_encoder.m_PLT) {\n marker_info = opj_tcd_marker_info_create(\n p_j2k->m_specific_param.m_encoder.m_PLT);\n if (marker_info == NULL) {\n opj_event_msg(p_manager, EVT_ERROR,\n \"Cannot encode tile: opj_tcd_marker_info_create() failed\\n\");\n return OPJ_FALSE;\n }\n }\n\n if (l_remaining_data <\n p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT) {\n opj_event_msg(p_manager, EVT_ERROR,\n \"Not enough bytes in output buffer to write SOD marker\\n\");\n opj_tcd_marker_info_destroy(marker_info);\n return OPJ_FALSE;\n }\n l_remaining_data -= p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT;\n\n if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number,\n p_data + 2,\n p_data_written, l_remaining_data, l_cstr_info,\n marker_info,\n p_manager)) {\n opj_event_msg(p_manager, EVT_ERROR, \"Cannot encode tile\\n\");\n opj_tcd_marker_info_destroy(marker_info);\n return OPJ_FALSE;\n }\n\n /* For SOD */\n *p_data_written += 2;\n\n if (p_j2k->m_specific_param.m_encoder.m_PLT) {\n OPJ_UINT32 l_data_written_PLT = 0;\n OPJ_BYTE* p_PLT_buffer = (OPJ_BYTE*)opj_malloc(\n p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT);\n if (!p_PLT_buffer) {\n opj_event_msg(p_manager, EVT_ERROR, \"Cannot allocate memory\\n\");\n opj_tcd_marker_info_destroy(marker_info);\n return OPJ_FALSE;\n }\n if (!opj_j2k_write_plt_in_memory(p_j2k,\n marker_info,\n p_PLT_buffer,\n &l_data_written_PLT,\n p_manager)) {\n opj_tcd_marker_info_destroy(marker_info);\n opj_free(p_PLT_buffer);\n return OPJ_FALSE;\n }\n\n assert(l_data_written_PLT <=\n p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT);\n\n /* Move PLT marker(s) before SOD */\n memmove(p_data + l_data_written_PLT, p_data, *p_data_written);\n memcpy(p_data, p_PLT_buffer, l_data_written_PLT);\n opj_free(p_PLT_buffer);\n *p_data_written += l_data_written_PLT;\n }\n\n opj_tcd_marker_info_destroy(marker_info);\n\n return OPJ_TRUE;\n}", "project": "openjpeg", "hash": 110807645529220467738052209881275757752, "size": 142, "commit_id": "73fdf28342e4594019af26eb6a347a34eceb6296", "message": "opj_j2k_write_sod(): avoid potential heap buffer overflow (fixes #1299) (probably master only)", "target": 0, "dataset": "other", "idx": 357326} {"func": "p11_rpc_buffer_get_attribute (p11_buffer *buffer,\n\t\t\t size_t *offset,\n\t\t\t CK_ATTRIBUTE *attr)\n{\n\tuint32_t type, length;\n\tunsigned char validity;\n\tp11_rpc_attribute_serializer *serializer;\n\tp11_rpc_value_type value_type;\n\n\t/* The attribute type */\n\tif (!p11_rpc_buffer_get_uint32 (buffer, offset, &type))\n\t\treturn false;\n\n\t/* Attribute validity */\n\tif (!p11_rpc_buffer_get_byte (buffer, offset, &validity))\n\t\treturn false;\n\n\t/* Not a valid attribute */\n\tif (!validity) {\n\t\tattr->ulValueLen = ((CK_ULONG)-1);\n\t\tattr->type = type;\n\t\treturn true;\n\t}\n\n\tif (!p11_rpc_buffer_get_uint32 (buffer, offset, &length))\n\t\treturn false;\n\n\t/* Decode the attribute value */\n\tvalue_type = map_attribute_to_value_type (type);\n\tassert (value_type < ELEMS (p11_rpc_attribute_serializers));\n\tserializer = &p11_rpc_attribute_serializers[value_type];\n\tassert (serializer != NULL);\n\tif (!serializer->decode (buffer, offset, attr->pValue, &attr->ulValueLen))\n\t\treturn false;\n\tif (!attr->pValue)\n\t\tattr->ulValueLen = length;\n\tattr->type = type;\n\treturn true;\n}", "project": "p11-kit", "hash": 23421043781240478058626749820986768771, "size": 39, "commit_id": "2617f3ef888e103324a28811886b99ed0a56346d", "message": "Check attribute length against buffer size\n\nIf an attribute's length does not match the length of the byte array\ninside it, one length was used for allocation, and the other was used\nfor memcpy. This additional check will instead return an error on\nmalformed messages.", "target": 1, "dataset": "other", "idx": 204380} {"func": "p11_rpc_buffer_get_attribute (p11_buffer *buffer,\n\t\t\t size_t *offset,\n\t\t\t CK_ATTRIBUTE *attr)\n{\n\tuint32_t type, length, decode_length;\n\tunsigned char validity;\n\tp11_rpc_attribute_serializer *serializer;\n\tp11_rpc_value_type value_type;\n\n\t/* The attribute type */\n\tif (!p11_rpc_buffer_get_uint32 (buffer, offset, &type))\n\t\treturn false;\n\n\t/* Attribute validity */\n\tif (!p11_rpc_buffer_get_byte (buffer, offset, &validity))\n\t\treturn false;\n\n\t/* Not a valid attribute */\n\tif (!validity) {\n\t\tattr->ulValueLen = ((CK_ULONG)-1);\n\t\tattr->type = type;\n\t\treturn true;\n\t}\n\n\tif (!p11_rpc_buffer_get_uint32 (buffer, offset, &length))\n\t\treturn false;\n\n\t/* Decode the attribute value */\n\tvalue_type = map_attribute_to_value_type (type);\n\tassert (value_type < ELEMS (p11_rpc_attribute_serializers));\n\tserializer = &p11_rpc_attribute_serializers[value_type];\n\tassert (serializer != NULL);\n\tif (!serializer->decode (buffer, offset, attr->pValue, &attr->ulValueLen))\n\t\treturn false;\n\tif (!attr->pValue) {\n\t\tdecode_length = attr->ulValueLen;\n\t\tattr->ulValueLen = length;\n\t\tif (decode_length > length) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tattr->type = type;\n\treturn true;\n}", "project": "p11-kit", "hash": 163590899753051294882112912981598223663, "size": 44, "commit_id": "2617f3ef888e103324a28811886b99ed0a56346d", "message": "Check attribute length against buffer size\n\nIf an attribute's length does not match the length of the byte array\ninside it, one length was used for allocation, and the other was used\nfor memcpy. This additional check will instead return an error on\nmalformed messages.", "target": 0, "dataset": "other", "idx": 358130} {"func": "static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *\n p_code_block)\n{\n OPJ_UINT32 l_data_size;\n\n /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */\n /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */\n /* and +7 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 3) */\n /* and +26 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 7) */\n /* TODO: is there a theoretical upper-bound for the compressed code */\n /* block size ? */\n l_data_size = 26 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *\n (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));\n\n if (l_data_size > p_code_block->data_size) {\n if (p_code_block->data) {\n /* We refer to data - 1 since below we incremented it */\n opj_free(p_code_block->data - 1);\n }\n p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);\n if (! p_code_block->data) {\n p_code_block->data_size = 0U;\n return OPJ_FALSE;\n }\n p_code_block->data_size = l_data_size;\n\n /* We reserve the initial byte as a fake byte to a non-FF value */\n /* and increment the data pointer, so that opj_mqc_init_enc() */\n /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */\n /* it. */\n p_code_block->data[0] = 0;\n p_code_block->data += 1; /*why +1 ?*/\n }\n return OPJ_TRUE;\n}", "project": "openjpeg", "hash": 74332118889396083730693045237215462948, "size": 35, "commit_id": "15cf3d95814dc931ca0ecb132f81cb152e051bae", "message": "Encoder: grow again buffer size in opj_tcd_code_block_enc_allocate_data() (fixes #1283)", "target": 1, "dataset": "other", "idx": 204411} {"func": "static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *\n p_code_block)\n{\n OPJ_UINT32 l_data_size;\n\n /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */\n /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */\n /* and +7 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 3) */\n /* and +26 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 7) */\n /* and +28 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 44) */\n /* TODO: is there a theoretical upper-bound for the compressed code */\n /* block size ? */\n l_data_size = 28 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *\n (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));\n\n if (l_data_size > p_code_block->data_size) {\n if (p_code_block->data) {\n /* We refer to data - 1 since below we incremented it */\n opj_free(p_code_block->data - 1);\n }\n p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);\n if (! p_code_block->data) {\n p_code_block->data_size = 0U;\n return OPJ_FALSE;\n }\n p_code_block->data_size = l_data_size;\n\n /* We reserve the initial byte as a fake byte to a non-FF value */\n /* and increment the data pointer, so that opj_mqc_init_enc() */\n /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */\n /* it. */\n p_code_block->data[0] = 0;\n p_code_block->data += 1; /*why +1 ?*/\n }\n return OPJ_TRUE;\n}", "project": "openjpeg", "hash": 90613075038304196793521501973130942392, "size": 36, "commit_id": "15cf3d95814dc931ca0ecb132f81cb152e051bae", "message": "Encoder: grow again buffer size in opj_tcd_code_block_enc_allocate_data() (fixes #1283)", "target": 0, "dataset": "other", "idx": 359168} {"func": "static int shm_create(XShmSegmentInfo *shm, XImage **ximg_ptr, int w, int h,\n char *name) {\n\n\tXImage *xim;\n\tstatic int reported_flip = 0;\n\tint db = 0;\n\n\tshm->shmid = -1;\n\tshm->shmaddr = (char *) -1;\n\t*ximg_ptr = NULL;\n\n\tif (nofb) {\n\t\treturn 1;\n\t}\n\n\tX_LOCK;\n\n\tif (! using_shm || xform24to32 || raw_fb) {\n\t\t/* we only need the XImage created */\n\t\txim = XCreateImage_wr(dpy, default_visual, depth, ZPixmap,\n\t\t 0, NULL, w, h, raw_fb ? 32 : BitmapPad(dpy), 0);\n\n\t\tX_UNLOCK;\n\n\t\tif (xim == NULL) {\n\t\t\trfbErr(\"XCreateImage(%s) failed.\\n\", name);\n\t\t\tif (quiet) {\n\t\t\t\tfprintf(stderr, \"XCreateImage(%s) failed.\\n\",\n\t\t\t\t name);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\tif (db) fprintf(stderr, \"shm_create simple %d %d\\t%p %s\\n\", w, h, (void *)xim, name);\n\t\txim->data = (char *) malloc(xim->bytes_per_line * xim->height);\n\t\tif (xim->data == NULL) {\n\t\t\trfbErr(\"XCreateImage(%s) data malloc failed.\\n\", name);\n\t\t\tif (quiet) {\n\t\t\t\tfprintf(stderr, \"XCreateImage(%s) data malloc\"\n\t\t\t\t \" failed.\\n\", name);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\tif (flip_byte_order) {\n\t\t\tchar *order = flip_ximage_byte_order(xim);\n\t\t\tif (! reported_flip && ! quiet) {\n\t\t\t\trfbLog(\"Changing XImage byte order\"\n\t\t\t\t \" to %s\\n\", order);\n\t\t\t\treported_flip = 1;\n\t\t\t}\n\t\t}\n\n\t\t*ximg_ptr = xim;\n\t\treturn 1;\n\t}\n\n\tif (! dpy) {\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\txim = XShmCreateImage_wr(dpy, default_visual, depth, ZPixmap, NULL,\n\t shm, w, h);\n\n\tif (xim == NULL) {\n\t\trfbErr(\"XShmCreateImage(%s) failed.\\n\", name);\n\t\tif (quiet) {\n\t\t\tfprintf(stderr, \"XShmCreateImage(%s) failed.\\n\", name);\n\t\t}\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\t*ximg_ptr = xim;\n\n#if HAVE_XSHM\n\tshm->shmid = shmget(IPC_PRIVATE,\n\t xim->bytes_per_line * xim->height, IPC_CREAT | 0777);\n\n\tif (shm->shmid == -1) {\n\t\trfbErr(\"shmget(%s) failed.\\n\", name);\n\t\trfbLogPerror(\"shmget\");\n\n\t\tXDestroyImage(xim);\n\t\t*ximg_ptr = NULL;\n\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\tshm->shmaddr = xim->data = (char *) shmat(shm->shmid, 0, 0);\n\n\tif (shm->shmaddr == (char *)-1) {\n\t\trfbErr(\"shmat(%s) failed.\\n\", name);\n\t\trfbLogPerror(\"shmat\");\n\n\t\tXDestroyImage(xim);\n\t\t*ximg_ptr = NULL;\n\n\t\tshmctl(shm->shmid, IPC_RMID, 0);\n\t\tshm->shmid = -1;\n\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\tshm->readOnly = False;\n\n\tif (! XShmAttach_wr(dpy, shm)) {\n\t\trfbErr(\"XShmAttach(%s) failed.\\n\", name);\n\t\tXDestroyImage(xim);\n\t\t*ximg_ptr = NULL;\n\n\t\tshmdt(shm->shmaddr);\n\t\tshm->shmaddr = (char *) -1;\n\n\t\tshmctl(shm->shmid, IPC_RMID, 0);\n\t\tshm->shmid = -1;\n\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n#endif\n\n\tX_UNLOCK;\n\treturn 1;\n}", "project": "x11vnc", "hash": 101234356332723009809336080171659591661, "size": 126, "commit_id": "69eeb9f7baa14ca03b16c9de821f9876def7a36a", "message": "scan: limit access to shared memory segments to current user", "target": 1, "dataset": "other", "idx": 204491} {"func": "static int shm_create(XShmSegmentInfo *shm, XImage **ximg_ptr, int w, int h,\n char *name) {\n\n\tXImage *xim;\n\tstatic int reported_flip = 0;\n\tint db = 0;\n\n\tshm->shmid = -1;\n\tshm->shmaddr = (char *) -1;\n\t*ximg_ptr = NULL;\n\n\tif (nofb) {\n\t\treturn 1;\n\t}\n\n\tX_LOCK;\n\n\tif (! using_shm || xform24to32 || raw_fb) {\n\t\t/* we only need the XImage created */\n\t\txim = XCreateImage_wr(dpy, default_visual, depth, ZPixmap,\n\t\t 0, NULL, w, h, raw_fb ? 32 : BitmapPad(dpy), 0);\n\n\t\tX_UNLOCK;\n\n\t\tif (xim == NULL) {\n\t\t\trfbErr(\"XCreateImage(%s) failed.\\n\", name);\n\t\t\tif (quiet) {\n\t\t\t\tfprintf(stderr, \"XCreateImage(%s) failed.\\n\",\n\t\t\t\t name);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\tif (db) fprintf(stderr, \"shm_create simple %d %d\\t%p %s\\n\", w, h, (void *)xim, name);\n\t\txim->data = (char *) malloc(xim->bytes_per_line * xim->height);\n\t\tif (xim->data == NULL) {\n\t\t\trfbErr(\"XCreateImage(%s) data malloc failed.\\n\", name);\n\t\t\tif (quiet) {\n\t\t\t\tfprintf(stderr, \"XCreateImage(%s) data malloc\"\n\t\t\t\t \" failed.\\n\", name);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\tif (flip_byte_order) {\n\t\t\tchar *order = flip_ximage_byte_order(xim);\n\t\t\tif (! reported_flip && ! quiet) {\n\t\t\t\trfbLog(\"Changing XImage byte order\"\n\t\t\t\t \" to %s\\n\", order);\n\t\t\t\treported_flip = 1;\n\t\t\t}\n\t\t}\n\n\t\t*ximg_ptr = xim;\n\t\treturn 1;\n\t}\n\n\tif (! dpy) {\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\txim = XShmCreateImage_wr(dpy, default_visual, depth, ZPixmap, NULL,\n\t shm, w, h);\n\n\tif (xim == NULL) {\n\t\trfbErr(\"XShmCreateImage(%s) failed.\\n\", name);\n\t\tif (quiet) {\n\t\t\tfprintf(stderr, \"XShmCreateImage(%s) failed.\\n\", name);\n\t\t}\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\t*ximg_ptr = xim;\n\n#if HAVE_XSHM\n\tshm->shmid = shmget(IPC_PRIVATE,\n\t xim->bytes_per_line * xim->height, IPC_CREAT | 0600);\n\n\tif (shm->shmid == -1) {\n\t\trfbErr(\"shmget(%s) failed.\\n\", name);\n\t\trfbLogPerror(\"shmget\");\n\n\t\tXDestroyImage(xim);\n\t\t*ximg_ptr = NULL;\n\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\tshm->shmaddr = xim->data = (char *) shmat(shm->shmid, 0, 0);\n\n\tif (shm->shmaddr == (char *)-1) {\n\t\trfbErr(\"shmat(%s) failed.\\n\", name);\n\t\trfbLogPerror(\"shmat\");\n\n\t\tXDestroyImage(xim);\n\t\t*ximg_ptr = NULL;\n\n\t\tshmctl(shm->shmid, IPC_RMID, 0);\n\t\tshm->shmid = -1;\n\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n\n\tshm->readOnly = False;\n\n\tif (! XShmAttach_wr(dpy, shm)) {\n\t\trfbErr(\"XShmAttach(%s) failed.\\n\", name);\n\t\tXDestroyImage(xim);\n\t\t*ximg_ptr = NULL;\n\n\t\tshmdt(shm->shmaddr);\n\t\tshm->shmaddr = (char *) -1;\n\n\t\tshmctl(shm->shmid, IPC_RMID, 0);\n\t\tshm->shmid = -1;\n\n\t\tX_UNLOCK;\n\t\treturn 0;\n\t}\n#endif\n\n\tX_UNLOCK;\n\treturn 1;\n}", "project": "x11vnc", "hash": 251759810483318878247162187332724697979, "size": 126, "commit_id": "69eeb9f7baa14ca03b16c9de821f9876def7a36a", "message": "scan: limit access to shared memory segments to current user", "target": 0, "dataset": "other", "idx": 360762} {"func": "void stralgoLCS(client *c) {\n uint32_t i, j;\n long long minmatchlen = 0;\n sds a = NULL, b = NULL;\n int getlen = 0, getidx = 0, withmatchlen = 0;\n robj *obja = NULL, *objb = NULL;\n\n for (j = 2; j < (uint32_t)c->argc; j++) {\n char *opt = c->argv[j]->ptr;\n int moreargs = (c->argc-1) - j;\n\n if (!strcasecmp(opt,\"IDX\")) {\n getidx = 1;\n } else if (!strcasecmp(opt,\"LEN\")) {\n getlen = 1;\n } else if (!strcasecmp(opt,\"WITHMATCHLEN\")) {\n withmatchlen = 1;\n } else if (!strcasecmp(opt,\"MINMATCHLEN\") && moreargs) {\n if (getLongLongFromObjectOrReply(c,c->argv[j+1],&minmatchlen,NULL)\n != C_OK) goto cleanup;\n if (minmatchlen < 0) minmatchlen = 0;\n j++;\n } else if (!strcasecmp(opt,\"STRINGS\") && moreargs > 1) {\n if (a != NULL) {\n addReplyError(c,\"Either use STRINGS or KEYS\");\n goto cleanup;\n }\n a = c->argv[j+1]->ptr;\n b = c->argv[j+2]->ptr;\n j += 2;\n } else if (!strcasecmp(opt,\"KEYS\") && moreargs > 1) {\n if (a != NULL) {\n addReplyError(c,\"Either use STRINGS or KEYS\");\n goto cleanup;\n }\n obja = lookupKeyRead(c->db,c->argv[j+1]);\n objb = lookupKeyRead(c->db,c->argv[j+2]);\n if ((obja && obja->type != OBJ_STRING) ||\n (objb && objb->type != OBJ_STRING))\n {\n addReplyError(c,\n \"The specified keys must contain string values\");\n /* Don't cleanup the objects, we need to do that\n * only after callign getDecodedObject(). */\n obja = NULL;\n objb = NULL;\n goto cleanup;\n }\n obja = obja ? getDecodedObject(obja) : createStringObject(\"\",0);\n objb = objb ? getDecodedObject(objb) : createStringObject(\"\",0);\n a = obja->ptr;\n b = objb->ptr;\n j += 2;\n } else {\n addReply(c,shared.syntaxerr);\n goto cleanup;\n }\n }\n\n /* Complain if the user passed ambiguous parameters. */\n if (a == NULL) {\n addReplyError(c,\"Please specify two strings: \"\n \"STRINGS or KEYS options are mandatory\");\n goto cleanup;\n } else if (getlen && getidx) {\n addReplyError(c,\n \"If you want both the length and indexes, please \"\n \"just use IDX.\");\n goto cleanup;\n }\n\n /* Compute the LCS using the vanilla dynamic programming technique of\n * building a table of LCS(x,y) substrings. */\n uint32_t alen = sdslen(a);\n uint32_t blen = sdslen(b);\n\n /* Setup an uint32_t array to store at LCS[i,j] the length of the\n * LCS A0..i-1, B0..j-1. Note that we have a linear array here, so\n * we index it as LCS[j+(blen+1)*j] */\n uint32_t *lcs = zmalloc((alen+1)*(blen+1)*sizeof(uint32_t));\n #define LCS(A,B) lcs[(B)+((A)*(blen+1))]\n\n /* Start building the LCS table. */\n for (uint32_t i = 0; i <= alen; i++) {\n for (uint32_t j = 0; j <= blen; j++) {\n if (i == 0 || j == 0) {\n /* If one substring has length of zero, the\n * LCS length is zero. */\n LCS(i,j) = 0;\n } else if (a[i-1] == b[j-1]) {\n /* The len LCS (and the LCS itself) of two\n * sequences with the same final character, is the\n * LCS of the two sequences without the last char\n * plus that last char. */\n LCS(i,j) = LCS(i-1,j-1)+1;\n } else {\n /* If the last character is different, take the longest\n * between the LCS of the first string and the second\n * minus the last char, and the reverse. */\n uint32_t lcs1 = LCS(i-1,j);\n uint32_t lcs2 = LCS(i,j-1);\n LCS(i,j) = lcs1 > lcs2 ? lcs1 : lcs2;\n }\n }\n }\n\n /* Store the actual LCS string in \"result\" if needed. We create\n * it backward, but the length is already known, we store it into idx. */\n uint32_t idx = LCS(alen,blen);\n sds result = NULL; /* Resulting LCS string. */\n void *arraylenptr = NULL; /* Deffered length of the array for IDX. */\n uint32_t arange_start = alen, /* alen signals that values are not set. */\n arange_end = 0,\n brange_start = 0,\n brange_end = 0;\n\n /* Do we need to compute the actual LCS string? Allocate it in that case. */\n int computelcs = getidx || !getlen;\n if (computelcs) result = sdsnewlen(SDS_NOINIT,idx);\n\n /* Start with a deferred array if we have to emit the ranges. */\n uint32_t arraylen = 0; /* Number of ranges emitted in the array. */\n if (getidx) {\n addReplyMapLen(c,2);\n addReplyBulkCString(c,\"matches\");\n arraylenptr = addReplyDeferredLen(c);\n }\n\n i = alen, j = blen;\n while (computelcs && i > 0 && j > 0) {\n int emit_range = 0;\n if (a[i-1] == b[j-1]) {\n /* If there is a match, store the character and reduce\n * the indexes to look for a new match. */\n result[idx-1] = a[i-1];\n\n /* Track the current range. */\n if (arange_start == alen) {\n arange_start = i-1;\n arange_end = i-1;\n brange_start = j-1;\n brange_end = j-1;\n } else {\n /* Let's see if we can extend the range backward since\n * it is contiguous. */\n if (arange_start == i && brange_start == j) {\n arange_start--;\n brange_start--;\n } else {\n emit_range = 1;\n }\n }\n /* Emit the range if we matched with the first byte of\n * one of the two strings. We'll exit the loop ASAP. */\n if (arange_start == 0 || brange_start == 0) emit_range = 1;\n idx--; i--; j--;\n } else {\n /* Otherwise reduce i and j depending on the largest\n * LCS between, to understand what direction we need to go. */\n uint32_t lcs1 = LCS(i-1,j);\n uint32_t lcs2 = LCS(i,j-1);\n if (lcs1 > lcs2)\n i--;\n else\n j--;\n if (arange_start != alen) emit_range = 1;\n }\n\n /* Emit the current range if needed. */\n uint32_t match_len = arange_end - arange_start + 1;\n if (emit_range) {\n if (minmatchlen == 0 || match_len >= minmatchlen) {\n if (arraylenptr) {\n addReplyArrayLen(c,2+withmatchlen);\n addReplyArrayLen(c,2);\n addReplyLongLong(c,arange_start);\n addReplyLongLong(c,arange_end);\n addReplyArrayLen(c,2);\n addReplyLongLong(c,brange_start);\n addReplyLongLong(c,brange_end);\n if (withmatchlen) addReplyLongLong(c,match_len);\n arraylen++;\n }\n }\n arange_start = alen; /* Restart at the next match. */\n }\n }\n\n /* Signal modified key, increment dirty, ... */\n\n /* Reply depending on the given options. */\n if (arraylenptr) {\n addReplyBulkCString(c,\"len\");\n addReplyLongLong(c,LCS(alen,blen));\n setDeferredArrayLen(c,arraylenptr,arraylen);\n } else if (getlen) {\n addReplyLongLong(c,LCS(alen,blen));\n } else {\n addReplyBulkSds(c,result);\n result = NULL;\n }\n\n /* Cleanup. */\n sdsfree(result);\n zfree(lcs);\n\ncleanup:\n if (obja) decrRefCount(obja);\n if (objb) decrRefCount(objb);\n return;\n}", "project": "redis", "hash": 5416716427636361581435192994670558250, "size": 211, "commit_id": "394614a5f91d88380f480c4610926a865b5b0f16", "message": "Fix integer overflow in STRALGO LCS (CVE-2021-29477)\n\nAn integer overflow bug in Redis version 6.0 or newer could be exploited using\nthe STRALGO LCS command to corrupt the heap and potentially result with remote\ncode execution.\n\n(cherry picked from commit f0c5f920d0f88bd8aa376a2c05af4902789d1ef9)", "target": 1, "dataset": "other", "idx": 204533} {"func": "void stralgoLCS(client *c) {\n uint32_t i, j;\n long long minmatchlen = 0;\n sds a = NULL, b = NULL;\n int getlen = 0, getidx = 0, withmatchlen = 0;\n robj *obja = NULL, *objb = NULL;\n\n for (j = 2; j < (uint32_t)c->argc; j++) {\n char *opt = c->argv[j]->ptr;\n int moreargs = (c->argc-1) - j;\n\n if (!strcasecmp(opt,\"IDX\")) {\n getidx = 1;\n } else if (!strcasecmp(opt,\"LEN\")) {\n getlen = 1;\n } else if (!strcasecmp(opt,\"WITHMATCHLEN\")) {\n withmatchlen = 1;\n } else if (!strcasecmp(opt,\"MINMATCHLEN\") && moreargs) {\n if (getLongLongFromObjectOrReply(c,c->argv[j+1],&minmatchlen,NULL)\n != C_OK) goto cleanup;\n if (minmatchlen < 0) minmatchlen = 0;\n j++;\n } else if (!strcasecmp(opt,\"STRINGS\") && moreargs > 1) {\n if (a != NULL) {\n addReplyError(c,\"Either use STRINGS or KEYS\");\n goto cleanup;\n }\n a = c->argv[j+1]->ptr;\n b = c->argv[j+2]->ptr;\n j += 2;\n } else if (!strcasecmp(opt,\"KEYS\") && moreargs > 1) {\n if (a != NULL) {\n addReplyError(c,\"Either use STRINGS or KEYS\");\n goto cleanup;\n }\n obja = lookupKeyRead(c->db,c->argv[j+1]);\n objb = lookupKeyRead(c->db,c->argv[j+2]);\n if ((obja && obja->type != OBJ_STRING) ||\n (objb && objb->type != OBJ_STRING))\n {\n addReplyError(c,\n \"The specified keys must contain string values\");\n /* Don't cleanup the objects, we need to do that\n * only after callign getDecodedObject(). */\n obja = NULL;\n objb = NULL;\n goto cleanup;\n }\n obja = obja ? getDecodedObject(obja) : createStringObject(\"\",0);\n objb = objb ? getDecodedObject(objb) : createStringObject(\"\",0);\n a = obja->ptr;\n b = objb->ptr;\n j += 2;\n } else {\n addReply(c,shared.syntaxerr);\n goto cleanup;\n }\n }\n\n /* Complain if the user passed ambiguous parameters. */\n if (a == NULL) {\n addReplyError(c,\"Please specify two strings: \"\n \"STRINGS or KEYS options are mandatory\");\n goto cleanup;\n } else if (getlen && getidx) {\n addReplyError(c,\n \"If you want both the length and indexes, please \"\n \"just use IDX.\");\n goto cleanup;\n }\n\n /* Compute the LCS using the vanilla dynamic programming technique of\n * building a table of LCS(x,y) substrings. */\n uint32_t alen = sdslen(a);\n uint32_t blen = sdslen(b);\n\n /* Setup an uint32_t array to store at LCS[i,j] the length of the\n * LCS A0..i-1, B0..j-1. Note that we have a linear array here, so\n * we index it as LCS[j+(blen+1)*j] */\n uint32_t *lcs = zmalloc((size_t)(alen+1)*(blen+1)*sizeof(uint32_t));\n #define LCS(A,B) lcs[(B)+((A)*(blen+1))]\n\n /* Start building the LCS table. */\n for (uint32_t i = 0; i <= alen; i++) {\n for (uint32_t j = 0; j <= blen; j++) {\n if (i == 0 || j == 0) {\n /* If one substring has length of zero, the\n * LCS length is zero. */\n LCS(i,j) = 0;\n } else if (a[i-1] == b[j-1]) {\n /* The len LCS (and the LCS itself) of two\n * sequences with the same final character, is the\n * LCS of the two sequences without the last char\n * plus that last char. */\n LCS(i,j) = LCS(i-1,j-1)+1;\n } else {\n /* If the last character is different, take the longest\n * between the LCS of the first string and the second\n * minus the last char, and the reverse. */\n uint32_t lcs1 = LCS(i-1,j);\n uint32_t lcs2 = LCS(i,j-1);\n LCS(i,j) = lcs1 > lcs2 ? lcs1 : lcs2;\n }\n }\n }\n\n /* Store the actual LCS string in \"result\" if needed. We create\n * it backward, but the length is already known, we store it into idx. */\n uint32_t idx = LCS(alen,blen);\n sds result = NULL; /* Resulting LCS string. */\n void *arraylenptr = NULL; /* Deffered length of the array for IDX. */\n uint32_t arange_start = alen, /* alen signals that values are not set. */\n arange_end = 0,\n brange_start = 0,\n brange_end = 0;\n\n /* Do we need to compute the actual LCS string? Allocate it in that case. */\n int computelcs = getidx || !getlen;\n if (computelcs) result = sdsnewlen(SDS_NOINIT,idx);\n\n /* Start with a deferred array if we have to emit the ranges. */\n uint32_t arraylen = 0; /* Number of ranges emitted in the array. */\n if (getidx) {\n addReplyMapLen(c,2);\n addReplyBulkCString(c,\"matches\");\n arraylenptr = addReplyDeferredLen(c);\n }\n\n i = alen, j = blen;\n while (computelcs && i > 0 && j > 0) {\n int emit_range = 0;\n if (a[i-1] == b[j-1]) {\n /* If there is a match, store the character and reduce\n * the indexes to look for a new match. */\n result[idx-1] = a[i-1];\n\n /* Track the current range. */\n if (arange_start == alen) {\n arange_start = i-1;\n arange_end = i-1;\n brange_start = j-1;\n brange_end = j-1;\n } else {\n /* Let's see if we can extend the range backward since\n * it is contiguous. */\n if (arange_start == i && brange_start == j) {\n arange_start--;\n brange_start--;\n } else {\n emit_range = 1;\n }\n }\n /* Emit the range if we matched with the first byte of\n * one of the two strings. We'll exit the loop ASAP. */\n if (arange_start == 0 || brange_start == 0) emit_range = 1;\n idx--; i--; j--;\n } else {\n /* Otherwise reduce i and j depending on the largest\n * LCS between, to understand what direction we need to go. */\n uint32_t lcs1 = LCS(i-1,j);\n uint32_t lcs2 = LCS(i,j-1);\n if (lcs1 > lcs2)\n i--;\n else\n j--;\n if (arange_start != alen) emit_range = 1;\n }\n\n /* Emit the current range if needed. */\n uint32_t match_len = arange_end - arange_start + 1;\n if (emit_range) {\n if (minmatchlen == 0 || match_len >= minmatchlen) {\n if (arraylenptr) {\n addReplyArrayLen(c,2+withmatchlen);\n addReplyArrayLen(c,2);\n addReplyLongLong(c,arange_start);\n addReplyLongLong(c,arange_end);\n addReplyArrayLen(c,2);\n addReplyLongLong(c,brange_start);\n addReplyLongLong(c,brange_end);\n if (withmatchlen) addReplyLongLong(c,match_len);\n arraylen++;\n }\n }\n arange_start = alen; /* Restart at the next match. */\n }\n }\n\n /* Signal modified key, increment dirty, ... */\n\n /* Reply depending on the given options. */\n if (arraylenptr) {\n addReplyBulkCString(c,\"len\");\n addReplyLongLong(c,LCS(alen,blen));\n setDeferredArrayLen(c,arraylenptr,arraylen);\n } else if (getlen) {\n addReplyLongLong(c,LCS(alen,blen));\n } else {\n addReplyBulkSds(c,result);\n result = NULL;\n }\n\n /* Cleanup. */\n sdsfree(result);\n zfree(lcs);\n\ncleanup:\n if (obja) decrRefCount(obja);\n if (objb) decrRefCount(objb);\n return;\n}", "project": "redis", "hash": 327629069030382399823532872609259616525, "size": 211, "commit_id": "394614a5f91d88380f480c4610926a865b5b0f16", "message": "Fix integer overflow in STRALGO LCS (CVE-2021-29477)\n\nAn integer overflow bug in Redis version 6.0 or newer could be exploited using\nthe STRALGO LCS command to corrupt the heap and potentially result with remote\ncode execution.\n\n(cherry picked from commit f0c5f920d0f88bd8aa376a2c05af4902789d1ef9)", "target": 0, "dataset": "other", "idx": 361275} {"func": "rleUncompress (int inLength, int maxLength, const signed char in[], char out[])\n{\n char *outStart = out;\n\n while (inLength > 0)\n {\n\tif (*in < 0)\n\t{\n\t int count = -((int)*in++);\n\t inLength -= count + 1;\n\n\t if (0 > (maxLength -= count))\n\t\treturn 0;\n\n // check the input buffer is big enough to contain\n // 'count' bytes of remaining data\n if (inLength < 0)\n return 0;\n\n memcpy(out, in, count);\n out += count;\n in += count;\n\t}\n\telse\n\t{\n\t int count = *in++;\n\t inLength -= 2;\n\n\t if (0 > (maxLength -= count + 1))\n\t\treturn 0;\n\n memset(out, *(char*)in, count+1);\n out += count+1;\n\n\t in++;\n\t}\n }\n\n return out - outStart;\n}", "project": "openexr", "hash": 304669280453166082193019580418525426392, "size": 40, "commit_id": "25259a84827234a283f6f9db72978198c7a3f268", "message": "detect buffer overflows in RleUncompress (#1036)\n\nSigned-off-by: Peter Hillman ", "target": 1, "dataset": "other", "idx": 204639} {"func": "rleUncompress (int inLength, int maxLength, const signed char in[], char out[])\n{\n char *outStart = out;\n\n while (inLength > 0)\n {\n\tif (*in < 0)\n\t{\n\t int count = -((int)*in++);\n\t inLength -= count + 1;\n\n\t if (0 > (maxLength -= count))\n\t\treturn 0;\n\n // check the input buffer is big enough to contain\n // 'count' bytes of remaining data\n if (inLength < 0)\n return 0;\n\n memcpy(out, in, count);\n out += count;\n in += count;\n\t}\n\telse\n\t{\n\t int count = *in++;\n\t inLength -= 2;\n\n\t if (0 > (maxLength -= count + 1))\n\t\treturn 0;\n\n // check the input buffer is big enough to contain\n // byte to be duplicated\n if (inLength < 0)\n return 0;\n\n memset(out, *(char*)in, count+1);\n out += count+1;\n\n\t in++;\n\t}\n }\n\n return out - outStart;\n}", "project": "openexr", "hash": 253476937124885143941445089513595709318, "size": 45, "commit_id": "25259a84827234a283f6f9db72978198c7a3f268", "message": "detect buffer overflows in RleUncompress (#1036)\n\nSigned-off-by: Peter Hillman ", "target": 0, "dataset": "other", "idx": 362854} {"func": "static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)\n{\n\tbool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG;\n\tu32 chunk_size = mr->chunk_size, headroom = mr->headroom;\n\tunsigned int chunks, chunks_per_page;\n\tu64 addr = mr->addr, size = mr->len;\n\tint size_chk, err;\n\n\tif (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) {\n\t\t/* Strictly speaking we could support this, if:\n\t\t * - huge pages, or*\n\t\t * - using an IOMMU, or\n\t\t * - making sure the memory area is consecutive\n\t\t * but for now, we simply say \"computer says no\".\n\t\t */\n\t\treturn -EINVAL;\n\t}\n\n\tif (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG |\n\t\t\tXDP_UMEM_USES_NEED_WAKEUP))\n\t\treturn -EINVAL;\n\n\tif (!unaligned_chunks && !is_power_of_2(chunk_size))\n\t\treturn -EINVAL;\n\n\tif (!PAGE_ALIGNED(addr)) {\n\t\t/* Memory area has to be page size aligned. For\n\t\t * simplicity, this might change.\n\t\t */\n\t\treturn -EINVAL;\n\t}\n\n\tif ((addr + size) < addr)\n\t\treturn -EINVAL;\n\n\tchunks = (unsigned int)div_u64(size, chunk_size);\n\tif (chunks == 0)\n\t\treturn -EINVAL;\n\n\tif (!unaligned_chunks) {\n\t\tchunks_per_page = PAGE_SIZE / chunk_size;\n\t\tif (chunks < chunks_per_page || chunks % chunks_per_page)\n\t\t\treturn -EINVAL;\n\t}\n\n\tsize_chk = chunk_size - headroom - XDP_PACKET_HEADROOM;\n\tif (size_chk < 0)\n\t\treturn -EINVAL;\n\n\tumem->address = (unsigned long)addr;\n\tumem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK\n\t\t\t\t\t : ~((u64)chunk_size - 1);\n\tumem->size = size;\n\tumem->headroom = headroom;\n\tumem->chunk_size_nohr = chunk_size - headroom;\n\tumem->npgs = size / PAGE_SIZE;\n\tumem->pgs = NULL;\n\tumem->user = NULL;\n\tumem->flags = mr->flags;\n\tINIT_LIST_HEAD(&umem->xsk_list);\n\tspin_lock_init(&umem->xsk_list_lock);\n\n\trefcount_set(&umem->users, 1);\n\n\terr = xdp_umem_account_pages(umem);\n\tif (err)\n\t\treturn err;\n\n\terr = xdp_umem_pin_pages(umem);\n\tif (err)\n\t\tgoto out_account;\n\n\tumem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages),\n\t\t\t GFP_KERNEL_ACCOUNT);\n\tif (!umem->pages) {\n\t\terr = -ENOMEM;\n\t\tgoto out_pin;\n\t}\n\n\terr = xdp_umem_map_pages(umem);\n\tif (!err)\n\t\treturn 0;\n\n\tkvfree(umem->pages);\n\nout_pin:\n\txdp_umem_unpin_pages(umem);\nout_account:\n\txdp_umem_unaccount_pages(umem);\n\treturn err;\n}", "project": "linux", "hash": 269028637877237764370672455302491205384, "size": 91, "commit_id": "99e3a236dd43d06c65af0a2ef9cb44306aef6e02", "message": "xsk: Add missing check on user supplied headroom size\n\nAdd a check that the headroom cannot be larger than the available\nspace in the chunk. In the current code, a malicious user can set the\nheadroom to a value larger than the chunk size minus the fixed XDP\nheadroom. That way packets with a length larger than the supported\nsize in the umem could get accepted and result in an out-of-bounds\nwrite.\n\nFixes: c0c77d8fb787 (\"xsk: add user memory registration support sockopt\")\nReported-by: Bui Quang Minh \nSigned-off-by: Magnus Karlsson \nSigned-off-by: Daniel Borkmann \nLink: https://bugzilla.kernel.org/show_bug.cgi?id=207225\nLink: https://lore.kernel.org/bpf/1586849715-23490-1-git-send-email-magnus.karlsson@intel.com", "target": 1, "dataset": "other", "idx": 204723} {"func": "static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)\n{\n\tbool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG;\n\tu32 chunk_size = mr->chunk_size, headroom = mr->headroom;\n\tunsigned int chunks, chunks_per_page;\n\tu64 addr = mr->addr, size = mr->len;\n\tint err;\n\n\tif (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) {\n\t\t/* Strictly speaking we could support this, if:\n\t\t * - huge pages, or*\n\t\t * - using an IOMMU, or\n\t\t * - making sure the memory area is consecutive\n\t\t * but for now, we simply say \"computer says no\".\n\t\t */\n\t\treturn -EINVAL;\n\t}\n\n\tif (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG |\n\t\t\tXDP_UMEM_USES_NEED_WAKEUP))\n\t\treturn -EINVAL;\n\n\tif (!unaligned_chunks && !is_power_of_2(chunk_size))\n\t\treturn -EINVAL;\n\n\tif (!PAGE_ALIGNED(addr)) {\n\t\t/* Memory area has to be page size aligned. For\n\t\t * simplicity, this might change.\n\t\t */\n\t\treturn -EINVAL;\n\t}\n\n\tif ((addr + size) < addr)\n\t\treturn -EINVAL;\n\n\tchunks = (unsigned int)div_u64(size, chunk_size);\n\tif (chunks == 0)\n\t\treturn -EINVAL;\n\n\tif (!unaligned_chunks) {\n\t\tchunks_per_page = PAGE_SIZE / chunk_size;\n\t\tif (chunks < chunks_per_page || chunks % chunks_per_page)\n\t\t\treturn -EINVAL;\n\t}\n\n\tif (headroom >= chunk_size - XDP_PACKET_HEADROOM)\n\t\treturn -EINVAL;\n\n\tumem->address = (unsigned long)addr;\n\tumem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK\n\t\t\t\t\t : ~((u64)chunk_size - 1);\n\tumem->size = size;\n\tumem->headroom = headroom;\n\tumem->chunk_size_nohr = chunk_size - headroom;\n\tumem->npgs = size / PAGE_SIZE;\n\tumem->pgs = NULL;\n\tumem->user = NULL;\n\tumem->flags = mr->flags;\n\tINIT_LIST_HEAD(&umem->xsk_list);\n\tspin_lock_init(&umem->xsk_list_lock);\n\n\trefcount_set(&umem->users, 1);\n\n\terr = xdp_umem_account_pages(umem);\n\tif (err)\n\t\treturn err;\n\n\terr = xdp_umem_pin_pages(umem);\n\tif (err)\n\t\tgoto out_account;\n\n\tumem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages),\n\t\t\t GFP_KERNEL_ACCOUNT);\n\tif (!umem->pages) {\n\t\terr = -ENOMEM;\n\t\tgoto out_pin;\n\t}\n\n\terr = xdp_umem_map_pages(umem);\n\tif (!err)\n\t\treturn 0;\n\n\tkvfree(umem->pages);\n\nout_pin:\n\txdp_umem_unpin_pages(umem);\nout_account:\n\txdp_umem_unaccount_pages(umem);\n\treturn err;\n}", "project": "linux", "hash": 42054657955985470671897377670619516821, "size": 90, "commit_id": "99e3a236dd43d06c65af0a2ef9cb44306aef6e02", "message": "xsk: Add missing check on user supplied headroom size\n\nAdd a check that the headroom cannot be larger than the available\nspace in the chunk. In the current code, a malicious user can set the\nheadroom to a value larger than the chunk size minus the fixed XDP\nheadroom. That way packets with a length larger than the supported\nsize in the umem could get accepted and result in an out-of-bounds\nwrite.\n\nFixes: c0c77d8fb787 (\"xsk: add user memory registration support sockopt\")\nReported-by: Bui Quang Minh \nSigned-off-by: Magnus Karlsson \nSigned-off-by: Daniel Borkmann \nLink: https://bugzilla.kernel.org/show_bug.cgi?id=207225\nLink: https://lore.kernel.org/bpf/1586849715-23490-1-git-send-email-magnus.karlsson@intel.com", "target": 0, "dataset": "other", "idx": 364107} {"func": "static inline int pri2fac(const int pri)\n{\n\tint fac = pri >> 3;\n\treturn (fac > 23) ? LOG_FAC_INVLD : fac;\n}", "project": "rsyslog", "hash": 38375841940809111922591785804510290465, "size": 5, "commit_id": "8a4ada405e98ed3470f2c5f54e52339e7263c258", "message": "prevent PRI underflow", "target": 1, "dataset": "other", "idx": 204724} {"func": "static inline int pri2fac(const int pri)\n{\n\tunsigned fac = pri >> 3;\n\treturn (fac > 23) ? LOG_FAC_INVLD : fac;\n}", "project": "rsyslog", "hash": 132599495943349320656124963251558173960, "size": 5, "commit_id": "8a4ada405e98ed3470f2c5f54e52339e7263c258", "message": "prevent PRI underflow", "target": 0, "dataset": "other", "idx": 364120} {"func": "void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,\n\t\tunsigned long address, bool freeze, struct page *page)\n{\n\tspinlock_t *ptl;\n\tstruct mmu_notifier_range range;\n\n\tmmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,\n\t\t\t\taddress & HPAGE_PMD_MASK,\n\t\t\t\t(address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE);\n\tmmu_notifier_invalidate_range_start(&range);\n\tptl = pmd_lock(vma->vm_mm, pmd);\n\n\t/*\n\t * If caller asks to setup a migration entries, we need a page to check\n\t * pmd against. Otherwise we can end up replacing wrong page.\n\t */\n\tVM_BUG_ON(freeze && !page);\n\tif (page && page != pmd_page(*pmd))\n\t goto out;\n\n\tif (pmd_trans_huge(*pmd)) {\n\t\tpage = pmd_page(*pmd);\n\t\tif (PageMlocked(page))\n\t\t\tclear_page_mlock(page);\n\t} else if (!(pmd_devmap(*pmd) || is_pmd_migration_entry(*pmd)))\n\t\tgoto out;\n\t__split_huge_pmd_locked(vma, pmd, range.start, freeze);\nout:\n\tspin_unlock(ptl);\n\t/*\n\t * No need to double call mmu_notifier->invalidate_range() callback.\n\t * They are 3 cases to consider inside __split_huge_pmd_locked():\n\t * 1) pmdp_huge_clear_flush_notify() call invalidate_range() obvious\n\t * 2) __split_huge_zero_page_pmd() read only zero page and any write\n\t * fault will trigger a flush_notify before pointing to a new page\n\t * (it is fine if the secondary mmu keeps pointing to the old zero\n\t * page in the meantime)\n\t * 3) Split a huge pmd into pte pointing to the same page. No need\n\t * to invalidate secondary tlb entry they are all still valid.\n\t * any further changes to individual pte will notify. So no need\n\t * to call mmu_notifier->invalidate_range()\n\t */\n\tmmu_notifier_invalidate_range_only_end(&range);\n}", "project": "linux", "hash": 232560186172248161602253290668425073906, "size": 44, "commit_id": "c444eb564fb16645c172d550359cb3d75fe8a040", "message": "mm: thp: make the THP mapcount atomic against __split_huge_pmd_locked()\n\nWrite protect anon page faults require an accurate mapcount to decide\nif to break the COW or not. This is implemented in the THP path with\nreuse_swap_page() ->\npage_trans_huge_map_swapcount()/page_trans_huge_mapcount().\n\nIf the COW triggers while the other processes sharing the page are\nunder a huge pmd split, to do an accurate reading, we must ensure the\nmapcount isn't computed while it's being transferred from the head\npage to the tail pages.\n\nreuse_swap_cache() already runs serialized by the page lock, so it's\nenough to add the page lock around __split_huge_pmd_locked too, in\norder to add the missing serialization.\n\nNote: the commit in \"Fixes\" is just to facilitate the backporting,\nbecause the code before such commit didn't try to do an accurate THP\nmapcount calculation and it instead used the page_count() to decide if\nto COW or not. Both the page_count and the pin_count are THP-wide\nrefcounts, so they're inaccurate if used in\nreuse_swap_page(). Reverting such commit (besides the unrelated fix to\nthe local anon_vma assignment) would have also opened the window for\nmemory corruption side effects to certain workloads as documented in\nsuch commit header.\n\nSigned-off-by: Andrea Arcangeli \nSuggested-by: Jann Horn \nReported-by: Jann Horn \nAcked-by: Kirill A. Shutemov \nFixes: 6d0a07edd17c (\"mm: thp: calculate the mapcount correctly for THP pages during WP faults\")\nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds ", "target": 1, "dataset": "other", "idx": 204725} {"func": "void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd,\n\t\tunsigned long address, bool freeze, struct page *page)\n{\n\tspinlock_t *ptl;\n\tstruct mmu_notifier_range range;\n\tbool was_locked = false;\n\tpmd_t _pmd;\n\n\tmmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,\n\t\t\t\taddress & HPAGE_PMD_MASK,\n\t\t\t\t(address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE);\n\tmmu_notifier_invalidate_range_start(&range);\n\tptl = pmd_lock(vma->vm_mm, pmd);\n\n\t/*\n\t * If caller asks to setup a migration entries, we need a page to check\n\t * pmd against. Otherwise we can end up replacing wrong page.\n\t */\n\tVM_BUG_ON(freeze && !page);\n\tif (page) {\n\t\tVM_WARN_ON_ONCE(!PageLocked(page));\n\t\twas_locked = true;\n\t\tif (page != pmd_page(*pmd))\n\t\t\tgoto out;\n\t}\n\nrepeat:\n\tif (pmd_trans_huge(*pmd)) {\n\t\tif (!page) {\n\t\t\tpage = pmd_page(*pmd);\n\t\t\tif (unlikely(!trylock_page(page))) {\n\t\t\t\tget_page(page);\n\t\t\t\t_pmd = *pmd;\n\t\t\t\tspin_unlock(ptl);\n\t\t\t\tlock_page(page);\n\t\t\t\tspin_lock(ptl);\n\t\t\t\tif (unlikely(!pmd_same(*pmd, _pmd))) {\n\t\t\t\t\tunlock_page(page);\n\t\t\t\t\tput_page(page);\n\t\t\t\t\tpage = NULL;\n\t\t\t\t\tgoto repeat;\n\t\t\t\t}\n\t\t\t\tput_page(page);\n\t\t\t}\n\t\t}\n\t\tif (PageMlocked(page))\n\t\t\tclear_page_mlock(page);\n\t} else if (!(pmd_devmap(*pmd) || is_pmd_migration_entry(*pmd)))\n\t\tgoto out;\n\t__split_huge_pmd_locked(vma, pmd, range.start, freeze);\nout:\n\tspin_unlock(ptl);\n\tif (!was_locked && page)\n\t\tunlock_page(page);\n\t/*\n\t * No need to double call mmu_notifier->invalidate_range() callback.\n\t * They are 3 cases to consider inside __split_huge_pmd_locked():\n\t * 1) pmdp_huge_clear_flush_notify() call invalidate_range() obvious\n\t * 2) __split_huge_zero_page_pmd() read only zero page and any write\n\t * fault will trigger a flush_notify before pointing to a new page\n\t * (it is fine if the secondary mmu keeps pointing to the old zero\n\t * page in the meantime)\n\t * 3) Split a huge pmd into pte pointing to the same page. No need\n\t * to invalidate secondary tlb entry they are all still valid.\n\t * any further changes to individual pte will notify. So no need\n\t * to call mmu_notifier->invalidate_range()\n\t */\n\tmmu_notifier_invalidate_range_only_end(&range);\n}", "project": "linux", "hash": 305184181549084038258030671746596105420, "size": 69, "commit_id": "c444eb564fb16645c172d550359cb3d75fe8a040", "message": "mm: thp: make the THP mapcount atomic against __split_huge_pmd_locked()\n\nWrite protect anon page faults require an accurate mapcount to decide\nif to break the COW or not. This is implemented in the THP path with\nreuse_swap_page() ->\npage_trans_huge_map_swapcount()/page_trans_huge_mapcount().\n\nIf the COW triggers while the other processes sharing the page are\nunder a huge pmd split, to do an accurate reading, we must ensure the\nmapcount isn't computed while it's being transferred from the head\npage to the tail pages.\n\nreuse_swap_cache() already runs serialized by the page lock, so it's\nenough to add the page lock around __split_huge_pmd_locked too, in\norder to add the missing serialization.\n\nNote: the commit in \"Fixes\" is just to facilitate the backporting,\nbecause the code before such commit didn't try to do an accurate THP\nmapcount calculation and it instead used the page_count() to decide if\nto COW or not. Both the page_count and the pin_count are THP-wide\nrefcounts, so they're inaccurate if used in\nreuse_swap_page(). Reverting such commit (besides the unrelated fix to\nthe local anon_vma assignment) would have also opened the window for\nmemory corruption side effects to certain workloads as documented in\nsuch commit header.\n\nSigned-off-by: Andrea Arcangeli \nSuggested-by: Jann Horn \nReported-by: Jann Horn \nAcked-by: Kirill A. Shutemov \nFixes: 6d0a07edd17c (\"mm: thp: calculate the mapcount correctly for THP pages during WP faults\")\nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds ", "target": 0, "dataset": "other", "idx": 364123} {"func": "int parse_arguments(int *argc_p, const char ***argv_p)\n{\n\tstatic poptContext pc;\n\tchar *ref = lp_refuse_options(module_id);\n\tconst char *arg, **argv = *argv_p;\n\tint argc = *argc_p;\n\tint opt;\n\n\tif (ref && *ref)\n\t\tset_refuse_options(ref);\n\tif (am_daemon) {\n\t\tset_refuse_options(\"log-file*\");\n#ifdef ICONV_OPTION\n\t\tif (!*lp_charset(module_id))\n\t\t\tset_refuse_options(\"iconv\");\n#endif\n\t}\n\n#ifdef ICONV_OPTION\n\tif (!am_daemon && protect_args <= 0 && (arg = getenv(\"RSYNC_ICONV\")) != NULL && *arg)\n\t\ticonv_opt = strdup(arg);\n#endif\n\n\t/* TODO: Call poptReadDefaultConfig; handle errors. */\n\n\t/* The context leaks in case of an error, but if there's a\n\t * problem we always exit anyhow. */\n\tif (pc)\n\t\tpoptFreeContext(pc);\n\tpc = poptGetContext(RSYNC_NAME, argc, argv, long_options, 0);\n\tif (!am_server) {\n\t\tpoptReadDefaultConfig(pc, 0);\n\t\tpopt_unalias(pc, \"--daemon\");\n\t\tpopt_unalias(pc, \"--server\");\n\t}\n\n\twhile ((opt = poptGetNextOpt(pc)) != -1) {\n\t\t/* most options are handled automatically by popt;\n\t\t * only special cases are returned and listed here. */\n\n\t\tswitch (opt) {\n\t\tcase OPT_VERSION:\n\t\t\tprint_rsync_version(FINFO);\n\t\t\texit_cleanup(0);\n\n\t\tcase OPT_SERVER:\n\t\t\tif (!am_server) {\n\t\t\t\t/* Disable popt aliases on the server side and\n\t\t\t\t * then start parsing the options again. */\n\t\t\t\tpoptFreeContext(pc);\n\t\t\t\tpc = poptGetContext(RSYNC_NAME, argc, argv,\n\t\t\t\t\t\t long_options, 0);\n\t\t\t\tam_server = 1;\n\t\t\t}\n#ifdef ICONV_OPTION\n\t\t\ticonv_opt = NULL;\n#endif\n\t\t\tbreak;\n\n\t\tcase OPT_SENDER:\n\t\t\tif (!am_server) {\n\t\t\t\tusage(FERROR);\n\t\t\t\texit_cleanup(RERR_SYNTAX);\n\t\t\t}\n\t\t\tam_sender = 1;\n\t\t\tbreak;\n\n\t\tcase OPT_DAEMON:\n\t\t\tif (am_daemon) {\n\t\t\t\tstrlcpy(err_buf,\n\t\t\t\t\t\"Attempt to hack rsync thwarted!\\n\",\n\t\t\t\t\tsizeof err_buf);\n\t\t\t\treturn 0;\n\t\t\t}\n#ifdef ICONV_OPTION\n\t\t\ticonv_opt = NULL;\n#endif\n\t\t\tprotect_args = 0;\n\t\t\tpoptFreeContext(pc);\n\t\t\tpc = poptGetContext(RSYNC_NAME, argc, argv,\n\t\t\t\t\t long_daemon_options, 0);\n\t\t\twhile ((opt = poptGetNextOpt(pc)) != -1) {\n\t\t\t\tchar **cpp;\n\t\t\t\tswitch (opt) {\n\t\t\t\tcase 'h':\n\t\t\t\t\tdaemon_usage(FINFO);\n\t\t\t\t\texit_cleanup(0);\n\n\t\t\t\tcase 'M':\n\t\t\t\t\targ = poptGetOptArg(pc);\n\t\t\t\t\tif (!strchr(arg, '=')) {\n\t\t\t\t\t\trprintf(FERROR,\n\t\t\t\t\t\t \"--dparam value is missing an '=': %s\\n\",\n\t\t\t\t\t\t arg);\n\t\t\t\t\t\tgoto daemon_error;\n\t\t\t\t\t}\n\t\t\t\t\tcpp = EXPAND_ITEM_LIST(&dparam_list, char *, 4);\n\t\t\t\t\t*cpp = strdup(arg);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'v':\n\t\t\t\t\tverbose++;\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\trprintf(FERROR,\n\t\t\t\t\t \"rsync: %s: %s (in daemon mode)\\n\",\n\t\t\t\t\t poptBadOption(pc, POPT_BADOPTION_NOALIAS),\n\t\t\t\t\t poptStrerror(opt));\n\t\t\t\t\tgoto daemon_error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (dparam_list.count && !set_dparams(1))\n\t\t\t\texit_cleanup(RERR_SYNTAX);\n\n\t\t\tif (tmpdir && strlen(tmpdir) >= MAXPATHLEN - 10) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t \"the --temp-dir path is WAY too long.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tif (!daemon_opt) {\n\t\t\t\trprintf(FERROR, \"Daemon option(s) used without --daemon.\\n\");\n\t\t\t daemon_error:\n\t\t\t\trprintf(FERROR,\n\t\t\t\t \"(Type \\\"rsync --daemon --help\\\" for assistance with daemon mode.)\\n\");\n\t\t\t\texit_cleanup(RERR_SYNTAX);\n\t\t\t}\n\n\t\t\t*argv_p = argv = poptGetArgs(pc);\n\t\t\t*argc_p = argc = count_args(argv);\n\t\t\tam_starting_up = 0;\n\t\t\tdaemon_opt = 0;\n\t\t\tam_daemon = 1;\n\t\t\treturn 1;\n\n\t\tcase OPT_MODIFY_WINDOW:\n\t\t\t/* The value has already been set by popt, but\n\t\t\t * we need to remember that we're using a\n\t\t\t * non-default setting. */\n\t\t\tmodify_window_set = 1;\n\t\t\tbreak;\n\n\t\tcase OPT_FILTER:\n\t\t\tparse_filter_str(&filter_list, poptGetOptArg(pc),\n\t\t\t\t\trule_template(0), 0);\n\t\t\tbreak;\n\n\t\tcase OPT_EXCLUDE:\n\t\t\tparse_filter_str(&filter_list, poptGetOptArg(pc),\n\t\t\t\t\trule_template(0), XFLG_OLD_PREFIXES);\n\t\t\tbreak;\n\n\t\tcase OPT_INCLUDE:\n\t\t\tparse_filter_str(&filter_list, poptGetOptArg(pc),\n\t\t\t\t\trule_template(FILTRULE_INCLUDE), XFLG_OLD_PREFIXES);\n\t\t\tbreak;\n\n\t\tcase OPT_EXCLUDE_FROM:\n\t\tcase OPT_INCLUDE_FROM:\n\t\t\targ = poptGetOptArg(pc);\n\t\t\tif (sanitize_paths)\n\t\t\t\targ = sanitize_path(NULL, arg, NULL, 0, SP_DEFAULT);\n\t\t\tif (daemon_filter_list.head) {\n\t\t\t\tint rej;\n\t\t\t\tchar *cp = strdup(arg);\n\t\t\t\tif (!cp)\n\t\t\t\t\tout_of_memory(\"parse_arguments\");\n\t\t\t\tif (!*cp)\n\t\t\t\t\trej = 1;\n\t\t\t\telse {\n\t\t\t\t\tchar *dir = cp + (*cp == '/' ? module_dirlen : 0);\n\t\t\t\t\tclean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);\n\t\t\t\t\trej = check_filter(&daemon_filter_list, FLOG, dir, 0) < 0;\n\t\t\t\t}\n\t\t\t\tfree(cp);\n\t\t\t\tif (rej)\n\t\t\t\t\tgoto options_rejected;\n\t\t\t}\n\t\t\tparse_filter_file(&filter_list, arg,\n\t\t\t\trule_template(opt == OPT_INCLUDE_FROM ? FILTRULE_INCLUDE : 0),\n\t\t\t\tXFLG_FATAL_ERRORS | XFLG_OLD_PREFIXES);\n\t\t\tbreak;\n\n\t\tcase 'a':\n\t\t\tif (refused_archive_part) {\n\t\t\t\tcreate_refuse_error(refused_archive_part);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (!recurse) /* preserve recurse == 2 */\n\t\t\t\trecurse = 1;\n#ifdef SUPPORT_LINKS\n\t\t\tpreserve_links = 1;\n#endif\n\t\t\tpreserve_perms = 1;\n\t\t\tpreserve_times = 1;\n\t\t\tpreserve_gid = 1;\n\t\t\tpreserve_uid = 1;\n\t\t\tpreserve_devices = 1;\n\t\t\tpreserve_specials = 1;\n\t\t\tbreak;\n\n\t\tcase 'D':\n\t\t\tpreserve_devices = preserve_specials = 1;\n\t\t\tbreak;\n\n\t\tcase OPT_NO_D:\n\t\t\tpreserve_devices = preserve_specials = 0;\n\t\t\tbreak;\n\n\t\tcase 'h':\n\t\t\thuman_readable++;\n\t\t\tbreak;\n\n\t\tcase 'H':\n\t\t\tpreserve_hard_links++;\n\t\t\tbreak;\n\n\t\tcase 'i':\n\t\t\titemize_changes++;\n\t\t\tbreak;\n\n\t\tcase 'v':\n\t\t\tverbose++;\n\t\t\tbreak;\n\n\t\tcase 'y':\n\t\t\tfuzzy_basis++;\n\t\t\tbreak;\n\n\t\tcase 'q':\n\t\t\tquiet++;\n\t\t\tbreak;\n\n\t\tcase 'x':\n\t\t\tone_file_system++;\n\t\t\tbreak;\n\n\t\tcase 'F':\n\t\t\tswitch (++F_option_cnt) {\n\t\t\tcase 1:\n\t\t\t\tparse_filter_str(&filter_list,\": /.rsync-filter\",rule_template(0),0);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tparse_filter_str(&filter_list,\"- .rsync-filter\",rule_template(0),0);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'P':\n\t\t\tif (refused_partial || refused_progress) {\n\t\t\t\tcreate_refuse_error(refused_partial\n\t\t\t\t ? refused_partial : refused_progress);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tdo_progress = 1;\n\t\t\tkeep_partial = 1;\n\t\t\tbreak;\n\n\t\tcase 'z':\n\t\t\tdo_compression++;\n\t\t\tbreak;\n\n\t\tcase 'M':\n\t\t\targ = poptGetOptArg(pc);\n\t\t\tif (*arg != '-') {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"Remote option must start with a dash: %s\\n\", arg);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (remote_option_cnt+2 >= remote_option_alloc) {\n\t\t\t\tremote_option_alloc += 16;\n\t\t\t\tremote_options = realloc_array(remote_options,\n\t\t\t\t\t\t\tconst char *, remote_option_alloc);\n\t\t\t\tif (!remote_options)\n\t\t\t\t\tout_of_memory(\"parse_arguments\");\n\t\t\t\tif (!remote_option_cnt)\n\t\t\t\t\tremote_options[0] = \"ARG0\";\n\t\t\t}\n\t\t\tremote_options[++remote_option_cnt] = arg;\n\t\t\tremote_options[remote_option_cnt+1] = NULL;\n\t\t\tbreak;\n\n\t\tcase OPT_WRITE_BATCH:\n\t\t\t/* batch_name is already set */\n\t\t\twrite_batch = 1;\n\t\t\tbreak;\n\n\t\tcase OPT_ONLY_WRITE_BATCH:\n\t\t\t/* batch_name is already set */\n\t\t\twrite_batch = -1;\n\t\t\tbreak;\n\n\t\tcase OPT_READ_BATCH:\n\t\t\t/* batch_name is already set */\n\t\t\tread_batch = 1;\n\t\t\tbreak;\n\n\t\tcase OPT_NO_ICONV:\n#ifdef ICONV_OPTION\n\t\t\ticonv_opt = NULL;\n#endif\n\t\t\tbreak;\n\n\t\tcase OPT_MAX_SIZE:\n\t\t\tif ((max_size = parse_size_arg(&max_size_arg, 'b')) < 0) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"--max-size value is invalid: %s\\n\",\n\t\t\t\t\tmax_size_arg);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OPT_MIN_SIZE:\n\t\t\tif ((min_size = parse_size_arg(&min_size_arg, 'b')) < 0) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"--min-size value is invalid: %s\\n\",\n\t\t\t\t\tmin_size_arg);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OPT_BWLIMIT:\n\t\t\t{\n\t\t\t\tOFF_T limit = parse_size_arg(&bwlimit_arg, 'K');\n\t\t\t\tif (limit < 0) {\n\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\t\"--bwlimit value is invalid: %s\\n\", bwlimit_arg);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tbwlimit = (limit + 512) / 1024;\n\t\t\t\tif (limit && !bwlimit) {\n\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\t\"--bwlimit value is too small: %s\\n\", bwlimit_arg);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OPT_APPEND:\n\t\t\tif (am_server)\n\t\t\t\tappend_mode++;\n\t\t\telse\n\t\t\t\tappend_mode = 1;\n\t\t\tbreak;\n\n\t\tcase OPT_LINK_DEST:\n#ifdef SUPPORT_HARD_LINKS\n\t\t\tlink_dest = 1;\n\t\t\tdest_option = \"--link-dest\";\n\t\t\tgoto set_dest_dir;\n#else\n\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t \"hard links are not supported on this %s\\n\",\n\t\t\t\t am_server ? \"server\" : \"client\");\n\t\t\treturn 0;\n#endif\n\n\t\tcase OPT_COPY_DEST:\n\t\t\tcopy_dest = 1;\n\t\t\tdest_option = \"--copy-dest\";\n\t\t\tgoto set_dest_dir;\n\n\t\tcase OPT_COMPARE_DEST:\n\t\t\tcompare_dest = 1;\n\t\t\tdest_option = \"--compare-dest\";\n\t\tset_dest_dir:\n\t\t\tif (basis_dir_cnt >= MAX_BASIS_DIRS) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"ERROR: at most %d %s args may be specified\\n\",\n\t\t\t\t\tMAX_BASIS_DIRS, dest_option);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t/* We defer sanitizing this arg until we know what\n\t\t\t * our destination directory is going to be. */\n\t\t\tbasis_dir[basis_dir_cnt++] = (char *)poptGetOptArg(pc);\n\t\t\tbreak;\n\n\t\tcase OPT_CHMOD:\n\t\t\targ = poptGetOptArg(pc);\n\t\t\tif (!parse_chmod(arg, &chmod_modes)) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t \"Invalid argument passed to --chmod (%s)\\n\",\n\t\t\t\t arg);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OPT_INFO:\n\t\t\targ = poptGetOptArg(pc);\n\t\t\tparse_output_words(info_words, info_levels, arg, USER_PRIORITY);\n\t\t\tbreak;\n\n\t\tcase OPT_DEBUG:\n\t\t\targ = poptGetOptArg(pc);\n\t\t\tparse_output_words(debug_words, debug_levels, arg, USER_PRIORITY);\n\t\t\tbreak;\n\n\t\tcase OPT_USERMAP:\n\t\t\tif (usermap) {\n\t\t\t\tif (usermap_via_chown) {\n\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t \"--usermap conflicts with prior --chown.\\n\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t \"You can only specify --usermap once.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tusermap = (char *)poptGetOptArg(pc);\n\t\t\tusermap_via_chown = False;\n\t\t\tbreak;\n\n\t\tcase OPT_GROUPMAP:\n\t\t\tif (groupmap) {\n\t\t\t\tif (groupmap_via_chown) {\n\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t \"--groupmap conflicts with prior --chown.\\n\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t \"You can only specify --groupmap once.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tgroupmap = (char *)poptGetOptArg(pc);\n\t\t\tgroupmap_via_chown = False;\n\t\t\tbreak;\n\n\t\tcase OPT_CHOWN: {\n\t\t\tconst char *chown = poptGetOptArg(pc);\n\t\t\tint len;\n\t\t\tif ((arg = strchr(chown, ':')) != NULL)\n\t\t\t\tlen = arg++ - chown;\n\t\t\telse\n\t\t\t\tlen = strlen(chown);\n\t\t\tif (len) {\n\t\t\t\tif (usermap) {\n\t\t\t\t\tif (!usermap_via_chown) {\n\t\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\t \"--chown conflicts with prior --usermap.\\n\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t \"You can only specify a user-affecting --chown once.\\n\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tif (asprintf(&usermap, \"*:%.*s\", len, chown) < 0)\n\t\t\t\t\tout_of_memory(\"parse_arguments\");\n\t\t\t\tusermap_via_chown = True;\n\t\t\t}\n\t\t\tif (arg && *arg) {\n\t\t\t\tif (groupmap) {\n\t\t\t\t\tif (!groupmap_via_chown) {\n\t\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\t \"--chown conflicts with prior --groupmap.\\n\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t \"You can only specify a group-affecting --chown once.\\n\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tif (asprintf(&groupmap, \"*:%s\", arg) < 0)\n\t\t\t\t\tout_of_memory(\"parse_arguments\");\n\t\t\t\tgroupmap_via_chown = True;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tcase OPT_HELP:\n\t\t\tusage(FINFO);\n\t\t\texit_cleanup(0);\n\n\t\tcase 'A':\n#ifdef SUPPORT_ACLS\n\t\t\tpreserve_acls = 1;\n\t\t\tpreserve_perms = 1;\n\t\t\tbreak;\n#else\n\t\t\t/* FIXME: this should probably be ignored with a\n\t\t\t * warning and then countermeasures taken to\n\t\t\t * restrict group and other access in the presence\n\t\t\t * of any more restrictive ACLs, but this is safe\n\t\t\t * for now */\n\t\t\tsnprintf(err_buf,sizeof(err_buf),\n \"ACLs are not supported on this %s\\n\",\n\t\t\t\t am_server ? \"server\" : \"client\");\n\t\t\treturn 0;\n#endif\n\n\t\tcase 'X':\n#ifdef SUPPORT_XATTRS\n\t\t\tpreserve_xattrs++;\n\t\t\tbreak;\n#else\n\t\t\tsnprintf(err_buf,sizeof(err_buf),\n\t\t\t\t \"extended attributes are not supported on this %s\\n\",\n\t\t\t\t am_server ? \"server\" : \"client\");\n\t\t\treturn 0;\n#endif\n\n\t\tdefault:\n\t\t\t/* A large opt value means that set_refuse_options()\n\t\t\t * turned this option off. */\n\t\t\tif (opt >= OPT_REFUSED_BASE) {\n\t\t\t\tcreate_refuse_error(opt);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tsnprintf(err_buf, sizeof err_buf, \"%s%s: %s\\n\",\n\t\t\t\t am_server ? \"on remote machine: \" : \"\",\n\t\t\t\t poptBadOption(pc, POPT_BADOPTION_NOALIAS),\n\t\t\t\t poptStrerror(opt));\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tif (protect_args < 0) {\n\t\tif (am_server)\n\t\t\tprotect_args = 0;\n\t\telse if ((arg = getenv(\"RSYNC_PROTECT_ARGS\")) != NULL && *arg)\n\t\t\tprotect_args = atoi(arg) ? 1 : 0;\n\t\telse {\n#ifdef RSYNC_USE_PROTECTED_ARGS\n\t\t\tprotect_args = 1;\n#else\n\t\t\tprotect_args = 0;\n#endif\n\t\t}\n\t}\n\n\tif (checksum_choice && strcmp(checksum_choice, \"auto\") != 0 && strcmp(checksum_choice, \"auto,auto\") != 0) {\n\t\t/* Call this early to verify the args and figure out if we need to force\n\t\t * --whole-file. Note that the parse function will get called again later,\n\t\t * just in case an \"auto\" choice needs to know the protocol_version. */\n\t\tif (parse_checksum_choice())\n\t\t\twhole_file = 1;\n\t} else\n\t\tchecksum_choice = NULL;\n\n\tif (human_readable > 1 && argc == 2 && !am_server) {\n\t\t/* Allow the old meaning of 'h' (--help) on its own. */\n\t\tusage(FINFO);\n\t\texit_cleanup(0);\n\t}\n\n\tif (do_compression || def_compress_level != NOT_SPECIFIED) {\n\t\tif (def_compress_level == NOT_SPECIFIED)\n\t\t\tdef_compress_level = Z_DEFAULT_COMPRESSION;\n\t\telse if (def_compress_level < Z_DEFAULT_COMPRESSION || def_compress_level > Z_BEST_COMPRESSION) {\n\t\t\tsnprintf(err_buf, sizeof err_buf, \"--compress-level value is invalid: %d\\n\",\n\t\t\t\t def_compress_level);\n\t\t\treturn 0;\n\t\t} else if (def_compress_level == Z_NO_COMPRESSION)\n\t\t\tdo_compression = 0;\n\t\telse if (!do_compression)\n\t\t\tdo_compression = 1;\n\t\tif (do_compression && refused_compress) {\n\t\t\tcreate_refuse_error(refused_compress);\n\t\t\treturn 0;\n\t\t}\n#ifdef EXTERNAL_ZLIB\n\t\tif (do_compression == 1) {\n\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\"This rsync lacks old-style --compress due to its external zlib. Try -zz.\\n\");\n\t\t\tif (am_server)\n\t\t\t\treturn 0;\n\t\t\tfprintf(stderr, \"%s\" \"Continuing without compression.\\n\\n\", err_buf);\n\t\t\tdo_compression = 0;\n\t\t}\n#endif\n\t}\n\n#ifdef HAVE_SETVBUF\n\tif (outbuf_mode && !am_server) {\n\t\tint mode = *(uchar *)outbuf_mode;\n\t\tif (islower(mode))\n\t\t\tmode = toupper(mode);\n\t\tfflush(stdout); /* Just in case... */\n\t\tswitch (mode) {\n\t\tcase 'N': /* None */\n\t\tcase 'U': /* Unbuffered */\n\t\t\tmode = _IONBF;\n\t\t\tbreak;\n\t\tcase 'L': /* Line */\n\t\t\tmode = _IOLBF;\n\t\t\tbreak;\n\t\tcase 'B': /* Block */\n\t\tcase 'F': /* Full */\n\t\t\tmode = _IOFBF;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\"Invalid --outbuf setting -- specify N, L, or B.\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tsetvbuf(stdout, (char *)NULL, mode, 0);\n\t}\n\n\tif (msgs2stderr) {\n\t\t/* Make stderr line buffered for better sharing of the stream. */\n\t\tfflush(stderr); /* Just in case... */\n\t\tsetvbuf(stderr, (char *)NULL, _IOLBF, 0);\n\t}\n#endif\n\n\tset_output_verbosity(verbose, DEFAULT_PRIORITY);\n\n\tif (do_stats) {\n\t\tparse_output_words(info_words, info_levels,\n\t\t\tverbose > 1 ? \"stats3\" : \"stats2\", DEFAULT_PRIORITY);\n\t}\n\n#ifdef ICONV_OPTION\n\tif (iconv_opt && protect_args != 2) {\n\t\tif (!am_server && strcmp(iconv_opt, \"-\") == 0)\n\t\t\ticonv_opt = NULL;\n\t\telse\n\t\t\tneed_unsorted_flist = 1;\n\t}\n\tif (refused_no_iconv && !iconv_opt) {\n\t\tcreate_refuse_error(refused_no_iconv);\n\t\treturn 0;\n\t}\n#endif\n\n\tif (fuzzy_basis > 1)\n\t\tfuzzy_basis = basis_dir_cnt + 1;\n\n\tif (protect_args == 1 && am_server)\n\t\treturn 1;\n\n\t*argv_p = argv = poptGetArgs(pc);\n\t*argc_p = argc = count_args(argv);\n\n#ifndef SUPPORT_LINKS\n\tif (preserve_links && !am_sender) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"symlinks are not supported on this %s\\n\",\n\t\t\t am_server ? \"server\" : \"client\");\n\t\treturn 0;\n\t}\n#endif\n\n#ifndef SUPPORT_HARD_LINKS\n\tif (preserve_hard_links) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"hard links are not supported on this %s\\n\",\n\t\t\t am_server ? \"server\" : \"client\");\n\t\treturn 0;\n\t}\n#endif\n\n#ifdef SUPPORT_XATTRS\n\tif (am_root < 0 && preserve_xattrs > 1) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"--fake-super conflicts with -XX\\n\");\n\t\treturn 0;\n\t}\n#else\n\tif (am_root < 0) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"--fake-super requires an rsync with extended attributes enabled\\n\");\n\t\treturn 0;\n\t}\n#endif\n\n\tif (block_size > MAX_BLOCK_SIZE) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"--block-size=%lu is too large (max: %u)\\n\", block_size, MAX_BLOCK_SIZE);\n\t\treturn 0;\n\t}\n\n\tif (write_batch && read_batch) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"--write-batch and --read-batch can not be used together\\n\");\n\t\treturn 0;\n\t}\n\tif (write_batch > 0 || read_batch) {\n\t\tif (am_server) {\n\t\t\trprintf(FINFO,\n\t\t\t\t\"ignoring --%s-batch option sent to server\\n\",\n\t\t\t\twrite_batch ? \"write\" : \"read\");\n\t\t\t/* We don't actually exit_cleanup(), so that we can\n\t\t\t * still service older version clients that still send\n\t\t\t * batch args to server. */\n\t\t\tread_batch = write_batch = 0;\n\t\t\tbatch_name = NULL;\n\t\t} else if (dry_run)\n\t\t\twrite_batch = 0;\n\t} else if (write_batch < 0 && dry_run)\n\t\twrite_batch = 0;\n\tif (read_batch && files_from) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"--read-batch cannot be used with --files-from\\n\");\n\t\treturn 0;\n\t}\n\tif (read_batch && remove_source_files) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"--read-batch cannot be used with --remove-%s-files\\n\",\n\t\t\tremove_source_files == 1 ? \"source\" : \"sent\");\n\t\treturn 0;\n\t}\n\tif (batch_name && strlen(batch_name) > MAX_BATCH_NAME_LEN) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"the batch-file name must be %d characters or less.\\n\",\n\t\t\tMAX_BATCH_NAME_LEN);\n\t\treturn 0;\n\t}\n\n\tif (tmpdir && strlen(tmpdir) >= MAXPATHLEN - 10) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"the --temp-dir path is WAY too long.\\n\");\n\t\treturn 0;\n\t}\n\n\tif (max_delete < 0 && max_delete != INT_MIN) {\n\t\t/* Negative numbers are treated as \"no deletions\". */\n\t\tmax_delete = 0;\n\t}\n\n\tif (compare_dest + copy_dest + link_dest > 1) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"You may not mix --compare-dest, --copy-dest, and --link-dest.\\n\");\n\t\treturn 0;\n\t}\n\n\tif (files_from) {\n\t\tif (recurse == 1) /* preserve recurse == 2 */\n\t\t\trecurse = 0;\n\t\tif (xfer_dirs < 0)\n\t\t\txfer_dirs = 1;\n\t}\n\n\tif (argc < 2 && !read_batch && !am_server)\n\t\tlist_only |= 1;\n\n\tif (xfer_dirs >= 4) {\n\t\tparse_filter_str(&filter_list, \"- /*/*\", rule_template(0), 0);\n\t\trecurse = xfer_dirs = 1;\n\t} else if (recurse)\n\t\txfer_dirs = 1;\n\telse if (xfer_dirs < 0)\n\t\txfer_dirs = list_only ? 1 : 0;\n\n\tif (relative_paths < 0)\n\t\trelative_paths = files_from? 1 : 0;\n\tif (!relative_paths)\n\t\timplied_dirs = 0;\n\n\tif (delete_before + !!delete_during + delete_after > 1) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"You may not combine multiple --delete-WHEN options.\\n\");\n\t\treturn 0;\n\t}\n\tif (delete_before || delete_during || delete_after)\n\t\tdelete_mode = 1;\n\telse if (delete_mode || delete_excluded) {\n\t\t/* Only choose now between before & during if one is refused. */\n\t\tif (refused_delete_before) {\n\t\t\tif (!refused_delete_during)\n\t\t\t\tdelete_during = 1;\n\t\t\telse {\n\t\t\t\tcreate_refuse_error(refused_delete_before);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t} else if (refused_delete_during)\n\t\t\tdelete_before = 1;\n\t\tdelete_mode = 1;\n\t}\n\tif (!xfer_dirs && delete_mode) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"--delete does not work without --recursive (-r) or --dirs (-d).\\n\");\n\t\treturn 0;\n\t}\n\n\tif (missing_args == 3) /* simplify if both options were specified */\n\t\tmissing_args = 2;\n\tif (refused_delete && (delete_mode || missing_args == 2)) {\n\t\tcreate_refuse_error(refused_delete);\n\t\treturn 0;\n\t}\n\n\tif (remove_source_files) {\n\t\t/* We only want to infer this refusal of --remove-source-files\n\t\t * via the refusal of \"delete\", not any of the \"delete-FOO\"\n\t\t * options. */\n\t\tif (refused_delete && am_sender) {\n\t\t\tcreate_refuse_error(refused_delete);\n\t\t\treturn 0;\n\t\t}\n\t\tneed_messages_from_generator = 1;\n\t}\n\n\tif (munge_symlinks && !am_daemon) {\n\t\tSTRUCT_STAT st;\n\t\tchar prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */\n\t\tstrlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */\n\t\tif (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {\n\t\t\trprintf(FERROR, \"Symlink munging is unsafe when a %s directory exists.\\n\",\n\t\t\t\tprefix);\n\t\t\texit_cleanup(RERR_UNSUPPORTED);\n\t\t}\n\t}\n\n\tif (sanitize_paths) {\n\t\tint i;\n\t\tfor (i = argc; i-- > 0; )\n\t\t\targv[i] = sanitize_path(NULL, argv[i], \"\", 0, SP_KEEP_DOT_DIRS);\n\t\tif (tmpdir)\n\t\t\ttmpdir = sanitize_path(NULL, tmpdir, NULL, 0, SP_DEFAULT);\n\t\tif (backup_dir)\n\t\t\tbackup_dir = sanitize_path(NULL, backup_dir, NULL, 0, SP_DEFAULT);\n\t}\n\tif (daemon_filter_list.head && !am_sender) {\n\t\tfilter_rule_list *elp = &daemon_filter_list;\n\t\tif (tmpdir) {\n\t\t\tchar *dir;\n\t\t\tif (!*tmpdir)\n\t\t\t\tgoto options_rejected;\n\t\t\tdir = tmpdir + (*tmpdir == '/' ? module_dirlen : 0);\n\t\t\tclean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);\n\t\t\tif (check_filter(elp, FLOG, dir, 1) < 0)\n\t\t\t\tgoto options_rejected;\n\t\t}\n\t\tif (backup_dir) {\n\t\t\tchar *dir;\n\t\t\tif (!*backup_dir)\n\t\t\t\tgoto options_rejected;\n\t\t\tdir = backup_dir + (*backup_dir == '/' ? module_dirlen : 0);\n\t\t\tclean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);\n\t\t\tif (check_filter(elp, FLOG, dir, 1) < 0)\n\t\t\t\tgoto options_rejected;\n\t\t}\n\t}\n\n\tif (!backup_suffix)\n\t\tbackup_suffix = backup_dir ? \"\" : BACKUP_SUFFIX;\n\tbackup_suffix_len = strlen(backup_suffix);\n\tif (strchr(backup_suffix, '/') != NULL) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"--suffix cannot contain slashes: %s\\n\",\n\t\t\tbackup_suffix);\n\t\treturn 0;\n\t}\n\tif (backup_dir) {\n\t\tsize_t len;\n\t\twhile (*backup_dir == '.' && backup_dir[1] == '/')\n\t\t\tbackup_dir += 2;\n\t\tif (*backup_dir == '.' && backup_dir[1] == '\\0')\n\t\t\tbackup_dir++;\n\t\tlen = strlcpy(backup_dir_buf, backup_dir, sizeof backup_dir_buf);\n\t\tif (len > sizeof backup_dir_buf - 128) {\n\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\"the --backup-dir path is WAY too long.\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tbackup_dir_len = (int)len;\n\t\tif (!backup_dir_len) {\n\t\t\tbackup_dir_len = -1;\n\t\t\tbackup_dir = NULL;\n\t\t} else if (backup_dir_buf[backup_dir_len - 1] != '/') {\n\t\t\tbackup_dir_buf[backup_dir_len++] = '/';\n\t\t\tbackup_dir_buf[backup_dir_len] = '\\0';\n\t\t}\n\t\tbackup_dir_remainder = sizeof backup_dir_buf - backup_dir_len;\n\t}\n\tif (backup_dir) {\n\t\t/* No need for a suffix or a protect rule. */\n\t} else if (!backup_suffix_len && (!am_server || !am_sender)) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"--suffix cannot be empty %s\\n\", backup_dir_len < 0\n\t\t\t? \"when --backup-dir is the same as the dest dir\"\n\t\t\t: \"without a --backup-dir\");\n\t\treturn 0;\n\t} else if (make_backups && delete_mode && !delete_excluded && !am_server) {\n\t\tsnprintf(backup_dir_buf, sizeof backup_dir_buf,\n\t\t\t\"P *%s\", backup_suffix);\n\t\tparse_filter_str(&filter_list, backup_dir_buf, rule_template(0), 0);\n\t}\n\n\tif (preserve_times) {\n\t\tpreserve_times = PRESERVE_FILE_TIMES;\n\t\tif (!omit_dir_times)\n\t\t\tpreserve_times |= PRESERVE_DIR_TIMES;\n#ifdef CAN_SET_SYMLINK_TIMES\n\t\tif (!omit_link_times)\n\t\t\tpreserve_times |= PRESERVE_LINK_TIMES;\n#endif\n\t}\n\n\tif (make_backups && !backup_dir) {\n\t\tomit_dir_times = 0; /* Implied, so avoid -O to sender. */\n\t\tpreserve_times &= ~PRESERVE_DIR_TIMES;\n\t}\n\n\tif (stdout_format) {\n\t\tif (am_server && log_format_has(stdout_format, 'I'))\n\t\t\tstdout_format_has_i = 2;\n\t\telse if (log_format_has(stdout_format, 'i'))\n\t\t\tstdout_format_has_i = itemize_changes | 1;\n\t\tif (!log_format_has(stdout_format, 'b')\n\t\t && !log_format_has(stdout_format, 'c')\n\t\t && !log_format_has(stdout_format, 'C'))\n\t\t\tlog_before_transfer = !am_server;\n\t} else if (itemize_changes) {\n\t\tstdout_format = \"%i %n%L\";\n\t\tstdout_format_has_i = itemize_changes;\n\t\tlog_before_transfer = !am_server;\n\t}\n\n\tif (do_progress && !am_server) {\n\t\tif (!log_before_transfer && INFO_EQ(NAME, 0))\n\t\t\tparse_output_words(info_words, info_levels, \"name\", DEFAULT_PRIORITY);\n\t\tparse_output_words(info_words, info_levels, \"flist2,progress\", DEFAULT_PRIORITY);\n\t}\n\n\tif (dry_run)\n\t\tdo_xfers = 0;\n\n\tset_io_timeout(io_timeout);\n\n\tif (INFO_GTE(NAME, 1) && !stdout_format) {\n\t\tstdout_format = \"%n%L\";\n\t\tlog_before_transfer = !am_server;\n\t}\n\tif (stdout_format_has_i || log_format_has(stdout_format, 'o'))\n\t\tstdout_format_has_o_or_i = 1;\n\n\tif (logfile_name && !am_daemon) {\n\t\tif (!logfile_format) {\n\t\t\tlogfile_format = \"%i %n%L\";\n\t\t\tlogfile_format_has_i = logfile_format_has_o_or_i = 1;\n\t\t} else {\n\t\t\tif (log_format_has(logfile_format, 'i'))\n\t\t\t\tlogfile_format_has_i = 1;\n\t\t\tif (logfile_format_has_i || log_format_has(logfile_format, 'o'))\n\t\t\t\tlogfile_format_has_o_or_i = 1;\n\t\t}\n\t\tlog_init(0);\n\t} else if (!am_daemon)\n\t\tlogfile_format = NULL;\n\n\tif (daemon_bwlimit && (!bwlimit || bwlimit > daemon_bwlimit))\n\t\tbwlimit = daemon_bwlimit;\n\tif (bwlimit) {\n\t\tbwlimit_writemax = (size_t)bwlimit * 128;\n\t\tif (bwlimit_writemax < 512)\n\t\t\tbwlimit_writemax = 512;\n\t}\n\n\tif (append_mode) {\n\t\tif (whole_file > 0) {\n\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t \"--append cannot be used with --whole-file\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tif (refused_inplace) {\n\t\t\tcreate_refuse_error(refused_inplace);\n\t\t\treturn 0;\n\t\t}\n\t\tinplace = 1;\n\t}\n\n\tif (delay_updates && !partial_dir)\n\t\tpartial_dir = tmp_partialdir;\n\n\tif (inplace) {\n#ifdef HAVE_FTRUNCATE\n\t\tif (partial_dir) {\n\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t \"--%s cannot be used with --%s\\n\",\n\t\t\t\t append_mode ? \"append\" : \"inplace\",\n\t\t\t\t delay_updates ? \"delay-updates\" : \"partial-dir\");\n\t\t\treturn 0;\n\t\t}\n\t\t/* --inplace implies --partial for refusal purposes, but we\n\t\t * clear the keep_partial flag for internal logic purposes. */\n\t\tif (refused_partial) {\n\t\t\tcreate_refuse_error(refused_partial);\n\t\t\treturn 0;\n\t\t}\n\t\tkeep_partial = 0;\n#else\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"--%s is not supported on this %s\\n\",\n\t\t\t append_mode ? \"append\" : \"inplace\",\n\t\t\t am_server ? \"server\" : \"client\");\n\t\treturn 0;\n#endif\n\t} else {\n\t\tif (keep_partial && !partial_dir && !am_server) {\n\t\t\tif ((arg = getenv(\"RSYNC_PARTIAL_DIR\")) != NULL && *arg)\n\t\t\t\tpartial_dir = strdup(arg);\n\t\t}\n\t\tif (partial_dir) {\n\t\t\tif (*partial_dir)\n\t\t\t\tclean_fname(partial_dir, CFN_COLLAPSE_DOT_DOT_DIRS);\n\t\t\tif (!*partial_dir || strcmp(partial_dir, \".\") == 0)\n\t\t\t\tpartial_dir = NULL;\n\t\t\tif (!partial_dir && refused_partial) {\n\t\t\t\tcreate_refuse_error(refused_partial);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tkeep_partial = 1;\n\t\t}\n\t}\n\n\tif (files_from) {\n\t\tchar *h, *p;\n\t\tint q;\n\t\tif (argc > 2 || (!am_daemon && !am_server && argc == 1)) {\n\t\t\tusage(FERROR);\n\t\t\texit_cleanup(RERR_SYNTAX);\n\t\t}\n\t\tif (strcmp(files_from, \"-\") == 0) {\n\t\t\tfilesfrom_fd = 0;\n\t\t\tif (am_server)\n\t\t\t\tfilesfrom_host = \"\"; /* reading from socket */\n\t\t} else if ((p = check_for_hostspec(files_from, &h, &q)) != 0) {\n\t\t\tif (am_server) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"The --files-from sent to the server cannot specify a host.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfiles_from = p;\n\t\t\tfilesfrom_host = h;\n\t\t\tif (strcmp(files_from, \"-\") == 0) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"Invalid --files-from remote filename\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t} else {\n\t\t\tif (sanitize_paths)\n\t\t\t\tfiles_from = sanitize_path(NULL, files_from, NULL, 0, SP_DEFAULT);\n\t\t\tif (daemon_filter_list.head) {\n\t\t\t\tchar *dir;\n\t\t\t\tif (!*files_from)\n\t\t\t\t\tgoto options_rejected;\n\t\t\t\tdir = files_from + (*files_from == '/' ? module_dirlen : 0);\n\t\t\t\tclean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);\n\t\t\t\tif (check_filter(&daemon_filter_list, FLOG, dir, 0) < 0)\n\t\t\t\t\tgoto options_rejected;\n\t\t\t}\n\t\t\tfilesfrom_fd = open(files_from, O_RDONLY|O_BINARY);\n\t\t\tif (filesfrom_fd < 0) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"failed to open files-from file %s: %s\\n\",\n\t\t\t\t\tfiles_from, strerror(errno));\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tam_starting_up = 0;\n\n\treturn 1;\n\n options_rejected:\n\tsnprintf(err_buf, sizeof err_buf,\n\t\t\"Your options have been rejected by the server.\\n\");\n\treturn 0;\n}", "project": "rsync", "hash": 282111307716565365896500155152540425903, "size": 1062, "commit_id": "7706303828fcde524222babb2833864a4bd09e07", "message": "Ignore --protect-args when already sent by client\n\nIn parse_arguments when --protect-args is encountered the function exits\nearly. The caller is expected to check protect_args, and recall\nparse_arguments setting protect_args to 2. This patch prevents the\nclient from resetting protect_args during the second pass of\nparse_arguments. This prevents parse_arguments returning early the\nsecond time before it's able to sanitize the arguments it received.", "target": 1, "dataset": "other", "idx": 204749} {"func": "int parse_arguments(int *argc_p, const char ***argv_p)\n{\n\tstatic poptContext pc;\n\tchar *ref = lp_refuse_options(module_id);\n\tconst char *arg, **argv = *argv_p;\n\tint argc = *argc_p;\n\tint opt;\n\tint orig_protect_args = protect_args;\n\n\tif (ref && *ref)\n\t\tset_refuse_options(ref);\n\tif (am_daemon) {\n\t\tset_refuse_options(\"log-file*\");\n#ifdef ICONV_OPTION\n\t\tif (!*lp_charset(module_id))\n\t\t\tset_refuse_options(\"iconv\");\n#endif\n\t}\n\n#ifdef ICONV_OPTION\n\tif (!am_daemon && protect_args <= 0 && (arg = getenv(\"RSYNC_ICONV\")) != NULL && *arg)\n\t\ticonv_opt = strdup(arg);\n#endif\n\n\t/* TODO: Call poptReadDefaultConfig; handle errors. */\n\n\t/* The context leaks in case of an error, but if there's a\n\t * problem we always exit anyhow. */\n\tif (pc)\n\t\tpoptFreeContext(pc);\n\tpc = poptGetContext(RSYNC_NAME, argc, argv, long_options, 0);\n\tif (!am_server) {\n\t\tpoptReadDefaultConfig(pc, 0);\n\t\tpopt_unalias(pc, \"--daemon\");\n\t\tpopt_unalias(pc, \"--server\");\n\t}\n\n\twhile ((opt = poptGetNextOpt(pc)) != -1) {\n\t\t/* most options are handled automatically by popt;\n\t\t * only special cases are returned and listed here. */\n\n\t\tswitch (opt) {\n\t\tcase OPT_VERSION:\n\t\t\tprint_rsync_version(FINFO);\n\t\t\texit_cleanup(0);\n\n\t\tcase OPT_SERVER:\n\t\t\tif (!am_server) {\n\t\t\t\t/* Disable popt aliases on the server side and\n\t\t\t\t * then start parsing the options again. */\n\t\t\t\tpoptFreeContext(pc);\n\t\t\t\tpc = poptGetContext(RSYNC_NAME, argc, argv,\n\t\t\t\t\t\t long_options, 0);\n\t\t\t\tam_server = 1;\n\t\t\t}\n#ifdef ICONV_OPTION\n\t\t\ticonv_opt = NULL;\n#endif\n\t\t\tbreak;\n\n\t\tcase OPT_SENDER:\n\t\t\tif (!am_server) {\n\t\t\t\tusage(FERROR);\n\t\t\t\texit_cleanup(RERR_SYNTAX);\n\t\t\t}\n\t\t\tam_sender = 1;\n\t\t\tbreak;\n\n\t\tcase OPT_DAEMON:\n\t\t\tif (am_daemon) {\n\t\t\t\tstrlcpy(err_buf,\n\t\t\t\t\t\"Attempt to hack rsync thwarted!\\n\",\n\t\t\t\t\tsizeof err_buf);\n\t\t\t\treturn 0;\n\t\t\t}\n#ifdef ICONV_OPTION\n\t\t\ticonv_opt = NULL;\n#endif\n\t\t\tprotect_args = 0;\n\t\t\tpoptFreeContext(pc);\n\t\t\tpc = poptGetContext(RSYNC_NAME, argc, argv,\n\t\t\t\t\t long_daemon_options, 0);\n\t\t\twhile ((opt = poptGetNextOpt(pc)) != -1) {\n\t\t\t\tchar **cpp;\n\t\t\t\tswitch (opt) {\n\t\t\t\tcase 'h':\n\t\t\t\t\tdaemon_usage(FINFO);\n\t\t\t\t\texit_cleanup(0);\n\n\t\t\t\tcase 'M':\n\t\t\t\t\targ = poptGetOptArg(pc);\n\t\t\t\t\tif (!strchr(arg, '=')) {\n\t\t\t\t\t\trprintf(FERROR,\n\t\t\t\t\t\t \"--dparam value is missing an '=': %s\\n\",\n\t\t\t\t\t\t arg);\n\t\t\t\t\t\tgoto daemon_error;\n\t\t\t\t\t}\n\t\t\t\t\tcpp = EXPAND_ITEM_LIST(&dparam_list, char *, 4);\n\t\t\t\t\t*cpp = strdup(arg);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'v':\n\t\t\t\t\tverbose++;\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\trprintf(FERROR,\n\t\t\t\t\t \"rsync: %s: %s (in daemon mode)\\n\",\n\t\t\t\t\t poptBadOption(pc, POPT_BADOPTION_NOALIAS),\n\t\t\t\t\t poptStrerror(opt));\n\t\t\t\t\tgoto daemon_error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (dparam_list.count && !set_dparams(1))\n\t\t\t\texit_cleanup(RERR_SYNTAX);\n\n\t\t\tif (tmpdir && strlen(tmpdir) >= MAXPATHLEN - 10) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t \"the --temp-dir path is WAY too long.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tif (!daemon_opt) {\n\t\t\t\trprintf(FERROR, \"Daemon option(s) used without --daemon.\\n\");\n\t\t\t daemon_error:\n\t\t\t\trprintf(FERROR,\n\t\t\t\t \"(Type \\\"rsync --daemon --help\\\" for assistance with daemon mode.)\\n\");\n\t\t\t\texit_cleanup(RERR_SYNTAX);\n\t\t\t}\n\n\t\t\t*argv_p = argv = poptGetArgs(pc);\n\t\t\t*argc_p = argc = count_args(argv);\n\t\t\tam_starting_up = 0;\n\t\t\tdaemon_opt = 0;\n\t\t\tam_daemon = 1;\n\t\t\treturn 1;\n\n\t\tcase OPT_MODIFY_WINDOW:\n\t\t\t/* The value has already been set by popt, but\n\t\t\t * we need to remember that we're using a\n\t\t\t * non-default setting. */\n\t\t\tmodify_window_set = 1;\n\t\t\tbreak;\n\n\t\tcase OPT_FILTER:\n\t\t\tparse_filter_str(&filter_list, poptGetOptArg(pc),\n\t\t\t\t\trule_template(0), 0);\n\t\t\tbreak;\n\n\t\tcase OPT_EXCLUDE:\n\t\t\tparse_filter_str(&filter_list, poptGetOptArg(pc),\n\t\t\t\t\trule_template(0), XFLG_OLD_PREFIXES);\n\t\t\tbreak;\n\n\t\tcase OPT_INCLUDE:\n\t\t\tparse_filter_str(&filter_list, poptGetOptArg(pc),\n\t\t\t\t\trule_template(FILTRULE_INCLUDE), XFLG_OLD_PREFIXES);\n\t\t\tbreak;\n\n\t\tcase OPT_EXCLUDE_FROM:\n\t\tcase OPT_INCLUDE_FROM:\n\t\t\targ = poptGetOptArg(pc);\n\t\t\tif (sanitize_paths)\n\t\t\t\targ = sanitize_path(NULL, arg, NULL, 0, SP_DEFAULT);\n\t\t\tif (daemon_filter_list.head) {\n\t\t\t\tint rej;\n\t\t\t\tchar *cp = strdup(arg);\n\t\t\t\tif (!cp)\n\t\t\t\t\tout_of_memory(\"parse_arguments\");\n\t\t\t\tif (!*cp)\n\t\t\t\t\trej = 1;\n\t\t\t\telse {\n\t\t\t\t\tchar *dir = cp + (*cp == '/' ? module_dirlen : 0);\n\t\t\t\t\tclean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);\n\t\t\t\t\trej = check_filter(&daemon_filter_list, FLOG, dir, 0) < 0;\n\t\t\t\t}\n\t\t\t\tfree(cp);\n\t\t\t\tif (rej)\n\t\t\t\t\tgoto options_rejected;\n\t\t\t}\n\t\t\tparse_filter_file(&filter_list, arg,\n\t\t\t\trule_template(opt == OPT_INCLUDE_FROM ? FILTRULE_INCLUDE : 0),\n\t\t\t\tXFLG_FATAL_ERRORS | XFLG_OLD_PREFIXES);\n\t\t\tbreak;\n\n\t\tcase 'a':\n\t\t\tif (refused_archive_part) {\n\t\t\t\tcreate_refuse_error(refused_archive_part);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (!recurse) /* preserve recurse == 2 */\n\t\t\t\trecurse = 1;\n#ifdef SUPPORT_LINKS\n\t\t\tpreserve_links = 1;\n#endif\n\t\t\tpreserve_perms = 1;\n\t\t\tpreserve_times = 1;\n\t\t\tpreserve_gid = 1;\n\t\t\tpreserve_uid = 1;\n\t\t\tpreserve_devices = 1;\n\t\t\tpreserve_specials = 1;\n\t\t\tbreak;\n\n\t\tcase 'D':\n\t\t\tpreserve_devices = preserve_specials = 1;\n\t\t\tbreak;\n\n\t\tcase OPT_NO_D:\n\t\t\tpreserve_devices = preserve_specials = 0;\n\t\t\tbreak;\n\n\t\tcase 'h':\n\t\t\thuman_readable++;\n\t\t\tbreak;\n\n\t\tcase 'H':\n\t\t\tpreserve_hard_links++;\n\t\t\tbreak;\n\n\t\tcase 'i':\n\t\t\titemize_changes++;\n\t\t\tbreak;\n\n\t\tcase 'v':\n\t\t\tverbose++;\n\t\t\tbreak;\n\n\t\tcase 'y':\n\t\t\tfuzzy_basis++;\n\t\t\tbreak;\n\n\t\tcase 'q':\n\t\t\tquiet++;\n\t\t\tbreak;\n\n\t\tcase 'x':\n\t\t\tone_file_system++;\n\t\t\tbreak;\n\n\t\tcase 'F':\n\t\t\tswitch (++F_option_cnt) {\n\t\t\tcase 1:\n\t\t\t\tparse_filter_str(&filter_list,\": /.rsync-filter\",rule_template(0),0);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tparse_filter_str(&filter_list,\"- .rsync-filter\",rule_template(0),0);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'P':\n\t\t\tif (refused_partial || refused_progress) {\n\t\t\t\tcreate_refuse_error(refused_partial\n\t\t\t\t ? refused_partial : refused_progress);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tdo_progress = 1;\n\t\t\tkeep_partial = 1;\n\t\t\tbreak;\n\n\t\tcase 'z':\n\t\t\tdo_compression++;\n\t\t\tbreak;\n\n\t\tcase 'M':\n\t\t\targ = poptGetOptArg(pc);\n\t\t\tif (*arg != '-') {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"Remote option must start with a dash: %s\\n\", arg);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (remote_option_cnt+2 >= remote_option_alloc) {\n\t\t\t\tremote_option_alloc += 16;\n\t\t\t\tremote_options = realloc_array(remote_options,\n\t\t\t\t\t\t\tconst char *, remote_option_alloc);\n\t\t\t\tif (!remote_options)\n\t\t\t\t\tout_of_memory(\"parse_arguments\");\n\t\t\t\tif (!remote_option_cnt)\n\t\t\t\t\tremote_options[0] = \"ARG0\";\n\t\t\t}\n\t\t\tremote_options[++remote_option_cnt] = arg;\n\t\t\tremote_options[remote_option_cnt+1] = NULL;\n\t\t\tbreak;\n\n\t\tcase OPT_WRITE_BATCH:\n\t\t\t/* batch_name is already set */\n\t\t\twrite_batch = 1;\n\t\t\tbreak;\n\n\t\tcase OPT_ONLY_WRITE_BATCH:\n\t\t\t/* batch_name is already set */\n\t\t\twrite_batch = -1;\n\t\t\tbreak;\n\n\t\tcase OPT_READ_BATCH:\n\t\t\t/* batch_name is already set */\n\t\t\tread_batch = 1;\n\t\t\tbreak;\n\n\t\tcase OPT_NO_ICONV:\n#ifdef ICONV_OPTION\n\t\t\ticonv_opt = NULL;\n#endif\n\t\t\tbreak;\n\n\t\tcase OPT_MAX_SIZE:\n\t\t\tif ((max_size = parse_size_arg(&max_size_arg, 'b')) < 0) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"--max-size value is invalid: %s\\n\",\n\t\t\t\t\tmax_size_arg);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OPT_MIN_SIZE:\n\t\t\tif ((min_size = parse_size_arg(&min_size_arg, 'b')) < 0) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"--min-size value is invalid: %s\\n\",\n\t\t\t\t\tmin_size_arg);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OPT_BWLIMIT:\n\t\t\t{\n\t\t\t\tOFF_T limit = parse_size_arg(&bwlimit_arg, 'K');\n\t\t\t\tif (limit < 0) {\n\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\t\"--bwlimit value is invalid: %s\\n\", bwlimit_arg);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tbwlimit = (limit + 512) / 1024;\n\t\t\t\tif (limit && !bwlimit) {\n\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\t\"--bwlimit value is too small: %s\\n\", bwlimit_arg);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OPT_APPEND:\n\t\t\tif (am_server)\n\t\t\t\tappend_mode++;\n\t\t\telse\n\t\t\t\tappend_mode = 1;\n\t\t\tbreak;\n\n\t\tcase OPT_LINK_DEST:\n#ifdef SUPPORT_HARD_LINKS\n\t\t\tlink_dest = 1;\n\t\t\tdest_option = \"--link-dest\";\n\t\t\tgoto set_dest_dir;\n#else\n\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t \"hard links are not supported on this %s\\n\",\n\t\t\t\t am_server ? \"server\" : \"client\");\n\t\t\treturn 0;\n#endif\n\n\t\tcase OPT_COPY_DEST:\n\t\t\tcopy_dest = 1;\n\t\t\tdest_option = \"--copy-dest\";\n\t\t\tgoto set_dest_dir;\n\n\t\tcase OPT_COMPARE_DEST:\n\t\t\tcompare_dest = 1;\n\t\t\tdest_option = \"--compare-dest\";\n\t\tset_dest_dir:\n\t\t\tif (basis_dir_cnt >= MAX_BASIS_DIRS) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"ERROR: at most %d %s args may be specified\\n\",\n\t\t\t\t\tMAX_BASIS_DIRS, dest_option);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t/* We defer sanitizing this arg until we know what\n\t\t\t * our destination directory is going to be. */\n\t\t\tbasis_dir[basis_dir_cnt++] = (char *)poptGetOptArg(pc);\n\t\t\tbreak;\n\n\t\tcase OPT_CHMOD:\n\t\t\targ = poptGetOptArg(pc);\n\t\t\tif (!parse_chmod(arg, &chmod_modes)) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t \"Invalid argument passed to --chmod (%s)\\n\",\n\t\t\t\t arg);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase OPT_INFO:\n\t\t\targ = poptGetOptArg(pc);\n\t\t\tparse_output_words(info_words, info_levels, arg, USER_PRIORITY);\n\t\t\tbreak;\n\n\t\tcase OPT_DEBUG:\n\t\t\targ = poptGetOptArg(pc);\n\t\t\tparse_output_words(debug_words, debug_levels, arg, USER_PRIORITY);\n\t\t\tbreak;\n\n\t\tcase OPT_USERMAP:\n\t\t\tif (usermap) {\n\t\t\t\tif (usermap_via_chown) {\n\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t \"--usermap conflicts with prior --chown.\\n\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t \"You can only specify --usermap once.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tusermap = (char *)poptGetOptArg(pc);\n\t\t\tusermap_via_chown = False;\n\t\t\tbreak;\n\n\t\tcase OPT_GROUPMAP:\n\t\t\tif (groupmap) {\n\t\t\t\tif (groupmap_via_chown) {\n\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t \"--groupmap conflicts with prior --chown.\\n\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t \"You can only specify --groupmap once.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tgroupmap = (char *)poptGetOptArg(pc);\n\t\t\tgroupmap_via_chown = False;\n\t\t\tbreak;\n\n\t\tcase OPT_CHOWN: {\n\t\t\tconst char *chown = poptGetOptArg(pc);\n\t\t\tint len;\n\t\t\tif ((arg = strchr(chown, ':')) != NULL)\n\t\t\t\tlen = arg++ - chown;\n\t\t\telse\n\t\t\t\tlen = strlen(chown);\n\t\t\tif (len) {\n\t\t\t\tif (usermap) {\n\t\t\t\t\tif (!usermap_via_chown) {\n\t\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\t \"--chown conflicts with prior --usermap.\\n\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t \"You can only specify a user-affecting --chown once.\\n\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tif (asprintf(&usermap, \"*:%.*s\", len, chown) < 0)\n\t\t\t\t\tout_of_memory(\"parse_arguments\");\n\t\t\t\tusermap_via_chown = True;\n\t\t\t}\n\t\t\tif (arg && *arg) {\n\t\t\t\tif (groupmap) {\n\t\t\t\t\tif (!groupmap_via_chown) {\n\t\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\t \"--chown conflicts with prior --groupmap.\\n\");\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t \"You can only specify a group-affecting --chown once.\\n\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tif (asprintf(&groupmap, \"*:%s\", arg) < 0)\n\t\t\t\t\tout_of_memory(\"parse_arguments\");\n\t\t\t\tgroupmap_via_chown = True;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tcase OPT_HELP:\n\t\t\tusage(FINFO);\n\t\t\texit_cleanup(0);\n\n\t\tcase 'A':\n#ifdef SUPPORT_ACLS\n\t\t\tpreserve_acls = 1;\n\t\t\tpreserve_perms = 1;\n\t\t\tbreak;\n#else\n\t\t\t/* FIXME: this should probably be ignored with a\n\t\t\t * warning and then countermeasures taken to\n\t\t\t * restrict group and other access in the presence\n\t\t\t * of any more restrictive ACLs, but this is safe\n\t\t\t * for now */\n\t\t\tsnprintf(err_buf,sizeof(err_buf),\n \"ACLs are not supported on this %s\\n\",\n\t\t\t\t am_server ? \"server\" : \"client\");\n\t\t\treturn 0;\n#endif\n\n\t\tcase 'X':\n#ifdef SUPPORT_XATTRS\n\t\t\tpreserve_xattrs++;\n\t\t\tbreak;\n#else\n\t\t\tsnprintf(err_buf,sizeof(err_buf),\n\t\t\t\t \"extended attributes are not supported on this %s\\n\",\n\t\t\t\t am_server ? \"server\" : \"client\");\n\t\t\treturn 0;\n#endif\n\n\t\tdefault:\n\t\t\t/* A large opt value means that set_refuse_options()\n\t\t\t * turned this option off. */\n\t\t\tif (opt >= OPT_REFUSED_BASE) {\n\t\t\t\tcreate_refuse_error(opt);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tsnprintf(err_buf, sizeof err_buf, \"%s%s: %s\\n\",\n\t\t\t\t am_server ? \"on remote machine: \" : \"\",\n\t\t\t\t poptBadOption(pc, POPT_BADOPTION_NOALIAS),\n\t\t\t\t poptStrerror(opt));\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tif (protect_args < 0) {\n\t\tif (am_server)\n\t\t\tprotect_args = 0;\n\t\telse if ((arg = getenv(\"RSYNC_PROTECT_ARGS\")) != NULL && *arg)\n\t\t\tprotect_args = atoi(arg) ? 1 : 0;\n\t\telse {\n#ifdef RSYNC_USE_PROTECTED_ARGS\n\t\t\tprotect_args = 1;\n#else\n\t\t\tprotect_args = 0;\n#endif\n\t\t}\n\t}\n\n\tif (checksum_choice && strcmp(checksum_choice, \"auto\") != 0 && strcmp(checksum_choice, \"auto,auto\") != 0) {\n\t\t/* Call this early to verify the args and figure out if we need to force\n\t\t * --whole-file. Note that the parse function will get called again later,\n\t\t * just in case an \"auto\" choice needs to know the protocol_version. */\n\t\tif (parse_checksum_choice())\n\t\t\twhole_file = 1;\n\t} else\n\t\tchecksum_choice = NULL;\n\n\tif (human_readable > 1 && argc == 2 && !am_server) {\n\t\t/* Allow the old meaning of 'h' (--help) on its own. */\n\t\tusage(FINFO);\n\t\texit_cleanup(0);\n\t}\n\n\tif (do_compression || def_compress_level != NOT_SPECIFIED) {\n\t\tif (def_compress_level == NOT_SPECIFIED)\n\t\t\tdef_compress_level = Z_DEFAULT_COMPRESSION;\n\t\telse if (def_compress_level < Z_DEFAULT_COMPRESSION || def_compress_level > Z_BEST_COMPRESSION) {\n\t\t\tsnprintf(err_buf, sizeof err_buf, \"--compress-level value is invalid: %d\\n\",\n\t\t\t\t def_compress_level);\n\t\t\treturn 0;\n\t\t} else if (def_compress_level == Z_NO_COMPRESSION)\n\t\t\tdo_compression = 0;\n\t\telse if (!do_compression)\n\t\t\tdo_compression = 1;\n\t\tif (do_compression && refused_compress) {\n\t\t\tcreate_refuse_error(refused_compress);\n\t\t\treturn 0;\n\t\t}\n#ifdef EXTERNAL_ZLIB\n\t\tif (do_compression == 1) {\n\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\"This rsync lacks old-style --compress due to its external zlib. Try -zz.\\n\");\n\t\t\tif (am_server)\n\t\t\t\treturn 0;\n\t\t\tfprintf(stderr, \"%s\" \"Continuing without compression.\\n\\n\", err_buf);\n\t\t\tdo_compression = 0;\n\t\t}\n#endif\n\t}\n\n#ifdef HAVE_SETVBUF\n\tif (outbuf_mode && !am_server) {\n\t\tint mode = *(uchar *)outbuf_mode;\n\t\tif (islower(mode))\n\t\t\tmode = toupper(mode);\n\t\tfflush(stdout); /* Just in case... */\n\t\tswitch (mode) {\n\t\tcase 'N': /* None */\n\t\tcase 'U': /* Unbuffered */\n\t\t\tmode = _IONBF;\n\t\t\tbreak;\n\t\tcase 'L': /* Line */\n\t\t\tmode = _IOLBF;\n\t\t\tbreak;\n\t\tcase 'B': /* Block */\n\t\tcase 'F': /* Full */\n\t\t\tmode = _IOFBF;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\"Invalid --outbuf setting -- specify N, L, or B.\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tsetvbuf(stdout, (char *)NULL, mode, 0);\n\t}\n\n\tif (msgs2stderr) {\n\t\t/* Make stderr line buffered for better sharing of the stream. */\n\t\tfflush(stderr); /* Just in case... */\n\t\tsetvbuf(stderr, (char *)NULL, _IOLBF, 0);\n\t}\n#endif\n\n\tset_output_verbosity(verbose, DEFAULT_PRIORITY);\n\n\tif (do_stats) {\n\t\tparse_output_words(info_words, info_levels,\n\t\t\tverbose > 1 ? \"stats3\" : \"stats2\", DEFAULT_PRIORITY);\n\t}\n\n#ifdef ICONV_OPTION\n\tif (iconv_opt && protect_args != 2) {\n\t\tif (!am_server && strcmp(iconv_opt, \"-\") == 0)\n\t\t\ticonv_opt = NULL;\n\t\telse\n\t\t\tneed_unsorted_flist = 1;\n\t}\n\tif (refused_no_iconv && !iconv_opt) {\n\t\tcreate_refuse_error(refused_no_iconv);\n\t\treturn 0;\n\t}\n#endif\n\n\tif (fuzzy_basis > 1)\n\t\tfuzzy_basis = basis_dir_cnt + 1;\n\n\t/* Don't let the client reset protect_args if it was already processed */\n\tif (orig_protect_args == 2 && am_server)\n\t\tprotect_args = orig_protect_args;\n\n\tif (protect_args == 1 && am_server)\n\t\treturn 1;\n\n\t*argv_p = argv = poptGetArgs(pc);\n\t*argc_p = argc = count_args(argv);\n\n#ifndef SUPPORT_LINKS\n\tif (preserve_links && !am_sender) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"symlinks are not supported on this %s\\n\",\n\t\t\t am_server ? \"server\" : \"client\");\n\t\treturn 0;\n\t}\n#endif\n\n#ifndef SUPPORT_HARD_LINKS\n\tif (preserve_hard_links) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"hard links are not supported on this %s\\n\",\n\t\t\t am_server ? \"server\" : \"client\");\n\t\treturn 0;\n\t}\n#endif\n\n#ifdef SUPPORT_XATTRS\n\tif (am_root < 0 && preserve_xattrs > 1) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"--fake-super conflicts with -XX\\n\");\n\t\treturn 0;\n\t}\n#else\n\tif (am_root < 0) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"--fake-super requires an rsync with extended attributes enabled\\n\");\n\t\treturn 0;\n\t}\n#endif\n\n\tif (block_size > MAX_BLOCK_SIZE) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"--block-size=%lu is too large (max: %u)\\n\", block_size, MAX_BLOCK_SIZE);\n\t\treturn 0;\n\t}\n\n\tif (write_batch && read_batch) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"--write-batch and --read-batch can not be used together\\n\");\n\t\treturn 0;\n\t}\n\tif (write_batch > 0 || read_batch) {\n\t\tif (am_server) {\n\t\t\trprintf(FINFO,\n\t\t\t\t\"ignoring --%s-batch option sent to server\\n\",\n\t\t\t\twrite_batch ? \"write\" : \"read\");\n\t\t\t/* We don't actually exit_cleanup(), so that we can\n\t\t\t * still service older version clients that still send\n\t\t\t * batch args to server. */\n\t\t\tread_batch = write_batch = 0;\n\t\t\tbatch_name = NULL;\n\t\t} else if (dry_run)\n\t\t\twrite_batch = 0;\n\t} else if (write_batch < 0 && dry_run)\n\t\twrite_batch = 0;\n\tif (read_batch && files_from) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"--read-batch cannot be used with --files-from\\n\");\n\t\treturn 0;\n\t}\n\tif (read_batch && remove_source_files) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"--read-batch cannot be used with --remove-%s-files\\n\",\n\t\t\tremove_source_files == 1 ? \"source\" : \"sent\");\n\t\treturn 0;\n\t}\n\tif (batch_name && strlen(batch_name) > MAX_BATCH_NAME_LEN) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"the batch-file name must be %d characters or less.\\n\",\n\t\t\tMAX_BATCH_NAME_LEN);\n\t\treturn 0;\n\t}\n\n\tif (tmpdir && strlen(tmpdir) >= MAXPATHLEN - 10) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"the --temp-dir path is WAY too long.\\n\");\n\t\treturn 0;\n\t}\n\n\tif (max_delete < 0 && max_delete != INT_MIN) {\n\t\t/* Negative numbers are treated as \"no deletions\". */\n\t\tmax_delete = 0;\n\t}\n\n\tif (compare_dest + copy_dest + link_dest > 1) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"You may not mix --compare-dest, --copy-dest, and --link-dest.\\n\");\n\t\treturn 0;\n\t}\n\n\tif (files_from) {\n\t\tif (recurse == 1) /* preserve recurse == 2 */\n\t\t\trecurse = 0;\n\t\tif (xfer_dirs < 0)\n\t\t\txfer_dirs = 1;\n\t}\n\n\tif (argc < 2 && !read_batch && !am_server)\n\t\tlist_only |= 1;\n\n\tif (xfer_dirs >= 4) {\n\t\tparse_filter_str(&filter_list, \"- /*/*\", rule_template(0), 0);\n\t\trecurse = xfer_dirs = 1;\n\t} else if (recurse)\n\t\txfer_dirs = 1;\n\telse if (xfer_dirs < 0)\n\t\txfer_dirs = list_only ? 1 : 0;\n\n\tif (relative_paths < 0)\n\t\trelative_paths = files_from? 1 : 0;\n\tif (!relative_paths)\n\t\timplied_dirs = 0;\n\n\tif (delete_before + !!delete_during + delete_after > 1) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"You may not combine multiple --delete-WHEN options.\\n\");\n\t\treturn 0;\n\t}\n\tif (delete_before || delete_during || delete_after)\n\t\tdelete_mode = 1;\n\telse if (delete_mode || delete_excluded) {\n\t\t/* Only choose now between before & during if one is refused. */\n\t\tif (refused_delete_before) {\n\t\t\tif (!refused_delete_during)\n\t\t\t\tdelete_during = 1;\n\t\t\telse {\n\t\t\t\tcreate_refuse_error(refused_delete_before);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t} else if (refused_delete_during)\n\t\t\tdelete_before = 1;\n\t\tdelete_mode = 1;\n\t}\n\tif (!xfer_dirs && delete_mode) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"--delete does not work without --recursive (-r) or --dirs (-d).\\n\");\n\t\treturn 0;\n\t}\n\n\tif (missing_args == 3) /* simplify if both options were specified */\n\t\tmissing_args = 2;\n\tif (refused_delete && (delete_mode || missing_args == 2)) {\n\t\tcreate_refuse_error(refused_delete);\n\t\treturn 0;\n\t}\n\n\tif (remove_source_files) {\n\t\t/* We only want to infer this refusal of --remove-source-files\n\t\t * via the refusal of \"delete\", not any of the \"delete-FOO\"\n\t\t * options. */\n\t\tif (refused_delete && am_sender) {\n\t\t\tcreate_refuse_error(refused_delete);\n\t\t\treturn 0;\n\t\t}\n\t\tneed_messages_from_generator = 1;\n\t}\n\n\tif (munge_symlinks && !am_daemon) {\n\t\tSTRUCT_STAT st;\n\t\tchar prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */\n\t\tstrlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */\n\t\tif (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {\n\t\t\trprintf(FERROR, \"Symlink munging is unsafe when a %s directory exists.\\n\",\n\t\t\t\tprefix);\n\t\t\texit_cleanup(RERR_UNSUPPORTED);\n\t\t}\n\t}\n\n\tif (sanitize_paths) {\n\t\tint i;\n\t\tfor (i = argc; i-- > 0; )\n\t\t\targv[i] = sanitize_path(NULL, argv[i], \"\", 0, SP_KEEP_DOT_DIRS);\n\t\tif (tmpdir)\n\t\t\ttmpdir = sanitize_path(NULL, tmpdir, NULL, 0, SP_DEFAULT);\n\t\tif (backup_dir)\n\t\t\tbackup_dir = sanitize_path(NULL, backup_dir, NULL, 0, SP_DEFAULT);\n\t}\n\tif (daemon_filter_list.head && !am_sender) {\n\t\tfilter_rule_list *elp = &daemon_filter_list;\n\t\tif (tmpdir) {\n\t\t\tchar *dir;\n\t\t\tif (!*tmpdir)\n\t\t\t\tgoto options_rejected;\n\t\t\tdir = tmpdir + (*tmpdir == '/' ? module_dirlen : 0);\n\t\t\tclean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);\n\t\t\tif (check_filter(elp, FLOG, dir, 1) < 0)\n\t\t\t\tgoto options_rejected;\n\t\t}\n\t\tif (backup_dir) {\n\t\t\tchar *dir;\n\t\t\tif (!*backup_dir)\n\t\t\t\tgoto options_rejected;\n\t\t\tdir = backup_dir + (*backup_dir == '/' ? module_dirlen : 0);\n\t\t\tclean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);\n\t\t\tif (check_filter(elp, FLOG, dir, 1) < 0)\n\t\t\t\tgoto options_rejected;\n\t\t}\n\t}\n\n\tif (!backup_suffix)\n\t\tbackup_suffix = backup_dir ? \"\" : BACKUP_SUFFIX;\n\tbackup_suffix_len = strlen(backup_suffix);\n\tif (strchr(backup_suffix, '/') != NULL) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"--suffix cannot contain slashes: %s\\n\",\n\t\t\tbackup_suffix);\n\t\treturn 0;\n\t}\n\tif (backup_dir) {\n\t\tsize_t len;\n\t\twhile (*backup_dir == '.' && backup_dir[1] == '/')\n\t\t\tbackup_dir += 2;\n\t\tif (*backup_dir == '.' && backup_dir[1] == '\\0')\n\t\t\tbackup_dir++;\n\t\tlen = strlcpy(backup_dir_buf, backup_dir, sizeof backup_dir_buf);\n\t\tif (len > sizeof backup_dir_buf - 128) {\n\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\"the --backup-dir path is WAY too long.\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tbackup_dir_len = (int)len;\n\t\tif (!backup_dir_len) {\n\t\t\tbackup_dir_len = -1;\n\t\t\tbackup_dir = NULL;\n\t\t} else if (backup_dir_buf[backup_dir_len - 1] != '/') {\n\t\t\tbackup_dir_buf[backup_dir_len++] = '/';\n\t\t\tbackup_dir_buf[backup_dir_len] = '\\0';\n\t\t}\n\t\tbackup_dir_remainder = sizeof backup_dir_buf - backup_dir_len;\n\t}\n\tif (backup_dir) {\n\t\t/* No need for a suffix or a protect rule. */\n\t} else if (!backup_suffix_len && (!am_server || !am_sender)) {\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\"--suffix cannot be empty %s\\n\", backup_dir_len < 0\n\t\t\t? \"when --backup-dir is the same as the dest dir\"\n\t\t\t: \"without a --backup-dir\");\n\t\treturn 0;\n\t} else if (make_backups && delete_mode && !delete_excluded && !am_server) {\n\t\tsnprintf(backup_dir_buf, sizeof backup_dir_buf,\n\t\t\t\"P *%s\", backup_suffix);\n\t\tparse_filter_str(&filter_list, backup_dir_buf, rule_template(0), 0);\n\t}\n\n\tif (preserve_times) {\n\t\tpreserve_times = PRESERVE_FILE_TIMES;\n\t\tif (!omit_dir_times)\n\t\t\tpreserve_times |= PRESERVE_DIR_TIMES;\n#ifdef CAN_SET_SYMLINK_TIMES\n\t\tif (!omit_link_times)\n\t\t\tpreserve_times |= PRESERVE_LINK_TIMES;\n#endif\n\t}\n\n\tif (make_backups && !backup_dir) {\n\t\tomit_dir_times = 0; /* Implied, so avoid -O to sender. */\n\t\tpreserve_times &= ~PRESERVE_DIR_TIMES;\n\t}\n\n\tif (stdout_format) {\n\t\tif (am_server && log_format_has(stdout_format, 'I'))\n\t\t\tstdout_format_has_i = 2;\n\t\telse if (log_format_has(stdout_format, 'i'))\n\t\t\tstdout_format_has_i = itemize_changes | 1;\n\t\tif (!log_format_has(stdout_format, 'b')\n\t\t && !log_format_has(stdout_format, 'c')\n\t\t && !log_format_has(stdout_format, 'C'))\n\t\t\tlog_before_transfer = !am_server;\n\t} else if (itemize_changes) {\n\t\tstdout_format = \"%i %n%L\";\n\t\tstdout_format_has_i = itemize_changes;\n\t\tlog_before_transfer = !am_server;\n\t}\n\n\tif (do_progress && !am_server) {\n\t\tif (!log_before_transfer && INFO_EQ(NAME, 0))\n\t\t\tparse_output_words(info_words, info_levels, \"name\", DEFAULT_PRIORITY);\n\t\tparse_output_words(info_words, info_levels, \"flist2,progress\", DEFAULT_PRIORITY);\n\t}\n\n\tif (dry_run)\n\t\tdo_xfers = 0;\n\n\tset_io_timeout(io_timeout);\n\n\tif (INFO_GTE(NAME, 1) && !stdout_format) {\n\t\tstdout_format = \"%n%L\";\n\t\tlog_before_transfer = !am_server;\n\t}\n\tif (stdout_format_has_i || log_format_has(stdout_format, 'o'))\n\t\tstdout_format_has_o_or_i = 1;\n\n\tif (logfile_name && !am_daemon) {\n\t\tif (!logfile_format) {\n\t\t\tlogfile_format = \"%i %n%L\";\n\t\t\tlogfile_format_has_i = logfile_format_has_o_or_i = 1;\n\t\t} else {\n\t\t\tif (log_format_has(logfile_format, 'i'))\n\t\t\t\tlogfile_format_has_i = 1;\n\t\t\tif (logfile_format_has_i || log_format_has(logfile_format, 'o'))\n\t\t\t\tlogfile_format_has_o_or_i = 1;\n\t\t}\n\t\tlog_init(0);\n\t} else if (!am_daemon)\n\t\tlogfile_format = NULL;\n\n\tif (daemon_bwlimit && (!bwlimit || bwlimit > daemon_bwlimit))\n\t\tbwlimit = daemon_bwlimit;\n\tif (bwlimit) {\n\t\tbwlimit_writemax = (size_t)bwlimit * 128;\n\t\tif (bwlimit_writemax < 512)\n\t\t\tbwlimit_writemax = 512;\n\t}\n\n\tif (append_mode) {\n\t\tif (whole_file > 0) {\n\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t \"--append cannot be used with --whole-file\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tif (refused_inplace) {\n\t\t\tcreate_refuse_error(refused_inplace);\n\t\t\treturn 0;\n\t\t}\n\t\tinplace = 1;\n\t}\n\n\tif (delay_updates && !partial_dir)\n\t\tpartial_dir = tmp_partialdir;\n\n\tif (inplace) {\n#ifdef HAVE_FTRUNCATE\n\t\tif (partial_dir) {\n\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t \"--%s cannot be used with --%s\\n\",\n\t\t\t\t append_mode ? \"append\" : \"inplace\",\n\t\t\t\t delay_updates ? \"delay-updates\" : \"partial-dir\");\n\t\t\treturn 0;\n\t\t}\n\t\t/* --inplace implies --partial for refusal purposes, but we\n\t\t * clear the keep_partial flag for internal logic purposes. */\n\t\tif (refused_partial) {\n\t\t\tcreate_refuse_error(refused_partial);\n\t\t\treturn 0;\n\t\t}\n\t\tkeep_partial = 0;\n#else\n\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t \"--%s is not supported on this %s\\n\",\n\t\t\t append_mode ? \"append\" : \"inplace\",\n\t\t\t am_server ? \"server\" : \"client\");\n\t\treturn 0;\n#endif\n\t} else {\n\t\tif (keep_partial && !partial_dir && !am_server) {\n\t\t\tif ((arg = getenv(\"RSYNC_PARTIAL_DIR\")) != NULL && *arg)\n\t\t\t\tpartial_dir = strdup(arg);\n\t\t}\n\t\tif (partial_dir) {\n\t\t\tif (*partial_dir)\n\t\t\t\tclean_fname(partial_dir, CFN_COLLAPSE_DOT_DOT_DIRS);\n\t\t\tif (!*partial_dir || strcmp(partial_dir, \".\") == 0)\n\t\t\t\tpartial_dir = NULL;\n\t\t\tif (!partial_dir && refused_partial) {\n\t\t\t\tcreate_refuse_error(refused_partial);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tkeep_partial = 1;\n\t\t}\n\t}\n\n\tif (files_from) {\n\t\tchar *h, *p;\n\t\tint q;\n\t\tif (argc > 2 || (!am_daemon && !am_server && argc == 1)) {\n\t\t\tusage(FERROR);\n\t\t\texit_cleanup(RERR_SYNTAX);\n\t\t}\n\t\tif (strcmp(files_from, \"-\") == 0) {\n\t\t\tfilesfrom_fd = 0;\n\t\t\tif (am_server)\n\t\t\t\tfilesfrom_host = \"\"; /* reading from socket */\n\t\t} else if ((p = check_for_hostspec(files_from, &h, &q)) != 0) {\n\t\t\tif (am_server) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"The --files-from sent to the server cannot specify a host.\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tfiles_from = p;\n\t\t\tfilesfrom_host = h;\n\t\t\tif (strcmp(files_from, \"-\") == 0) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"Invalid --files-from remote filename\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t} else {\n\t\t\tif (sanitize_paths)\n\t\t\t\tfiles_from = sanitize_path(NULL, files_from, NULL, 0, SP_DEFAULT);\n\t\t\tif (daemon_filter_list.head) {\n\t\t\t\tchar *dir;\n\t\t\t\tif (!*files_from)\n\t\t\t\t\tgoto options_rejected;\n\t\t\t\tdir = files_from + (*files_from == '/' ? module_dirlen : 0);\n\t\t\t\tclean_fname(dir, CFN_COLLAPSE_DOT_DOT_DIRS);\n\t\t\t\tif (check_filter(&daemon_filter_list, FLOG, dir, 0) < 0)\n\t\t\t\t\tgoto options_rejected;\n\t\t\t}\n\t\t\tfilesfrom_fd = open(files_from, O_RDONLY|O_BINARY);\n\t\t\tif (filesfrom_fd < 0) {\n\t\t\t\tsnprintf(err_buf, sizeof err_buf,\n\t\t\t\t\t\"failed to open files-from file %s: %s\\n\",\n\t\t\t\t\tfiles_from, strerror(errno));\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tam_starting_up = 0;\n\n\treturn 1;\n\n options_rejected:\n\tsnprintf(err_buf, sizeof err_buf,\n\t\t\"Your options have been rejected by the server.\\n\");\n\treturn 0;\n}", "project": "rsync", "hash": 212765220547978151069862672879986367926, "size": 1067, "commit_id": "7706303828fcde524222babb2833864a4bd09e07", "message": "Ignore --protect-args when already sent by client\n\nIn parse_arguments when --protect-args is encountered the function exits\nearly. The caller is expected to check protect_args, and recall\nparse_arguments setting protect_args to 2. This patch prevents the\nclient from resetting protect_args during the second pass of\nparse_arguments. This prevents parse_arguments returning early the\nsecond time before it's able to sanitize the arguments it received.", "target": 0, "dataset": "other", "idx": 364670} {"func": "static int tipc_nl_retrieve_key(struct nlattr **attrs,\n\t\t\t\tstruct tipc_aead_key **key)\n{\n\tstruct nlattr *attr = attrs[TIPC_NLA_NODE_KEY];\n\n\tif (!attr)\n\t\treturn -ENODATA;\n\n\t*key = (struct tipc_aead_key *)nla_data(attr);\n\tif (nla_len(attr) < tipc_aead_key_size(*key))\n\t\treturn -EINVAL;\n\n\treturn 0;\n}", "project": "linux", "hash": 284003867985169166932353704253458867619, "size": 14, "commit_id": "0217ed2848e8538bcf9172d97ed2eeb4a26041bb", "message": "tipc: better validate user input in tipc_nl_retrieve_key()\n\nBefore calling tipc_aead_key_size(ptr), we need to ensure\nwe have enough data to dereference ptr->keylen.\n\nWe probably also want to make sure tipc_aead_key_size()\nwont overflow with malicious ptr->keylen values.\n\nSyzbot reported:\n\nBUG: KMSAN: uninit-value in __tipc_nl_node_set_key net/tipc/node.c:2971 [inline]\nBUG: KMSAN: uninit-value in tipc_nl_node_set_key+0x9bf/0x13b0 net/tipc/node.c:3023\nCPU: 0 PID: 21060 Comm: syz-executor.5 Not tainted 5.11.0-rc7-syzkaller #0\nHardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011\nCall Trace:\n __dump_stack lib/dump_stack.c:79 [inline]\n dump_stack+0x21c/0x280 lib/dump_stack.c:120\n kmsan_report+0xfb/0x1e0 mm/kmsan/kmsan_report.c:118\n __msan_warning+0x5f/0xa0 mm/kmsan/kmsan_instr.c:197\n __tipc_nl_node_set_key net/tipc/node.c:2971 [inline]\n tipc_nl_node_set_key+0x9bf/0x13b0 net/tipc/node.c:3023\n genl_family_rcv_msg_doit net/netlink/genetlink.c:739 [inline]\n genl_family_rcv_msg net/netlink/genetlink.c:783 [inline]\n genl_rcv_msg+0x1319/0x1610 net/netlink/genetlink.c:800\n netlink_rcv_skb+0x6fa/0x810 net/netlink/af_netlink.c:2494\n genl_rcv+0x63/0x80 net/netlink/genetlink.c:811\n netlink_unicast_kernel net/netlink/af_netlink.c:1304 [inline]\n netlink_unicast+0x11d6/0x14a0 net/netlink/af_netlink.c:1330\n netlink_sendmsg+0x1740/0x1840 net/netlink/af_netlink.c:1919\n sock_sendmsg_nosec net/socket.c:652 [inline]\n sock_sendmsg net/socket.c:672 [inline]\n ____sys_sendmsg+0xcfc/0x12f0 net/socket.c:2345\n ___sys_sendmsg net/socket.c:2399 [inline]\n __sys_sendmsg+0x714/0x830 net/socket.c:2432\n __compat_sys_sendmsg net/compat.c:347 [inline]\n __do_compat_sys_sendmsg net/compat.c:354 [inline]\n __se_compat_sys_sendmsg+0xa7/0xc0 net/compat.c:351\n __ia32_compat_sys_sendmsg+0x4a/0x70 net/compat.c:351\n do_syscall_32_irqs_on arch/x86/entry/common.c:79 [inline]\n __do_fast_syscall_32+0x102/0x160 arch/x86/entry/common.c:141\n do_fast_syscall_32+0x6a/0xc0 arch/x86/entry/common.c:166\n do_SYSENTER_32+0x73/0x90 arch/x86/entry/common.c:209\n entry_SYSENTER_compat_after_hwframe+0x4d/0x5c\nRIP: 0023:0xf7f60549\nCode: 03 74 c0 01 10 05 03 74 b8 01 10 06 03 74 b4 01 10 07 03 74 b0 01 10 08 03 74 d8 01 00 00 00 00 00 51 52 55 89 e5 0f 34 cd 80 <5d> 5a 59 c3 90 90 90 90 8d b4 26 00 00 00 00 8d b4 26 00 00 00 00\nRSP: 002b:00000000f555a5fc EFLAGS: 00000296 ORIG_RAX: 0000000000000172\nRAX: ffffffffffffffda RBX: 0000000000000003 RCX: 0000000020000200\nRDX: 0000000000000000 RSI: 0000000000000000 RDI: 0000000000000000\nRBP: 0000000000000000 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000000\nR13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000000\n\nUninit was created at:\n kmsan_save_stack_with_flags mm/kmsan/kmsan.c:121 [inline]\n kmsan_internal_poison_shadow+0x5c/0xf0 mm/kmsan/kmsan.c:104\n kmsan_slab_alloc+0x8d/0xe0 mm/kmsan/kmsan_hooks.c:76\n slab_alloc_node mm/slub.c:2907 [inline]\n __kmalloc_node_track_caller+0xa37/0x1430 mm/slub.c:4527\n __kmalloc_reserve net/core/skbuff.c:142 [inline]\n __alloc_skb+0x2f8/0xb30 net/core/skbuff.c:210\n alloc_skb include/linux/skbuff.h:1099 [inline]\n netlink_alloc_large_skb net/netlink/af_netlink.c:1176 [inline]\n netlink_sendmsg+0xdbc/0x1840 net/netlink/af_netlink.c:1894\n sock_sendmsg_nosec net/socket.c:652 [inline]\n sock_sendmsg net/socket.c:672 [inline]\n ____sys_sendmsg+0xcfc/0x12f0 net/socket.c:2345\n ___sys_sendmsg net/socket.c:2399 [inline]\n __sys_sendmsg+0x714/0x830 net/socket.c:2432\n __compat_sys_sendmsg net/compat.c:347 [inline]\n __do_compat_sys_sendmsg net/compat.c:354 [inline]\n __se_compat_sys_sendmsg+0xa7/0xc0 net/compat.c:351\n __ia32_compat_sys_sendmsg+0x4a/0x70 net/compat.c:351\n do_syscall_32_irqs_on arch/x86/entry/common.c:79 [inline]\n __do_fast_syscall_32+0x102/0x160 arch/x86/entry/common.c:141\n do_fast_syscall_32+0x6a/0xc0 arch/x86/entry/common.c:166\n do_SYSENTER_32+0x73/0x90 arch/x86/entry/common.c:209\n entry_SYSENTER_compat_after_hwframe+0x4d/0x5c\n\nFixes: e1f32190cf7d (\"tipc: add support for AEAD key setting via netlink\")\nSigned-off-by: Eric Dumazet \nCc: Tuong Lien \nCc: Jon Maloy \nCc: Ying Xue \nReported-by: syzbot \nSigned-off-by: David S. Miller ", "target": 1, "dataset": "other", "idx": 204764} {"func": "static int tipc_nl_retrieve_key(struct nlattr **attrs,\n\t\t\t\tstruct tipc_aead_key **pkey)\n{\n\tstruct nlattr *attr = attrs[TIPC_NLA_NODE_KEY];\n\tstruct tipc_aead_key *key;\n\n\tif (!attr)\n\t\treturn -ENODATA;\n\n\tif (nla_len(attr) < sizeof(*key))\n\t\treturn -EINVAL;\n\tkey = (struct tipc_aead_key *)nla_data(attr);\n\tif (key->keylen > TIPC_AEAD_KEYLEN_MAX ||\n\t nla_len(attr) < tipc_aead_key_size(key))\n\t\treturn -EINVAL;\n\n\t*pkey = key;\n\treturn 0;\n}", "project": "linux", "hash": 184504004987990882955216536013391680124, "size": 19, "commit_id": "0217ed2848e8538bcf9172d97ed2eeb4a26041bb", "message": "tipc: better validate user input in tipc_nl_retrieve_key()\n\nBefore calling tipc_aead_key_size(ptr), we need to ensure\nwe have enough data to dereference ptr->keylen.\n\nWe probably also want to make sure tipc_aead_key_size()\nwont overflow with malicious ptr->keylen values.\n\nSyzbot reported:\n\nBUG: KMSAN: uninit-value in __tipc_nl_node_set_key net/tipc/node.c:2971 [inline]\nBUG: KMSAN: uninit-value in tipc_nl_node_set_key+0x9bf/0x13b0 net/tipc/node.c:3023\nCPU: 0 PID: 21060 Comm: syz-executor.5 Not tainted 5.11.0-rc7-syzkaller #0\nHardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011\nCall Trace:\n __dump_stack lib/dump_stack.c:79 [inline]\n dump_stack+0x21c/0x280 lib/dump_stack.c:120\n kmsan_report+0xfb/0x1e0 mm/kmsan/kmsan_report.c:118\n __msan_warning+0x5f/0xa0 mm/kmsan/kmsan_instr.c:197\n __tipc_nl_node_set_key net/tipc/node.c:2971 [inline]\n tipc_nl_node_set_key+0x9bf/0x13b0 net/tipc/node.c:3023\n genl_family_rcv_msg_doit net/netlink/genetlink.c:739 [inline]\n genl_family_rcv_msg net/netlink/genetlink.c:783 [inline]\n genl_rcv_msg+0x1319/0x1610 net/netlink/genetlink.c:800\n netlink_rcv_skb+0x6fa/0x810 net/netlink/af_netlink.c:2494\n genl_rcv+0x63/0x80 net/netlink/genetlink.c:811\n netlink_unicast_kernel net/netlink/af_netlink.c:1304 [inline]\n netlink_unicast+0x11d6/0x14a0 net/netlink/af_netlink.c:1330\n netlink_sendmsg+0x1740/0x1840 net/netlink/af_netlink.c:1919\n sock_sendmsg_nosec net/socket.c:652 [inline]\n sock_sendmsg net/socket.c:672 [inline]\n ____sys_sendmsg+0xcfc/0x12f0 net/socket.c:2345\n ___sys_sendmsg net/socket.c:2399 [inline]\n __sys_sendmsg+0x714/0x830 net/socket.c:2432\n __compat_sys_sendmsg net/compat.c:347 [inline]\n __do_compat_sys_sendmsg net/compat.c:354 [inline]\n __se_compat_sys_sendmsg+0xa7/0xc0 net/compat.c:351\n __ia32_compat_sys_sendmsg+0x4a/0x70 net/compat.c:351\n do_syscall_32_irqs_on arch/x86/entry/common.c:79 [inline]\n __do_fast_syscall_32+0x102/0x160 arch/x86/entry/common.c:141\n do_fast_syscall_32+0x6a/0xc0 arch/x86/entry/common.c:166\n do_SYSENTER_32+0x73/0x90 arch/x86/entry/common.c:209\n entry_SYSENTER_compat_after_hwframe+0x4d/0x5c\nRIP: 0023:0xf7f60549\nCode: 03 74 c0 01 10 05 03 74 b8 01 10 06 03 74 b4 01 10 07 03 74 b0 01 10 08 03 74 d8 01 00 00 00 00 00 51 52 55 89 e5 0f 34 cd 80 <5d> 5a 59 c3 90 90 90 90 8d b4 26 00 00 00 00 8d b4 26 00 00 00 00\nRSP: 002b:00000000f555a5fc EFLAGS: 00000296 ORIG_RAX: 0000000000000172\nRAX: ffffffffffffffda RBX: 0000000000000003 RCX: 0000000020000200\nRDX: 0000000000000000 RSI: 0000000000000000 RDI: 0000000000000000\nRBP: 0000000000000000 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000000\nR13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000000\n\nUninit was created at:\n kmsan_save_stack_with_flags mm/kmsan/kmsan.c:121 [inline]\n kmsan_internal_poison_shadow+0x5c/0xf0 mm/kmsan/kmsan.c:104\n kmsan_slab_alloc+0x8d/0xe0 mm/kmsan/kmsan_hooks.c:76\n slab_alloc_node mm/slub.c:2907 [inline]\n __kmalloc_node_track_caller+0xa37/0x1430 mm/slub.c:4527\n __kmalloc_reserve net/core/skbuff.c:142 [inline]\n __alloc_skb+0x2f8/0xb30 net/core/skbuff.c:210\n alloc_skb include/linux/skbuff.h:1099 [inline]\n netlink_alloc_large_skb net/netlink/af_netlink.c:1176 [inline]\n netlink_sendmsg+0xdbc/0x1840 net/netlink/af_netlink.c:1894\n sock_sendmsg_nosec net/socket.c:652 [inline]\n sock_sendmsg net/socket.c:672 [inline]\n ____sys_sendmsg+0xcfc/0x12f0 net/socket.c:2345\n ___sys_sendmsg net/socket.c:2399 [inline]\n __sys_sendmsg+0x714/0x830 net/socket.c:2432\n __compat_sys_sendmsg net/compat.c:347 [inline]\n __do_compat_sys_sendmsg net/compat.c:354 [inline]\n __se_compat_sys_sendmsg+0xa7/0xc0 net/compat.c:351\n __ia32_compat_sys_sendmsg+0x4a/0x70 net/compat.c:351\n do_syscall_32_irqs_on arch/x86/entry/common.c:79 [inline]\n __do_fast_syscall_32+0x102/0x160 arch/x86/entry/common.c:141\n do_fast_syscall_32+0x6a/0xc0 arch/x86/entry/common.c:166\n do_SYSENTER_32+0x73/0x90 arch/x86/entry/common.c:209\n entry_SYSENTER_compat_after_hwframe+0x4d/0x5c\n\nFixes: e1f32190cf7d (\"tipc: add support for AEAD key setting via netlink\")\nSigned-off-by: Eric Dumazet \nCc: Tuong Lien \nCc: Jon Maloy \nCc: Ying Xue \nReported-by: syzbot \nSigned-off-by: David S. Miller ", "target": 0, "dataset": "other", "idx": 364977} {"func": "lyxml_parse_elem(struct ly_ctx *ctx, const char *data, unsigned int *len, struct lyxml_elem *parent, int options)\n{\n const char *c = data, *start, *e;\n const char *lws; /* leading white space for handling mixed content */\n int uc;\n char *str;\n char *prefix = NULL;\n unsigned int prefix_len = 0;\n struct lyxml_elem *elem = NULL, *child;\n struct lyxml_attr *attr;\n unsigned int size;\n int nons_flag = 0, closed_flag = 0;\n\n *len = 0;\n\n if (*c != '<') {\n return NULL;\n }\n\n /* locate element name */\n c++;\n e = c;\n\n uc = lyxml_getutf8(ctx, e, &size);\n if (!is_xmlnamestartchar(uc)) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_NONE, NULL, \"NameStartChar of the element\");\n return NULL;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n while (is_xmlnamechar(uc)) {\n if (*e == ':') {\n if (prefix_len) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_NONE, NULL, \"element name, multiple colons found\");\n goto error;\n }\n /* element in a namespace */\n start = e + 1;\n\n /* look for the prefix in namespaces */\n prefix_len = e - c;\n LY_CHECK_ERR_GOTO(prefix, LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, e), error);\n prefix = malloc((prefix_len + 1) * sizeof *prefix);\n LY_CHECK_ERR_GOTO(!prefix, LOGMEM(ctx), error);\n memcpy(prefix, c, prefix_len);\n prefix[prefix_len] = '\\0';\n c = start;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n }\n if (!*e) {\n LOGVAL(ctx, LYE_EOF, LY_VLOG_NONE, NULL);\n free(prefix);\n return NULL;\n }\n\n /* allocate element structure */\n elem = calloc(1, sizeof *elem);\n LY_CHECK_ERR_RETURN(!elem, free(prefix); LOGMEM(ctx), NULL);\n\n elem->next = NULL;\n elem->prev = elem;\n if (parent) {\n lyxml_add_child(ctx, parent, elem);\n }\n\n /* store the name into the element structure */\n elem->name = lydict_insert(ctx, c, e - c);\n c = e;\n\nprocess:\n ign_xmlws(c);\n if (!strncmp(\"/>\", c, 2)) {\n /* we are done, it was EmptyElemTag */\n c += 2;\n elem->content = lydict_insert(ctx, \"\", 0);\n closed_flag = 1;\n } else if (*c == '>') {\n /* process element content */\n c++;\n lws = NULL;\n\n while (*c) {\n if (!strncmp(c, \"child) {\n /* leading white spaces were actually content */\n goto store_content;\n }\n\n /* Etag */\n c += 2;\n /* get name and check it */\n e = c;\n uc = lyxml_getutf8(ctx, e, &size);\n if (!is_xmlnamestartchar(uc)) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"NameStartChar of the element\");\n goto error;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n while (is_xmlnamechar(uc)) {\n if (*e == ':') {\n /* element in a namespace */\n start = e + 1;\n\n /* look for the prefix in namespaces */\n if (!prefix || memcmp(prefix, c, e - c)) {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem,\n \"Invalid (different namespaces) opening (%s) and closing element tags.\", elem->name);\n goto error;\n }\n c = start;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n }\n if (!*e) {\n LOGVAL(ctx, LYE_EOF, LY_VLOG_NONE, NULL);\n goto error;\n }\n\n /* check that it corresponds to opening tag */\n size = e - c;\n str = malloc((size + 1) * sizeof *str);\n LY_CHECK_ERR_GOTO(!str, LOGMEM(ctx), error);\n memcpy(str, c, e - c);\n str[e - c] = '\\0';\n if (size != strlen(elem->name) || memcmp(str, elem->name, size)) {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem,\n \"Invalid (mixed names) opening (%s) and closing (%s) element tags.\", elem->name, str);\n free(str);\n goto error;\n }\n free(str);\n c = e;\n\n ign_xmlws(c);\n if (*c != '>') {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem, \"Data after closing element tag \\\"%s\\\".\", elem->name);\n goto error;\n }\n c++;\n if (!(elem->flags & LYXML_ELEM_MIXED) && !elem->content) {\n /* there was no content, but we don't want NULL (only if mixed content) */\n elem->content = lydict_insert(ctx, \"\", 0);\n }\n closed_flag = 1;\n break;\n\n } else if (!strncmp(c, \"\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"flags & LYXML_ELEM_MIXED) {\n /* we have a mixed content */\n goto store_content;\n } else {\n /* leading white spaces were only formatting */\n lws = NULL;\n }\n }\n if (elem->content) {\n /* we have a mixed content */\n if (options & LYXML_PARSE_NOMIXEDCONTENT) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"XML element with mixed content\");\n goto error;\n }\n child = calloc(1, sizeof *child);\n LY_CHECK_ERR_GOTO(!child, LOGMEM(ctx), error);\n child->content = elem->content;\n elem->content = NULL;\n lyxml_add_child(ctx, elem, child);\n elem->flags |= LYXML_ELEM_MIXED;\n }\n child = lyxml_parse_elem(ctx, c, &size, elem, options);\n if (!child) {\n goto error;\n }\n c += size; /* move after processed child element */\n } else if (is_xmlws(*c)) {\n lws = c;\n ign_xmlws(c);\n } else {\nstore_content:\n /* store text content */\n if (lws) {\n /* process content including the leading white spaces */\n c = lws;\n lws = NULL;\n }\n str = parse_text(ctx, c, '<', &size);\n if (!str && !size) {\n goto error;\n }\n elem->content = lydict_insert_zc(ctx, str);\n c += size; /* move after processed text content */\n\n if (elem->child) {\n /* we have a mixed content */\n if (options & LYXML_PARSE_NOMIXEDCONTENT) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"XML element with mixed content\");\n goto error;\n }\n child = calloc(1, sizeof *child);\n LY_CHECK_ERR_GOTO(!child, LOGMEM(ctx), error);\n child->content = elem->content;\n elem->content = NULL;\n lyxml_add_child(ctx, elem, child);\n elem->flags |= LYXML_ELEM_MIXED;\n }\n }\n }\n } else {\n /* process attribute */\n attr = parse_attr(ctx, c, &size, elem);\n if (!attr) {\n goto error;\n }\n c += size; /* move after processed attribute */\n\n /* check namespace */\n if (attr->type == LYXML_ATTR_NS) {\n if ((!prefix || !prefix[0]) && !attr->name) {\n if (attr->value) {\n /* default prefix */\n elem->ns = (struct lyxml_ns *)attr;\n } else {\n /* xmlns=\"\" -> no namespace */\n nons_flag = 1;\n }\n } else if (prefix && prefix[0] && attr->name && !strncmp(attr->name, prefix, prefix_len + 1)) {\n /* matching namespace with prefix */\n elem->ns = (struct lyxml_ns *)attr;\n }\n }\n\n /* go back to finish element processing */\n goto process;\n }\n\n *len = c - data;\n\n if (!closed_flag) {\n LOGVAL(ctx, LYE_XML_MISS, LY_VLOG_XML, elem, \"closing element tag\", elem->name);\n goto error;\n }\n\n /* resolve all attribute prefixes */\n LY_TREE_FOR(elem->attr, attr) {\n if (attr->type == LYXML_ATTR_STD_UNRES) {\n str = (char *)attr->ns;\n attr->ns = lyxml_get_ns(elem, str);\n free(str);\n attr->type = LYXML_ATTR_STD;\n }\n }\n\n if (!elem->ns && !nons_flag && parent) {\n elem->ns = lyxml_get_ns(parent, prefix_len ? prefix : NULL);\n }\n free(prefix);\n return elem;\n\nerror:\n lyxml_free(ctx, elem);\n free(prefix);\n return NULL;\n}", "project": "libyang", "hash": 134258831294213793369395985834060205285, "size": 292, "commit_id": "298b30ea4ebee137226acf9bb38678bd82704582", "message": "common FEATURE add a hard limit for recursion\n\nFixes #1453", "target": 1, "dataset": "other", "idx": 204825} {"func": "lyxml_parse_elem(struct ly_ctx *ctx, const char *data, unsigned int *len, struct lyxml_elem *parent, int options,\n int bt_count)\n{\n const char *c = data, *start, *e;\n const char *lws; /* leading white space for handling mixed content */\n int uc;\n char *str;\n char *prefix = NULL;\n unsigned int prefix_len = 0;\n struct lyxml_elem *elem = NULL, *child;\n struct lyxml_attr *attr;\n unsigned int size;\n int nons_flag = 0, closed_flag = 0;\n\n *len = 0;\n\n if (bt_count > LY_RECURSION_LIMIT) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_NONE, NULL, \"Recursion limit %d reached\", LY_RECURSION_LIMIT);\n return NULL;\n }\n\n if (*c != '<') {\n return NULL;\n }\n\n /* locate element name */\n c++;\n e = c;\n\n uc = lyxml_getutf8(ctx, e, &size);\n if (!is_xmlnamestartchar(uc)) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_NONE, NULL, \"NameStartChar of the element\");\n return NULL;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n while (is_xmlnamechar(uc)) {\n if (*e == ':') {\n if (prefix_len) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_NONE, NULL, \"element name, multiple colons found\");\n goto error;\n }\n /* element in a namespace */\n start = e + 1;\n\n /* look for the prefix in namespaces */\n prefix_len = e - c;\n LY_CHECK_ERR_GOTO(prefix, LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, e), error);\n prefix = malloc((prefix_len + 1) * sizeof *prefix);\n LY_CHECK_ERR_GOTO(!prefix, LOGMEM(ctx), error);\n memcpy(prefix, c, prefix_len);\n prefix[prefix_len] = '\\0';\n c = start;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n }\n if (!*e) {\n LOGVAL(ctx, LYE_EOF, LY_VLOG_NONE, NULL);\n free(prefix);\n return NULL;\n }\n\n /* allocate element structure */\n elem = calloc(1, sizeof *elem);\n LY_CHECK_ERR_RETURN(!elem, free(prefix); LOGMEM(ctx), NULL);\n\n elem->next = NULL;\n elem->prev = elem;\n if (parent) {\n lyxml_add_child(ctx, parent, elem);\n }\n\n /* store the name into the element structure */\n elem->name = lydict_insert(ctx, c, e - c);\n c = e;\n\nprocess:\n ign_xmlws(c);\n if (!strncmp(\"/>\", c, 2)) {\n /* we are done, it was EmptyElemTag */\n c += 2;\n elem->content = lydict_insert(ctx, \"\", 0);\n closed_flag = 1;\n } else if (*c == '>') {\n /* process element content */\n c++;\n lws = NULL;\n\n while (*c) {\n if (!strncmp(c, \"child) {\n /* leading white spaces were actually content */\n goto store_content;\n }\n\n /* Etag */\n c += 2;\n /* get name and check it */\n e = c;\n uc = lyxml_getutf8(ctx, e, &size);\n if (!is_xmlnamestartchar(uc)) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"NameStartChar of the element\");\n goto error;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n while (is_xmlnamechar(uc)) {\n if (*e == ':') {\n /* element in a namespace */\n start = e + 1;\n\n /* look for the prefix in namespaces */\n if (!prefix || memcmp(prefix, c, e - c)) {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem,\n \"Invalid (different namespaces) opening (%s) and closing element tags.\", elem->name);\n goto error;\n }\n c = start;\n }\n e += size;\n uc = lyxml_getutf8(ctx, e, &size);\n }\n if (!*e) {\n LOGVAL(ctx, LYE_EOF, LY_VLOG_NONE, NULL);\n goto error;\n }\n\n /* check that it corresponds to opening tag */\n size = e - c;\n str = malloc((size + 1) * sizeof *str);\n LY_CHECK_ERR_GOTO(!str, LOGMEM(ctx), error);\n memcpy(str, c, e - c);\n str[e - c] = '\\0';\n if (size != strlen(elem->name) || memcmp(str, elem->name, size)) {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem,\n \"Invalid (mixed names) opening (%s) and closing (%s) element tags.\", elem->name, str);\n free(str);\n goto error;\n }\n free(str);\n c = e;\n\n ign_xmlws(c);\n if (*c != '>') {\n LOGVAL(ctx, LYE_SPEC, LY_VLOG_XML, elem, \"Data after closing element tag \\\"%s\\\".\", elem->name);\n goto error;\n }\n c++;\n if (!(elem->flags & LYXML_ELEM_MIXED) && !elem->content) {\n /* there was no content, but we don't want NULL (only if mixed content) */\n elem->content = lydict_insert(ctx, \"\", 0);\n }\n closed_flag = 1;\n break;\n\n } else if (!strncmp(c, \"\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"\", &size)) {\n goto error;\n }\n c += size;\n } else if (!strncmp(c, \"flags & LYXML_ELEM_MIXED) {\n /* we have a mixed content */\n goto store_content;\n } else {\n /* leading white spaces were only formatting */\n lws = NULL;\n }\n }\n if (elem->content) {\n /* we have a mixed content */\n if (options & LYXML_PARSE_NOMIXEDCONTENT) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"XML element with mixed content\");\n goto error;\n }\n child = calloc(1, sizeof *child);\n LY_CHECK_ERR_GOTO(!child, LOGMEM(ctx), error);\n child->content = elem->content;\n elem->content = NULL;\n lyxml_add_child(ctx, elem, child);\n elem->flags |= LYXML_ELEM_MIXED;\n }\n child = lyxml_parse_elem(ctx, c, &size, elem, options, bt_count + 1);\n if (!child) {\n goto error;\n }\n c += size; /* move after processed child element */\n } else if (is_xmlws(*c)) {\n lws = c;\n ign_xmlws(c);\n } else {\nstore_content:\n /* store text content */\n if (lws) {\n /* process content including the leading white spaces */\n c = lws;\n lws = NULL;\n }\n str = parse_text(ctx, c, '<', &size);\n if (!str && !size) {\n goto error;\n }\n elem->content = lydict_insert_zc(ctx, str);\n c += size; /* move after processed text content */\n\n if (elem->child) {\n /* we have a mixed content */\n if (options & LYXML_PARSE_NOMIXEDCONTENT) {\n LOGVAL(ctx, LYE_XML_INVAL, LY_VLOG_XML, elem, \"XML element with mixed content\");\n goto error;\n }\n child = calloc(1, sizeof *child);\n LY_CHECK_ERR_GOTO(!child, LOGMEM(ctx), error);\n child->content = elem->content;\n elem->content = NULL;\n lyxml_add_child(ctx, elem, child);\n elem->flags |= LYXML_ELEM_MIXED;\n }\n }\n }\n } else {\n /* process attribute */\n attr = parse_attr(ctx, c, &size, elem);\n if (!attr) {\n goto error;\n }\n c += size; /* move after processed attribute */\n\n /* check namespace */\n if (attr->type == LYXML_ATTR_NS) {\n if ((!prefix || !prefix[0]) && !attr->name) {\n if (attr->value) {\n /* default prefix */\n elem->ns = (struct lyxml_ns *)attr;\n } else {\n /* xmlns=\"\" -> no namespace */\n nons_flag = 1;\n }\n } else if (prefix && prefix[0] && attr->name && !strncmp(attr->name, prefix, prefix_len + 1)) {\n /* matching namespace with prefix */\n elem->ns = (struct lyxml_ns *)attr;\n }\n }\n\n /* go back to finish element processing */\n goto process;\n }\n\n *len = c - data;\n\n if (!closed_flag) {\n LOGVAL(ctx, LYE_XML_MISS, LY_VLOG_XML, elem, \"closing element tag\", elem->name);\n goto error;\n }\n\n /* resolve all attribute prefixes */\n LY_TREE_FOR(elem->attr, attr) {\n if (attr->type == LYXML_ATTR_STD_UNRES) {\n str = (char *)attr->ns;\n attr->ns = lyxml_get_ns(elem, str);\n free(str);\n attr->type = LYXML_ATTR_STD;\n }\n }\n\n if (!elem->ns && !nons_flag && parent) {\n elem->ns = lyxml_get_ns(parent, prefix_len ? prefix : NULL);\n }\n free(prefix);\n return elem;\n\nerror:\n lyxml_free(ctx, elem);\n free(prefix);\n return NULL;\n}", "project": "libyang", "hash": 212643853321618671175691086891444459949, "size": 298, "commit_id": "298b30ea4ebee137226acf9bb38678bd82704582", "message": "common FEATURE add a hard limit for recursion\n\nFixes #1453", "target": 0, "dataset": "other", "idx": 366009} {"func": "lyxml_parse_mem(struct ly_ctx *ctx, const char *data, int options)\n{\n FUN_IN;\n\n const char *c = data;\n unsigned int len;\n struct lyxml_elem *root, *first = NULL, *next;\n\n if (!ctx) {\n LOGARG;\n return NULL;\n }\n\n if (!data) {\n /* nothing to parse */\n return NULL;\n }\n\nrepeat:\n /* process document */\n while (1) {\n if (!*c) {\n /* eof */\n return first;\n } else if (is_xmlws(*c)) {\n /* skip whitespaces */\n ign_xmlws(c);\n } else if (!strncmp(c, \"\", &len)) {\n goto error;\n }\n c += len;\n } else if (!strncmp(c, \"\", &len)) {\n goto error;\n }\n c += len;\n } else if (!strncmp(c, \" */\n LOGERR(ctx, LY_EINVAL, \"DOCTYPE not supported in XML documents.\");\n goto error;\n } else if (*c == '<') {\n /* element - process it in next loop to strictly follow XML\n * format\n */\n break;\n } else {\n LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, c);\n goto error;\n }\n }\n\n root = lyxml_parse_elem(ctx, c, &len, NULL, options);\n if (!root) {\n goto error;\n } else if (!first) {\n first = root;\n } else {\n first->prev->next = root;\n root->prev = first->prev;\n first->prev = root;\n }\n c += len;\n\n /* ignore the rest of document where can be comments, PIs and whitespaces,\n * note that we are not detecting syntax errors in these parts\n */\n ign_xmlws(c);\n if (*c) {\n if (options & LYXML_PARSE_MULTIROOT) {\n goto repeat;\n } else {\n LOGWRN(ctx, \"There are some not parsed data:\\n%s\", c);\n }\n }\n\n return first;\n\nerror:\n LY_TREE_FOR_SAFE(first, next, root) {\n lyxml_free(ctx, root);\n }\n return NULL;\n}", "project": "libyang", "hash": 338248480891388136536572477802663278084, "size": 89, "commit_id": "298b30ea4ebee137226acf9bb38678bd82704582", "message": "common FEATURE add a hard limit for recursion\n\nFixes #1453", "target": 1, "dataset": "other", "idx": 204826} {"func": "lyxml_parse_mem(struct ly_ctx *ctx, const char *data, int options)\n{\n FUN_IN;\n\n const char *c = data;\n unsigned int len;\n struct lyxml_elem *root, *first = NULL, *next;\n\n if (!ctx) {\n LOGARG;\n return NULL;\n }\n\n if (!data) {\n /* nothing to parse */\n return NULL;\n }\n\nrepeat:\n /* process document */\n while (1) {\n if (!*c) {\n /* eof */\n return first;\n } else if (is_xmlws(*c)) {\n /* skip whitespaces */\n ign_xmlws(c);\n } else if (!strncmp(c, \"\", &len)) {\n goto error;\n }\n c += len;\n } else if (!strncmp(c, \"\", &len)) {\n goto error;\n }\n c += len;\n } else if (!strncmp(c, \" */\n LOGERR(ctx, LY_EINVAL, \"DOCTYPE not supported in XML documents.\");\n goto error;\n } else if (*c == '<') {\n /* element - process it in next loop to strictly follow XML\n * format\n */\n break;\n } else {\n LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, c);\n goto error;\n }\n }\n\n root = lyxml_parse_elem(ctx, c, &len, NULL, options, 0);\n if (!root) {\n goto error;\n } else if (!first) {\n first = root;\n } else {\n first->prev->next = root;\n root->prev = first->prev;\n first->prev = root;\n }\n c += len;\n\n /* ignore the rest of document where can be comments, PIs and whitespaces,\n * note that we are not detecting syntax errors in these parts\n */\n ign_xmlws(c);\n if (*c) {\n if (options & LYXML_PARSE_MULTIROOT) {\n goto repeat;\n } else {\n LOGWRN(ctx, \"There are some not parsed data:\\n%s\", c);\n }\n }\n\n return first;\n\nerror:\n LY_TREE_FOR_SAFE(first, next, root) {\n lyxml_free(ctx, root);\n }\n return NULL;\n}", "project": "libyang", "hash": 317835994028173949459715381216752210577, "size": 89, "commit_id": "298b30ea4ebee137226acf9bb38678bd82704582", "message": "common FEATURE add a hard limit for recursion\n\nFixes #1453", "target": 0, "dataset": "other", "idx": 366026} {"func": "int mpol_parse_str(char *str, struct mempolicy **mpol)\n{\n\tstruct mempolicy *new = NULL;\n\tunsigned short mode_flags;\n\tnodemask_t nodes;\n\tchar *nodelist = strchr(str, ':');\n\tchar *flags = strchr(str, '=');\n\tint err = 1, mode;\n\n\tif (flags)\n\t\t*flags++ = '\\0';\t/* terminate mode string */\n\n\tif (nodelist) {\n\t\t/* NUL-terminate mode or flags string */\n\t\t*nodelist++ = '\\0';\n\t\tif (nodelist_parse(nodelist, nodes))\n\t\t\tgoto out;\n\t\tif (!nodes_subset(nodes, node_states[N_MEMORY]))\n\t\t\tgoto out;\n\t} else\n\t\tnodes_clear(nodes);\n\n\tmode = match_string(policy_modes, MPOL_MAX, str);\n\tif (mode < 0)\n\t\tgoto out;\n\n\tswitch (mode) {\n\tcase MPOL_PREFERRED:\n\t\t/*\n\t\t * Insist on a nodelist of one node only\n\t\t */\n\t\tif (nodelist) {\n\t\t\tchar *rest = nodelist;\n\t\t\twhile (isdigit(*rest))\n\t\t\t\trest++;\n\t\t\tif (*rest)\n\t\t\t\tgoto out;\n\t\t}\n\t\tbreak;\n\tcase MPOL_INTERLEAVE:\n\t\t/*\n\t\t * Default to online nodes with memory if no nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tnodes = node_states[N_MEMORY];\n\t\tbreak;\n\tcase MPOL_LOCAL:\n\t\t/*\n\t\t * Don't allow a nodelist; mpol_new() checks flags\n\t\t */\n\t\tif (nodelist)\n\t\t\tgoto out;\n\t\tmode = MPOL_PREFERRED;\n\t\tbreak;\n\tcase MPOL_DEFAULT:\n\t\t/*\n\t\t * Insist on a empty nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\terr = 0;\n\t\tgoto out;\n\tcase MPOL_BIND:\n\t\t/*\n\t\t * Insist on a nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tgoto out;\n\t}\n\n\tmode_flags = 0;\n\tif (flags) {\n\t\t/*\n\t\t * Currently, we only support two mutually exclusive\n\t\t * mode flags.\n\t\t */\n\t\tif (!strcmp(flags, \"static\"))\n\t\t\tmode_flags |= MPOL_F_STATIC_NODES;\n\t\telse if (!strcmp(flags, \"relative\"))\n\t\t\tmode_flags |= MPOL_F_RELATIVE_NODES;\n\t\telse\n\t\t\tgoto out;\n\t}\n\n\tnew = mpol_new(mode, mode_flags, &nodes);\n\tif (IS_ERR(new))\n\t\tgoto out;\n\n\t/*\n\t * Save nodes for mpol_to_str() to show the tmpfs mount options\n\t * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.\n\t */\n\tif (mode != MPOL_PREFERRED)\n\t\tnew->v.nodes = nodes;\n\telse if (nodelist)\n\t\tnew->v.preferred_node = first_node(nodes);\n\telse\n\t\tnew->flags |= MPOL_F_LOCAL;\n\n\t/*\n\t * Save nodes for contextualization: this will be used to \"clone\"\n\t * the mempolicy in a specific context [cpuset] at a later time.\n\t */\n\tnew->w.user_nodemask = nodes;\n\n\terr = 0;\n\nout:\n\t/* Restore string for error message */\n\tif (nodelist)\n\t\t*--nodelist = ':';\n\tif (flags)\n\t\t*--flags = '=';\n\tif (!err)\n\t\t*mpol = new;\n\treturn err;\n}", "project": "linux", "hash": 222498222544209649377028812404138990797, "size": 116, "commit_id": "aa9f7d5172fac9bf1f09e678c35e287a40a7b7dd", "message": "mm: mempolicy: require at least one nodeid for MPOL_PREFERRED\n\nUsing an empty (malformed) nodelist that is not caught during mount option\nparsing leads to a stack-out-of-bounds access.\n\nThe option string that was used was: \"mpol=prefer:,\". However,\nMPOL_PREFERRED requires a single node number, which is not being provided\nhere.\n\nAdd a check that 'nodes' is not empty after parsing for MPOL_PREFERRED's\nnodeid.\n\nFixes: 095f1fc4ebf3 (\"mempolicy: rework shmem mpol parsing and display\")\nReported-by: Entropy Moe <3ntr0py1337@gmail.com>\nReported-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nSigned-off-by: Randy Dunlap \nSigned-off-by: Andrew Morton \nTested-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nCc: Lee Schermerhorn \nLink: http://lkml.kernel.org/r/89526377-7eb6-b662-e1d8-4430928abde9@infradead.org\nSigned-off-by: Linus Torvalds ", "target": 1, "dataset": "other", "idx": 204856} {"func": "int mpol_parse_str(char *str, struct mempolicy **mpol)\n{\n\tstruct mempolicy *new = NULL;\n\tunsigned short mode_flags;\n\tnodemask_t nodes;\n\tchar *nodelist = strchr(str, ':');\n\tchar *flags = strchr(str, '=');\n\tint err = 1, mode;\n\n\tif (flags)\n\t\t*flags++ = '\\0';\t/* terminate mode string */\n\n\tif (nodelist) {\n\t\t/* NUL-terminate mode or flags string */\n\t\t*nodelist++ = '\\0';\n\t\tif (nodelist_parse(nodelist, nodes))\n\t\t\tgoto out;\n\t\tif (!nodes_subset(nodes, node_states[N_MEMORY]))\n\t\t\tgoto out;\n\t} else\n\t\tnodes_clear(nodes);\n\n\tmode = match_string(policy_modes, MPOL_MAX, str);\n\tif (mode < 0)\n\t\tgoto out;\n\n\tswitch (mode) {\n\tcase MPOL_PREFERRED:\n\t\t/*\n\t\t * Insist on a nodelist of one node only, although later\n\t\t * we use first_node(nodes) to grab a single node, so here\n\t\t * nodelist (or nodes) cannot be empty.\n\t\t */\n\t\tif (nodelist) {\n\t\t\tchar *rest = nodelist;\n\t\t\twhile (isdigit(*rest))\n\t\t\t\trest++;\n\t\t\tif (*rest)\n\t\t\t\tgoto out;\n\t\t\tif (nodes_empty(nodes))\n\t\t\t\tgoto out;\n\t\t}\n\t\tbreak;\n\tcase MPOL_INTERLEAVE:\n\t\t/*\n\t\t * Default to online nodes with memory if no nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tnodes = node_states[N_MEMORY];\n\t\tbreak;\n\tcase MPOL_LOCAL:\n\t\t/*\n\t\t * Don't allow a nodelist; mpol_new() checks flags\n\t\t */\n\t\tif (nodelist)\n\t\t\tgoto out;\n\t\tmode = MPOL_PREFERRED;\n\t\tbreak;\n\tcase MPOL_DEFAULT:\n\t\t/*\n\t\t * Insist on a empty nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\terr = 0;\n\t\tgoto out;\n\tcase MPOL_BIND:\n\t\t/*\n\t\t * Insist on a nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tgoto out;\n\t}\n\n\tmode_flags = 0;\n\tif (flags) {\n\t\t/*\n\t\t * Currently, we only support two mutually exclusive\n\t\t * mode flags.\n\t\t */\n\t\tif (!strcmp(flags, \"static\"))\n\t\t\tmode_flags |= MPOL_F_STATIC_NODES;\n\t\telse if (!strcmp(flags, \"relative\"))\n\t\t\tmode_flags |= MPOL_F_RELATIVE_NODES;\n\t\telse\n\t\t\tgoto out;\n\t}\n\n\tnew = mpol_new(mode, mode_flags, &nodes);\n\tif (IS_ERR(new))\n\t\tgoto out;\n\n\t/*\n\t * Save nodes for mpol_to_str() to show the tmpfs mount options\n\t * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.\n\t */\n\tif (mode != MPOL_PREFERRED)\n\t\tnew->v.nodes = nodes;\n\telse if (nodelist)\n\t\tnew->v.preferred_node = first_node(nodes);\n\telse\n\t\tnew->flags |= MPOL_F_LOCAL;\n\n\t/*\n\t * Save nodes for contextualization: this will be used to \"clone\"\n\t * the mempolicy in a specific context [cpuset] at a later time.\n\t */\n\tnew->w.user_nodemask = nodes;\n\n\terr = 0;\n\nout:\n\t/* Restore string for error message */\n\tif (nodelist)\n\t\t*--nodelist = ':';\n\tif (flags)\n\t\t*--flags = '=';\n\tif (!err)\n\t\t*mpol = new;\n\treturn err;\n}", "project": "linux", "hash": 184911246501013902029875653873691151, "size": 120, "commit_id": "aa9f7d5172fac9bf1f09e678c35e287a40a7b7dd", "message": "mm: mempolicy: require at least one nodeid for MPOL_PREFERRED\n\nUsing an empty (malformed) nodelist that is not caught during mount option\nparsing leads to a stack-out-of-bounds access.\n\nThe option string that was used was: \"mpol=prefer:,\". However,\nMPOL_PREFERRED requires a single node number, which is not being provided\nhere.\n\nAdd a check that 'nodes' is not empty after parsing for MPOL_PREFERRED's\nnodeid.\n\nFixes: 095f1fc4ebf3 (\"mempolicy: rework shmem mpol parsing and display\")\nReported-by: Entropy Moe <3ntr0py1337@gmail.com>\nReported-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nSigned-off-by: Randy Dunlap \nSigned-off-by: Andrew Morton \nTested-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nCc: Lee Schermerhorn \nLink: http://lkml.kernel.org/r/89526377-7eb6-b662-e1d8-4430928abde9@infradead.org\nSigned-off-by: Linus Torvalds ", "target": 0, "dataset": "other", "idx": 366756} {"func": "static void sm501_2d_operation(SM501State *s)\n{\n int cmd = (s->twoD_control >> 16) & 0x1F;\n int rtl = s->twoD_control & BIT(27);\n int format = (s->twoD_stretch >> 20) & 0x3;\n int rop_mode = (s->twoD_control >> 15) & 0x1; /* 1 for rop2, else rop3 */\n /* 1 if rop2 source is the pattern, otherwise the source is the bitmap */\n int rop2_source_is_pattern = (s->twoD_control >> 14) & 0x1;\n int rop = s->twoD_control & 0xFF;\n int dst_x = (s->twoD_destination >> 16) & 0x01FFF;\n int dst_y = s->twoD_destination & 0xFFFF;\n int width = (s->twoD_dimension >> 16) & 0x1FFF;\n int height = s->twoD_dimension & 0xFFFF;\n uint32_t dst_base = s->twoD_destination_base & 0x03FFFFFF;\n uint8_t *dst = s->local_mem + dst_base;\n int dst_pitch = (s->twoD_pitch >> 16) & 0x1FFF;\n int crt = (s->dc_crt_control & SM501_DC_CRT_CONTROL_SEL) ? 1 : 0;\n int fb_len = get_width(s, crt) * get_height(s, crt) * get_bpp(s, crt);\n\n if ((s->twoD_stretch >> 16) & 0xF) {\n qemu_log_mask(LOG_UNIMP, \"sm501: only XY addressing is supported.\\n\");\n return;\n }\n\n if (rop_mode == 0) {\n if (rop != 0xcc) {\n /* Anything other than plain copies are not supported */\n qemu_log_mask(LOG_UNIMP, \"sm501: rop3 mode with rop %x is not \"\n \"supported.\\n\", rop);\n }\n } else {\n if (rop2_source_is_pattern && rop != 0x5) {\n /* For pattern source, we support only inverse dest */\n qemu_log_mask(LOG_UNIMP, \"sm501: rop2 source being the pattern and \"\n \"rop %x is not supported.\\n\", rop);\n } else {\n if (rop != 0x5 && rop != 0xc) {\n /* Anything other than plain copies or inverse dest is not\n * supported */\n qemu_log_mask(LOG_UNIMP, \"sm501: rop mode %x is not \"\n \"supported.\\n\", rop);\n }\n }\n }\n\n if (s->twoD_source_base & BIT(27) || s->twoD_destination_base & BIT(27)) {\n qemu_log_mask(LOG_UNIMP, \"sm501: only local memory is supported.\\n\");\n return;\n }\n\n switch (cmd) {\n case 0x00: /* copy area */\n {\n int src_x = (s->twoD_source >> 16) & 0x01FFF;\n int src_y = s->twoD_source & 0xFFFF;\n uint32_t src_base = s->twoD_source_base & 0x03FFFFFF;\n uint8_t *src = s->local_mem + src_base;\n int src_pitch = s->twoD_pitch & 0x1FFF;\n\n#define COPY_AREA(_bpp, _pixel_type, rtl) { \\\n int y, x, index_d, index_s; \\\n for (y = 0; y < height; y++) { \\\n for (x = 0; x < width; x++) { \\\n _pixel_type val; \\\n \\\n if (rtl) { \\\n index_s = ((src_y - y) * src_pitch + src_x - x) * _bpp; \\\n index_d = ((dst_y - y) * dst_pitch + dst_x - x) * _bpp; \\\n } else { \\\n index_s = ((src_y + y) * src_pitch + src_x + x) * _bpp; \\\n index_d = ((dst_y + y) * dst_pitch + dst_x + x) * _bpp; \\\n } \\\n if (rop_mode == 1 && rop == 5) { \\\n /* Invert dest */ \\\n val = ~*(_pixel_type *)&dst[index_d]; \\\n } else { \\\n val = *(_pixel_type *)&src[index_s]; \\\n } \\\n *(_pixel_type *)&dst[index_d] = val; \\\n } \\\n } \\\n }\n switch (format) {\n case 0:\n COPY_AREA(1, uint8_t, rtl);\n break;\n case 1:\n COPY_AREA(2, uint16_t, rtl);\n break;\n case 2:\n COPY_AREA(4, uint32_t, rtl);\n break;\n }\n break;\n }\n case 0x01: /* fill rectangle */\n {\n uint32_t color = s->twoD_foreground;\n\n#define FILL_RECT(_bpp, _pixel_type) { \\\n int y, x; \\\n for (y = 0; y < height; y++) { \\\n for (x = 0; x < width; x++) { \\\n int index = ((dst_y + y) * dst_pitch + dst_x + x) * _bpp; \\\n *(_pixel_type *)&dst[index] = (_pixel_type)color; \\\n } \\\n } \\\n }\n\n switch (format) {\n case 0:\n FILL_RECT(1, uint8_t);\n break;\n case 1:\n color = cpu_to_le16(color);\n FILL_RECT(2, uint16_t);\n break;\n case 2:\n color = cpu_to_le32(color);\n FILL_RECT(4, uint32_t);\n break;\n }\n break;\n }\n default:\n qemu_log_mask(LOG_UNIMP, \"sm501: not implemented 2D operation: %d\\n\",\n cmd);\n return;\n }\n\n if (dst_base >= get_fb_addr(s, crt) &&\n dst_base <= get_fb_addr(s, crt) + fb_len) {\n int dst_len = MIN(fb_len, ((dst_y + height - 1) * dst_pitch +\n dst_x + width) * (1 << format));\n if (dst_len) {\n memory_region_set_dirty(&s->local_mem_region, dst_base, dst_len);\n }\n }\n}", "project": "qemu", "hash": 231921026198244072541449258178431781416, "size": 139, "commit_id": "b15a22bbcbe6a78dc3d88fe3134985e4cdd87de4", "message": "sm501: Replace hand written implementation with pixman where possible\n\nBesides being faster this should also prevent malicious guests to\nabuse 2D engine to overwrite data or cause a crash.\n\nSigned-off-by: BALATON Zoltan \nMessage-id: 58666389b6cae256e4e972a32c05cf8aa51bffc0.1590089984.git.balaton@eik.bme.hu\nSigned-off-by: Gerd Hoffmann ", "target": 1, "dataset": "other", "idx": 204867} {"func": "static void sm501_2d_operation(SM501State *s)\n{\n int cmd = (s->twoD_control >> 16) & 0x1F;\n int rtl = s->twoD_control & BIT(27);\n int format = (s->twoD_stretch >> 20) & 0x3;\n int rop_mode = (s->twoD_control >> 15) & 0x1; /* 1 for rop2, else rop3 */\n /* 1 if rop2 source is the pattern, otherwise the source is the bitmap */\n int rop2_source_is_pattern = (s->twoD_control >> 14) & 0x1;\n int rop = s->twoD_control & 0xFF;\n unsigned int dst_x = (s->twoD_destination >> 16) & 0x01FFF;\n unsigned int dst_y = s->twoD_destination & 0xFFFF;\n unsigned int width = (s->twoD_dimension >> 16) & 0x1FFF;\n unsigned int height = s->twoD_dimension & 0xFFFF;\n uint32_t dst_base = s->twoD_destination_base & 0x03FFFFFF;\n unsigned int dst_pitch = (s->twoD_pitch >> 16) & 0x1FFF;\n int crt = (s->dc_crt_control & SM501_DC_CRT_CONTROL_SEL) ? 1 : 0;\n int fb_len = get_width(s, crt) * get_height(s, crt) * get_bpp(s, crt);\n\n if ((s->twoD_stretch >> 16) & 0xF) {\n qemu_log_mask(LOG_UNIMP, \"sm501: only XY addressing is supported.\\n\");\n return;\n }\n\n if (s->twoD_source_base & BIT(27) || s->twoD_destination_base & BIT(27)) {\n qemu_log_mask(LOG_UNIMP, \"sm501: only local memory is supported.\\n\");\n return;\n }\n\n if (!dst_pitch) {\n qemu_log_mask(LOG_GUEST_ERROR, \"sm501: Zero dest pitch.\\n\");\n return;\n }\n\n if (!width || !height) {\n qemu_log_mask(LOG_GUEST_ERROR, \"sm501: Zero size 2D op.\\n\");\n return;\n }\n\n if (rtl) {\n dst_x -= width - 1;\n dst_y -= height - 1;\n }\n\n if (dst_base >= get_local_mem_size(s) || dst_base +\n (dst_x + width + (dst_y + height) * (dst_pitch + width)) *\n (1 << format) >= get_local_mem_size(s)) {\n qemu_log_mask(LOG_GUEST_ERROR, \"sm501: 2D op dest is outside vram.\\n\");\n return;\n }\n\n switch (cmd) {\n case 0: /* BitBlt */\n {\n unsigned int src_x = (s->twoD_source >> 16) & 0x01FFF;\n unsigned int src_y = s->twoD_source & 0xFFFF;\n uint32_t src_base = s->twoD_source_base & 0x03FFFFFF;\n unsigned int src_pitch = s->twoD_pitch & 0x1FFF;\n\n if (!src_pitch) {\n qemu_log_mask(LOG_GUEST_ERROR, \"sm501: Zero src pitch.\\n\");\n return;\n }\n\n if (rtl) {\n src_x -= width - 1;\n src_y -= height - 1;\n }\n\n if (src_base >= get_local_mem_size(s) || src_base +\n (src_x + width + (src_y + height) * (src_pitch + width)) *\n (1 << format) >= get_local_mem_size(s)) {\n qemu_log_mask(LOG_GUEST_ERROR,\n \"sm501: 2D op src is outside vram.\\n\");\n return;\n }\n\n if ((rop_mode && rop == 0x5) || (!rop_mode && rop == 0x55)) {\n /* Invert dest, is there a way to do this with pixman? */\n unsigned int x, y, i;\n uint8_t *d = s->local_mem + dst_base;\n\n for (y = 0; y < height; y++) {\n i = (dst_x + (dst_y + y) * dst_pitch) * (1 << format);\n for (x = 0; x < width; x++, i += (1 << format)) {\n switch (format) {\n case 0:\n d[i] = ~d[i];\n break;\n case 1:\n *(uint16_t *)&d[i] = ~*(uint16_t *)&d[i];\n break;\n case 2:\n *(uint32_t *)&d[i] = ~*(uint32_t *)&d[i];\n break;\n }\n }\n }\n } else {\n /* Do copy src for unimplemented ops, better than unpainted area */\n if ((rop_mode && (rop != 0xc || rop2_source_is_pattern)) ||\n (!rop_mode && rop != 0xcc)) {\n qemu_log_mask(LOG_UNIMP,\n \"sm501: rop%d op %x%s not implemented\\n\",\n (rop_mode ? 2 : 3), rop,\n (rop2_source_is_pattern ?\n \" with pattern source\" : \"\"));\n }\n /* Check for overlaps, this could be made more exact */\n uint32_t sb, se, db, de;\n sb = src_base + src_x + src_y * (width + src_pitch);\n se = sb + width + height * (width + src_pitch);\n db = dst_base + dst_x + dst_y * (width + dst_pitch);\n de = db + width + height * (width + dst_pitch);\n if (rtl && ((db >= sb && db <= se) || (de >= sb && de <= se))) {\n /* regions may overlap: copy via temporary */\n int llb = width * (1 << format);\n int tmp_stride = DIV_ROUND_UP(llb, sizeof(uint32_t));\n uint32_t *tmp = g_malloc(tmp_stride * sizeof(uint32_t) *\n height);\n pixman_blt((uint32_t *)&s->local_mem[src_base], tmp,\n src_pitch * (1 << format) / sizeof(uint32_t),\n tmp_stride, 8 * (1 << format), 8 * (1 << format),\n src_x, src_y, 0, 0, width, height);\n pixman_blt(tmp, (uint32_t *)&s->local_mem[dst_base],\n tmp_stride,\n dst_pitch * (1 << format) / sizeof(uint32_t),\n 8 * (1 << format), 8 * (1 << format),\n 0, 0, dst_x, dst_y, width, height);\n g_free(tmp);\n } else {\n pixman_blt((uint32_t *)&s->local_mem[src_base],\n (uint32_t *)&s->local_mem[dst_base],\n src_pitch * (1 << format) / sizeof(uint32_t),\n dst_pitch * (1 << format) / sizeof(uint32_t),\n 8 * (1 << format), 8 * (1 << format),\n src_x, src_y, dst_x, dst_y, width, height);\n }\n }\n break;\n }\n case 1: /* Rectangle Fill */\n {\n uint32_t color = s->twoD_foreground;\n\n if (format == 2) {\n color = cpu_to_le32(color);\n } else if (format == 1) {\n color = cpu_to_le16(color);\n }\n\n pixman_fill((uint32_t *)&s->local_mem[dst_base],\n dst_pitch * (1 << format) / sizeof(uint32_t),\n 8 * (1 << format), dst_x, dst_y, width, height, color);\n break;\n }\n default:\n qemu_log_mask(LOG_UNIMP, \"sm501: not implemented 2D operation: %d\\n\",\n cmd);\n return;\n }\n\n if (dst_base >= get_fb_addr(s, crt) &&\n dst_base <= get_fb_addr(s, crt) + fb_len) {\n int dst_len = MIN(fb_len, ((dst_y + height - 1) * dst_pitch +\n dst_x + width) * (1 << format));\n if (dst_len) {\n memory_region_set_dirty(&s->local_mem_region, dst_base, dst_len);\n }\n }\n}", "project": "qemu", "hash": 193599277263988750788636095730957842514, "size": 170, "commit_id": "b15a22bbcbe6a78dc3d88fe3134985e4cdd87de4", "message": "sm501: Replace hand written implementation with pixman where possible\n\nBesides being faster this should also prevent malicious guests to\nabuse 2D engine to overwrite data or cause a crash.\n\nSigned-off-by: BALATON Zoltan \nMessage-id: 58666389b6cae256e4e972a32c05cf8aa51bffc0.1590089984.git.balaton@eik.bme.hu\nSigned-off-by: Gerd Hoffmann ", "target": 0, "dataset": "other", "idx": 367048} {"func": " int MemIo::seek(int64 offset, Position pos )\n {\n int64 newIdx = 0;\n\n switch (pos) {\n case BasicIo::cur:\n newIdx = p_->idx_ + offset;\n break;\n case BasicIo::beg:\n newIdx = offset;\n break;\n case BasicIo::end:\n newIdx = p_->size_ + offset;\n break;\n }\n\n if (newIdx < 0)\n return 1;\n\n p_->idx_ = static_cast(newIdx); //not very sure about this. need more test!! - note by Shawn fly2xj@gmail.com //TODO\n p_->eof_ = false;\n return 0;\n }", "project": "exiv2", "hash": 299218834992083440493543625582483690654, "size": 23, "commit_id": "bd0afe0390439b2c424d881c8c6eb0c5624e31d9", "message": "Add bounds check to MemIo::seek(). (#944)\n\n- Regression test for missing bounds check in MemIo::seek()\r\n- Add bounds check to MemIo::seek(), this fixes CVE-2019-13504", "target": 1, "dataset": "other", "idx": 204868} {"func": " int MemIo::seek(int64 offset, Position pos )\n {\n int64 newIdx = 0;\n\n switch (pos) {\n case BasicIo::cur:\n newIdx = p_->idx_ + offset;\n break;\n case BasicIo::beg:\n newIdx = offset;\n break;\n case BasicIo::end:\n newIdx = p_->size_ + offset;\n break;\n }\n\n if (newIdx < 0)\n return 1;\n\n if (static_cast(newIdx) > p_->size_) {\n p_->eof_ = true;\n return 1;\n }\n\n p_->idx_ = static_cast(newIdx);\n p_->eof_ = false;\n return 0;\n }", "project": "exiv2", "hash": 109191990002104936880753982885886945308, "size": 28, "commit_id": "bd0afe0390439b2c424d881c8c6eb0c5624e31d9", "message": "Add bounds check to MemIo::seek(). (#944)\n\n- Regression test for missing bounds check in MemIo::seek()\r\n- Add bounds check to MemIo::seek(), this fixes CVE-2019-13504", "target": 0, "dataset": "other", "idx": 367064} {"func": "BPMDetect::BPMDetect(int numChannels, int aSampleRate) :\r\n beat_lpf(_LPF_coeffs)\r\n{\r\n beats.reserve(250); // initial reservation to prevent frequent reallocation\r\n\r\n this->sampleRate = aSampleRate;\r\n this->channels = numChannels;\r\n\r\n decimateSum = 0;\r\n decimateCount = 0;\r\n\r\n // choose decimation factor so that result is approx. 1000 Hz\r\n decimateBy = sampleRate / TARGET_SRATE;\r\n assert(decimateBy > 0);\r\n assert(INPUT_BLOCK_SIZE < decimateBy * DECIMATED_BLOCK_SIZE);\r\n\r\n // Calculate window length & starting item according to desired min & max bpms\r\n windowLen = (60 * sampleRate) / (decimateBy * MIN_BPM);\r\n windowStart = (60 * sampleRate) / (decimateBy * MAX_BPM_RANGE);\r\n\r\n assert(windowLen > windowStart);\r\n\r\n // allocate new working objects\r\n xcorr = new float[windowLen];\r\n memset(xcorr, 0, windowLen * sizeof(float));\r\n\r\n pos = 0;\r\n peakPos = 0;\r\n peakVal = 0;\r\n init_scaler = 1;\r\n beatcorr_ringbuffpos = 0;\r\n beatcorr_ringbuff = new float[windowLen];\r\n memset(beatcorr_ringbuff, 0, windowLen * sizeof(float));\r\n\r\n // allocate processing buffer\r\n buffer = new FIFOSampleBuffer();\r\n // we do processing in mono mode\r\n buffer->setChannels(1);\r\n buffer->clear();\r\n\r\n // calculate hamming windows\r\n hamw = new float[XCORR_UPDATE_SEQUENCE];\r\n hamming(hamw, XCORR_UPDATE_SEQUENCE);\r\n hamw2 = new float[XCORR_UPDATE_SEQUENCE / 2];\r\n hamming(hamw2, XCORR_UPDATE_SEQUENCE / 2);\r\n}\r", "project": "soundtouch", "hash": 338493797798567657703708124487583988357, "size": 46, "commit_id": "a1c400eb2cff849c0e5f9d6916d69ffea3ad2c85", "message": "Fix issue CVE-2018-17096: Replace assert with runtime exception", "target": 1, "dataset": "other", "idx": 205562} {"func": "BPMDetect::BPMDetect(int numChannels, int aSampleRate) :\r\n beat_lpf(_LPF_coeffs)\r\n{\r\n beats.reserve(250); // initial reservation to prevent frequent reallocation\r\n\r\n this->sampleRate = aSampleRate;\r\n this->channels = numChannels;\r\n\r\n decimateSum = 0;\r\n decimateCount = 0;\r\n\r\n // choose decimation factor so that result is approx. 1000 Hz\r\n decimateBy = sampleRate / TARGET_SRATE;\r\n if ((decimateBy <= 0) || (decimateBy * DECIMATED_BLOCK_SIZE < INPUT_BLOCK_SIZE))\r\n {\r\n ST_THROW_RT_ERROR(\"Too small samplerate\");\r\n }\r\n\r\n // Calculate window length & starting item according to desired min & max bpms\r\n windowLen = (60 * sampleRate) / (decimateBy * MIN_BPM);\r\n windowStart = (60 * sampleRate) / (decimateBy * MAX_BPM_RANGE);\r\n\r\n assert(windowLen > windowStart);\r\n\r\n // allocate new working objects\r\n xcorr = new float[windowLen];\r\n memset(xcorr, 0, windowLen * sizeof(float));\r\n\r\n pos = 0;\r\n peakPos = 0;\r\n peakVal = 0;\r\n init_scaler = 1;\r\n beatcorr_ringbuffpos = 0;\r\n beatcorr_ringbuff = new float[windowLen];\r\n memset(beatcorr_ringbuff, 0, windowLen * sizeof(float));\r\n\r\n // allocate processing buffer\r\n buffer = new FIFOSampleBuffer();\r\n // we do processing in mono mode\r\n buffer->setChannels(1);\r\n buffer->clear();\r\n\r\n // calculate hamming windows\r\n hamw = new float[XCORR_UPDATE_SEQUENCE];\r\n hamming(hamw, XCORR_UPDATE_SEQUENCE);\r\n hamw2 = new float[XCORR_UPDATE_SEQUENCE / 2];\r\n hamming(hamw2, XCORR_UPDATE_SEQUENCE / 2);\r\n}\r", "project": "soundtouch", "hash": 9975483775436489168942805933636882922, "size": 48, "commit_id": "a1c400eb2cff849c0e5f9d6916d69ffea3ad2c85", "message": "Fix issue CVE-2018-17096: Replace assert with runtime exception", "target": 0, "dataset": "other", "idx": 368106} {"func": "hivex_open (const char *filename, int flags)\n{\n hive_h *h = NULL;\n\n assert (sizeof (struct ntreg_header) == 0x1000);\n assert (offsetof (struct ntreg_header, csum) == 0x1fc);\n\n h = calloc (1, sizeof *h);\n if (h == NULL)\n goto error;\n\n h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK;\n\n const char *debug = getenv (\"HIVEX_DEBUG\");\n if (debug && STREQ (debug, \"1\"))\n h->msglvl = 2;\n\n DEBUG (2, \"created handle %p\", h);\n\n h->writable = !!(flags & HIVEX_OPEN_WRITE);\n h->unsafe = !!(flags & HIVEX_OPEN_UNSAFE);\n h->filename = strdup (filename);\n if (h->filename == NULL)\n goto error;\n\n#ifdef O_CLOEXEC\n h->fd = open (filename, O_RDONLY | O_CLOEXEC | O_BINARY);\n#else\n h->fd = open (filename, O_RDONLY | O_BINARY);\n#endif\n if (h->fd == -1)\n goto error;\n#ifndef O_CLOEXEC\n fcntl (h->fd, F_SETFD, FD_CLOEXEC);\n#endif\n\n struct stat statbuf;\n if (fstat (h->fd, &statbuf) == -1)\n goto error;\n\n h->size = statbuf.st_size;\n\n if (h->size < 0x2000) {\n SET_ERRNO (EINVAL,\n \"%s: file is too small to be a Windows NT Registry hive file\",\n filename);\n goto error;\n }\n\n if (!h->writable) {\n h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);\n if (h->addr == MAP_FAILED)\n goto error;\n\n DEBUG (2, \"mapped file at %p\", h->addr);\n } else {\n h->addr = malloc (h->size);\n if (h->addr == NULL)\n goto error;\n\n if (full_read (h->fd, h->addr, h->size) < h->size)\n goto error;\n\n /* We don't need the file descriptor along this path, since we\n * have read all the data.\n */\n if (close (h->fd) == -1)\n goto error;\n h->fd = -1;\n }\n\n /* Check header. */\n if (h->hdr->magic[0] != 'r' ||\n h->hdr->magic[1] != 'e' ||\n h->hdr->magic[2] != 'g' ||\n h->hdr->magic[3] != 'f') {\n SET_ERRNO (ENOTSUP,\n \"%s: not a Windows NT Registry hive file\", filename);\n goto error;\n }\n\n /* Check major version. */\n uint32_t major_ver = le32toh (h->hdr->major_ver);\n if (major_ver != 1) {\n SET_ERRNO (ENOTSUP,\n \"%s: hive file major version %\" PRIu32 \" (expected 1)\",\n filename, major_ver);\n goto error;\n }\n\n h->bitmap = calloc (1 + h->size / 32, 1);\n if (h->bitmap == NULL)\n goto error;\n\n /* Header checksum. */\n uint32_t sum = header_checksum (h);\n if (sum != le32toh (h->hdr->csum)) {\n SET_ERRNO (EINVAL, \"%s: bad checksum in hive header\", filename);\n goto error;\n }\n\n for (int t=0; ticonv_cache[t].mutex);\n h->iconv_cache[t].handle = NULL;\n }\n\n /* Last modified time. */\n h->last_modified = le64toh ((int64_t) h->hdr->last_modified);\n\n if (h->msglvl >= 2) {\n char *name = _hivex_recode (h, utf16le_to_utf8,\n h->hdr->name, 64, NULL);\n\n fprintf (stderr,\n \"hivex_open: header fields:\\n\"\n \" file version %\" PRIu32 \".%\" PRIu32 \"\\n\"\n \" sequence nos %\" PRIu32 \" %\" PRIu32 \"\\n\"\n \" (sequences nos should match if hive was synched at shutdown)\\n\"\n \" last modified %\" PRIi64 \"\\n\"\n \" (Windows filetime, x 100 ns since 1601-01-01)\\n\"\n \" original file name %s\\n\"\n \" (only 32 chars are stored, name is probably truncated)\\n\"\n \" root offset 0x%x + 0x1000\\n\"\n \" end of last page 0x%x + 0x1000 (total file size 0x%zx)\\n\"\n \" checksum 0x%x (calculated 0x%x)\\n\",\n major_ver, le32toh (h->hdr->minor_ver),\n le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),\n h->last_modified,\n name ? name : \"(conversion failed)\",\n le32toh (h->hdr->offset),\n le32toh (h->hdr->blocks), h->size,\n le32toh (h->hdr->csum), sum);\n free (name);\n }\n\n h->rootoffs = le32toh (h->hdr->offset) + 0x1000;\n h->endpages = le32toh (h->hdr->blocks) + 0x1000;\n\n DEBUG (2, \"root offset = 0x%zx\", h->rootoffs);\n\n /* We'll set this flag when we see a block with the root offset (ie.\n * the root block).\n */\n int seen_root_block = 0, bad_root_block = 0;\n\n /* Collect some stats. */\n size_t pages = 0; /* Number of hbin pages read. */\n size_t smallest_page = SIZE_MAX, largest_page = 0;\n size_t blocks = 0; /* Total number of blocks found. */\n size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;\n size_t used_blocks = 0; /* Total number of used blocks found. */\n size_t used_size = 0; /* Total size (bytes) of used blocks. */\n\n /* Read the pages and blocks. The aim here is to be robust against\n * corrupt or malicious registries. So we make sure the loops\n * always make forward progress. We add the address of each block\n * we read to a hash table so pointers will only reference the start\n * of valid blocks.\n */\n size_t off;\n struct ntreg_hbin_page *page;\n for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {\n if (off >= h->endpages)\n break;\n\n page = (struct ntreg_hbin_page *) ((char *) h->addr + off);\n if (page->magic[0] != 'h' ||\n page->magic[1] != 'b' ||\n page->magic[2] != 'i' ||\n page->magic[3] != 'n') {\n\n if (!h->unsafe) {\n SET_ERRNO (ENOTSUP,\n \"%s: trailing garbage at end of file \"\n \"(at 0x%zx, after %zu pages)\",\n filename, off, pages);\n goto error;\n }\n\n DEBUG (2,\n \"page not found at expected offset 0x%zx, \"\n \"seeking until one is found or EOF is reached\",\n off);\n\n int found = 0;\n while (off < h->size) {\n off += 0x1000;\n\n if (off >= h->endpages)\n break;\n\n page = (struct ntreg_hbin_page *) ((char *) h->addr + off);\n if (page->magic[0] == 'h' &&\n page->magic[1] == 'b' &&\n page->magic[2] == 'i' &&\n page->magic[3] == 'n') {\n DEBUG (2, \"found next page by seeking at 0x%zx\", off);\n found = 1;\n break;\n }\n }\n\n if (!found) {\n DEBUG (2, \"page not found and end of pages section reached\");\n break;\n }\n }\n\n size_t page_size = le32toh (page->page_size);\n DEBUG (2, \"page at 0x%zx, size %zu\", off, page_size);\n pages++;\n if (page_size < smallest_page) smallest_page = page_size;\n if (page_size > largest_page) largest_page = page_size;\n\n if (page_size <= sizeof (struct ntreg_hbin_page) ||\n (page_size & 0x0fff) != 0) {\n SET_ERRNO (ENOTSUP,\n \"%s: page size %zu at 0x%zx, bad registry\",\n filename, page_size, off);\n goto error;\n }\n\n if (off + page_size > h->size) {\n SET_ERRNO (ENOTSUP,\n \"%s: page size %zu at 0x%zx extends beyond end of file, bad registry\",\n filename, page_size, off);\n goto error;\n }\n\n size_t page_offset = le32toh(page->offset_first) + 0x1000;\n\n if (page_offset != off) {\n SET_ERRNO (ENOTSUP,\n \"%s: declared page offset (0x%zx) does not match computed \"\n \"offset (0x%zx), bad registry\",\n filename, page_offset, off);\n goto error;\n }\n\n /* Read the blocks in this page. */\n size_t blkoff;\n struct ntreg_hbin_block *block;\n size_t seg_len;\n for (blkoff = off + 0x20;\n blkoff < off + page_size;\n blkoff += seg_len) {\n blocks++;\n\n int is_root = blkoff == h->rootoffs;\n if (is_root)\n seen_root_block = 1;\n\n block = (struct ntreg_hbin_block *) ((char *) h->addr + blkoff);\n int used;\n seg_len = block_len (h, blkoff, &used);\n/* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78665 */\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wstrict-overflow\"\n if (seg_len <= 4 || (seg_len & 3) != 0) {\n#pragma GCC diagnostic pop\n if (is_root || !h->unsafe) {\n SET_ERRNO (ENOTSUP,\n \"%s, the block at 0x%zx has invalid size %\" PRIu32\n \", bad registry\",\n filename, blkoff, le32toh (block->seg_len));\n goto error;\n } else {\n DEBUG (2,\n \"%s: block at 0x%zx has invalid size %\" PRIu32 \", skipping\",\n filename, blkoff, le32toh (block->seg_len));\n break;\n }\n }\n\n if (h->msglvl >= 2) {\n unsigned char *id = (unsigned char *) block->id;\n int id0 = id[0], id1 = id[1];\n\n fprintf (stderr, \"%s: %s: \"\n \"%s block id %d,%d (%c%c) at 0x%zx size %zu%s\\n\",\n \"hivex\", __func__,\n used ? \"used\" : \"free\",\n id0, id1,\n c_isprint (id0) ? id0 : '.',\n c_isprint (id1) ? id1 : '.',\n blkoff,\n seg_len, is_root ? \" (root)\" : \"\");\n }\n\n blocks_bytes += seg_len;\n if (seg_len < smallest_block) smallest_block = seg_len;\n if (seg_len > largest_block) largest_block = seg_len;\n\n if (is_root && !used)\n bad_root_block = 1;\n\n if (used) {\n used_blocks++;\n used_size += seg_len;\n\n /* Root block must be an nk-block. */\n if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))\n bad_root_block = 1;\n\n /* Note this blkoff is a valid address. */\n BITMAP_SET (h->bitmap, blkoff);\n }\n }\n }\n\n if (!seen_root_block) {\n SET_ERRNO (ENOTSUP, \"%s: no root block found\", filename);\n goto error;\n }\n\n if (bad_root_block) {\n SET_ERRNO (ENOTSUP, \"%s: bad root block (free or not nk)\", filename);\n goto error;\n }\n\n DEBUG (1, \"successfully read Windows Registry hive file:\\n\"\n \" pages: %zu [sml: %zu, lge: %zu]\\n\"\n \" blocks: %zu [sml: %zu, avg: %zu, lge: %zu]\\n\"\n \" blocks used: %zu\\n\"\n \" bytes used: %zu\",\n pages, smallest_page, largest_page,\n blocks, smallest_block, blocks_bytes / blocks, largest_block,\n used_blocks, used_size);\n\n return h;\n\n error:;\n int err = errno;\n if (h) {\n free (h->bitmap);\n if (h->addr && h->size && h->addr != MAP_FAILED) {\n if (!h->writable)\n munmap (h->addr, h->size);\n else\n free (h->addr);\n }\n if (h->fd >= 0)\n close (h->fd);\n free (h->filename);\n free (h);\n }\n errno = err;\n return NULL;\n}", "project": "hivex", "hash": 255254112256589566988814098457378736252, "size": 349, "commit_id": "8f1935733b10d974a1a4176d38dd151ed98cf381", "message": "lib/handle.c: Bounds check for block exceeding page length (CVE-2021-3504)\n\nHives are encoded as fixed-sized pages containing smaller variable-\nlength blocks:\n\n +-------------------+-------------------+-------------------+--\n | header |[ blk ][blk][ blk ]|[blk][blk][blk] |\n +-------------------+-------------------+-------------------+--\n\nBlocks should not straddle a page boundary. However because blocks\ncontain a 32 bit length field it is possible to construct an invalid\nhive where the last block in a page overlaps either the next page or\nthe end of the file:\n\n +-------------------+-------------------+\n | header |[ blk ][blk][ blk ..... ]\n +-------------------+-------------------+\n\nHivex lacked a bounds check and would process the registry. Because\nthe rest of the code assumes this situation can never happen it was\npossible to have a block containing some field (eg. a registry key\nname) which would extend beyond the end of the file. Hivex mmaps or\nmallocs the file, causing hivex to read memory beyond the end of the\nmapped region, resulting in reading other memory structures or a\ncrash. (Writing beyond the end of the mapped region seems to be\nimpossible because we always allocate a new page before writing.)\n\nThis commit adds a check which rejects the malformed registry on\nhivex_open.\n\nCredit: Jeremy Galindo, Sr Security Engineer, Datto.com\nSigned-off-by: Richard W.M. Jones \nFixes: CVE-2021-3504\nFixes: https://bugzilla.redhat.com/show_bug.cgi?id=1949687", "target": 1, "dataset": "other", "idx": 205584} {"func": "hivex_open (const char *filename, int flags)\n{\n hive_h *h = NULL;\n\n assert (sizeof (struct ntreg_header) == 0x1000);\n assert (offsetof (struct ntreg_header, csum) == 0x1fc);\n\n h = calloc (1, sizeof *h);\n if (h == NULL)\n goto error;\n\n h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK;\n\n const char *debug = getenv (\"HIVEX_DEBUG\");\n if (debug && STREQ (debug, \"1\"))\n h->msglvl = 2;\n\n DEBUG (2, \"created handle %p\", h);\n\n h->writable = !!(flags & HIVEX_OPEN_WRITE);\n h->unsafe = !!(flags & HIVEX_OPEN_UNSAFE);\n h->filename = strdup (filename);\n if (h->filename == NULL)\n goto error;\n\n#ifdef O_CLOEXEC\n h->fd = open (filename, O_RDONLY | O_CLOEXEC | O_BINARY);\n#else\n h->fd = open (filename, O_RDONLY | O_BINARY);\n#endif\n if (h->fd == -1)\n goto error;\n#ifndef O_CLOEXEC\n fcntl (h->fd, F_SETFD, FD_CLOEXEC);\n#endif\n\n struct stat statbuf;\n if (fstat (h->fd, &statbuf) == -1)\n goto error;\n\n h->size = statbuf.st_size;\n\n if (h->size < 0x2000) {\n SET_ERRNO (EINVAL,\n \"%s: file is too small to be a Windows NT Registry hive file\",\n filename);\n goto error;\n }\n\n if (!h->writable) {\n h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);\n if (h->addr == MAP_FAILED)\n goto error;\n\n DEBUG (2, \"mapped file at %p\", h->addr);\n } else {\n h->addr = malloc (h->size);\n if (h->addr == NULL)\n goto error;\n\n if (full_read (h->fd, h->addr, h->size) < h->size)\n goto error;\n\n /* We don't need the file descriptor along this path, since we\n * have read all the data.\n */\n if (close (h->fd) == -1)\n goto error;\n h->fd = -1;\n }\n\n /* Check header. */\n if (h->hdr->magic[0] != 'r' ||\n h->hdr->magic[1] != 'e' ||\n h->hdr->magic[2] != 'g' ||\n h->hdr->magic[3] != 'f') {\n SET_ERRNO (ENOTSUP,\n \"%s: not a Windows NT Registry hive file\", filename);\n goto error;\n }\n\n /* Check major version. */\n uint32_t major_ver = le32toh (h->hdr->major_ver);\n if (major_ver != 1) {\n SET_ERRNO (ENOTSUP,\n \"%s: hive file major version %\" PRIu32 \" (expected 1)\",\n filename, major_ver);\n goto error;\n }\n\n h->bitmap = calloc (1 + h->size / 32, 1);\n if (h->bitmap == NULL)\n goto error;\n\n /* Header checksum. */\n uint32_t sum = header_checksum (h);\n if (sum != le32toh (h->hdr->csum)) {\n SET_ERRNO (EINVAL, \"%s: bad checksum in hive header\", filename);\n goto error;\n }\n\n for (int t=0; ticonv_cache[t].mutex);\n h->iconv_cache[t].handle = NULL;\n }\n\n /* Last modified time. */\n h->last_modified = le64toh ((int64_t) h->hdr->last_modified);\n\n if (h->msglvl >= 2) {\n char *name = _hivex_recode (h, utf16le_to_utf8,\n h->hdr->name, 64, NULL);\n\n fprintf (stderr,\n \"hivex_open: header fields:\\n\"\n \" file version %\" PRIu32 \".%\" PRIu32 \"\\n\"\n \" sequence nos %\" PRIu32 \" %\" PRIu32 \"\\n\"\n \" (sequences nos should match if hive was synched at shutdown)\\n\"\n \" last modified %\" PRIi64 \"\\n\"\n \" (Windows filetime, x 100 ns since 1601-01-01)\\n\"\n \" original file name %s\\n\"\n \" (only 32 chars are stored, name is probably truncated)\\n\"\n \" root offset 0x%x + 0x1000\\n\"\n \" end of last page 0x%x + 0x1000 (total file size 0x%zx)\\n\"\n \" checksum 0x%x (calculated 0x%x)\\n\",\n major_ver, le32toh (h->hdr->minor_ver),\n le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),\n h->last_modified,\n name ? name : \"(conversion failed)\",\n le32toh (h->hdr->offset),\n le32toh (h->hdr->blocks), h->size,\n le32toh (h->hdr->csum), sum);\n free (name);\n }\n\n h->rootoffs = le32toh (h->hdr->offset) + 0x1000;\n h->endpages = le32toh (h->hdr->blocks) + 0x1000;\n\n DEBUG (2, \"root offset = 0x%zx\", h->rootoffs);\n\n /* We'll set this flag when we see a block with the root offset (ie.\n * the root block).\n */\n int seen_root_block = 0, bad_root_block = 0;\n\n /* Collect some stats. */\n size_t pages = 0; /* Number of hbin pages read. */\n size_t smallest_page = SIZE_MAX, largest_page = 0;\n size_t blocks = 0; /* Total number of blocks found. */\n size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;\n size_t used_blocks = 0; /* Total number of used blocks found. */\n size_t used_size = 0; /* Total size (bytes) of used blocks. */\n\n /* Read the pages and blocks. The aim here is to be robust against\n * corrupt or malicious registries. So we make sure the loops\n * always make forward progress. We add the address of each block\n * we read to a hash table so pointers will only reference the start\n * of valid blocks.\n */\n size_t off;\n struct ntreg_hbin_page *page;\n for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {\n if (off >= h->endpages)\n break;\n\n page = (struct ntreg_hbin_page *) ((char *) h->addr + off);\n if (page->magic[0] != 'h' ||\n page->magic[1] != 'b' ||\n page->magic[2] != 'i' ||\n page->magic[3] != 'n') {\n\n if (!h->unsafe) {\n SET_ERRNO (ENOTSUP,\n \"%s: trailing garbage at end of file \"\n \"(at 0x%zx, after %zu pages)\",\n filename, off, pages);\n goto error;\n }\n\n DEBUG (2,\n \"page not found at expected offset 0x%zx, \"\n \"seeking until one is found or EOF is reached\",\n off);\n\n int found = 0;\n while (off < h->size) {\n off += 0x1000;\n\n if (off >= h->endpages)\n break;\n\n page = (struct ntreg_hbin_page *) ((char *) h->addr + off);\n if (page->magic[0] == 'h' &&\n page->magic[1] == 'b' &&\n page->magic[2] == 'i' &&\n page->magic[3] == 'n') {\n DEBUG (2, \"found next page by seeking at 0x%zx\", off);\n found = 1;\n break;\n }\n }\n\n if (!found) {\n DEBUG (2, \"page not found and end of pages section reached\");\n break;\n }\n }\n\n size_t page_size = le32toh (page->page_size);\n DEBUG (2, \"page at 0x%zx, size %zu\", off, page_size);\n pages++;\n if (page_size < smallest_page) smallest_page = page_size;\n if (page_size > largest_page) largest_page = page_size;\n\n if (page_size <= sizeof (struct ntreg_hbin_page) ||\n (page_size & 0x0fff) != 0) {\n SET_ERRNO (ENOTSUP,\n \"%s: page size %zu at 0x%zx, bad registry\",\n filename, page_size, off);\n goto error;\n }\n\n if (off + page_size > h->size) {\n SET_ERRNO (ENOTSUP,\n \"%s: page size %zu at 0x%zx extends beyond end of file, bad registry\",\n filename, page_size, off);\n goto error;\n }\n\n size_t page_offset = le32toh(page->offset_first) + 0x1000;\n\n if (page_offset != off) {\n SET_ERRNO (ENOTSUP,\n \"%s: declared page offset (0x%zx) does not match computed \"\n \"offset (0x%zx), bad registry\",\n filename, page_offset, off);\n goto error;\n }\n\n /* Read the blocks in this page. */\n size_t blkoff;\n struct ntreg_hbin_block *block;\n size_t seg_len;\n for (blkoff = off + 0x20;\n blkoff < off + page_size;\n blkoff += seg_len) {\n blocks++;\n\n int is_root = blkoff == h->rootoffs;\n if (is_root)\n seen_root_block = 1;\n\n block = (struct ntreg_hbin_block *) ((char *) h->addr + blkoff);\n int used;\n seg_len = block_len (h, blkoff, &used);\n/* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78665 */\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wstrict-overflow\"\n if (seg_len <= 4 || (seg_len & 3) != 0) {\n#pragma GCC diagnostic pop\n if (is_root || !h->unsafe) {\n SET_ERRNO (ENOTSUP,\n \"%s, the block at 0x%zx size %\" PRIu32\n \" <= 4 or not a multiple of 4, bad registry\",\n filename, blkoff, le32toh (block->seg_len));\n goto error;\n } else {\n DEBUG (2,\n \"%s: block at 0x%zx has invalid size %\" PRIu32 \", skipping\",\n filename, blkoff, le32toh (block->seg_len));\n break;\n }\n }\n\n if (blkoff + seg_len > off + page_size) {\n SET_ERRNO (ENOTSUP,\n \"%s, the block at 0x%zx size %\" PRIu32\n \" extends beyond the current page, bad registry\",\n filename, blkoff, le32toh (block->seg_len));\n goto error;\n }\n\n if (h->msglvl >= 2) {\n unsigned char *id = (unsigned char *) block->id;\n int id0 = id[0], id1 = id[1];\n\n fprintf (stderr, \"%s: %s: \"\n \"%s block id %d,%d (%c%c) at 0x%zx size %zu%s\\n\",\n \"hivex\", __func__,\n used ? \"used\" : \"free\",\n id0, id1,\n c_isprint (id0) ? id0 : '.',\n c_isprint (id1) ? id1 : '.',\n blkoff,\n seg_len, is_root ? \" (root)\" : \"\");\n }\n\n blocks_bytes += seg_len;\n if (seg_len < smallest_block) smallest_block = seg_len;\n if (seg_len > largest_block) largest_block = seg_len;\n\n if (is_root && !used)\n bad_root_block = 1;\n\n if (used) {\n used_blocks++;\n used_size += seg_len;\n\n /* Root block must be an nk-block. */\n if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))\n bad_root_block = 1;\n\n /* Note this blkoff is a valid address. */\n BITMAP_SET (h->bitmap, blkoff);\n }\n }\n }\n\n if (!seen_root_block) {\n SET_ERRNO (ENOTSUP, \"%s: no root block found\", filename);\n goto error;\n }\n\n if (bad_root_block) {\n SET_ERRNO (ENOTSUP, \"%s: bad root block (free or not nk)\", filename);\n goto error;\n }\n\n DEBUG (1, \"successfully read Windows Registry hive file:\\n\"\n \" pages: %zu [sml: %zu, lge: %zu]\\n\"\n \" blocks: %zu [sml: %zu, avg: %zu, lge: %zu]\\n\"\n \" blocks used: %zu\\n\"\n \" bytes used: %zu\",\n pages, smallest_page, largest_page,\n blocks, smallest_block, blocks_bytes / blocks, largest_block,\n used_blocks, used_size);\n\n return h;\n\n error:;\n int err = errno;\n if (h) {\n free (h->bitmap);\n if (h->addr && h->size && h->addr != MAP_FAILED) {\n if (!h->writable)\n munmap (h->addr, h->size);\n else\n free (h->addr);\n }\n if (h->fd >= 0)\n close (h->fd);\n free (h->filename);\n free (h);\n }\n errno = err;\n return NULL;\n}", "project": "hivex", "hash": 191982106855348682819795174886766010383, "size": 357, "commit_id": "8f1935733b10d974a1a4176d38dd151ed98cf381", "message": "lib/handle.c: Bounds check for block exceeding page length (CVE-2021-3504)\n\nHives are encoded as fixed-sized pages containing smaller variable-\nlength blocks:\n\n +-------------------+-------------------+-------------------+--\n | header |[ blk ][blk][ blk ]|[blk][blk][blk] |\n +-------------------+-------------------+-------------------+--\n\nBlocks should not straddle a page boundary. However because blocks\ncontain a 32 bit length field it is possible to construct an invalid\nhive where the last block in a page overlaps either the next page or\nthe end of the file:\n\n +-------------------+-------------------+\n | header |[ blk ][blk][ blk ..... ]\n +-------------------+-------------------+\n\nHivex lacked a bounds check and would process the registry. Because\nthe rest of the code assumes this situation can never happen it was\npossible to have a block containing some field (eg. a registry key\nname) which would extend beyond the end of the file. Hivex mmaps or\nmallocs the file, causing hivex to read memory beyond the end of the\nmapped region, resulting in reading other memory structures or a\ncrash. (Writing beyond the end of the mapped region seems to be\nimpossible because we always allocate a new page before writing.)\n\nThis commit adds a check which rejects the malformed registry on\nhivex_open.\n\nCredit: Jeremy Galindo, Sr Security Engineer, Datto.com\nSigned-off-by: Richard W.M. Jones \nFixes: CVE-2021-3504\nFixes: https://bugzilla.redhat.com/show_bug.cgi?id=1949687", "target": 0, "dataset": "other", "idx": 368604} {"func": "static inline void ConvertLuvToXYZ(const double L,const double u,const double v,\n double *X,double *Y,double *Z)\n{\n double\n gamma;\n\n assert(X != (double *) NULL);\n assert(Y != (double *) NULL);\n assert(Z != (double *) NULL);\n if (L > (CIEK*CIEEpsilon))\n *Y=(double) pow((L+16.0)/116.0,3.0);\n else\n *Y=L/CIEK;\n gamma=PerceptibleReciprocal((((52.0*L/(u+13.0*L*(4.0*D65X/(D65X+15.0*D65Y+\n 3.0*D65Z))))-1.0)/3.0)-(-1.0/3.0));\n *X=gamma*((*Y*((39.0*L/(v+13.0*L*(9.0*D65Y/(D65X+15.0*D65Y+3.0*D65Z))))-5.0))+\n 5.0*(*Y));\n *Z=(*X*(((52.0*L/(u+13.0*L*(4.0*D65X/(D65X+15.0*D65Y+3.0*D65Z))))-1.0)/3.0))-\n 5.0*(*Y);\n}", "project": "ImageMagick", "hash": 38417910825899276057542672543600594750, "size": 20, "commit_id": "a855d3ad660f307fdb071794351822f9ce878c4e", "message": "https://github.com/ImageMagick/ImageMagick/issues/3317", "target": 1, "dataset": "other", "idx": 205631} {"func": "static inline void ConvertLuvToXYZ(const double L,const double u,const double v,\n double *X,double *Y,double *Z)\n{\n double\n gamma;\n\n assert(X != (double *) NULL);\n assert(Y != (double *) NULL);\n assert(Z != (double *) NULL);\n if (L > (CIEK*CIEEpsilon))\n *Y=(double) pow((L+16.0)/116.0,3.0);\n else\n *Y=L/CIEK;\n gamma=PerceptibleReciprocal((((52.0*L*PerceptibleReciprocal(u+13.0*L*\n (4.0*D65X/(D65X+15.0*D65Y+3.0*D65Z))))-1.0)/3.0)-(-1.0/3.0));\n *X=gamma*((*Y*((39.0*L*PerceptibleReciprocal(v+13.0*L*(9.0*D65Y/\n (D65X+15.0*D65Y+3.0*D65Z))))-5.0))+5.0*(*Y));\n *Z=(*X*(((52.0*L*PerceptibleReciprocal(u+13.0*L*(4.0*D65X/\n (D65X+15.0*D65Y+3.0*D65Z))))-1.0)/3.0))-5.0*(*Y);\n}", "project": "ImageMagick", "hash": 187280963848298459107445613020860070554, "size": 20, "commit_id": "a855d3ad660f307fdb071794351822f9ce878c4e", "message": "https://github.com/ImageMagick/ImageMagick/issues/3317", "target": 0, "dataset": "other", "idx": 369443} {"func": "Value ExpressionArrayToObject::evaluate(const Document& root, Variables* variables) const {\n const Value input = _children[0]->evaluate(root, variables);\n if (input.nullish()) {\n return Value(BSONNULL);\n }\n\n uassert(40386,\n str::stream() << \"$arrayToObject requires an array input, found: \"\n << typeName(input.getType()),\n input.isArray());\n\n MutableDocument output;\n const vector& array = input.getArray();\n if (array.empty()) {\n return output.freezeToValue();\n }\n\n // There are two accepted input formats in an array: [ [key, val] ] or [ {k:key, v:val} ]. The\n // first array element determines the format for the rest of the array. Mixing input formats is\n // not allowed.\n bool inputArrayFormat;\n if (array[0].isArray()) {\n inputArrayFormat = true;\n } else if (array[0].getType() == BSONType::Object) {\n inputArrayFormat = false;\n } else {\n uasserted(40398,\n str::stream() << \"Unrecognised input type format for $arrayToObject: \"\n << typeName(array[0].getType()));\n }\n\n for (auto&& elem : array) {\n if (inputArrayFormat == true) {\n uassert(\n 40396,\n str::stream() << \"$arrayToObject requires a consistent input format. Elements must\"\n \"all be arrays or all be objects. Array was detected, now found: \"\n << typeName(elem.getType()),\n elem.isArray());\n\n const vector& valArray = elem.getArray();\n\n uassert(40397,\n str::stream() << \"$arrayToObject requires an array of size 2 arrays,\"\n \"found array of size: \"\n << valArray.size(),\n (valArray.size() == 2));\n\n uassert(40395,\n str::stream() << \"$arrayToObject requires an array of key-value pairs, where \"\n \"the key must be of type string. Found key type: \"\n << typeName(valArray[0].getType()),\n (valArray[0].getType() == BSONType::String));\n\n output[valArray[0].getString()] = valArray[1];\n\n } else {\n uassert(\n 40391,\n str::stream() << \"$arrayToObject requires a consistent input format. Elements must\"\n \"all be arrays or all be objects. Object was detected, now found: \"\n << typeName(elem.getType()),\n (elem.getType() == BSONType::Object));\n\n uassert(40392,\n str::stream() << \"$arrayToObject requires an object keys of 'k' and 'v'. \"\n \"Found incorrect number of keys:\"\n << elem.getDocument().computeSize(),\n (elem.getDocument().computeSize() == 2));\n\n Value key = elem.getDocument().getField(\"k\");\n Value value = elem.getDocument().getField(\"v\");\n\n uassert(40393,\n str::stream() << \"$arrayToObject requires an object with keys 'k' and 'v'. \"\n \"Missing either or both keys from: \"\n << elem.toString(),\n (!key.missing() && !value.missing()));\n\n uassert(\n 40394,\n str::stream() << \"$arrayToObject requires an object with keys 'k' and 'v', where \"\n \"the value of 'k' must be of type string. Found type: \"\n << typeName(key.getType()),\n (key.getType() == BSONType::String));\n\n output[key.getString()] = value;\n }\n }\n\n return output.freezeToValue();\n}", "project": "mongo", "hash": 251402268363123730144063928657664987891, "size": 92, "commit_id": "1772b9a0393b55e6a280a35e8f0a1f75c014f301", "message": "SERVER-49404 Enforce additional checks in $arrayToObject", "target": 1, "dataset": "other", "idx": 205669} {"func": "Value ExpressionArrayToObject::evaluate(const Document& root, Variables* variables) const {\n const Value input = _children[0]->evaluate(root, variables);\n if (input.nullish()) {\n return Value(BSONNULL);\n }\n\n uassert(40386,\n str::stream() << \"$arrayToObject requires an array input, found: \"\n << typeName(input.getType()),\n input.isArray());\n\n MutableDocument output;\n const vector& array = input.getArray();\n if (array.empty()) {\n return output.freezeToValue();\n }\n\n // There are two accepted input formats in an array: [ [key, val] ] or [ {k:key, v:val} ]. The\n // first array element determines the format for the rest of the array. Mixing input formats is\n // not allowed.\n bool inputArrayFormat;\n if (array[0].isArray()) {\n inputArrayFormat = true;\n } else if (array[0].getType() == BSONType::Object) {\n inputArrayFormat = false;\n } else {\n uasserted(40398,\n str::stream() << \"Unrecognised input type format for $arrayToObject: \"\n << typeName(array[0].getType()));\n }\n\n for (auto&& elem : array) {\n if (inputArrayFormat == true) {\n uassert(\n 40396,\n str::stream() << \"$arrayToObject requires a consistent input format. Elements must\"\n \"all be arrays or all be objects. Array was detected, now found: \"\n << typeName(elem.getType()),\n elem.isArray());\n\n const vector& valArray = elem.getArray();\n\n uassert(40397,\n str::stream() << \"$arrayToObject requires an array of size 2 arrays,\"\n \"found array of size: \"\n << valArray.size(),\n (valArray.size() == 2));\n\n uassert(40395,\n str::stream() << \"$arrayToObject requires an array of key-value pairs, where \"\n \"the key must be of type string. Found key type: \"\n << typeName(valArray[0].getType()),\n (valArray[0].getType() == BSONType::String));\n\n auto keyName = valArray[0].getStringData();\n\n uassert(4940400,\n \"Key field cannot contain an embedded null byte\",\n keyName.find('\\0') == std::string::npos);\n\n output[keyName] = valArray[1];\n\n } else {\n uassert(\n 40391,\n str::stream() << \"$arrayToObject requires a consistent input format. Elements must\"\n \"all be arrays or all be objects. Object was detected, now found: \"\n << typeName(elem.getType()),\n (elem.getType() == BSONType::Object));\n\n uassert(40392,\n str::stream() << \"$arrayToObject requires an object keys of 'k' and 'v'. \"\n \"Found incorrect number of keys:\"\n << elem.getDocument().computeSize(),\n (elem.getDocument().computeSize() == 2));\n\n Value key = elem.getDocument().getField(\"k\");\n Value value = elem.getDocument().getField(\"v\");\n\n uassert(40393,\n str::stream() << \"$arrayToObject requires an object with keys 'k' and 'v'. \"\n \"Missing either or both keys from: \"\n << elem.toString(),\n (!key.missing() && !value.missing()));\n\n uassert(\n 40394,\n str::stream() << \"$arrayToObject requires an object with keys 'k' and 'v', where \"\n \"the value of 'k' must be of type string. Found type: \"\n << typeName(key.getType()),\n (key.getType() == BSONType::String));\n\n auto keyName = key.getStringData();\n\n uassert(4940401,\n \"Key field cannot contain an embedded null byte\",\n keyName.find('\\0') == std::string::npos);\n\n output[keyName] = value;\n }\n }\n\n return output.freezeToValue();\n}", "project": "mongo", "hash": 32132725791897768420289240736903683617, "size": 104, "commit_id": "1772b9a0393b55e6a280a35e8f0a1f75c014f301", "message": "SERVER-49404 Enforce additional checks in $arrayToObject", "target": 0, "dataset": "other", "idx": 370060} {"func": "static MSUSB_PIPE_DESCRIPTOR** msusb_mspipes_read(wStream* s, UINT32 NumberOfPipes)\n{\n\tUINT32 pnum;\n\tMSUSB_PIPE_DESCRIPTOR** MsPipes;\n\n\tif (Stream_GetRemainingCapacity(s) < 12 * NumberOfPipes)\n\t\treturn NULL;\n\n\tMsPipes = (MSUSB_PIPE_DESCRIPTOR**)calloc(NumberOfPipes, sizeof(MSUSB_PIPE_DESCRIPTOR*));\n\n\tif (!MsPipes)\n\t\treturn NULL;\n\n\tfor (pnum = 0; pnum < NumberOfPipes; pnum++)\n\t{\n\t\tMSUSB_PIPE_DESCRIPTOR* MsPipe = msusb_mspipe_new();\n\n\t\tif (!MsPipe)\n\t\t\tgoto out_error;\n\n\t\tStream_Read_UINT16(s, MsPipe->MaximumPacketSize);\n\t\tStream_Seek(s, 2);\n\t\tStream_Read_UINT32(s, MsPipe->MaximumTransferSize);\n\t\tStream_Read_UINT32(s, MsPipe->PipeFlags);\n\t\t/* Already set to zero by memset\n\t\t MsPipe->PipeHandle\t = 0;\n\t\t MsPipe->bEndpointAddress = 0;\n\t\t MsPipe->bInterval\t\t= 0;\n\t\t MsPipe->PipeType\t\t = 0;\n\t\t MsPipe->InitCompleted\t= 0;\n\t\t*/\n\t\tMsPipes[pnum] = MsPipe;\n\t}\n\n\treturn MsPipes;\nout_error:\n\n\tfor (pnum = 0; pnum < NumberOfPipes; pnum++)\n\t\tfree(MsPipes[pnum]);\n\n\tfree(MsPipes);\n\treturn NULL;\n}", "project": "FreeRDP", "hash": 43522950749896036127664697861930743417, "size": 43, "commit_id": "9f77fc3dd2394373e1be753952b00dafa1a9b7da", "message": "Fixed int overflow in msusb_mspipes_read\n\nThanks to hac425", "target": 1, "dataset": "other", "idx": 205671} {"func": "static MSUSB_PIPE_DESCRIPTOR** msusb_mspipes_read(wStream* s, UINT32 NumberOfPipes)\n{\n\tUINT32 pnum;\n\tMSUSB_PIPE_DESCRIPTOR** MsPipes;\n\n\tif (Stream_GetRemainingCapacity(s) / 12 < NumberOfPipes)\n\t\treturn NULL;\n\n\tMsPipes = (MSUSB_PIPE_DESCRIPTOR**)calloc(NumberOfPipes, sizeof(MSUSB_PIPE_DESCRIPTOR*));\n\n\tif (!MsPipes)\n\t\treturn NULL;\n\n\tfor (pnum = 0; pnum < NumberOfPipes; pnum++)\n\t{\n\t\tMSUSB_PIPE_DESCRIPTOR* MsPipe = msusb_mspipe_new();\n\n\t\tif (!MsPipe)\n\t\t\tgoto out_error;\n\n\t\tStream_Read_UINT16(s, MsPipe->MaximumPacketSize);\n\t\tStream_Seek(s, 2);\n\t\tStream_Read_UINT32(s, MsPipe->MaximumTransferSize);\n\t\tStream_Read_UINT32(s, MsPipe->PipeFlags);\n\t\t/* Already set to zero by memset\n\t\t MsPipe->PipeHandle\t = 0;\n\t\t MsPipe->bEndpointAddress = 0;\n\t\t MsPipe->bInterval\t\t= 0;\n\t\t MsPipe->PipeType\t\t = 0;\n\t\t MsPipe->InitCompleted\t= 0;\n\t\t*/\n\t\tMsPipes[pnum] = MsPipe;\n\t}\n\n\treturn MsPipes;\nout_error:\n\n\tfor (pnum = 0; pnum < NumberOfPipes; pnum++)\n\t\tfree(MsPipes[pnum]);\n\n\tfree(MsPipes);\n\treturn NULL;\n}", "project": "FreeRDP", "hash": 327097256253608261746407166636662999864, "size": 43, "commit_id": "9f77fc3dd2394373e1be753952b00dafa1a9b7da", "message": "Fixed int overflow in msusb_mspipes_read\n\nThanks to hac425", "target": 0, "dataset": "other", "idx": 370198} {"func": "static MagickBooleanType WriteAnimatedWEBPImage(const ImageInfo *image_info,\n Image *image,WebPConfig *configure,WebPMemoryWriter *writer_info,\n ExceptionInfo *exception)\n{\n Image\n *first_image;\n\n PictureMemory\n *current,\n *head;\n\n size_t\n effective_delta = 0,\n frame_timestamp = 0;\n\n WebPAnimEncoder\n *enc;\n\n WebPAnimEncoderOptions\n enc_options;\n\n WebPData\n webp_data;\n\n WebPPicture\n picture;\n\n WebPAnimEncoderOptionsInit(&enc_options);\n if (image_info->verbose)\n enc_options.verbose = 1;\n\n image=CoalesceImages(image, exception);\n first_image=image;\n enc=WebPAnimEncoderNew((int) image->page.width,(int) image->page.height,\n &enc_options);\n\n head=(PictureMemory *) calloc(sizeof(*head),1);\n current=head;\n\n while (image != NULL)\n {\n if (WebPPictureInit(&picture) == 0)\n ThrowWriterException(ResourceLimitError,\"UnableToEncodeImageFile\");\n\n WriteSingleWEBPImage(image_info, image, &picture, current, exception);\n\n effective_delta = image->delay*1000/image->ticks_per_second;\n if (effective_delta < 10)\n effective_delta = 100; /* Consistent with gif2webp */\n frame_timestamp+=effective_delta;\n\n WebPAnimEncoderAdd(enc,&picture,(int) frame_timestamp,configure);\n\n image = GetNextImageInList(image);\n current->next=(PictureMemory *) calloc(sizeof(*head), 1);\n current = current->next;\n }\n webp_data.bytes=writer_info->mem;\n webp_data.size=writer_info->size;\n WebPAnimEncoderAssemble(enc, &webp_data);\n WebPMemoryWriterClear(writer_info);\n writer_info->size=webp_data.size;\n writer_info->mem=(unsigned char *) webp_data.bytes;\n WebPAnimEncoderDelete(enc);\n DestroyImageList(first_image);\n FreePictureMemoryList(head);\n return(MagickTrue);\n}", "project": "ImageMagick6", "hash": 88540247361010854619934050091886652539, "size": 68, "commit_id": "a78d92dc0f468e79c3d761aae9707042952cdaca", "message": "https://github.com/ImageMagick/ImageMagick/issues/3176", "target": 1, "dataset": "other", "idx": 205720} {"func": "static MagickBooleanType WriteAnimatedWEBPImage(const ImageInfo *image_info,\n Image *image,WebPConfig *configure,WebPMemoryWriter *writer_info,\n ExceptionInfo *exception)\n{\n Image\n *first_image;\n\n PictureMemory\n *current,\n *head;\n\n size_t\n effective_delta = 0,\n frame_timestamp = 0;\n\n WebPAnimEncoder\n *enc;\n\n WebPAnimEncoderOptions\n enc_options;\n\n WebPData\n webp_data;\n\n WebPPicture\n picture;\n\n WebPAnimEncoderOptionsInit(&enc_options);\n if (image_info->verbose)\n enc_options.verbose = 1;\n\n image=CoalesceImages(image, exception);\n first_image=image;\n enc=WebPAnimEncoderNew((int) image->page.width,(int) image->page.height,\n &enc_options);\n\n head=(PictureMemory *) calloc(sizeof(*head),1);\n current=head;\n\n while (image != NULL)\n {\n if (WebPPictureInit(&picture) == 0)\n ThrowWriterException(ResourceLimitError,\"UnableToEncodeImageFile\");\n\n WriteSingleWEBPImage(image_info, image, &picture, current, exception);\n\n effective_delta = image->delay*1000*PerceptibleReciprocal(\n image->ticks_per_second);\n if (effective_delta < 10)\n effective_delta = 100; /* Consistent with gif2webp */\n frame_timestamp+=effective_delta;\n\n WebPAnimEncoderAdd(enc,&picture,(int) frame_timestamp,configure);\n\n image = GetNextImageInList(image);\n current->next=(PictureMemory *) calloc(sizeof(*head), 1);\n current = current->next;\n }\n webp_data.bytes=writer_info->mem;\n webp_data.size=writer_info->size;\n WebPAnimEncoderAssemble(enc, &webp_data);\n WebPMemoryWriterClear(writer_info);\n writer_info->size=webp_data.size;\n writer_info->mem=(unsigned char *) webp_data.bytes;\n WebPAnimEncoderDelete(enc);\n DestroyImageList(first_image);\n FreePictureMemoryList(head);\n return(MagickTrue);\n}", "project": "ImageMagick6", "hash": 184885542608773702111101964268936553139, "size": 69, "commit_id": "a78d92dc0f468e79c3d761aae9707042952cdaca", "message": "https://github.com/ImageMagick/ImageMagick/issues/3176", "target": 0, "dataset": "other", "idx": 370809} {"func": "MagickExport double GenerateDifferentialNoise(RandomInfo *random_info,\n const Quantum pixel,const NoiseType noise_type,const MagickRealType attenuate)\n{\n#define SigmaUniform (attenuate*0.015625)\n#define SigmaGaussian (attenuate*0.015625)\n#define SigmaImpulse (attenuate*0.1)\n#define SigmaLaplacian (attenuate*0.0390625)\n#define SigmaMultiplicativeGaussian (attenuate*0.5)\n#define SigmaPoisson (attenuate*12.5)\n#define SigmaRandom (attenuate)\n#define TauGaussian (attenuate*0.078125)\n\n double\n alpha,\n beta,\n noise,\n sigma;\n\n alpha=GetPseudoRandomValue(random_info);\n switch (noise_type)\n {\n case UniformNoise:\n default:\n {\n noise=(double) (pixel+QuantumRange*SigmaUniform*(alpha-0.5));\n break;\n }\n case GaussianNoise:\n {\n double\n gamma,\n tau;\n\n if (fabs(alpha) < MagickEpsilon)\n alpha=1.0;\n beta=GetPseudoRandomValue(random_info);\n gamma=sqrt(-2.0*log(alpha));\n sigma=gamma*cos((double) (2.0*MagickPI*beta));\n tau=gamma*sin((double) (2.0*MagickPI*beta));\n noise=(double) (pixel+sqrt((double) pixel)*SigmaGaussian*sigma+\n QuantumRange*TauGaussian*tau);\n break;\n }\n case ImpulseNoise:\n {\n if (alpha < (SigmaImpulse/2.0))\n noise=0.0;\n else\n if (alpha >= (1.0-(SigmaImpulse/2.0)))\n noise=(double) QuantumRange;\n else\n noise=(double) pixel;\n break;\n }\n case LaplacianNoise:\n {\n if (alpha <= 0.5)\n {\n if (alpha <= MagickEpsilon)\n noise=(double) (pixel-QuantumRange);\n else\n noise=(double) (pixel+QuantumRange*SigmaLaplacian*log(2.0*alpha)+\n 0.5);\n break;\n }\n beta=1.0-alpha;\n if (beta <= (0.5*MagickEpsilon))\n noise=(double) (pixel+QuantumRange);\n else\n noise=(double) (pixel-QuantumRange*SigmaLaplacian*log(2.0*beta)+0.5);\n break;\n }\n case MultiplicativeGaussianNoise:\n {\n sigma=1.0;\n if (alpha > MagickEpsilon)\n sigma=sqrt(-2.0*log(alpha));\n beta=GetPseudoRandomValue(random_info);\n noise=(double) (pixel+pixel*SigmaMultiplicativeGaussian*sigma*\n cos((double) (2.0*MagickPI*beta))/2.0);\n break;\n }\n case PoissonNoise:\n {\n double\n poisson;\n\n ssize_t\n i;\n\n poisson=exp(-SigmaPoisson*QuantumScale*pixel);\n for (i=0; alpha > poisson; i++)\n {\n beta=GetPseudoRandomValue(random_info);\n alpha*=beta;\n }\n noise=(double) (QuantumRange*i/SigmaPoisson);\n break;\n }\n case RandomNoise:\n {\n noise=(double) (QuantumRange*SigmaRandom*alpha);\n break;\n }\n }\n return(noise);\n}", "project": "ImageMagick6", "hash": 254287255275900171659283262606636567539, "size": 107, "commit_id": "90255f0834eead08d59f46b0bda7b1580451cc0f", "message": "https://github.com/ImageMagick/ImageMagick/issues/3077", "target": 1, "dataset": "other", "idx": 205775} {"func": "MagickExport double GenerateDifferentialNoise(RandomInfo *random_info,\n const Quantum pixel,const NoiseType noise_type,const MagickRealType attenuate)\n{\n#define SigmaUniform (attenuate*0.015625)\n#define SigmaGaussian (attenuate*0.015625)\n#define SigmaImpulse (attenuate*0.1)\n#define SigmaLaplacian (attenuate*0.0390625)\n#define SigmaMultiplicativeGaussian (attenuate*0.5)\n#define SigmaPoisson (attenuate*12.5)\n#define SigmaRandom (attenuate)\n#define TauGaussian (attenuate*0.078125)\n\n double\n alpha,\n beta,\n noise,\n sigma;\n\n alpha=GetPseudoRandomValue(random_info);\n switch (noise_type)\n {\n case UniformNoise:\n default:\n {\n noise=(double) (pixel+QuantumRange*SigmaUniform*(alpha-0.5));\n break;\n }\n case GaussianNoise:\n {\n double\n gamma,\n tau;\n\n if (fabs(alpha) < MagickEpsilon)\n alpha=1.0;\n beta=GetPseudoRandomValue(random_info);\n gamma=sqrt(-2.0*log(alpha));\n sigma=gamma*cos((double) (2.0*MagickPI*beta));\n tau=gamma*sin((double) (2.0*MagickPI*beta));\n noise=(double) (pixel+sqrt((double) pixel)*SigmaGaussian*sigma+\n QuantumRange*TauGaussian*tau);\n break;\n }\n case ImpulseNoise:\n {\n if (alpha < (SigmaImpulse/2.0))\n noise=0.0;\n else\n if (alpha >= (1.0-(SigmaImpulse/2.0)))\n noise=(double) QuantumRange;\n else\n noise=(double) pixel;\n break;\n }\n case LaplacianNoise:\n {\n if (alpha <= 0.5)\n {\n if (alpha <= MagickEpsilon)\n noise=(double) (pixel-QuantumRange);\n else\n noise=(double) (pixel+QuantumRange*SigmaLaplacian*log(2.0*alpha)+\n 0.5);\n break;\n }\n beta=1.0-alpha;\n if (beta <= (0.5*MagickEpsilon))\n noise=(double) (pixel+QuantumRange);\n else\n noise=(double) (pixel-QuantumRange*SigmaLaplacian*log(2.0*beta)+0.5);\n break;\n }\n case MultiplicativeGaussianNoise:\n {\n sigma=1.0;\n if (alpha > MagickEpsilon)\n sigma=sqrt(-2.0*log(alpha));\n beta=GetPseudoRandomValue(random_info);\n noise=(double) (pixel+pixel*SigmaMultiplicativeGaussian*sigma*\n cos((double) (2.0*MagickPI*beta))/2.0);\n break;\n }\n case PoissonNoise:\n {\n double\n poisson;\n\n ssize_t\n i;\n\n poisson=exp(-SigmaPoisson*QuantumScale*pixel);\n for (i=0; alpha > poisson; i++)\n {\n beta=GetPseudoRandomValue(random_info);\n alpha*=beta;\n }\n noise=(double) (QuantumRange*i*PerceptibleReciprocal(SigmaPoisson));\n break;\n }\n case RandomNoise:\n {\n noise=(double) (QuantumRange*SigmaRandom*alpha);\n break;\n }\n }\n return(noise);\n}", "project": "ImageMagick6", "hash": 58007218466345329691975839082535306927, "size": 107, "commit_id": "90255f0834eead08d59f46b0bda7b1580451cc0f", "message": "https://github.com/ImageMagick/ImageMagick/issues/3077", "target": 0, "dataset": "other", "idx": 371767} {"func": "srs_timestamp_check(srs_t *srs, const char *stamp)\n{\n\tconst char\t*sp;\n\tchar\t\t*bp;\n\tint\t\t\t off;\n\ttime_t\t\t now;\n\ttime_t\t\t then;\n\n\t/* We had better go around this loop exactly twice! */\n\tthen = 0;\n\tfor (sp = stamp; *sp; sp++) {\n\t\tbp = strchr(SRS_TIME_BASECHARS, toupper(*sp));\n\t\tif (bp == NULL)\n\t\t\treturn SRS_EBADTIMESTAMPCHAR;\n\t\toff = bp - SRS_TIME_BASECHARS;\n\t\tthen = (then << SRS_TIME_BASEBITS) | off;\n\t}\n\n\ttime(&now);\n\tnow = (now / SRS_TIME_PRECISION) % SRS_TIME_SLOTS;\n\twhile (now < then)\n\t\tnow = now + SRS_TIME_SLOTS;\n\n\tif (now <= then + srs->maxage)\n\t\treturn SRS_SUCCESS;\n\treturn SRS_ETIMESTAMPOUTOFDATE;\n}", "project": "postsrsd", "hash": 230822056572576587686188533238108797740, "size": 27, "commit_id": "4733fb11f6bec6524bb8518c5e1a699288c26bac", "message": "SECURITY: Fix potential denial of service attack against PostSRSd\n\nI discovered that PostSRSd could be tricked into consuming a lot of CPU\ntime with an SRS address that has an excessively long time stamp tag,\ne.g.\n\nSRS0=HHHH=TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT=0@example.com", "target": 1, "dataset": "other", "idx": 205810} {"func": "srs_timestamp_check(srs_t *srs, const char *stamp)\n{\n\tconst char\t*sp;\n\tchar\t\t*bp;\n\tint\t\t\t off;\n\ttime_t\t\t now;\n\ttime_t\t\t then;\n\n\tif (strlen(stamp) != 2) return SRS_ETIMESTAMPOUTOFDATE;\n\t/* We had better go around this loop exactly twice! */\n\tthen = 0;\n\tfor (sp = stamp; *sp; sp++) {\n\t\tbp = strchr(SRS_TIME_BASECHARS, toupper(*sp));\n\t\tif (bp == NULL)\n\t\t\treturn SRS_EBADTIMESTAMPCHAR;\n\t\toff = bp - SRS_TIME_BASECHARS;\n\t\tthen = (then << SRS_TIME_BASEBITS) | off;\n\t}\n\n\ttime(&now);\n\tnow = (now / SRS_TIME_PRECISION) % SRS_TIME_SLOTS;\n\twhile (now < then)\n\t\tnow = now + SRS_TIME_SLOTS;\n\n\tif (now <= then + srs->maxage)\n\t\treturn SRS_SUCCESS;\n\treturn SRS_ETIMESTAMPOUTOFDATE;\n}", "project": "postsrsd", "hash": 179575258576723630835422814195992797694, "size": 28, "commit_id": "4733fb11f6bec6524bb8518c5e1a699288c26bac", "message": "SECURITY: Fix potential denial of service attack against PostSRSd\n\nI discovered that PostSRSd could be tricked into consuming a lot of CPU\ntime with an SRS address that has an excessively long time stamp tag,\ne.g.\n\nSRS0=HHHH=TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT=0@example.com", "target": 0, "dataset": "other", "idx": 372380} {"func": "static rsRetVal qAddDirect(qqueue_t *pThis, void* pUsr)\n{\n\tbatch_t singleBatch;\n\tbatch_obj_t batchObj;\n\tDEFiRet;\n\n\t//TODO: init batchObj (states _OK and new fields -- CHECK)\n\tASSERT(pThis != NULL);\n\n\t/* calling the consumer is quite different here than it is from a worker thread */\n\t/* we need to provide the consumer's return value back to the caller because in direct\n\t * mode the consumer probably has a lot to convey (which get's lost in the other modes\n\t * because they are asynchronous. But direct mode is deliberately synchronous.\n\t * rgerhards, 2008-02-12\n\t * We use our knowledge about the batch_t structure below, but without that, we\n\t * pay a too-large performance toll... -- rgerhards, 2009-04-22\n\t */\n\tmemset(&batchObj, 0, sizeof(batch_obj_t));\n\tmemset(&singleBatch, 0, sizeof(batch_t));\n\tbatchObj.state = BATCH_STATE_RDY;\n\tbatchObj.pUsrp = (obj_t*) pUsr;\n\tbatchObj.bFilterOK = 1;\n\tsingleBatch.nElem = 1; /* there always is only one in direct mode */\n\tsingleBatch.pElem = &batchObj;\n\tiRet = pThis->pConsumer(pThis->pUsr, &singleBatch, &pThis->bShutdownImmediate);\n\tobjDestruct(pUsr);\n\n\tRETiRet;\n}", "project": "rsyslog", "hash": 246917057648162918663491604797767470769, "size": 29, "commit_id": "dfa88369d4ca4290db56b843f9eabdae1bfe0fd5", "message": "bugfix: memory leak when $RepeatedMsgReduction on was used\n\nbug tracker: http://bugzilla.adiscon.com/show_bug.cgi?id=225", "target": 1, "dataset": "other", "idx": 205840} {"func": "static rsRetVal qAddDirect(qqueue_t *pThis, void* pUsr)\n{\n\tbatch_t singleBatch;\n\tbatch_obj_t batchObj;\n\tint i;\n\tDEFiRet;\n\n\t//TODO: init batchObj (states _OK and new fields -- CHECK)\n\tASSERT(pThis != NULL);\n\n\t/* calling the consumer is quite different here than it is from a worker thread */\n\t/* we need to provide the consumer's return value back to the caller because in direct\n\t * mode the consumer probably has a lot to convey (which get's lost in the other modes\n\t * because they are asynchronous. But direct mode is deliberately synchronous.\n\t * rgerhards, 2008-02-12\n\t * We use our knowledge about the batch_t structure below, but without that, we\n\t * pay a too-large performance toll... -- rgerhards, 2009-04-22\n\t */\n\tmemset(&batchObj, 0, sizeof(batch_obj_t));\n\tmemset(&singleBatch, 0, sizeof(batch_t));\n\tbatchObj.state = BATCH_STATE_RDY;\n\tbatchObj.pUsrp = (obj_t*) pUsr;\n\tbatchObj.bFilterOK = 1;\n\tsingleBatch.nElem = 1; /* there always is only one in direct mode */\n\tsingleBatch.pElem = &batchObj;\n\tiRet = pThis->pConsumer(pThis->pUsr, &singleBatch, &pThis->bShutdownImmediate);\n\t/* delete the batch string params: TODO: create its own \"class\" for this */\n\tfor(i = 0 ; i < CONF_OMOD_NUMSTRINGS_MAXSIZE ; ++i) {\n\t\tfree(batchObj.staticActStrings[i]);\n\t}\n\tobjDestruct(pUsr);\n\n\tRETiRet;\n}", "project": "rsyslog", "hash": 258491197826171869327416197774899637452, "size": 34, "commit_id": "dfa88369d4ca4290db56b843f9eabdae1bfe0fd5", "message": "bugfix: memory leak when $RepeatedMsgReduction on was used\n\nbug tracker: http://bugzilla.adiscon.com/show_bug.cgi?id=225", "target": 0, "dataset": "other", "idx": 373783} {"func": "GC_API GC_ATTR_MALLOC void * GC_CALL GC_calloc_explicitly_typed(size_t n,\n size_t lb, GC_descr d)\n{\n word *op;\n size_t lg;\n GC_descr simple_descr;\n complex_descriptor *complex_descr;\n int descr_type;\n struct LeafDescriptor leaf;\n\n GC_ASSERT(GC_explicit_typing_initialized);\n descr_type = GC_make_array_descriptor((word)n, (word)lb, d, &simple_descr,\n &complex_descr, &leaf);\n switch(descr_type) {\n case NO_MEM: return(0);\n case SIMPLE: return(GC_malloc_explicitly_typed(n*lb, simple_descr));\n case LEAF:\n lb *= n;\n lb += sizeof(struct LeafDescriptor) + TYPD_EXTRA_BYTES;\n break;\n case COMPLEX:\n lb *= n;\n lb += TYPD_EXTRA_BYTES;\n break;\n }\n op = GC_malloc_kind(lb, GC_array_kind);\n if (EXPECT(NULL == op, FALSE))\n return NULL;\n lg = SMALL_OBJ(lb) ? GC_size_map[lb] : BYTES_TO_GRANULES(GC_size(op));\n if (descr_type == LEAF) {\n /* Set up the descriptor inside the object itself. */\n volatile struct LeafDescriptor * lp =\n (struct LeafDescriptor *)\n (op + GRANULES_TO_WORDS(lg)\n - (BYTES_TO_WORDS(sizeof(struct LeafDescriptor)) + 1));\n\n lp -> ld_tag = LEAF_TAG;\n lp -> ld_size = leaf.ld_size;\n lp -> ld_nelements = leaf.ld_nelements;\n lp -> ld_descriptor = leaf.ld_descriptor;\n ((volatile word *)op)[GRANULES_TO_WORDS(lg) - 1] = (word)lp;\n } else {\n# ifndef GC_NO_FINALIZATION\n size_t lw = GRANULES_TO_WORDS(lg);\n\n op[lw - 1] = (word)complex_descr;\n /* Make sure the descriptor is cleared once there is any danger */\n /* it may have been collected. */\n if (EXPECT(GC_general_register_disappearing_link(\n (void **)(op + lw - 1), op)\n == GC_NO_MEMORY, FALSE))\n# endif\n {\n /* Couldn't register it due to lack of memory. Punt. */\n /* This will probably fail too, but gives the recovery code */\n /* a chance. */\n return GC_malloc(lb);\n }\n }\n return op;\n}", "project": "bdwgc", "hash": 129186795195986820153089371839787067250, "size": 61, "commit_id": "4e1a6f9d8f2a49403bbd00b8c8e5324048fb84d4", "message": "Fix calloc_explicitly_typed in case of lb*n overflow\n\n* typd_mlc.c: Include limits.h (for SIZE_MAX).\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): New macro (same as in\nmalloc.c).\n* typd_mlc.c (GC_calloc_explicitly_typed): Return NULL if lb * n\noverflows (same algorithm as in calloc defined in malloc.c); eliminate\nlb *= n code duplication.", "target": 1, "dataset": "other", "idx": 205872} {"func": "GC_API GC_ATTR_MALLOC void * GC_CALL GC_calloc_explicitly_typed(size_t n,\n size_t lb, GC_descr d)\n{\n word *op;\n size_t lg;\n GC_descr simple_descr;\n complex_descriptor *complex_descr;\n int descr_type;\n struct LeafDescriptor leaf;\n\n GC_ASSERT(GC_explicit_typing_initialized);\n descr_type = GC_make_array_descriptor((word)n, (word)lb, d, &simple_descr,\n &complex_descr, &leaf);\n if ((lb | n) > GC_SQRT_SIZE_MAX /* fast initial check */\n && lb > 0 && n > GC_SIZE_MAX / lb)\n return NULL; /* n*lb overflow */\n lb *= n;\n switch(descr_type) {\n case NO_MEM: return(0);\n case SIMPLE:\n return GC_malloc_explicitly_typed(lb, simple_descr);\n case LEAF:\n lb += sizeof(struct LeafDescriptor) + TYPD_EXTRA_BYTES;\n break;\n case COMPLEX:\n lb += TYPD_EXTRA_BYTES;\n break;\n }\n op = GC_malloc_kind(lb, GC_array_kind);\n if (EXPECT(NULL == op, FALSE))\n return NULL;\n lg = SMALL_OBJ(lb) ? GC_size_map[lb] : BYTES_TO_GRANULES(GC_size(op));\n if (descr_type == LEAF) {\n /* Set up the descriptor inside the object itself. */\n volatile struct LeafDescriptor * lp =\n (struct LeafDescriptor *)\n (op + GRANULES_TO_WORDS(lg)\n - (BYTES_TO_WORDS(sizeof(struct LeafDescriptor)) + 1));\n\n lp -> ld_tag = LEAF_TAG;\n lp -> ld_size = leaf.ld_size;\n lp -> ld_nelements = leaf.ld_nelements;\n lp -> ld_descriptor = leaf.ld_descriptor;\n ((volatile word *)op)[GRANULES_TO_WORDS(lg) - 1] = (word)lp;\n } else {\n# ifndef GC_NO_FINALIZATION\n size_t lw = GRANULES_TO_WORDS(lg);\n\n op[lw - 1] = (word)complex_descr;\n /* Make sure the descriptor is cleared once there is any danger */\n /* it may have been collected. */\n if (EXPECT(GC_general_register_disappearing_link(\n (void **)(op + lw - 1), op)\n == GC_NO_MEMORY, FALSE))\n# endif\n {\n /* Couldn't register it due to lack of memory. Punt. */\n /* This will probably fail too, but gives the recovery code */\n /* a chance. */\n return GC_malloc(lb);\n }\n }\n return op;\n}", "project": "bdwgc", "hash": 196754813537280026105640227782301143544, "size": 64, "commit_id": "4e1a6f9d8f2a49403bbd00b8c8e5324048fb84d4", "message": "Fix calloc_explicitly_typed in case of lb*n overflow\n\n* typd_mlc.c: Include limits.h (for SIZE_MAX).\n* typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): New macro (same as in\nmalloc.c).\n* typd_mlc.c (GC_calloc_explicitly_typed): Return NULL if lb * n\noverflows (same algorithm as in calloc defined in malloc.c); eliminate\nlb *= n code duplication.", "target": 0, "dataset": "other", "idx": 374064} {"func": "ZEND_METHOD(exception, getTraceAsString)\n{\n\tzval *trace;\n\tchar *res, **str, *s_tmp;\n\tint res_len = 0, *len = &res_len, num = 0;\n\n\tDEFAULT_0_PARAMS;\n\t\n\tres = estrdup(\"\");\n\tstr = &res;\n\n\ttrace = zend_read_property(default_exception_ce, getThis(), \"trace\", sizeof(\"trace\")-1, 1 TSRMLS_CC);\n\tzend_hash_apply_with_arguments(Z_ARRVAL_P(trace) TSRMLS_CC, (apply_func_args_t)_build_trace_string, 3, str, len, &num);\n\n\ts_tmp = emalloc(1 + MAX_LENGTH_OF_LONG + 7 + 1);\n\tsprintf(s_tmp, \"#%d {main}\", num);\n\tTRACE_APPEND_STRL(s_tmp, strlen(s_tmp));\n\tefree(s_tmp);\n\n\tres[res_len] = '\\0';\t\n\tRETURN_STRINGL(res, res_len, 0); \n}", "project": "php-src", "hash": 241319124076641660271307693135429377686, "size": 22, "commit_id": "a894a8155fab068d68a04bf181dbaddfa01ccbb0", "message": "More fixes for bug #69152", "target": 1, "dataset": "other", "idx": 205882} {"func": "ZEND_METHOD(exception, getTraceAsString)\n{\n\tzval *trace;\n\tchar *res, **str, *s_tmp;\n\tint res_len = 0, *len = &res_len, num = 0;\n\n\tDEFAULT_0_PARAMS;\n\t\n\tres = estrdup(\"\");\n\tstr = &res;\n\n\ttrace = zend_read_property(default_exception_ce, getThis(), \"trace\", sizeof(\"trace\")-1, 1 TSRMLS_CC);\n\tif(Z_TYPE_P(trace) != IS_ARRAY) {\n\t\tRETURN_FALSE;\n\t}\n\tzend_hash_apply_with_arguments(Z_ARRVAL_P(trace) TSRMLS_CC, (apply_func_args_t)_build_trace_string, 3, str, len, &num);\n\n\ts_tmp = emalloc(1 + MAX_LENGTH_OF_LONG + 7 + 1);\n\tsprintf(s_tmp, \"#%d {main}\", num);\n\tTRACE_APPEND_STRL(s_tmp, strlen(s_tmp));\n\tefree(s_tmp);\n\n\tres[res_len] = '\\0';\t\n\tRETURN_STRINGL(res, res_len, 0); \n}", "project": "php-src", "hash": 150063148970590872214374230082563770268, "size": 25, "commit_id": "a894a8155fab068d68a04bf181dbaddfa01ccbb0", "message": "More fixes for bug #69152", "target": 0, "dataset": "other", "idx": 374450} {"func": "vmod_append(VRT_CTX, VCL_HEADER hdr, VCL_STRANDS s)\n{\n\tstruct http *hp;\n\tstruct strands st[1];\n\tconst char *p[s->n + 2];\n\tconst char *b;\n\n\tCHECK_OBJ_NOTNULL(ctx, VRT_CTX_MAGIC);\n\n\t/* prefix the strand with $hdr_name + space */\n\tp[0] = hdr->what + 1;\n\tp[1] = \" \";\n\tAN(memcpy(p + 2, s->p, s->n * sizeof *s->p));\n\tst->n = s->n + 2;\n\tst->p = p;\n\n\tb = VRT_StrandsWS(ctx->ws, NULL, st);\n\n\thp = VRT_selecthttp(ctx, hdr->where);\n\thttp_SetHeader(hp, b);\n}", "project": "varnish-modules", "hash": 324979881010693657557959501891217334918, "size": 21, "commit_id": "2c120e576ebb73bc247790184702ba58dc0afc39", "message": "Check VRT_StrandsWS() return value\n\nFixes: VSV00006", "target": 1, "dataset": "other", "idx": 205887} {"func": "vmod_append(VRT_CTX, VCL_HEADER hdr, VCL_STRANDS s)\n{\n\tstruct http *hp;\n\tstruct strands st[1];\n\tconst char *p[s->n + 2];\n\tconst char *b;\n\n\tCHECK_OBJ_NOTNULL(ctx, VRT_CTX_MAGIC);\n\n\t/* prefix the strand with $hdr_name + space */\n\tp[0] = hdr->what + 1;\n\tp[1] = \" \";\n\tAN(memcpy(p + 2, s->p, s->n * sizeof *s->p));\n\tst->n = s->n + 2;\n\tst->p = p;\n\n\tb = VRT_StrandsWS(ctx->ws, NULL, st);\n\tif (b == NULL) {\n\t\tVRT_fail(ctx, \"vmod_header: workspace allocation failure\");\n\t\treturn;\n\t}\n\n\thp = VRT_selecthttp(ctx, hdr->where);\n\thttp_SetHeader(hp, b);\n}", "project": "varnish-modules", "hash": 235596432137393318008443894497589238133, "size": 25, "commit_id": "2c120e576ebb73bc247790184702ba58dc0afc39", "message": "Check VRT_StrandsWS() return value\n\nFixes: VSV00006", "target": 0, "dataset": "other", "idx": 374508} {"func": "unsigned long perf_instruction_pointer(struct pt_regs *regs)\n{\n\tbool use_siar = regs_use_siar(regs);\n\tunsigned long siar = mfspr(SPRN_SIAR);\n\n\tif (ppmu->flags & PPMU_P10_DD1) {\n\t\tif (siar)\n\t\t\treturn siar;\n\t\telse\n\t\t\treturn regs->nip;\n\t} else if (use_siar && siar_valid(regs))\n\t\treturn mfspr(SPRN_SIAR) + perf_ip_adjust(regs);\n\telse if (use_siar)\n\t\treturn 0;\t\t// no valid instruction pointer\n\telse\n\t\treturn regs->nip;\n}", "project": "linux", "hash": 8700491383079660474540574671645428931, "size": 17, "commit_id": "60b7ed54a41b550d50caf7f2418db4a7e75b5bdc", "message": "powerpc/perf: Fix crash in perf_instruction_pointer() when ppmu is not set\n\nOn systems without any specific PMU driver support registered, running\nperf record causes Oops.\n\nThe relevant portion from call trace:\n\n BUG: Kernel NULL pointer dereference on read at 0x00000040\n Faulting instruction address: 0xc0021f0c\n Oops: Kernel access of bad area, sig: 11 [#1]\n BE PAGE_SIZE=4K PREEMPT CMPCPRO\n SAF3000 DIE NOTIFICATION\n CPU: 0 PID: 442 Comm: null_syscall Not tainted 5.13.0-rc6-s3k-dev-01645-g7649ee3d2957 #5164\n NIP: c0021f0c LR: c00e8ad8 CTR: c00d8a5c\n NIP perf_instruction_pointer+0x10/0x60\n LR perf_prepare_sample+0x344/0x674\n Call Trace:\n perf_prepare_sample+0x7c/0x674 (unreliable)\n perf_event_output_forward+0x3c/0x94\n __perf_event_overflow+0x74/0x14c\n perf_swevent_hrtimer+0xf8/0x170\n __hrtimer_run_queues.constprop.0+0x160/0x318\n hrtimer_interrupt+0x148/0x3b0\n timer_interrupt+0xc4/0x22c\n Decrementer_virt+0xb8/0xbc\n\nDuring perf record session, perf_instruction_pointer() is called to\ncapture the sample IP. This function in core-book3s accesses\nppmu->flags. If a platform specific PMU driver is not registered, ppmu\nis set to NULL and accessing its members results in a crash. Fix this\ncrash by checking if ppmu is set.\n\nFixes: 2ca13a4cc56c (\"powerpc/perf: Use regs->nip when SIAR is zero\")\nCc: stable@vger.kernel.org # v5.11+\nReported-by: Christophe Leroy \nSigned-off-by: Athira Rajeev \nTested-by: Christophe Leroy \nSigned-off-by: Michael Ellerman \nLink: https://lore.kernel.org/r/1623952506-1431-1-git-send-email-atrajeev@linux.vnet.ibm.com", "target": 1, "dataset": "other", "idx": 205900} {"func": "unsigned long perf_instruction_pointer(struct pt_regs *regs)\n{\n\tbool use_siar = regs_use_siar(regs);\n\tunsigned long siar = mfspr(SPRN_SIAR);\n\n\tif (ppmu && (ppmu->flags & PPMU_P10_DD1)) {\n\t\tif (siar)\n\t\t\treturn siar;\n\t\telse\n\t\t\treturn regs->nip;\n\t} else if (use_siar && siar_valid(regs))\n\t\treturn mfspr(SPRN_SIAR) + perf_ip_adjust(regs);\n\telse if (use_siar)\n\t\treturn 0;\t\t// no valid instruction pointer\n\telse\n\t\treturn regs->nip;\n}", "project": "linux", "hash": 187281309875844152562266298810867406643, "size": 17, "commit_id": "60b7ed54a41b550d50caf7f2418db4a7e75b5bdc", "message": "powerpc/perf: Fix crash in perf_instruction_pointer() when ppmu is not set\n\nOn systems without any specific PMU driver support registered, running\nperf record causes Oops.\n\nThe relevant portion from call trace:\n\n BUG: Kernel NULL pointer dereference on read at 0x00000040\n Faulting instruction address: 0xc0021f0c\n Oops: Kernel access of bad area, sig: 11 [#1]\n BE PAGE_SIZE=4K PREEMPT CMPCPRO\n SAF3000 DIE NOTIFICATION\n CPU: 0 PID: 442 Comm: null_syscall Not tainted 5.13.0-rc6-s3k-dev-01645-g7649ee3d2957 #5164\n NIP: c0021f0c LR: c00e8ad8 CTR: c00d8a5c\n NIP perf_instruction_pointer+0x10/0x60\n LR perf_prepare_sample+0x344/0x674\n Call Trace:\n perf_prepare_sample+0x7c/0x674 (unreliable)\n perf_event_output_forward+0x3c/0x94\n __perf_event_overflow+0x74/0x14c\n perf_swevent_hrtimer+0xf8/0x170\n __hrtimer_run_queues.constprop.0+0x160/0x318\n hrtimer_interrupt+0x148/0x3b0\n timer_interrupt+0xc4/0x22c\n Decrementer_virt+0xb8/0xbc\n\nDuring perf record session, perf_instruction_pointer() is called to\ncapture the sample IP. This function in core-book3s accesses\nppmu->flags. If a platform specific PMU driver is not registered, ppmu\nis set to NULL and accessing its members results in a crash. Fix this\ncrash by checking if ppmu is set.\n\nFixes: 2ca13a4cc56c (\"powerpc/perf: Use regs->nip when SIAR is zero\")\nCc: stable@vger.kernel.org # v5.11+\nReported-by: Christophe Leroy \nSigned-off-by: Athira Rajeev \nTested-by: Christophe Leroy \nSigned-off-by: Michael Ellerman \nLink: https://lore.kernel.org/r/1623952506-1431-1-git-send-email-atrajeev@linux.vnet.ibm.com", "target": 0, "dataset": "other", "idx": 374683} {"func": "SAPI_API SAPI_TREAT_DATA_FUNC(php_default_treat_data)\n{\n\tchar *res = NULL, *var, *val, *separator = NULL;\n\tconst char *c_var;\n\tzval array;\n\tint free_buffer = 0;\n\tchar *strtok_buf = NULL;\n\tzend_long count = 0;\n\n\tZVAL_UNDEF(&array);\n\tswitch (arg) {\n\t\tcase PARSE_POST:\n\t\tcase PARSE_GET:\n\t\tcase PARSE_COOKIE:\n\t\t\tarray_init(&array);\n\t\t\tswitch (arg) {\n\t\t\t\tcase PARSE_POST:\n\t\t\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_POST]);\n\t\t\t\t\tZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_POST], &array);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PARSE_GET:\n\t\t\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_GET]);\n\t\t\t\t\tZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_GET], &array);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PARSE_COOKIE:\n\t\t\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_COOKIE]);\n\t\t\t\t\tZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_COOKIE], &array);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tZVAL_COPY_VALUE(&array, destArray);\n\t\t\tbreak;\n\t}\n\n\tif (arg == PARSE_POST) {\n\t\tsapi_handle_post(&array);\n\t\treturn;\n\t}\n\n\tif (arg == PARSE_GET) {\t\t/* GET data */\n\t\tc_var = SG(request_info).query_string;\n\t\tif (c_var && *c_var) {\n\t\t\tres = (char *) estrdup(c_var);\n\t\t\tfree_buffer = 1;\n\t\t} else {\n\t\t\tfree_buffer = 0;\n\t\t}\n\t} else if (arg == PARSE_COOKIE) {\t\t/* Cookie data */\n\t\tc_var = SG(request_info).cookie_data;\n\t\tif (c_var && *c_var) {\n\t\t\tres = (char *) estrdup(c_var);\n\t\t\tfree_buffer = 1;\n\t\t} else {\n\t\t\tfree_buffer = 0;\n\t\t}\n\t} else if (arg == PARSE_STRING) {\t\t/* String data */\n\t\tres = str;\n\t\tfree_buffer = 1;\n\t}\n\n\tif (!res) {\n\t\treturn;\n\t}\n\n\tswitch (arg) {\n\t\tcase PARSE_GET:\n\t\tcase PARSE_STRING:\n\t\t\tseparator = PG(arg_separator).input;\n\t\t\tbreak;\n\t\tcase PARSE_COOKIE:\n\t\t\tseparator = \";\\0\";\n\t\t\tbreak;\n\t}\n\n\tvar = php_strtok_r(res, separator, &strtok_buf);\n\n\twhile (var) {\n\t\tval = strchr(var, '=');\n\n\t\tif (arg == PARSE_COOKIE) {\n\t\t\t/* Remove leading spaces from cookie names, needed for multi-cookie header where ; can be followed by a space */\n\t\t\twhile (isspace(*var)) {\n\t\t\t\tvar++;\n\t\t\t}\n\t\t\tif (var == val || *var == '\\0') {\n\t\t\t\tgoto next_cookie;\n\t\t\t}\n\t\t}\n\n\t\tif (++count > PG(max_input_vars)) {\n\t\t\tphp_error_docref(NULL, E_WARNING, \"Input variables exceeded \" ZEND_LONG_FMT \". To increase the limit change max_input_vars in php.ini.\", PG(max_input_vars));\n\t\t\tbreak;\n\t\t}\n\n\t\tif (val) { /* have a value */\n\t\t\tsize_t val_len;\n\t\t\tsize_t new_val_len;\n\n\t\t\t*val++ = '\\0';\n\t\t\tphp_url_decode(var, strlen(var));\n\t\t\tval_len = php_url_decode(val, strlen(val));\n\t\t\tval = estrndup(val, val_len);\n\t\t\tif (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len)) {\n\t\t\t\tphp_register_variable_safe(var, val, new_val_len, &array);\n\t\t\t}\n\t\t\tefree(val);\n\t\t} else {\n\t\t\tsize_t val_len;\n\t\t\tsize_t new_val_len;\n\n\t\t\tphp_url_decode(var, strlen(var));\n\t\t\tval_len = 0;\n\t\t\tval = estrndup(\"\", val_len);\n\t\t\tif (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len)) {\n\t\t\t\tphp_register_variable_safe(var, val, new_val_len, &array);\n\t\t\t}\n\t\t\tefree(val);\n\t\t}\nnext_cookie:\n\t\tvar = php_strtok_r(NULL, separator, &strtok_buf);\n\t}\n\n\tif (free_buffer) {\n\t\tefree(res);\n\t}\n}", "project": "php-src", "hash": 129611870495713562053024480121638591020, "size": 127, "commit_id": "6559fe912661ca5ce5f0eeeb591d928451428ed0", "message": "Do not decode cookie names anymore", "target": 1, "dataset": "other", "idx": 205909} {"func": "SAPI_API SAPI_TREAT_DATA_FUNC(php_default_treat_data)\n{\n\tchar *res = NULL, *var, *val, *separator = NULL;\n\tconst char *c_var;\n\tzval array;\n\tint free_buffer = 0;\n\tchar *strtok_buf = NULL;\n\tzend_long count = 0;\n\n\tZVAL_UNDEF(&array);\n\tswitch (arg) {\n\t\tcase PARSE_POST:\n\t\tcase PARSE_GET:\n\t\tcase PARSE_COOKIE:\n\t\t\tarray_init(&array);\n\t\t\tswitch (arg) {\n\t\t\t\tcase PARSE_POST:\n\t\t\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_POST]);\n\t\t\t\t\tZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_POST], &array);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PARSE_GET:\n\t\t\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_GET]);\n\t\t\t\t\tZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_GET], &array);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PARSE_COOKIE:\n\t\t\t\t\tzval_ptr_dtor(&PG(http_globals)[TRACK_VARS_COOKIE]);\n\t\t\t\t\tZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_COOKIE], &array);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tZVAL_COPY_VALUE(&array, destArray);\n\t\t\tbreak;\n\t}\n\n\tif (arg == PARSE_POST) {\n\t\tsapi_handle_post(&array);\n\t\treturn;\n\t}\n\n\tif (arg == PARSE_GET) {\t\t/* GET data */\n\t\tc_var = SG(request_info).query_string;\n\t\tif (c_var && *c_var) {\n\t\t\tres = (char *) estrdup(c_var);\n\t\t\tfree_buffer = 1;\n\t\t} else {\n\t\t\tfree_buffer = 0;\n\t\t}\n\t} else if (arg == PARSE_COOKIE) {\t\t/* Cookie data */\n\t\tc_var = SG(request_info).cookie_data;\n\t\tif (c_var && *c_var) {\n\t\t\tres = (char *) estrdup(c_var);\n\t\t\tfree_buffer = 1;\n\t\t} else {\n\t\t\tfree_buffer = 0;\n\t\t}\n\t} else if (arg == PARSE_STRING) {\t\t/* String data */\n\t\tres = str;\n\t\tfree_buffer = 1;\n\t}\n\n\tif (!res) {\n\t\treturn;\n\t}\n\n\tswitch (arg) {\n\t\tcase PARSE_GET:\n\t\tcase PARSE_STRING:\n\t\t\tseparator = PG(arg_separator).input;\n\t\t\tbreak;\n\t\tcase PARSE_COOKIE:\n\t\t\tseparator = \";\\0\";\n\t\t\tbreak;\n\t}\n\n\tvar = php_strtok_r(res, separator, &strtok_buf);\n\n\twhile (var) {\n\t\tval = strchr(var, '=');\n\n\t\tif (arg == PARSE_COOKIE) {\n\t\t\t/* Remove leading spaces from cookie names, needed for multi-cookie header where ; can be followed by a space */\n\t\t\twhile (isspace(*var)) {\n\t\t\t\tvar++;\n\t\t\t}\n\t\t\tif (var == val || *var == '\\0') {\n\t\t\t\tgoto next_cookie;\n\t\t\t}\n\t\t}\n\n\t\tif (++count > PG(max_input_vars)) {\n\t\t\tphp_error_docref(NULL, E_WARNING, \"Input variables exceeded \" ZEND_LONG_FMT \". To increase the limit change max_input_vars in php.ini.\", PG(max_input_vars));\n\t\t\tbreak;\n\t\t}\n\n\t\tif (val) { /* have a value */\n\t\t\tsize_t val_len;\n\t\t\tsize_t new_val_len;\n\n\t\t\t*val++ = '\\0';\n\t\t\tif (arg != PARSE_COOKIE) {\n\t\t\t\tphp_url_decode(var, strlen(var));\n\t\t\t}\n\t\t\tval_len = php_url_decode(val, strlen(val));\n\t\t\tval = estrndup(val, val_len);\n\t\t\tif (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len)) {\n\t\t\t\tphp_register_variable_safe(var, val, new_val_len, &array);\n\t\t\t}\n\t\t\tefree(val);\n\t\t} else {\n\t\t\tsize_t val_len;\n\t\t\tsize_t new_val_len;\n\n\t\t\tif (arg != PARSE_COOKIE) {\n\t\t\t\tphp_url_decode(var, strlen(var));\n\t\t\t}\n\t\t\tval_len = 0;\n\t\t\tval = estrndup(\"\", val_len);\n\t\t\tif (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len)) {\n\t\t\t\tphp_register_variable_safe(var, val, new_val_len, &array);\n\t\t\t}\n\t\t\tefree(val);\n\t\t}\nnext_cookie:\n\t\tvar = php_strtok_r(NULL, separator, &strtok_buf);\n\t}\n\n\tif (free_buffer) {\n\t\tefree(res);\n\t}\n}", "project": "php-src", "hash": 99217299303506150311767680298916812323, "size": 131, "commit_id": "6559fe912661ca5ce5f0eeeb591d928451428ed0", "message": "Do not decode cookie names anymore", "target": 0, "dataset": "other", "idx": 374974} {"func": "bool do_notify_parent(struct task_struct *tsk, int sig)\n{\n\tstruct kernel_siginfo info;\n\tunsigned long flags;\n\tstruct sighand_struct *psig;\n\tbool autoreap = false;\n\tu64 utime, stime;\n\n\tBUG_ON(sig == -1);\n\n \t/* do_notify_parent_cldstop should have been called instead. */\n \tBUG_ON(task_is_stopped_or_traced(tsk));\n\n\tBUG_ON(!tsk->ptrace &&\n\t (tsk->group_leader != tsk || !thread_group_empty(tsk)));\n\n\t/* Wake up all pidfd waiters */\n\tdo_notify_pidfd(tsk);\n\n\tif (sig != SIGCHLD) {\n\t\t/*\n\t\t * This is only possible if parent == real_parent.\n\t\t * Check if it has changed security domain.\n\t\t */\n\t\tif (tsk->parent_exec_id != tsk->parent->self_exec_id)\n\t\t\tsig = SIGCHLD;\n\t}\n\n\tclear_siginfo(&info);\n\tinfo.si_signo = sig;\n\tinfo.si_errno = 0;\n\t/*\n\t * We are under tasklist_lock here so our parent is tied to\n\t * us and cannot change.\n\t *\n\t * task_active_pid_ns will always return the same pid namespace\n\t * until a task passes through release_task.\n\t *\n\t * write_lock() currently calls preempt_disable() which is the\n\t * same as rcu_read_lock(), but according to Oleg, this is not\n\t * correct to rely on this\n\t */\n\trcu_read_lock();\n\tinfo.si_pid = task_pid_nr_ns(tsk, task_active_pid_ns(tsk->parent));\n\tinfo.si_uid = from_kuid_munged(task_cred_xxx(tsk->parent, user_ns),\n\t\t\t\t task_uid(tsk));\n\trcu_read_unlock();\n\n\ttask_cputime(tsk, &utime, &stime);\n\tinfo.si_utime = nsec_to_clock_t(utime + tsk->signal->utime);\n\tinfo.si_stime = nsec_to_clock_t(stime + tsk->signal->stime);\n\n\tinfo.si_status = tsk->exit_code & 0x7f;\n\tif (tsk->exit_code & 0x80)\n\t\tinfo.si_code = CLD_DUMPED;\n\telse if (tsk->exit_code & 0x7f)\n\t\tinfo.si_code = CLD_KILLED;\n\telse {\n\t\tinfo.si_code = CLD_EXITED;\n\t\tinfo.si_status = tsk->exit_code >> 8;\n\t}\n\n\tpsig = tsk->parent->sighand;\n\tspin_lock_irqsave(&psig->siglock, flags);\n\tif (!tsk->ptrace && sig == SIGCHLD &&\n\t (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN ||\n\t (psig->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDWAIT))) {\n\t\t/*\n\t\t * We are exiting and our parent doesn't care. POSIX.1\n\t\t * defines special semantics for setting SIGCHLD to SIG_IGN\n\t\t * or setting the SA_NOCLDWAIT flag: we should be reaped\n\t\t * automatically and not left for our parent's wait4 call.\n\t\t * Rather than having the parent do it as a magic kind of\n\t\t * signal handler, we just set this to tell do_exit that we\n\t\t * can be cleaned up without becoming a zombie. Note that\n\t\t * we still call __wake_up_parent in this case, because a\n\t\t * blocked sys_wait4 might now return -ECHILD.\n\t\t *\n\t\t * Whether we send SIGCHLD or not for SA_NOCLDWAIT\n\t\t * is implementation-defined: we do (if you don't want\n\t\t * it, just use SIG_IGN instead).\n\t\t */\n\t\tautoreap = true;\n\t\tif (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN)\n\t\t\tsig = 0;\n\t}\n\tif (valid_signal(sig) && sig)\n\t\t__group_send_sig_info(sig, &info, tsk->parent);\n\t__wake_up_parent(tsk, tsk->parent);\n\tspin_unlock_irqrestore(&psig->siglock, flags);\n\n\treturn autoreap;\n}", "project": "linux", "hash": 326403613636969146659682497730835154196, "size": 93, "commit_id": "d1e7fd6462ca9fc76650fbe6ca800e35b24267da", "message": "signal: Extend exec_id to 64bits\n\nReplace the 32bit exec_id with a 64bit exec_id to make it impossible\nto wrap the exec_id counter. With care an attacker can cause exec_id\nwrap and send arbitrary signals to a newly exec'd parent. This\nbypasses the signal sending checks if the parent changes their\ncredentials during exec.\n\nThe severity of this problem can been seen that in my limited testing\nof a 32bit exec_id it can take as little as 19s to exec 65536 times.\nWhich means that it can take as little as 14 days to wrap a 32bit\nexec_id. Adam Zabrocki has succeeded wrapping the self_exe_id in 7\ndays. Even my slower timing is in the uptime of a typical server.\nWhich means self_exec_id is simply a speed bump today, and if exec\ngets noticably faster self_exec_id won't even be a speed bump.\n\nExtending self_exec_id to 64bits introduces a problem on 32bit\narchitectures where reading self_exec_id is no longer atomic and can\ntake two read instructions. Which means that is is possible to hit\na window where the read value of exec_id does not match the written\nvalue. So with very lucky timing after this change this still\nremains expoiltable.\n\nI have updated the update of exec_id on exec to use WRITE_ONCE\nand the read of exec_id in do_notify_parent to use READ_ONCE\nto make it clear that there is no locking between these two\nlocations.\n\nLink: https://lore.kernel.org/kernel-hardening/20200324215049.GA3710@pi3.com.pl\nFixes: 2.3.23pre2\nCc: stable@vger.kernel.org\nSigned-off-by: \"Eric W. Biederman\" ", "target": 1, "dataset": "other", "idx": 205956} {"func": "bool do_notify_parent(struct task_struct *tsk, int sig)\n{\n\tstruct kernel_siginfo info;\n\tunsigned long flags;\n\tstruct sighand_struct *psig;\n\tbool autoreap = false;\n\tu64 utime, stime;\n\n\tBUG_ON(sig == -1);\n\n \t/* do_notify_parent_cldstop should have been called instead. */\n \tBUG_ON(task_is_stopped_or_traced(tsk));\n\n\tBUG_ON(!tsk->ptrace &&\n\t (tsk->group_leader != tsk || !thread_group_empty(tsk)));\n\n\t/* Wake up all pidfd waiters */\n\tdo_notify_pidfd(tsk);\n\n\tif (sig != SIGCHLD) {\n\t\t/*\n\t\t * This is only possible if parent == real_parent.\n\t\t * Check if it has changed security domain.\n\t\t */\n\t\tif (tsk->parent_exec_id != READ_ONCE(tsk->parent->self_exec_id))\n\t\t\tsig = SIGCHLD;\n\t}\n\n\tclear_siginfo(&info);\n\tinfo.si_signo = sig;\n\tinfo.si_errno = 0;\n\t/*\n\t * We are under tasklist_lock here so our parent is tied to\n\t * us and cannot change.\n\t *\n\t * task_active_pid_ns will always return the same pid namespace\n\t * until a task passes through release_task.\n\t *\n\t * write_lock() currently calls preempt_disable() which is the\n\t * same as rcu_read_lock(), but according to Oleg, this is not\n\t * correct to rely on this\n\t */\n\trcu_read_lock();\n\tinfo.si_pid = task_pid_nr_ns(tsk, task_active_pid_ns(tsk->parent));\n\tinfo.si_uid = from_kuid_munged(task_cred_xxx(tsk->parent, user_ns),\n\t\t\t\t task_uid(tsk));\n\trcu_read_unlock();\n\n\ttask_cputime(tsk, &utime, &stime);\n\tinfo.si_utime = nsec_to_clock_t(utime + tsk->signal->utime);\n\tinfo.si_stime = nsec_to_clock_t(stime + tsk->signal->stime);\n\n\tinfo.si_status = tsk->exit_code & 0x7f;\n\tif (tsk->exit_code & 0x80)\n\t\tinfo.si_code = CLD_DUMPED;\n\telse if (tsk->exit_code & 0x7f)\n\t\tinfo.si_code = CLD_KILLED;\n\telse {\n\t\tinfo.si_code = CLD_EXITED;\n\t\tinfo.si_status = tsk->exit_code >> 8;\n\t}\n\n\tpsig = tsk->parent->sighand;\n\tspin_lock_irqsave(&psig->siglock, flags);\n\tif (!tsk->ptrace && sig == SIGCHLD &&\n\t (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN ||\n\t (psig->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDWAIT))) {\n\t\t/*\n\t\t * We are exiting and our parent doesn't care. POSIX.1\n\t\t * defines special semantics for setting SIGCHLD to SIG_IGN\n\t\t * or setting the SA_NOCLDWAIT flag: we should be reaped\n\t\t * automatically and not left for our parent's wait4 call.\n\t\t * Rather than having the parent do it as a magic kind of\n\t\t * signal handler, we just set this to tell do_exit that we\n\t\t * can be cleaned up without becoming a zombie. Note that\n\t\t * we still call __wake_up_parent in this case, because a\n\t\t * blocked sys_wait4 might now return -ECHILD.\n\t\t *\n\t\t * Whether we send SIGCHLD or not for SA_NOCLDWAIT\n\t\t * is implementation-defined: we do (if you don't want\n\t\t * it, just use SIG_IGN instead).\n\t\t */\n\t\tautoreap = true;\n\t\tif (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN)\n\t\t\tsig = 0;\n\t}\n\tif (valid_signal(sig) && sig)\n\t\t__group_send_sig_info(sig, &info, tsk->parent);\n\t__wake_up_parent(tsk, tsk->parent);\n\tspin_unlock_irqrestore(&psig->siglock, flags);\n\n\treturn autoreap;\n}", "project": "linux", "hash": 91267481540745002935349375046199958172, "size": 93, "commit_id": "d1e7fd6462ca9fc76650fbe6ca800e35b24267da", "message": "signal: Extend exec_id to 64bits\n\nReplace the 32bit exec_id with a 64bit exec_id to make it impossible\nto wrap the exec_id counter. With care an attacker can cause exec_id\nwrap and send arbitrary signals to a newly exec'd parent. This\nbypasses the signal sending checks if the parent changes their\ncredentials during exec.\n\nThe severity of this problem can been seen that in my limited testing\nof a 32bit exec_id it can take as little as 19s to exec 65536 times.\nWhich means that it can take as little as 14 days to wrap a 32bit\nexec_id. Adam Zabrocki has succeeded wrapping the self_exe_id in 7\ndays. Even my slower timing is in the uptime of a typical server.\nWhich means self_exec_id is simply a speed bump today, and if exec\ngets noticably faster self_exec_id won't even be a speed bump.\n\nExtending self_exec_id to 64bits introduces a problem on 32bit\narchitectures where reading self_exec_id is no longer atomic and can\ntake two read instructions. Which means that is is possible to hit\na window where the read value of exec_id does not match the written\nvalue. So with very lucky timing after this change this still\nremains expoiltable.\n\nI have updated the update of exec_id on exec to use WRITE_ONCE\nand the read of exec_id in do_notify_parent to use READ_ONCE\nto make it clear that there is no locking between these two\nlocations.\n\nLink: https://lore.kernel.org/kernel-hardening/20200324215049.GA3710@pi3.com.pl\nFixes: 2.3.23pre2\nCc: stable@vger.kernel.org\nSigned-off-by: \"Eric W. Biederman\" ", "target": 0, "dataset": "other", "idx": 375155} {"func": "static struct ip *ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp)\n{\n register struct mbuf *m = dtom(slirp, ip);\n register struct ipasfrag *q;\n int hlen = ip->ip_hl << 2;\n int i, next;\n\n DEBUG_CALL(\"ip_reass\");\n DEBUG_ARG(\"ip = %p\", ip);\n DEBUG_ARG(\"fp = %p\", fp);\n DEBUG_ARG(\"m = %p\", m);\n\n /*\n * Presence of header sizes in mbufs\n * would confuse code below.\n * Fragment m_data is concatenated.\n */\n m->m_data += hlen;\n m->m_len -= hlen;\n\n /*\n * If first fragment to arrive, create a reassembly queue.\n */\n if (fp == NULL) {\n struct mbuf *t = m_get(slirp);\n\n if (t == NULL) {\n goto dropfrag;\n }\n fp = mtod(t, struct ipq *);\n insque(&fp->ip_link, &slirp->ipq.ip_link);\n fp->ipq_ttl = IPFRAGTTL;\n fp->ipq_p = ip->ip_p;\n fp->ipq_id = ip->ip_id;\n fp->frag_link.next = fp->frag_link.prev = &fp->frag_link;\n fp->ipq_src = ip->ip_src;\n fp->ipq_dst = ip->ip_dst;\n q = (struct ipasfrag *)fp;\n goto insert;\n }\n\n /*\n * Find a segment which begins after this one does.\n */\n for (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next)\n if (q->ipf_off > ip->ip_off)\n break;\n\n /*\n * If there is a preceding segment, it may provide some of\n * our data already. If so, drop the data from the incoming\n * segment. If it provides all of our data, drop us.\n */\n if (q->ipf_prev != &fp->frag_link) {\n struct ipasfrag *pq = q->ipf_prev;\n i = pq->ipf_off + pq->ipf_len - ip->ip_off;\n if (i > 0) {\n if (i >= ip->ip_len)\n goto dropfrag;\n m_adj(dtom(slirp, ip), i);\n ip->ip_off += i;\n ip->ip_len -= i;\n }\n }\n\n /*\n * While we overlap succeeding segments trim them or,\n * if they are completely covered, dequeue them.\n */\n while (q != (struct ipasfrag *)&fp->frag_link &&\n ip->ip_off + ip->ip_len > q->ipf_off) {\n i = (ip->ip_off + ip->ip_len) - q->ipf_off;\n if (i < q->ipf_len) {\n q->ipf_len -= i;\n q->ipf_off += i;\n m_adj(dtom(slirp, q), i);\n break;\n }\n q = q->ipf_next;\n m_free(dtom(slirp, q->ipf_prev));\n ip_deq(q->ipf_prev);\n }\n\ninsert:\n /*\n * Stick new segment in its place;\n * check for complete reassembly.\n */\n ip_enq(iptofrag(ip), q->ipf_prev);\n next = 0;\n for (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next) {\n if (q->ipf_off != next)\n return NULL;\n next += q->ipf_len;\n }\n if (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)\n return NULL;\n\n /*\n * Reassembly is complete; concatenate fragments.\n */\n q = fp->frag_link.next;\n m = dtom(slirp, q);\n\n q = (struct ipasfrag *)q->ipf_next;\n while (q != (struct ipasfrag *)&fp->frag_link) {\n struct mbuf *t = dtom(slirp, q);\n q = (struct ipasfrag *)q->ipf_next;\n m_cat(m, t);\n }\n\n /*\n * Create header for new ip packet by\n * modifying header of first packet;\n * dequeue and discard fragment reassembly header.\n * Make header visible.\n */\n q = fp->frag_link.next;\n\n /*\n * If the fragments concatenated to an mbuf that's\n * bigger than the total size of the fragment, then and\n * m_ext buffer was alloced. But fp->ipq_next points to\n * the old buffer (in the mbuf), so we must point ip\n * into the new buffer.\n */\n if (m->m_flags & M_EXT) {\n int delta = (char *)q - m->m_dat;\n q = (struct ipasfrag *)(m->m_ext + delta);\n }\n\n ip = fragtoip(q);\n ip->ip_len = next;\n ip->ip_tos &= ~1;\n ip->ip_src = fp->ipq_src;\n ip->ip_dst = fp->ipq_dst;\n remque(&fp->ip_link);\n (void)m_free(dtom(slirp, fp));\n m->m_len += (ip->ip_hl << 2);\n m->m_data -= (ip->ip_hl << 2);\n\n return ip;\n\ndropfrag:\n m_free(m);\n return NULL;\n}", "project": "libslirp", "hash": 138883903530681634140467642895512584556, "size": 149, "commit_id": "126c04acbabd7ad32c2b018fe10dfac2a3bc1210", "message": "Fix heap overflow in ip_reass on big packet input\n\nWhen the first fragment does not fit in the preallocated buffer, q will\nalready be pointing to the ext buffer, so we mustn't try to update it.\n\nSigned-off-by: Samuel Thibault ", "target": 1, "dataset": "other", "idx": 205959} {"func": "static struct ip *ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp)\n{\n register struct mbuf *m = dtom(slirp, ip);\n register struct ipasfrag *q;\n int hlen = ip->ip_hl << 2;\n int i, next;\n\n DEBUG_CALL(\"ip_reass\");\n DEBUG_ARG(\"ip = %p\", ip);\n DEBUG_ARG(\"fp = %p\", fp);\n DEBUG_ARG(\"m = %p\", m);\n\n /*\n * Presence of header sizes in mbufs\n * would confuse code below.\n * Fragment m_data is concatenated.\n */\n m->m_data += hlen;\n m->m_len -= hlen;\n\n /*\n * If first fragment to arrive, create a reassembly queue.\n */\n if (fp == NULL) {\n struct mbuf *t = m_get(slirp);\n\n if (t == NULL) {\n goto dropfrag;\n }\n fp = mtod(t, struct ipq *);\n insque(&fp->ip_link, &slirp->ipq.ip_link);\n fp->ipq_ttl = IPFRAGTTL;\n fp->ipq_p = ip->ip_p;\n fp->ipq_id = ip->ip_id;\n fp->frag_link.next = fp->frag_link.prev = &fp->frag_link;\n fp->ipq_src = ip->ip_src;\n fp->ipq_dst = ip->ip_dst;\n q = (struct ipasfrag *)fp;\n goto insert;\n }\n\n /*\n * Find a segment which begins after this one does.\n */\n for (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next)\n if (q->ipf_off > ip->ip_off)\n break;\n\n /*\n * If there is a preceding segment, it may provide some of\n * our data already. If so, drop the data from the incoming\n * segment. If it provides all of our data, drop us.\n */\n if (q->ipf_prev != &fp->frag_link) {\n struct ipasfrag *pq = q->ipf_prev;\n i = pq->ipf_off + pq->ipf_len - ip->ip_off;\n if (i > 0) {\n if (i >= ip->ip_len)\n goto dropfrag;\n m_adj(dtom(slirp, ip), i);\n ip->ip_off += i;\n ip->ip_len -= i;\n }\n }\n\n /*\n * While we overlap succeeding segments trim them or,\n * if they are completely covered, dequeue them.\n */\n while (q != (struct ipasfrag *)&fp->frag_link &&\n ip->ip_off + ip->ip_len > q->ipf_off) {\n i = (ip->ip_off + ip->ip_len) - q->ipf_off;\n if (i < q->ipf_len) {\n q->ipf_len -= i;\n q->ipf_off += i;\n m_adj(dtom(slirp, q), i);\n break;\n }\n q = q->ipf_next;\n m_free(dtom(slirp, q->ipf_prev));\n ip_deq(q->ipf_prev);\n }\n\ninsert:\n /*\n * Stick new segment in its place;\n * check for complete reassembly.\n */\n ip_enq(iptofrag(ip), q->ipf_prev);\n next = 0;\n for (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;\n q = q->ipf_next) {\n if (q->ipf_off != next)\n return NULL;\n next += q->ipf_len;\n }\n if (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)\n return NULL;\n\n /*\n * Reassembly is complete; concatenate fragments.\n */\n q = fp->frag_link.next;\n m = dtom(slirp, q);\n\n int was_ext = m->m_flags & M_EXT;\n\n q = (struct ipasfrag *)q->ipf_next;\n while (q != (struct ipasfrag *)&fp->frag_link) {\n struct mbuf *t = dtom(slirp, q);\n q = (struct ipasfrag *)q->ipf_next;\n m_cat(m, t);\n }\n\n /*\n * Create header for new ip packet by\n * modifying header of first packet;\n * dequeue and discard fragment reassembly header.\n * Make header visible.\n */\n q = fp->frag_link.next;\n\n /*\n * If the fragments concatenated to an mbuf that's\n * bigger than the total size of the fragment, then and\n * m_ext buffer was alloced. But fp->ipq_next points to\n * the old buffer (in the mbuf), so we must point ip\n * into the new buffer.\n */\n if (!was_ext && m->m_flags & M_EXT) {\n int delta = (char *)q - m->m_dat;\n q = (struct ipasfrag *)(m->m_ext + delta);\n }\n\n ip = fragtoip(q);\n ip->ip_len = next;\n ip->ip_tos &= ~1;\n ip->ip_src = fp->ipq_src;\n ip->ip_dst = fp->ipq_dst;\n remque(&fp->ip_link);\n (void)m_free(dtom(slirp, fp));\n m->m_len += (ip->ip_hl << 2);\n m->m_data -= (ip->ip_hl << 2);\n\n return ip;\n\ndropfrag:\n m_free(m);\n return NULL;\n}", "project": "libslirp", "hash": 51858820435074331770642832081553618150, "size": 151, "commit_id": "126c04acbabd7ad32c2b018fe10dfac2a3bc1210", "message": "Fix heap overflow in ip_reass on big packet input\n\nWhen the first fragment does not fit in the preallocated buffer, q will\nalready be pointing to the ext buffer, so we mustn't try to update it.\n\nSigned-off-by: Samuel Thibault ", "target": 0, "dataset": "other", "idx": 375358} {"func": "static SMacro *expand_one_smacro(Token ***tpp)\n{\n Token **params = NULL;\n const char *mname;\n Token *mstart = **tpp;\n Token *tline = mstart;\n SMacro *head, *m;\n int i;\n Token *t, *tup, *tafter;\n int nparam = 0;\n bool cond_comma;\n\n if (!tline)\n return false; /* Empty line, nothing to do */\n\n mname = tok_text(mstart);\n\n smacro_deadman.total--;\n smacro_deadman.levels--;\n\n if (unlikely(smacro_deadman.total < 0 || smacro_deadman.levels < 0)) {\n if (unlikely(!smacro_deadman.triggered)) {\n nasm_nonfatal(\"interminable macro recursion\");\n smacro_deadman.triggered = true;\n }\n goto not_a_macro;\n } else if (tline->type == TOK_ID || tline->type == TOK_PREPROC_ID) {\n head = (SMacro *)hash_findix(&smacros, mname);\n } else if (tline->type == TOK_LOCAL_MACRO) {\n Context *ctx = get_ctx(mname, &mname);\n head = ctx ? (SMacro *)hash_findix(&ctx->localmac, mname) : NULL;\n } else {\n goto not_a_macro;\n }\n\n /*\n * We've hit an identifier of some sort. First check whether the\n * identifier is a single-line macro at all, then think about\n * checking for parameters if necessary.\n */\n list_for_each(m, head) {\n if (unlikely(m->alias && ppopt.noaliases))\n continue;\n if (!mstrcmp(m->name, mname, m->casesense))\n break;\n }\n\n if (!m) {\n goto not_a_macro;\n }\n\n /* Parse parameters, if applicable */\n\n params = NULL;\n nparam = 0;\n\n if (m->nparam == 0) {\n /*\n * Simple case: the macro is parameterless.\n * Nothing to parse; the expansion code will\n * drop the macro name token.\n */\n } else {\n /*\n * Complicated case: at least one macro with this name\n * exists and takes parameters. We must find the\n * parameters in the call, count them, find the SMacro\n * that corresponds to that form of the macro call, and\n * substitute for the parameters when we expand. What a\n * pain.\n */\n Token *t;\n int paren, brackets;\n\n tline = tline->next;\n tline = skip_white(tline);\n if (!tok_is(tline, '(')) {\n /*\n * This macro wasn't called with parameters: ignore\n * the call. (Behaviour borrowed from gnu cpp.)\n */\n goto not_a_macro;\n }\n\n paren = 1;\n nparam = 1;\n brackets = 0;\n t = tline; /* tline points to leading ( */\n\n while (paren) {\n t = t->next;\n\n if (!t) {\n nasm_nonfatal(\"macro call expects terminating `)'\");\n goto not_a_macro;\n }\n\n if (t->type != TOK_OTHER || t->len != 1)\n continue;\n\n switch (t->text.a[0]) {\n case ',':\n if (!brackets && paren == 1)\n nparam++;\n break;\n\n case '{':\n brackets++;\n break;\n\n case '}':\n if (brackets > 0)\n brackets--;\n break;\n\n case '(':\n if (!brackets)\n paren++;\n break;\n\n case ')':\n if (!brackets)\n paren--;\n break;\n\n default:\n break; /* Normal token */\n }\n }\n\n /*\n * Look for a macro matching in both name and parameter count.\n * We already know any matches cannot be anywhere before the\n * current position of \"m\", so there is no reason to\n * backtrack.\n */\n while (1) {\n if (!m) {\n /*!\n *!macro-params-single [on] single-line macro calls with wrong parameter count\n *! warns about \\i{single-line macros} being invoked\n *! with the wrong number of parameters.\n */\n nasm_warn(WARN_MACRO_PARAMS_SINGLE|ERR_HOLD,\n \"single-line macro `%s' exists, \"\n \"but not taking %d parameter%s\",\n mname, nparam, (nparam == 1) ? \"\" : \"s\");\n goto not_a_macro;\n }\n\n if (!mstrcmp(m->name, mname, m->casesense)) {\n if (nparam == m->nparam)\n break; /* It's good */\n if (m->greedy && nparam >= m->nparam-1)\n break; /* Also good */\n }\n m = m->next;\n }\n }\n\n if (m->in_progress)\n goto not_a_macro;\n\n /* Expand the macro */\n m->in_progress = true;\n\n if (nparam) {\n /* Extract parameters */\n Token **phead, **pep;\n int white = 0;\n int brackets = 0;\n int paren;\n bool bracketed = false;\n bool bad_bracket = false;\n enum sparmflags flags;\n\n nparam = m->nparam;\n paren = 1;\n nasm_newn(params, nparam);\n i = 0;\n flags = m->params[i].flags;\n phead = pep = ¶ms[i];\n *pep = NULL;\n\n while (paren) {\n bool skip;\n char ch;\n\n tline = tline->next;\n\n if (!tline)\n nasm_nonfatal(\"macro call expects terminating `)'\");\n\n ch = 0;\n skip = false;\n\n\n switch (tline->type) {\n case TOK_OTHER:\n if (tline->len == 1)\n ch = tline->text.a[0];\n break;\n\n case TOK_WHITESPACE:\n if (!(flags & SPARM_NOSTRIP)) {\n if (brackets || *phead)\n white++; /* Keep interior whitespace */\n skip = true;\n }\n break;\n\n default:\n break;\n }\n\n switch (ch) {\n case ',':\n if (!brackets && paren == 1 && !(flags & SPARM_GREEDY)) {\n i++;\n nasm_assert(i < nparam);\n phead = pep = ¶ms[i];\n *pep = NULL;\n bracketed = false;\n skip = true;\n flags = m->params[i].flags;\n }\n break;\n\n case '{':\n if (!bracketed) {\n bracketed = !*phead && !(flags & SPARM_NOSTRIP);\n skip = bracketed;\n }\n brackets++;\n break;\n\n case '}':\n if (brackets > 0) {\n if (!--brackets)\n skip = bracketed;\n }\n break;\n\n case '(':\n if (!brackets)\n paren++;\n break;\n\n case ')':\n if (!brackets) {\n paren--;\n if (!paren) {\n skip = true;\n i++; /* Found last argument */\n }\n }\n break;\n\n default:\n break; /* Normal token */\n }\n\n if (!skip) {\n Token *t;\n\n bad_bracket |= bracketed && !brackets;\n\n if (white) {\n *pep = t = new_White(NULL);\n pep = &t->next;\n white = 0;\n }\n *pep = t = dup_Token(NULL, tline);\n pep = &t->next;\n }\n }\n\n /*\n * Possible further processing of parameters. Note that the\n * ordering matters here.\n */\n for (i = 0; i < nparam; i++) {\n enum sparmflags flags = m->params[i].flags;\n\n if (flags & SPARM_EVAL) {\n /* Evaluate this parameter as a number */\n struct ppscan pps;\n struct tokenval tokval;\n expr *evalresult;\n Token *eval_param;\n\n pps.tptr = eval_param = expand_smacro_noreset(params[i]);\n pps.ntokens = -1;\n tokval.t_type = TOKEN_INVALID;\n evalresult = evaluate(ppscan, &pps, &tokval, NULL, true, NULL);\n\n free_tlist(eval_param);\n params[i] = NULL;\n\n if (!evalresult) {\n /* Nothing meaningful to do */\n } else if (tokval.t_type) {\n nasm_nonfatal(\"invalid expression in parameter %d of macro `%s'\", i, m->name);\n } else if (!is_simple(evalresult)) {\n nasm_nonfatal(\"non-constant expression in parameter %d of macro `%s'\", i, m->name);\n } else {\n params[i] = make_tok_num(NULL, reloc_value(evalresult));\n }\n }\n\n if (flags & SPARM_STR) {\n /* Convert expansion to a quoted string */\n char *arg;\n Token *qs;\n\n qs = expand_smacro_noreset(params[i]);\n arg = detoken(qs, false);\n free_tlist(qs);\n params[i] = make_tok_qstr(NULL, arg);\n nasm_free(arg);\n }\n }\n }\n\n /* Note: we own the expansion this returns. */\n t = m->expand(m, params, nparam);\n\n tafter = tline->next; /* Skip past the macro call */\n tline->next = NULL;\t\t/* Truncate list at the macro call end */\n tline = tafter;\n\n tup = NULL;\n cond_comma = false;\n\n while (t) {\n enum pp_token_type type = t->type;\n Token *tnext = t->next;\n\n switch (type) {\n case TOK_PREPROC_Q:\n case TOK_PREPROC_SQ:\n delete_Token(t);\n t = dup_Token(tline, mstart);\n break;\n\n case TOK_PREPROC_QQ:\n case TOK_PREPROC_SQQ:\n {\n size_t mlen = strlen(m->name);\n\t size_t len;\n char *p;\n\n t->type = mstart->type;\n if (t->type == TOK_LOCAL_MACRO) {\n\t\tconst char *psp; /* prefix start pointer */\n const char *pep; /* prefix end pointer */\n\t\tsize_t plen;\n\n\t\tpsp = tok_text(mstart);\n get_ctx(psp, &pep);\n plen = pep - psp;\n\n len = mlen + plen;\n p = nasm_malloc(len + 1);\n p = mempcpy(p, psp, plen);\n } else {\n len = mlen;\n p = nasm_malloc(len + 1);\n }\n p = mempcpy(p, m->name, mlen);\n *p = '\\0';\n\t set_text_free(t, p, len);\n\n t->next = tline;\n break;\n }\n\n case TOK_COND_COMMA:\n delete_Token(t);\n t = cond_comma ? make_tok_char(tline, ',') : NULL;\n break;\n\n case TOK_ID:\n case TOK_PREPROC_ID:\n\tcase TOK_LOCAL_MACRO:\n {\n /*\n * Chain this into the target line *before* expanding,\n * that way we pick up any arguments to the new macro call,\n * if applicable.\n */\n Token **tp = &t;\n t->next = tline;\n expand_one_smacro(&tp);\n tline = *tp; /* First token left after any macro call */\n break;\n }\n default:\n if (is_smac_param(t->type)) {\n int param = smac_nparam(t->type);\n nasm_assert(!tup && param < nparam);\n delete_Token(t);\n t = NULL;\n tup = tnext;\n tnext = dup_tlist_reverse(params[param], NULL);\n cond_comma = false;\n } else {\n t->next = tline;\n }\n }\n\n if (t) {\n Token *endt = tline;\n\n tline = t;\n while (!cond_comma && t && t != endt) {\n cond_comma = t->type != TOK_WHITESPACE;\n t = t->next;\n }\n }\n\n if (tnext) {\n t = tnext;\n } else {\n t = tup;\n tup = NULL;\n }\n }\n\n **tpp = tline;\n for (t = tline; t && t != tafter; t = t->next)\n *tpp = &t->next;\n\n m->in_progress = false;\n\n /* Don't do this until after expansion or we will clobber mname */\n free_tlist(mstart);\n goto done;\n\n /*\n * No macro expansion needed; roll back to mstart (if necessary)\n * and then advance to the next input token. Note that this is\n * by far the common case!\n */\nnot_a_macro:\n *tpp = &mstart->next;\n m = NULL;\ndone:\n smacro_deadman.levels++;\n if (unlikely(params))\n free_tlist_array(params, nparam);\n return m;\n}", "project": "nasm", "hash": 74552473003065677858003804288043584224, "size": 453, "commit_id": "7c88289e222dc5ef9f53f9e86ecaab1924744b88", "message": "BR3392711: preproc: fix memory corruption in expand_one_smacro\n\nThe mempcpy helper returns *last* byte pointer thus when\nwe call set_text_free we have to pass a pointer to the\nstart of the string.\n\nSigned-off-by: Cyrill Gorcunov ", "target": 1, "dataset": "other", "idx": 205976} {"func": "static SMacro *expand_one_smacro(Token ***tpp)\n{\n Token **params = NULL;\n const char *mname;\n Token *mstart = **tpp;\n Token *tline = mstart;\n SMacro *head, *m;\n int i;\n Token *t, *tup, *tafter;\n int nparam = 0;\n bool cond_comma;\n\n if (!tline)\n return false; /* Empty line, nothing to do */\n\n mname = tok_text(mstart);\n\n smacro_deadman.total--;\n smacro_deadman.levels--;\n\n if (unlikely(smacro_deadman.total < 0 || smacro_deadman.levels < 0)) {\n if (unlikely(!smacro_deadman.triggered)) {\n nasm_nonfatal(\"interminable macro recursion\");\n smacro_deadman.triggered = true;\n }\n goto not_a_macro;\n } else if (tline->type == TOK_ID || tline->type == TOK_PREPROC_ID) {\n head = (SMacro *)hash_findix(&smacros, mname);\n } else if (tline->type == TOK_LOCAL_MACRO) {\n Context *ctx = get_ctx(mname, &mname);\n head = ctx ? (SMacro *)hash_findix(&ctx->localmac, mname) : NULL;\n } else {\n goto not_a_macro;\n }\n\n /*\n * We've hit an identifier of some sort. First check whether the\n * identifier is a single-line macro at all, then think about\n * checking for parameters if necessary.\n */\n list_for_each(m, head) {\n if (unlikely(m->alias && ppopt.noaliases))\n continue;\n if (!mstrcmp(m->name, mname, m->casesense))\n break;\n }\n\n if (!m) {\n goto not_a_macro;\n }\n\n /* Parse parameters, if applicable */\n\n params = NULL;\n nparam = 0;\n\n if (m->nparam == 0) {\n /*\n * Simple case: the macro is parameterless.\n * Nothing to parse; the expansion code will\n * drop the macro name token.\n */\n } else {\n /*\n * Complicated case: at least one macro with this name\n * exists and takes parameters. We must find the\n * parameters in the call, count them, find the SMacro\n * that corresponds to that form of the macro call, and\n * substitute for the parameters when we expand. What a\n * pain.\n */\n Token *t;\n int paren, brackets;\n\n tline = tline->next;\n tline = skip_white(tline);\n if (!tok_is(tline, '(')) {\n /*\n * This macro wasn't called with parameters: ignore\n * the call. (Behaviour borrowed from gnu cpp.)\n */\n goto not_a_macro;\n }\n\n paren = 1;\n nparam = 1;\n brackets = 0;\n t = tline; /* tline points to leading ( */\n\n while (paren) {\n t = t->next;\n\n if (!t) {\n nasm_nonfatal(\"macro call expects terminating `)'\");\n goto not_a_macro;\n }\n\n if (t->type != TOK_OTHER || t->len != 1)\n continue;\n\n switch (t->text.a[0]) {\n case ',':\n if (!brackets && paren == 1)\n nparam++;\n break;\n\n case '{':\n brackets++;\n break;\n\n case '}':\n if (brackets > 0)\n brackets--;\n break;\n\n case '(':\n if (!brackets)\n paren++;\n break;\n\n case ')':\n if (!brackets)\n paren--;\n break;\n\n default:\n break; /* Normal token */\n }\n }\n\n /*\n * Look for a macro matching in both name and parameter count.\n * We already know any matches cannot be anywhere before the\n * current position of \"m\", so there is no reason to\n * backtrack.\n */\n while (1) {\n if (!m) {\n /*!\n *!macro-params-single [on] single-line macro calls with wrong parameter count\n *! warns about \\i{single-line macros} being invoked\n *! with the wrong number of parameters.\n */\n nasm_warn(WARN_MACRO_PARAMS_SINGLE|ERR_HOLD,\n \"single-line macro `%s' exists, \"\n \"but not taking %d parameter%s\",\n mname, nparam, (nparam == 1) ? \"\" : \"s\");\n goto not_a_macro;\n }\n\n if (!mstrcmp(m->name, mname, m->casesense)) {\n if (nparam == m->nparam)\n break; /* It's good */\n if (m->greedy && nparam >= m->nparam-1)\n break; /* Also good */\n }\n m = m->next;\n }\n }\n\n if (m->in_progress)\n goto not_a_macro;\n\n /* Expand the macro */\n m->in_progress = true;\n\n if (nparam) {\n /* Extract parameters */\n Token **phead, **pep;\n int white = 0;\n int brackets = 0;\n int paren;\n bool bracketed = false;\n bool bad_bracket = false;\n enum sparmflags flags;\n\n nparam = m->nparam;\n paren = 1;\n nasm_newn(params, nparam);\n i = 0;\n flags = m->params[i].flags;\n phead = pep = ¶ms[i];\n *pep = NULL;\n\n while (paren) {\n bool skip;\n char ch;\n\n tline = tline->next;\n\n if (!tline)\n nasm_nonfatal(\"macro call expects terminating `)'\");\n\n ch = 0;\n skip = false;\n\n\n switch (tline->type) {\n case TOK_OTHER:\n if (tline->len == 1)\n ch = tline->text.a[0];\n break;\n\n case TOK_WHITESPACE:\n if (!(flags & SPARM_NOSTRIP)) {\n if (brackets || *phead)\n white++; /* Keep interior whitespace */\n skip = true;\n }\n break;\n\n default:\n break;\n }\n\n switch (ch) {\n case ',':\n if (!brackets && paren == 1 && !(flags & SPARM_GREEDY)) {\n i++;\n nasm_assert(i < nparam);\n phead = pep = ¶ms[i];\n *pep = NULL;\n bracketed = false;\n skip = true;\n flags = m->params[i].flags;\n }\n break;\n\n case '{':\n if (!bracketed) {\n bracketed = !*phead && !(flags & SPARM_NOSTRIP);\n skip = bracketed;\n }\n brackets++;\n break;\n\n case '}':\n if (brackets > 0) {\n if (!--brackets)\n skip = bracketed;\n }\n break;\n\n case '(':\n if (!brackets)\n paren++;\n break;\n\n case ')':\n if (!brackets) {\n paren--;\n if (!paren) {\n skip = true;\n i++; /* Found last argument */\n }\n }\n break;\n\n default:\n break; /* Normal token */\n }\n\n if (!skip) {\n Token *t;\n\n bad_bracket |= bracketed && !brackets;\n\n if (white) {\n *pep = t = new_White(NULL);\n pep = &t->next;\n white = 0;\n }\n *pep = t = dup_Token(NULL, tline);\n pep = &t->next;\n }\n }\n\n /*\n * Possible further processing of parameters. Note that the\n * ordering matters here.\n */\n for (i = 0; i < nparam; i++) {\n enum sparmflags flags = m->params[i].flags;\n\n if (flags & SPARM_EVAL) {\n /* Evaluate this parameter as a number */\n struct ppscan pps;\n struct tokenval tokval;\n expr *evalresult;\n Token *eval_param;\n\n pps.tptr = eval_param = expand_smacro_noreset(params[i]);\n pps.ntokens = -1;\n tokval.t_type = TOKEN_INVALID;\n evalresult = evaluate(ppscan, &pps, &tokval, NULL, true, NULL);\n\n free_tlist(eval_param);\n params[i] = NULL;\n\n if (!evalresult) {\n /* Nothing meaningful to do */\n } else if (tokval.t_type) {\n nasm_nonfatal(\"invalid expression in parameter %d of macro `%s'\", i, m->name);\n } else if (!is_simple(evalresult)) {\n nasm_nonfatal(\"non-constant expression in parameter %d of macro `%s'\", i, m->name);\n } else {\n params[i] = make_tok_num(NULL, reloc_value(evalresult));\n }\n }\n\n if (flags & SPARM_STR) {\n /* Convert expansion to a quoted string */\n char *arg;\n Token *qs;\n\n qs = expand_smacro_noreset(params[i]);\n arg = detoken(qs, false);\n free_tlist(qs);\n params[i] = make_tok_qstr(NULL, arg);\n nasm_free(arg);\n }\n }\n }\n\n /* Note: we own the expansion this returns. */\n t = m->expand(m, params, nparam);\n\n tafter = tline->next; /* Skip past the macro call */\n tline->next = NULL;\t\t/* Truncate list at the macro call end */\n tline = tafter;\n\n tup = NULL;\n cond_comma = false;\n\n while (t) {\n enum pp_token_type type = t->type;\n Token *tnext = t->next;\n\n switch (type) {\n case TOK_PREPROC_Q:\n case TOK_PREPROC_SQ:\n delete_Token(t);\n t = dup_Token(tline, mstart);\n break;\n\n case TOK_PREPROC_QQ:\n case TOK_PREPROC_SQQ:\n {\n size_t mlen = strlen(m->name);\n\t size_t len;\n char *p, *from;\n\n t->type = mstart->type;\n if (t->type == TOK_LOCAL_MACRO) {\n\t\tconst char *psp; /* prefix start pointer */\n const char *pep; /* prefix end pointer */\n\t\tsize_t plen;\n\n\t\tpsp = tok_text(mstart);\n get_ctx(psp, &pep);\n plen = pep - psp;\n\n len = mlen + plen;\n from = p = nasm_malloc(len + 1);\n p = mempcpy(p, psp, plen);\n } else {\n len = mlen;\n from = p = nasm_malloc(len + 1);\n }\n p = mempcpy(p, m->name, mlen);\n *p = '\\0';\n\t set_text_free(t, from, len);\n\n t->next = tline;\n break;\n }\n\n case TOK_COND_COMMA:\n delete_Token(t);\n t = cond_comma ? make_tok_char(tline, ',') : NULL;\n break;\n\n case TOK_ID:\n case TOK_PREPROC_ID:\n\tcase TOK_LOCAL_MACRO:\n {\n /*\n * Chain this into the target line *before* expanding,\n * that way we pick up any arguments to the new macro call,\n * if applicable.\n */\n Token **tp = &t;\n t->next = tline;\n expand_one_smacro(&tp);\n tline = *tp; /* First token left after any macro call */\n break;\n }\n default:\n if (is_smac_param(t->type)) {\n int param = smac_nparam(t->type);\n nasm_assert(!tup && param < nparam);\n delete_Token(t);\n t = NULL;\n tup = tnext;\n tnext = dup_tlist_reverse(params[param], NULL);\n cond_comma = false;\n } else {\n t->next = tline;\n }\n }\n\n if (t) {\n Token *endt = tline;\n\n tline = t;\n while (!cond_comma && t && t != endt) {\n cond_comma = t->type != TOK_WHITESPACE;\n t = t->next;\n }\n }\n\n if (tnext) {\n t = tnext;\n } else {\n t = tup;\n tup = NULL;\n }\n }\n\n **tpp = tline;\n for (t = tline; t && t != tafter; t = t->next)\n *tpp = &t->next;\n\n m->in_progress = false;\n\n /* Don't do this until after expansion or we will clobber mname */\n free_tlist(mstart);\n goto done;\n\n /*\n * No macro expansion needed; roll back to mstart (if necessary)\n * and then advance to the next input token. Note that this is\n * by far the common case!\n */\nnot_a_macro:\n *tpp = &mstart->next;\n m = NULL;\ndone:\n smacro_deadman.levels++;\n if (unlikely(params))\n free_tlist_array(params, nparam);\n return m;\n}", "project": "nasm", "hash": 103568277309255258992223520108689986234, "size": 453, "commit_id": "7c88289e222dc5ef9f53f9e86ecaab1924744b88", "message": "BR3392711: preproc: fix memory corruption in expand_one_smacro\n\nThe mempcpy helper returns *last* byte pointer thus when\nwe call set_text_free we have to pass a pointer to the\nstart of the string.\n\nSigned-off-by: Cyrill Gorcunov ", "target": 0, "dataset": "other", "idx": 375670} {"func": "int url_is_local_not_ssh(const char *url)\n{\n\tconst char *colon = strchr(url, ':');\n\tconst char *slash = strchr(url, '/');\n\treturn !colon || (slash && slash < colon) ||\n\t\thas_dos_drive_prefix(url);\n}", "project": "git", "hash": 93761688030965830881707145604603054740, "size": 7, "commit_id": "f82a97eb9197c1e3768e72648f37ce0ca3233734", "message": "mingw: handle `subst`-ed \"DOS drives\"\n\nOver a decade ago, in 25fe217b86c (Windows: Treat Windows style path\nnames., 2008-03-05), Git was taught to handle absolute Windows paths,\ni.e. paths that start with a drive letter and a colon.\n\nUnbeknownst to us, while drive letters of physical drives are limited to\nletters of the English alphabet, there is a way to assign virtual drive\nletters to arbitrary directories, via the `subst` command, which is\n_not_ limited to English letters.\n\nIt is therefore possible to have absolute Windows paths of the form\n`1:\\what\\the\\hex.txt`. Even \"better\": pretty much arbitrary Unicode\nletters can also be used, e.g. `\u00e4:\\tschib\u00e4t.sch`.\n\nWhile it can be sensibly argued that users who set up such funny drive\nletters really seek adverse consequences, the Windows Operating System\nis known to be a platform where many users are at the mercy of\nadministrators who have their very own idea of what constitutes a\nreasonable setup.\n\nTherefore, let's just make sure that such funny paths are still\nconsidered absolute paths by Git, on Windows.\n\nIn addition to Unicode characters, pretty much any character is a valid\ndrive letter, as far as `subst` is concerned, even `:` and `\"` or even a\nspace character. While it is probably the opposite of smart to use them,\nlet's safeguard `is_dos_drive_prefix()` against all of them.\n\nNote: `[::1]:repo` is a valid URL, but not a valid path on Windows.\nAs `[` is now considered a valid drive letter, we need to be very\ncareful to avoid misinterpreting such a string as valid local path in\n`url_is_local_not_ssh()`. To do that, we use the just-introduced\nfunction `is_valid_path()` (which will label the string as invalid file\nname because of the colon characters).\n\nThis fixes CVE-2019-1351.\n\nReported-by: Nicolas Joly \nSigned-off-by: Johannes Schindelin ", "target": 1, "dataset": "other", "idx": 206023} {"func": "int url_is_local_not_ssh(const char *url)\n{\n\tconst char *colon = strchr(url, ':');\n\tconst char *slash = strchr(url, '/');\n\treturn !colon || (slash && slash < colon) ||\n\t\t(has_dos_drive_prefix(url) && is_valid_path(url));\n}", "project": "git", "hash": 322711509457870301529370883808295524605, "size": 7, "commit_id": "f82a97eb9197c1e3768e72648f37ce0ca3233734", "message": "mingw: handle `subst`-ed \"DOS drives\"\n\nOver a decade ago, in 25fe217b86c (Windows: Treat Windows style path\nnames., 2008-03-05), Git was taught to handle absolute Windows paths,\ni.e. paths that start with a drive letter and a colon.\n\nUnbeknownst to us, while drive letters of physical drives are limited to\nletters of the English alphabet, there is a way to assign virtual drive\nletters to arbitrary directories, via the `subst` command, which is\n_not_ limited to English letters.\n\nIt is therefore possible to have absolute Windows paths of the form\n`1:\\what\\the\\hex.txt`. Even \"better\": pretty much arbitrary Unicode\nletters can also be used, e.g. `\u00e4:\\tschib\u00e4t.sch`.\n\nWhile it can be sensibly argued that users who set up such funny drive\nletters really seek adverse consequences, the Windows Operating System\nis known to be a platform where many users are at the mercy of\nadministrators who have their very own idea of what constitutes a\nreasonable setup.\n\nTherefore, let's just make sure that such funny paths are still\nconsidered absolute paths by Git, on Windows.\n\nIn addition to Unicode characters, pretty much any character is a valid\ndrive letter, as far as `subst` is concerned, even `:` and `\"` or even a\nspace character. While it is probably the opposite of smart to use them,\nlet's safeguard `is_dos_drive_prefix()` against all of them.\n\nNote: `[::1]:repo` is a valid URL, but not a valid path on Windows.\nAs `[` is now considered a valid drive letter, we need to be very\ncareful to avoid misinterpreting such a string as valid local path in\n`url_is_local_not_ssh()`. To do that, we use the just-introduced\nfunction `is_valid_path()` (which will label the string as invalid file\nname because of the colon characters).\n\nThis fixes CVE-2019-1351.\n\nReported-by: Nicolas Joly \nSigned-off-by: Johannes Schindelin ", "target": 0, "dataset": "other", "idx": 376250} {"func": "int nested_svm_vmrun(struct vcpu_svm *svm)\n{\n\tint ret;\n\tstruct vmcb *vmcb12;\n\tstruct vmcb *hsave = svm->nested.hsave;\n\tstruct vmcb *vmcb = svm->vmcb;\n\tstruct kvm_host_map map;\n\tu64 vmcb12_gpa;\n\n\tif (is_smm(&svm->vcpu)) {\n\t\tkvm_queue_exception(&svm->vcpu, UD_VECTOR);\n\t\treturn 1;\n\t}\n\n\tvmcb12_gpa = svm->vmcb->save.rax;\n\tret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb12_gpa), &map);\n\tif (ret == -EINVAL) {\n\t\tkvm_inject_gp(&svm->vcpu, 0);\n\t\treturn 1;\n\t} else if (ret) {\n\t\treturn kvm_skip_emulated_instruction(&svm->vcpu);\n\t}\n\n\tret = kvm_skip_emulated_instruction(&svm->vcpu);\n\n\tvmcb12 = map.hva;\n\n\tif (WARN_ON_ONCE(!svm->nested.initialized))\n\t\treturn -EINVAL;\n\n\tif (!nested_vmcb_checks(svm, vmcb12)) {\n\t\tvmcb12->control.exit_code = SVM_EXIT_ERR;\n\t\tvmcb12->control.exit_code_hi = 0;\n\t\tvmcb12->control.exit_info_1 = 0;\n\t\tvmcb12->control.exit_info_2 = 0;\n\t\tgoto out;\n\t}\n\n\ttrace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb12_gpa,\n\t\t\t vmcb12->save.rip,\n\t\t\t vmcb12->control.int_ctl,\n\t\t\t vmcb12->control.event_inj,\n\t\t\t vmcb12->control.nested_ctl);\n\n\ttrace_kvm_nested_intercepts(vmcb12->control.intercepts[INTERCEPT_CR] & 0xffff,\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_CR] >> 16,\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_EXCEPTION],\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_WORD3],\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_WORD4],\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_WORD5]);\n\n\t/* Clear internal status */\n\tkvm_clear_exception_queue(&svm->vcpu);\n\tkvm_clear_interrupt_queue(&svm->vcpu);\n\n\t/*\n\t * Save the old vmcb, so we don't need to pick what we save, but can\n\t * restore everything when a VMEXIT occurs\n\t */\n\thsave->save.es = vmcb->save.es;\n\thsave->save.cs = vmcb->save.cs;\n\thsave->save.ss = vmcb->save.ss;\n\thsave->save.ds = vmcb->save.ds;\n\thsave->save.gdtr = vmcb->save.gdtr;\n\thsave->save.idtr = vmcb->save.idtr;\n\thsave->save.efer = svm->vcpu.arch.efer;\n\thsave->save.cr0 = kvm_read_cr0(&svm->vcpu);\n\thsave->save.cr4 = svm->vcpu.arch.cr4;\n\thsave->save.rflags = kvm_get_rflags(&svm->vcpu);\n\thsave->save.rip = kvm_rip_read(&svm->vcpu);\n\thsave->save.rsp = vmcb->save.rsp;\n\thsave->save.rax = vmcb->save.rax;\n\tif (npt_enabled)\n\t\thsave->save.cr3 = vmcb->save.cr3;\n\telse\n\t\thsave->save.cr3 = kvm_read_cr3(&svm->vcpu);\n\n\tcopy_vmcb_control_area(&hsave->control, &vmcb->control);\n\n\tsvm->nested.nested_run_pending = 1;\n\n\tif (enter_svm_guest_mode(svm, vmcb12_gpa, vmcb12))\n\t\tgoto out_exit_err;\n\n\tif (nested_svm_vmrun_msrpm(svm))\n\t\tgoto out;\n\nout_exit_err:\n\tsvm->nested.nested_run_pending = 0;\n\n\tsvm->vmcb->control.exit_code = SVM_EXIT_ERR;\n\tsvm->vmcb->control.exit_code_hi = 0;\n\tsvm->vmcb->control.exit_info_1 = 0;\n\tsvm->vmcb->control.exit_info_2 = 0;\n\n\tnested_svm_vmexit(svm);\n\nout:\n\tkvm_vcpu_unmap(&svm->vcpu, &map, true);\n\n\treturn ret;\n}", "project": "linux", "hash": 141649806115592010502494780149120635226, "size": 102, "commit_id": "a58d9166a756a0f4a6618e4f593232593d6df134", "message": "KVM: SVM: load control fields from VMCB12 before checking them\n\nAvoid races between check and use of the nested VMCB controls. This\nfor example ensures that the VMRUN intercept is always reflected to the\nnested hypervisor, instead of being processed by the host. Without this\npatch, it is possible to end up with svm->nested.hsave pointing to\nthe MSR permission bitmap for nested guests.\n\nThis bug is CVE-2021-29657.\n\nReported-by: Felix Wilhelm \nCc: stable@vger.kernel.org\nFixes: 2fcf4876ada (\"KVM: nSVM: implement on demand allocation of the nested state\")\nSigned-off-by: Paolo Bonzini ", "target": 1, "dataset": "other", "idx": 206039} {"func": "int nested_svm_vmrun(struct vcpu_svm *svm)\n{\n\tint ret;\n\tstruct vmcb *vmcb12;\n\tstruct vmcb *hsave = svm->nested.hsave;\n\tstruct vmcb *vmcb = svm->vmcb;\n\tstruct kvm_host_map map;\n\tu64 vmcb12_gpa;\n\n\tif (is_smm(&svm->vcpu)) {\n\t\tkvm_queue_exception(&svm->vcpu, UD_VECTOR);\n\t\treturn 1;\n\t}\n\n\tvmcb12_gpa = svm->vmcb->save.rax;\n\tret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb12_gpa), &map);\n\tif (ret == -EINVAL) {\n\t\tkvm_inject_gp(&svm->vcpu, 0);\n\t\treturn 1;\n\t} else if (ret) {\n\t\treturn kvm_skip_emulated_instruction(&svm->vcpu);\n\t}\n\n\tret = kvm_skip_emulated_instruction(&svm->vcpu);\n\n\tvmcb12 = map.hva;\n\n\tif (WARN_ON_ONCE(!svm->nested.initialized))\n\t\treturn -EINVAL;\n\n\tload_nested_vmcb_control(svm, &vmcb12->control);\n\n\tif (!nested_vmcb_check_save(svm, vmcb12) ||\n\t !nested_vmcb_check_controls(&svm->nested.ctl)) {\n\t\tvmcb12->control.exit_code = SVM_EXIT_ERR;\n\t\tvmcb12->control.exit_code_hi = 0;\n\t\tvmcb12->control.exit_info_1 = 0;\n\t\tvmcb12->control.exit_info_2 = 0;\n\t\tgoto out;\n\t}\n\n\ttrace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb12_gpa,\n\t\t\t vmcb12->save.rip,\n\t\t\t vmcb12->control.int_ctl,\n\t\t\t vmcb12->control.event_inj,\n\t\t\t vmcb12->control.nested_ctl);\n\n\ttrace_kvm_nested_intercepts(vmcb12->control.intercepts[INTERCEPT_CR] & 0xffff,\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_CR] >> 16,\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_EXCEPTION],\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_WORD3],\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_WORD4],\n\t\t\t\t vmcb12->control.intercepts[INTERCEPT_WORD5]);\n\n\t/* Clear internal status */\n\tkvm_clear_exception_queue(&svm->vcpu);\n\tkvm_clear_interrupt_queue(&svm->vcpu);\n\n\t/*\n\t * Save the old vmcb, so we don't need to pick what we save, but can\n\t * restore everything when a VMEXIT occurs\n\t */\n\thsave->save.es = vmcb->save.es;\n\thsave->save.cs = vmcb->save.cs;\n\thsave->save.ss = vmcb->save.ss;\n\thsave->save.ds = vmcb->save.ds;\n\thsave->save.gdtr = vmcb->save.gdtr;\n\thsave->save.idtr = vmcb->save.idtr;\n\thsave->save.efer = svm->vcpu.arch.efer;\n\thsave->save.cr0 = kvm_read_cr0(&svm->vcpu);\n\thsave->save.cr4 = svm->vcpu.arch.cr4;\n\thsave->save.rflags = kvm_get_rflags(&svm->vcpu);\n\thsave->save.rip = kvm_rip_read(&svm->vcpu);\n\thsave->save.rsp = vmcb->save.rsp;\n\thsave->save.rax = vmcb->save.rax;\n\tif (npt_enabled)\n\t\thsave->save.cr3 = vmcb->save.cr3;\n\telse\n\t\thsave->save.cr3 = kvm_read_cr3(&svm->vcpu);\n\n\tcopy_vmcb_control_area(&hsave->control, &vmcb->control);\n\n\tsvm->nested.nested_run_pending = 1;\n\n\tif (enter_svm_guest_mode(svm, vmcb12_gpa, vmcb12))\n\t\tgoto out_exit_err;\n\n\tif (nested_svm_vmrun_msrpm(svm))\n\t\tgoto out;\n\nout_exit_err:\n\tsvm->nested.nested_run_pending = 0;\n\n\tsvm->vmcb->control.exit_code = SVM_EXIT_ERR;\n\tsvm->vmcb->control.exit_code_hi = 0;\n\tsvm->vmcb->control.exit_info_1 = 0;\n\tsvm->vmcb->control.exit_info_2 = 0;\n\n\tnested_svm_vmexit(svm);\n\nout:\n\tkvm_vcpu_unmap(&svm->vcpu, &map, true);\n\n\treturn ret;\n}", "project": "linux", "hash": 86206897187959108781935741539715146259, "size": 105, "commit_id": "a58d9166a756a0f4a6618e4f593232593d6df134", "message": "KVM: SVM: load control fields from VMCB12 before checking them\n\nAvoid races between check and use of the nested VMCB controls. This\nfor example ensures that the VMRUN intercept is always reflected to the\nnested hypervisor, instead of being processed by the host. Without this\npatch, it is possible to end up with svm->nested.hsave pointing to\nthe MSR permission bitmap for nested guests.\n\nThis bug is CVE-2021-29657.\n\nReported-by: Felix Wilhelm \nCc: stable@vger.kernel.org\nFixes: 2fcf4876ada (\"KVM: nSVM: implement on demand allocation of the nested state\")\nSigned-off-by: Paolo Bonzini ", "target": 0, "dataset": "other", "idx": 376647} {"func": "static avifBool avifParseImageGridBox(avifImageGrid * grid, const uint8_t * raw, size_t rawLen)\n{\n BEGIN_STREAM(s, raw, rawLen);\n\n uint8_t version, flags;\n CHECK(avifROStreamRead(&s, &version, 1)); // unsigned int(8) version = 0;\n if (version != 0) {\n return AVIF_FALSE;\n }\n CHECK(avifROStreamRead(&s, &flags, 1)); // unsigned int(8) flags;\n CHECK(avifROStreamRead(&s, &grid->rows, 1)); // unsigned int(8) rows_minus_one;\n CHECK(avifROStreamRead(&s, &grid->columns, 1)); // unsigned int(8) columns_minus_one;\n ++grid->rows;\n ++grid->columns;\n\n uint32_t fieldLength = ((flags & 1) + 1) * 16;\n if (fieldLength == 16) {\n uint16_t outputWidth16, outputHeight16;\n CHECK(avifROStreamReadU16(&s, &outputWidth16)); // unsigned int(FieldLength) output_width;\n CHECK(avifROStreamReadU16(&s, &outputHeight16)); // unsigned int(FieldLength) output_height;\n grid->outputWidth = outputWidth16;\n grid->outputHeight = outputHeight16;\n } else {\n if (fieldLength != 32) {\n // This should be impossible\n return AVIF_FALSE;\n }\n CHECK(avifROStreamReadU32(&s, &grid->outputWidth)); // unsigned int(FieldLength) output_width;\n CHECK(avifROStreamReadU32(&s, &grid->outputHeight)); // unsigned int(FieldLength) output_height;\n }\n return AVIF_TRUE;\n}", "project": "libavif", "hash": 315972070308824825121763094549602004029, "size": 32, "commit_id": "0a8e7244d494ae98e9756355dfbfb6697ded2ff9", "message": "Set max image size to 16384 * 16384\n\nFix https://crbug.com/oss-fuzz/24728 and\nhttps://crbug.com/oss-fuzz/24734.", "target": 1, "dataset": "other", "idx": 206065} {"func": "static avifBool avifParseImageGridBox(avifImageGrid * grid, const uint8_t * raw, size_t rawLen)\n{\n BEGIN_STREAM(s, raw, rawLen);\n\n uint8_t version, flags;\n CHECK(avifROStreamRead(&s, &version, 1)); // unsigned int(8) version = 0;\n if (version != 0) {\n return AVIF_FALSE;\n }\n CHECK(avifROStreamRead(&s, &flags, 1)); // unsigned int(8) flags;\n CHECK(avifROStreamRead(&s, &grid->rows, 1)); // unsigned int(8) rows_minus_one;\n CHECK(avifROStreamRead(&s, &grid->columns, 1)); // unsigned int(8) columns_minus_one;\n ++grid->rows;\n ++grid->columns;\n\n uint32_t fieldLength = ((flags & 1) + 1) * 16;\n if (fieldLength == 16) {\n uint16_t outputWidth16, outputHeight16;\n CHECK(avifROStreamReadU16(&s, &outputWidth16)); // unsigned int(FieldLength) output_width;\n CHECK(avifROStreamReadU16(&s, &outputHeight16)); // unsigned int(FieldLength) output_height;\n grid->outputWidth = outputWidth16;\n grid->outputHeight = outputHeight16;\n } else {\n if (fieldLength != 32) {\n // This should be impossible\n return AVIF_FALSE;\n }\n CHECK(avifROStreamReadU32(&s, &grid->outputWidth)); // unsigned int(FieldLength) output_width;\n CHECK(avifROStreamReadU32(&s, &grid->outputHeight)); // unsigned int(FieldLength) output_height;\n }\n if (grid->outputWidth > AVIF_MAX_IMAGE_SIZE / grid->outputHeight) {\n return AVIF_FALSE;\n }\n return AVIF_TRUE;\n}", "project": "libavif", "hash": 264973754740216159561213879015400903826, "size": 35, "commit_id": "0a8e7244d494ae98e9756355dfbfb6697ded2ff9", "message": "Set max image size to 16384 * 16384\n\nFix https://crbug.com/oss-fuzz/24728 and\nhttps://crbug.com/oss-fuzz/24734.", "target": 0, "dataset": "other", "idx": 376801} {"func": "static int codeCompare(\n Parse *pParse, /* The parsing (and code generating) context */\n Expr *pLeft, /* The left operand */\n Expr *pRight, /* The right operand */\n int opcode, /* The comparison opcode */\n int in1, int in2, /* Register holding operands */\n int dest, /* Jump here if true. */\n int jumpIfNull, /* If true, jump if either operand is NULL */\n int isCommuted /* The comparison has been commuted */\n){\n int p5;\n int addr;\n CollSeq *p4;\n\n if( isCommuted ){\n p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);\n }else{\n p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);\n }\n p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);\n addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,\n (void*)p4, P4_COLLSEQ);\n sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);\n return addr;\n}", "project": "sqlite", "hash": 208208245522129666857516610065395604656, "size": 25, "commit_id": "8654186b0236d556aa85528c2573ee0b6ab71be3", "message": "When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f", "target": 1, "dataset": "other", "idx": 206235} {"func": "static int codeCompare(\n Parse *pParse, /* The parsing (and code generating) context */\n Expr *pLeft, /* The left operand */\n Expr *pRight, /* The right operand */\n int opcode, /* The comparison opcode */\n int in1, int in2, /* Register holding operands */\n int dest, /* Jump here if true. */\n int jumpIfNull, /* If true, jump if either operand is NULL */\n int isCommuted /* The comparison has been commuted */\n){\n int p5;\n int addr;\n CollSeq *p4;\n\n if( pParse->nErr ) return 0;\n if( isCommuted ){\n p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);\n }else{\n p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);\n }\n p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);\n addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,\n (void*)p4, P4_COLLSEQ);\n sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);\n return addr;\n}", "project": "sqlite", "hash": 122085921151462389183406220419053423593, "size": 26, "commit_id": "8654186b0236d556aa85528c2573ee0b6ab71be3", "message": "When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f", "target": 0, "dataset": "other", "idx": 378666} {"func": "static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){\n assert( p->nOp>0 || p->aOp==0 );\n assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );\n if( p->nOp ){\n assert( p->aOp );\n sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);\n p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);\n }\n}", "project": "sqlite", "hash": 297573905934146601478250262407134446540, "size": 9, "commit_id": "8654186b0236d556aa85528c2573ee0b6ab71be3", "message": "When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f", "target": 1, "dataset": "other", "idx": 206236} {"func": "static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){\n assert( p->nOp>0 || p->aOp==0 );\n assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed\n || p->pParse->nErr>0 );\n if( p->nOp ){\n assert( p->aOp );\n sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);\n p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);\n }\n}", "project": "sqlite", "hash": 94525444203276371802552918193620025307, "size": 10, "commit_id": "8654186b0236d556aa85528c2573ee0b6ab71be3", "message": "When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f", "target": 0, "dataset": "other", "idx": 378537} {"func": "int sqlite3WindowRewrite(Parse *pParse, Select *p){\n int rc = SQLITE_OK;\n if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){\n Vdbe *v = sqlite3GetVdbe(pParse);\n sqlite3 *db = pParse->db;\n Select *pSub = 0; /* The subquery */\n SrcList *pSrc = p->pSrc;\n Expr *pWhere = p->pWhere;\n ExprList *pGroupBy = p->pGroupBy;\n Expr *pHaving = p->pHaving;\n ExprList *pSort = 0;\n\n ExprList *pSublist = 0; /* Expression list for sub-query */\n Window *pMWin = p->pWin; /* Master window object */\n Window *pWin; /* Window object iterator */\n Table *pTab;\n\n pTab = sqlite3DbMallocZero(db, sizeof(Table));\n if( pTab==0 ){\n return SQLITE_NOMEM;\n }\n\n p->pSrc = 0;\n p->pWhere = 0;\n p->pGroupBy = 0;\n p->pHaving = 0;\n p->selFlags &= ~SF_Aggregate;\n p->selFlags |= SF_WinRewrite;\n\n /* Create the ORDER BY clause for the sub-select. This is the concatenation\n ** of the window PARTITION and ORDER BY clauses. Then, if this makes it\n ** redundant, remove the ORDER BY from the parent SELECT. */\n pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);\n pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);\n if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){\n int nSave = pSort->nExpr;\n pSort->nExpr = p->pOrderBy->nExpr;\n if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){\n sqlite3ExprListDelete(db, p->pOrderBy);\n p->pOrderBy = 0;\n }\n pSort->nExpr = nSave;\n }\n\n /* Assign a cursor number for the ephemeral table used to buffer rows.\n ** The OpenEphemeral instruction is coded later, after it is known how\n ** many columns the table will have. */\n pMWin->iEphCsr = pParse->nTab++;\n pParse->nTab += 3;\n\n selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);\n selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);\n pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);\n\n /* Append the PARTITION BY and ORDER BY expressions to the to the \n ** sub-select expression list. They are required to figure out where \n ** boundaries for partitions and sets of peer rows lie. */\n pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);\n pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);\n\n /* Append the arguments passed to each window function to the\n ** sub-select expression list. Also allocate two registers for each\n ** window function - one for the accumulator, another for interim\n ** results. */\n for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n ExprList *pArgs = pWin->pOwner->x.pList;\n if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){\n selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);\n pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);\n pWin->bExprArgs = 1;\n }else{\n pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);\n pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);\n }\n if( pWin->pFilter ){\n Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);\n pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);\n }\n pWin->regAccum = ++pParse->nMem;\n pWin->regResult = ++pParse->nMem;\n sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);\n }\n\n /* If there is no ORDER BY or PARTITION BY clause, and the window\n ** function accepts zero arguments, and there are no other columns\n ** selected (e.g. \"SELECT row_number() OVER () FROM t1\"), it is possible\n ** that pSublist is still NULL here. Add a constant expression here to \n ** keep everything legal in this case. \n */\n if( pSublist==0 ){\n pSublist = sqlite3ExprListAppend(pParse, 0, \n sqlite3Expr(db, TK_INTEGER, \"0\")\n );\n }\n\n pSub = sqlite3SelectNew(\n pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0\n );\n p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);\n if( p->pSrc ){\n Table *pTab2;\n p->pSrc->a[0].pSelect = pSub;\n sqlite3SrcListAssignCursors(pParse, p->pSrc);\n pSub->selFlags |= SF_Expanded;\n pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);\n if( pTab2==0 ){\n rc = SQLITE_NOMEM;\n }else{\n memcpy(pTab, pTab2, sizeof(Table));\n pTab->tabFlags |= TF_Ephemeral;\n p->pSrc->a[0].pTab = pTab;\n pTab = pTab2;\n }\n sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);\n }else{\n sqlite3SelectDelete(db, pSub);\n }\n if( db->mallocFailed ) rc = SQLITE_NOMEM;\n sqlite3DbFree(db, pTab);\n }\n\n return rc;\n}", "project": "sqlite", "hash": 244312120903084545062595033064722321765, "size": 126, "commit_id": "8654186b0236d556aa85528c2573ee0b6ab71be3", "message": "When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f", "target": 1, "dataset": "other", "idx": 206237} {"func": "int sqlite3WindowRewrite(Parse *pParse, Select *p){\n int rc = SQLITE_OK;\n if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){\n Vdbe *v = sqlite3GetVdbe(pParse);\n sqlite3 *db = pParse->db;\n Select *pSub = 0; /* The subquery */\n SrcList *pSrc = p->pSrc;\n Expr *pWhere = p->pWhere;\n ExprList *pGroupBy = p->pGroupBy;\n Expr *pHaving = p->pHaving;\n ExprList *pSort = 0;\n\n ExprList *pSublist = 0; /* Expression list for sub-query */\n Window *pMWin = p->pWin; /* Master window object */\n Window *pWin; /* Window object iterator */\n Table *pTab;\n\n pTab = sqlite3DbMallocZero(db, sizeof(Table));\n if( pTab==0 ){\n return sqlite3ErrorToParser(db, SQLITE_NOMEM);\n }\n\n p->pSrc = 0;\n p->pWhere = 0;\n p->pGroupBy = 0;\n p->pHaving = 0;\n p->selFlags &= ~SF_Aggregate;\n p->selFlags |= SF_WinRewrite;\n\n /* Create the ORDER BY clause for the sub-select. This is the concatenation\n ** of the window PARTITION and ORDER BY clauses. Then, if this makes it\n ** redundant, remove the ORDER BY from the parent SELECT. */\n pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);\n pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);\n if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){\n int nSave = pSort->nExpr;\n pSort->nExpr = p->pOrderBy->nExpr;\n if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){\n sqlite3ExprListDelete(db, p->pOrderBy);\n p->pOrderBy = 0;\n }\n pSort->nExpr = nSave;\n }\n\n /* Assign a cursor number for the ephemeral table used to buffer rows.\n ** The OpenEphemeral instruction is coded later, after it is known how\n ** many columns the table will have. */\n pMWin->iEphCsr = pParse->nTab++;\n pParse->nTab += 3;\n\n selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);\n selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);\n pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);\n\n /* Append the PARTITION BY and ORDER BY expressions to the to the \n ** sub-select expression list. They are required to figure out where \n ** boundaries for partitions and sets of peer rows lie. */\n pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);\n pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);\n\n /* Append the arguments passed to each window function to the\n ** sub-select expression list. Also allocate two registers for each\n ** window function - one for the accumulator, another for interim\n ** results. */\n for(pWin=pMWin; pWin; pWin=pWin->pNextWin){\n ExprList *pArgs = pWin->pOwner->x.pList;\n if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){\n selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);\n pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);\n pWin->bExprArgs = 1;\n }else{\n pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);\n pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);\n }\n if( pWin->pFilter ){\n Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);\n pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);\n }\n pWin->regAccum = ++pParse->nMem;\n pWin->regResult = ++pParse->nMem;\n sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);\n }\n\n /* If there is no ORDER BY or PARTITION BY clause, and the window\n ** function accepts zero arguments, and there are no other columns\n ** selected (e.g. \"SELECT row_number() OVER () FROM t1\"), it is possible\n ** that pSublist is still NULL here. Add a constant expression here to \n ** keep everything legal in this case. \n */\n if( pSublist==0 ){\n pSublist = sqlite3ExprListAppend(pParse, 0, \n sqlite3Expr(db, TK_INTEGER, \"0\")\n );\n }\n\n pSub = sqlite3SelectNew(\n pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0\n );\n p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);\n if( p->pSrc ){\n Table *pTab2;\n p->pSrc->a[0].pSelect = pSub;\n sqlite3SrcListAssignCursors(pParse, p->pSrc);\n pSub->selFlags |= SF_Expanded;\n pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);\n if( pTab2==0 ){\n rc = SQLITE_NOMEM;\n }else{\n memcpy(pTab, pTab2, sizeof(Table));\n pTab->tabFlags |= TF_Ephemeral;\n p->pSrc->a[0].pTab = pTab;\n pTab = pTab2;\n }\n sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);\n sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);\n }else{\n sqlite3SelectDelete(db, pSub);\n }\n if( db->mallocFailed ) rc = SQLITE_NOMEM;\n sqlite3DbFree(db, pTab);\n }\n\n if( rc && pParse->nErr==0 ){\n assert( pParse->db->mallocFailed );\n return sqlite3ErrorToParser(pParse->db, SQLITE_NOMEM);\n }\n return rc;\n}", "project": "sqlite", "hash": 244558507838888566010387300747909731042, "size": 130, "commit_id": "8654186b0236d556aa85528c2573ee0b6ab71be3", "message": "When an error occurs while rewriting the parser tree for window functions\nin the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,\nand make sure that this shuts down any subsequent code generation that might\ndepend on the transformations that were implemented. This fixes a problem\ndiscovered by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f", "target": 0, "dataset": "other", "idx": 378646} {"func": "ansicstr (string, len, flags, sawc, rlen)\n char *string;\n int len, flags, *sawc, *rlen;\n{\n int c, temp;\n char *ret, *r, *s;\n unsigned long v;\n\n if (string == 0 || *string == '\\0')\n return ((char *)NULL);\n\n#if defined (HANDLE_MULTIBYTE)\n if (strstr (string, \"\\\\U\") != 0)\n ret = (char *)xmalloc (6*len + 1);\n else\n ret = (char *)xmalloc (4*len + 1);\n#else\n ret = (char *)xmalloc (2*len + 1);\t/* 2*len for possible CTLESC */\n#endif\n for (r = ret, s = string; s && *s; )\n {\n c = *s++;\n if (c != '\\\\' || *s == '\\0')\n\t*r++ = c;\n else\n\t{\n\t switch (c = *s++)\n\t {\n#if defined (__STDC__)\n\t case 'a': c = '\\a'; break;\n\t case 'v': c = '\\v'; break;\n#else\n\t case 'a': c = (int) 0x07; break;\n\t case 'v': c = (int) 0x0B; break;\n#endif\n\t case 'b': c = '\\b'; break;\n\t case 'e': case 'E':\t\t/* ESC -- non-ANSI */\n\t c = ESC; break;\n\t case 'f': c = '\\f'; break;\n\t case 'n': c = '\\n'; break;\n\t case 'r': c = '\\r'; break;\n\t case 't': c = '\\t'; break;\n\t case '1': case '2': case '3':\n\t case '4': case '5': case '6':\n\t case '7':\n#if 1\n\t if (flags & 1)\n\t\t{\n\t\t *r++ = '\\\\';\n\t\t break;\n\t\t}\n\t /*FALLTHROUGH*/\n#endif\n\t case '0':\n\t /* If (FLAGS & 1), we're translating a string for echo -e (or\n\t\t the equivalent xpg_echo option), so we obey the SUSv3/\n\t\t POSIX-2001 requirement and accept 0-3 octal digits after\n\t\t a leading `0'. */\n\t temp = 2 + ((flags & 1) && (c == '0'));\n\t for (c -= '0'; ISOCTAL (*s) && temp--; s++)\n\t\tc = (c * 8) + OCTVALUE (*s);\n\t c &= 0xFF;\n\t break;\n\t case 'x':\t\t\t/* Hex digit -- non-ANSI */\n\t if ((flags & 2) && *s == '{')\n\t\t{\n\t\t flags |= 16;\t\t/* internal flag value */\n\t\t s++;\n\t\t}\n\t /* Consume at least two hex characters */\n\t for (temp = 2, c = 0; ISXDIGIT ((unsigned char)*s) && temp--; s++)\n\t\tc = (c * 16) + HEXVALUE (*s);\n\t /* DGK says that after a `\\x{' ksh93 consumes ISXDIGIT chars\n\t\t until a non-xdigit or `}', so potentially more than two\n\t\t chars are consumed. */\n\t if (flags & 16)\n\t\t{\n\t\t for ( ; ISXDIGIT ((unsigned char)*s); s++)\n\t\t c = (c * 16) + HEXVALUE (*s);\n\t\t flags &= ~16;\n\t\t if (*s == '}')\n\t\t s++;\n\t }\n\t /* \\x followed by non-hex digits is passed through unchanged */\n\t else if (temp == 2)\n\t\t{\n\t\t *r++ = '\\\\';\n\t\t c = 'x';\n\t\t}\n\t c &= 0xFF;\n\t break;\n#if defined (HANDLE_MULTIBYTE)\n\t case 'u':\n\t case 'U':\n\t temp = (c == 'u') ? 4 : 8;\t/* \\uNNNN \\UNNNNNNNN */\n\t for (v = 0; ISXDIGIT ((unsigned char)*s) && temp--; s++)\n\t\tv = (v * 16) + HEXVALUE (*s);\n\t if (temp == ((c == 'u') ? 4 : 8))\n\t\t{\n\t\t *r++ = '\\\\';\t/* c remains unchanged */\n\t\t break;\n\t\t}\n\t else if (v <= 0x7f)\t/* <= 0x7f translates directly */\n\t\t{\n\t\t c = v;\n\t\t break;\n\t\t}\n\t else\n\t\t{\n\t\t temp = u32cconv (v, r);\n\t\t r += temp;\n\t\t continue;\n\t\t}\n#endif\n\t case '\\\\':\n\t break;\n\t case '\\'': case '\"': case '?':\n\t if (flags & 1)\n\t\t*r++ = '\\\\';\n\t break;\n\t case 'c':\n\t if (sawc)\n\t\t{\n\t\t *sawc = 1;\n\t\t *r = '\\0';\n\t\t if (rlen)\n\t\t *rlen = r - ret;\n\t\t return ret;\n\t\t}\n\t else if ((flags & 1) == 0 && *s == 0)\n\t\t;\t\t/* pass \\c through */\n\t else if ((flags & 1) == 0 && (c = *s))\n\t\t{\n\t\t s++;\n\t\t if ((flags & 2) && c == '\\\\' && c == *s)\n\t\t s++;\t/* Posix requires $'\\c\\\\' do backslash escaping */\n\t\t c = TOCTRL(c);\n\t\t break;\n\t\t}\n\t\t/*FALLTHROUGH*/\n\t default:\n\t\tif ((flags & 4) == 0)\n\t\t *r++ = '\\\\';\n\t\tbreak;\n\t }\n\t if ((flags & 2) && (c == CTLESC || c == CTLNUL))\n\t *r++ = CTLESC;\n\t *r++ = c;\n\t}\n }\n *r = '\\0';\n if (rlen)\n *rlen = r - ret;\n return ret;\n}", "project": "bash", "hash": 165715042020473394274093045888014469618, "size": 155, "commit_id": "863d31ae775d56b785dc5b0105b6d251515d81d5", "message": "commit bash-20120224 snapshot", "target": 1, "dataset": "other", "idx": 206271} {"func": "ansicstr (string, len, flags, sawc, rlen)\n char *string;\n int len, flags, *sawc, *rlen;\n{\n int c, temp;\n char *ret, *r, *s;\n unsigned long v;\n\n if (string == 0 || *string == '\\0')\n return ((char *)NULL);\n\n#if defined (HANDLE_MULTIBYTE)\n ret = (char *)xmalloc (4*len + 1);\n#else\n ret = (char *)xmalloc (2*len + 1);\t/* 2*len for possible CTLESC */\n#endif\n for (r = ret, s = string; s && *s; )\n {\n c = *s++;\n if (c != '\\\\' || *s == '\\0')\n\t*r++ = c;\n else\n\t{\n\t switch (c = *s++)\n\t {\n#if defined (__STDC__)\n\t case 'a': c = '\\a'; break;\n\t case 'v': c = '\\v'; break;\n#else\n\t case 'a': c = (int) 0x07; break;\n\t case 'v': c = (int) 0x0B; break;\n#endif\n\t case 'b': c = '\\b'; break;\n\t case 'e': case 'E':\t\t/* ESC -- non-ANSI */\n\t c = ESC; break;\n\t case 'f': c = '\\f'; break;\n\t case 'n': c = '\\n'; break;\n\t case 'r': c = '\\r'; break;\n\t case 't': c = '\\t'; break;\n\t case '1': case '2': case '3':\n\t case '4': case '5': case '6':\n\t case '7':\n#if 1\n\t if (flags & 1)\n\t\t{\n\t\t *r++ = '\\\\';\n\t\t break;\n\t\t}\n\t /*FALLTHROUGH*/\n#endif\n\t case '0':\n\t /* If (FLAGS & 1), we're translating a string for echo -e (or\n\t\t the equivalent xpg_echo option), so we obey the SUSv3/\n\t\t POSIX-2001 requirement and accept 0-3 octal digits after\n\t\t a leading `0'. */\n\t temp = 2 + ((flags & 1) && (c == '0'));\n\t for (c -= '0'; ISOCTAL (*s) && temp--; s++)\n\t\tc = (c * 8) + OCTVALUE (*s);\n\t c &= 0xFF;\n\t break;\n\t case 'x':\t\t\t/* Hex digit -- non-ANSI */\n\t if ((flags & 2) && *s == '{')\n\t\t{\n\t\t flags |= 16;\t\t/* internal flag value */\n\t\t s++;\n\t\t}\n\t /* Consume at least two hex characters */\n\t for (temp = 2, c = 0; ISXDIGIT ((unsigned char)*s) && temp--; s++)\n\t\tc = (c * 16) + HEXVALUE (*s);\n\t /* DGK says that after a `\\x{' ksh93 consumes ISXDIGIT chars\n\t\t until a non-xdigit or `}', so potentially more than two\n\t\t chars are consumed. */\n\t if (flags & 16)\n\t\t{\n\t\t for ( ; ISXDIGIT ((unsigned char)*s); s++)\n\t\t c = (c * 16) + HEXVALUE (*s);\n\t\t flags &= ~16;\n\t\t if (*s == '}')\n\t\t s++;\n\t }\n\t /* \\x followed by non-hex digits is passed through unchanged */\n\t else if (temp == 2)\n\t\t{\n\t\t *r++ = '\\\\';\n\t\t c = 'x';\n\t\t}\n\t c &= 0xFF;\n\t break;\n#if defined (HANDLE_MULTIBYTE)\n\t case 'u':\n\t case 'U':\n\t temp = (c == 'u') ? 4 : 8;\t/* \\uNNNN \\UNNNNNNNN */\n\t for (v = 0; ISXDIGIT ((unsigned char)*s) && temp--; s++)\n\t\tv = (v * 16) + HEXVALUE (*s);\n\t if (temp == ((c == 'u') ? 4 : 8))\n\t\t{\n\t\t *r++ = '\\\\';\t/* c remains unchanged */\n\t\t break;\n\t\t}\n\t else if (v <= 0x7f)\t/* <= 0x7f translates directly */\n\t\t{\n\t\t c = v;\n\t\t break;\n\t\t}\n\t else\n\t\t{\n\t\t temp = u32cconv (v, r);\n\t\t r += temp;\n\t\t continue;\n\t\t}\n#endif\n\t case '\\\\':\n\t break;\n\t case '\\'': case '\"': case '?':\n\t if (flags & 1)\n\t\t*r++ = '\\\\';\n\t break;\n\t case 'c':\n\t if (sawc)\n\t\t{\n\t\t *sawc = 1;\n\t\t *r = '\\0';\n\t\t if (rlen)\n\t\t *rlen = r - ret;\n\t\t return ret;\n\t\t}\n\t else if ((flags & 1) == 0 && *s == 0)\n\t\t;\t\t/* pass \\c through */\n\t else if ((flags & 1) == 0 && (c = *s))\n\t\t{\n\t\t s++;\n\t\t if ((flags & 2) && c == '\\\\' && c == *s)\n\t\t s++;\t/* Posix requires $'\\c\\\\' do backslash escaping */\n\t\t c = TOCTRL(c);\n\t\t break;\n\t\t}\n\t\t/*FALLTHROUGH*/\n\t default:\n\t\tif ((flags & 4) == 0)\n\t\t *r++ = '\\\\';\n\t\tbreak;\n\t }\n\t if ((flags & 2) && (c == CTLESC || c == CTLNUL))\n\t *r++ = CTLESC;\n\t *r++ = c;\n\t}\n }\n *r = '\\0';\n if (rlen)\n *rlen = r - ret;\n return ret;\n}", "project": "bash", "hash": 69386439653475961833656724891203304786, "size": 152, "commit_id": "863d31ae775d56b785dc5b0105b6d251515d81d5", "message": "commit bash-20120224 snapshot", "target": 0, "dataset": "other", "idx": 379446} {"func": "get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)\n/* This version is for reading raw-word-format PPM files with any maxval */\n{\n ppm_source_ptr source = (ppm_source_ptr)sinfo;\n register JSAMPROW ptr;\n register U_CHAR *bufferptr;\n register JSAMPLE *rescale = source->rescale;\n JDIMENSION col;\n unsigned int maxval = source->maxval;\n\n if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n ptr = source->pub.buffer[0];\n bufferptr = source->iobuffer;\n for (col = cinfo->image_width; col > 0; col--) {\n register unsigned int temp;\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n *ptr++ = rescale[temp];\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n *ptr++ = rescale[temp];\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n *ptr++ = rescale[temp];\n }\n return 1;\n}", "project": "libjpeg-turbo", "hash": 204167080044373314321748980723365143135, "size": 34, "commit_id": "f35fd27ec641c42d6b115bfa595e483ec58188d2", "message": "tjLoadImage: Fix issues w/loading 16-bit PPMs/PGMs\n\n- The PPM reader now throws an error rather than segfaulting (due to a\n buffer overrun) if an application attempts to load a 16-bit PPM file\n into a grayscale uncompressed image buffer. No known applications\n allowed that (not even the test applications in libjpeg-turbo),\n because that mode of operation was never expected to work and did not\n work under any circumstances. (In fact, it was necessary to modify\n TJBench in order to reproduce the issue outside of a fuzzing\n environment.) This was purely a matter of making the library bow out\n gracefully rather than crash if an application tries to do something\n really stupid.\n\n- The PPM reader now throws an error rather than generating incorrect\n pixels if an application attempts to load a 16-bit PGM file into an\n RGB uncompressed image buffer.\n\n- The PPM reader now correctly loads 16-bit PPM files into extended\n RGB uncompressed image buffers. (Previously it generated incorrect\n pixels unless the input colorspace was JCS_RGB or JCS_EXT_RGB.)\n\nThe only way that users could have potentially encountered these issues\nwas through the tjLoadImage() function. cjpeg and TJBench were\nunaffected.", "target": 1, "dataset": "other", "idx": 206275} {"func": "get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)\n/* This version is for reading raw-word-format PPM files with any maxval */\n{\n ppm_source_ptr source = (ppm_source_ptr)sinfo;\n register JSAMPROW ptr;\n register U_CHAR *bufferptr;\n register JSAMPLE *rescale = source->rescale;\n JDIMENSION col;\n unsigned int maxval = source->maxval;\n register int rindex = rgb_red[cinfo->in_color_space];\n register int gindex = rgb_green[cinfo->in_color_space];\n register int bindex = rgb_blue[cinfo->in_color_space];\n register int aindex = alpha_index[cinfo->in_color_space];\n register int ps = rgb_pixelsize[cinfo->in_color_space];\n\n if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n ptr = source->pub.buffer[0];\n bufferptr = source->iobuffer;\n for (col = cinfo->image_width; col > 0; col--) {\n register unsigned int temp;\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n ptr[rindex] = rescale[temp];\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n ptr[gindex] = rescale[temp];\n temp = UCH(*bufferptr++) << 8;\n temp |= UCH(*bufferptr++);\n if (temp > maxval)\n ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);\n ptr[bindex] = rescale[temp];\n if (aindex >= 0)\n ptr[aindex] = 0xFF;\n ptr += ps;\n }\n return 1;\n}", "project": "libjpeg-turbo", "hash": 339407012057712144590227800123035459765, "size": 42, "commit_id": "f35fd27ec641c42d6b115bfa595e483ec58188d2", "message": "tjLoadImage: Fix issues w/loading 16-bit PPMs/PGMs\n\n- The PPM reader now throws an error rather than segfaulting (due to a\n buffer overrun) if an application attempts to load a 16-bit PPM file\n into a grayscale uncompressed image buffer. No known applications\n allowed that (not even the test applications in libjpeg-turbo),\n because that mode of operation was never expected to work and did not\n work under any circumstances. (In fact, it was necessary to modify\n TJBench in order to reproduce the issue outside of a fuzzing\n environment.) This was purely a matter of making the library bow out\n gracefully rather than crash if an application tries to do something\n really stupid.\n\n- The PPM reader now throws an error rather than generating incorrect\n pixels if an application attempts to load a 16-bit PGM file into an\n RGB uncompressed image buffer.\n\n- The PPM reader now correctly loads 16-bit PPM files into extended\n RGB uncompressed image buffers. (Previously it generated incorrect\n pixels unless the input colorspace was JCS_RGB or JCS_EXT_RGB.)\n\nThe only way that users could have potentially encountered these issues\nwas through the tjLoadImage() function. cjpeg and TJBench were\nunaffected.", "target": 0, "dataset": "other", "idx": 379756} {"func": "\n\nstatic int\niscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group)\n{\n\tint err = 0;\n\tu32 portid;\n\tstruct iscsi_uevent *ev = nlmsg_data(nlh);\n\tstruct iscsi_transport *transport = NULL;\n\tstruct iscsi_internal *priv;\n\tstruct iscsi_cls_session *session;\n\tstruct iscsi_cls_conn *conn;\n\tstruct iscsi_endpoint *ep = NULL;\n\n\tif (!netlink_capable(skb, CAP_SYS_ADMIN))\n\t\treturn -EPERM;\n\n\tif (nlh->nlmsg_type == ISCSI_UEVENT_PATH_UPDATE)\n\t\t*group = ISCSI_NL_GRP_UIP;\n\telse\n\t\t*group = ISCSI_NL_GRP_ISCSID;\n\n\tpriv = iscsi_if_transport_lookup(iscsi_ptr(ev->transport_handle));\n\tif (!priv)\n\t\treturn -EINVAL;\n\ttransport = priv->iscsi_transport;\n\n\tif (!try_module_get(transport->owner))\n\t\treturn -EINVAL;\n\n\tportid = NETLINK_CB(skb).portid;\n\n\tswitch (nlh->nlmsg_type) {\n\tcase ISCSI_UEVENT_CREATE_SESSION:\n\t\terr = iscsi_if_create_session(priv, ep, ev,\n\t\t\t\t\t portid,\n\t\t\t\t\t ev->u.c_session.initial_cmdsn,\n\t\t\t\t\t ev->u.c_session.cmds_max,\n\t\t\t\t\t ev->u.c_session.queue_depth);\n\t\tbreak;\n\tcase ISCSI_UEVENT_CREATE_BOUND_SESSION:\n\t\tep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle);\n\t\tif (!ep) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\terr = iscsi_if_create_session(priv, ep, ev,\n\t\t\t\t\tportid,\n\t\t\t\t\tev->u.c_bound_session.initial_cmdsn,\n\t\t\t\t\tev->u.c_bound_session.cmds_max,\n\t\t\t\t\tev->u.c_bound_session.queue_depth);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_SESSION:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (!session)\n\t\t\terr = -EINVAL;\n\t\telse if (iscsi_session_has_conns(ev->u.d_session.sid))\n\t\t\terr = -EBUSY;\n\t\telse\n\t\t\ttransport->destroy_session(session);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_SESSION_ASYNC:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (!session)\n\t\t\terr = -EINVAL;\n\t\telse if (iscsi_session_has_conns(ev->u.d_session.sid))\n\t\t\terr = -EBUSY;\n\t\telse {\n\t\t\tunsigned long flags;\n\n\t\t\t/* Prevent this session from being found again */\n\t\t\tspin_lock_irqsave(&sesslock, flags);\n\t\t\tlist_del_init(&session->sess_list);\n\t\t\tspin_unlock_irqrestore(&sesslock, flags);\n\n\t\t\tqueue_work(iscsi_destroy_workq, &session->destroy_work);\n\t\t}\n\t\tbreak;\n\tcase ISCSI_UEVENT_UNBIND_SESSION:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (session)\n\t\t\tscsi_queue_work(iscsi_session_to_shost(session),\n\t\t\t\t\t&session->unbind_work);\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_CREATE_CONN:\n\t\terr = iscsi_if_create_conn(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_CONN:\n\t\terr = iscsi_if_destroy_conn(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_BIND_CONN:\n\t\tsession = iscsi_session_lookup(ev->u.b_conn.sid);\n\t\tconn = iscsi_conn_lookup(ev->u.b_conn.sid, ev->u.b_conn.cid);\n\n\t\tif (conn && conn->ep)\n\t\t\tiscsi_if_ep_disconnect(transport, conn->ep->id);\n\n\t\tif (!session || !conn) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\tmutex_lock(&conn_mutex);\n\t\tev->r.retcode =\ttransport->bind_conn(session, conn,\n\t\t\t\t\t\tev->u.b_conn.transport_eph,\n\t\t\t\t\t\tev->u.b_conn.is_leading);\n\t\tmutex_unlock(&conn_mutex);\n\n\t\tif (ev->r.retcode || !transport->ep_connect)\n\t\t\tbreak;\n\n\t\tep = iscsi_lookup_endpoint(ev->u.b_conn.transport_eph);\n\t\tif (ep) {\n\t\t\tep->conn = conn;\n\n\t\t\tmutex_lock(&conn->ep_mutex);\n\t\t\tconn->ep = ep;\n\t\t\tmutex_unlock(&conn->ep_mutex);\n\t\t} else\n\t\t\tiscsi_cls_conn_printk(KERN_ERR, conn,\n\t\t\t\t\t \"Could not set ep conn \"\n\t\t\t\t\t \"binding\\n\");\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_PARAM:\n\t\terr = iscsi_set_param(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_START_CONN:\n\t\tconn = iscsi_conn_lookup(ev->u.start_conn.sid, ev->u.start_conn.cid);\n\t\tif (conn) {\n\t\t\tmutex_lock(&conn_mutex);\n\t\t\tev->r.retcode = transport->start_conn(conn);\n\t\t\tif (!ev->r.retcode)\n\t\t\t\tconn->state = ISCSI_CONN_UP;\n\t\t\tmutex_unlock(&conn_mutex);\n\t\t}\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_STOP_CONN:\n\t\tconn = iscsi_conn_lookup(ev->u.stop_conn.sid, ev->u.stop_conn.cid);\n\t\tif (conn)\n\t\t\tiscsi_if_stop_conn(conn, ev->u.stop_conn.flag);\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_SEND_PDU:\n\t\tconn = iscsi_conn_lookup(ev->u.send_pdu.sid, ev->u.send_pdu.cid);\n\t\tif (conn) {\n\t\t\tmutex_lock(&conn_mutex);\n\t\t\tev->r.retcode =\ttransport->send_pdu(conn,\n\t\t\t\t(struct iscsi_hdr*)((char*)ev + sizeof(*ev)),\n\t\t\t\t(char*)ev + sizeof(*ev) + ev->u.send_pdu.hdr_size,\n\t\t\t\tev->u.send_pdu.data_size);\n\t\t\tmutex_unlock(&conn_mutex);\n\t\t}\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_STATS:\n\t\terr = iscsi_if_get_stats(transport, nlh);\n\t\tbreak;\n\tcase ISCSI_UEVENT_TRANSPORT_EP_CONNECT:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_POLL:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_DISCONNECT:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST:\n\t\terr = iscsi_if_transport_ep(transport, ev, nlh->nlmsg_type);\n\t\tbreak;\n\tcase ISCSI_UEVENT_TGT_DSCVR:\n\t\terr = iscsi_tgt_dscvr(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_HOST_PARAM:\n\t\terr = iscsi_set_host_param(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_PATH_UPDATE:\n\t\terr = iscsi_set_path(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_IFACE_PARAMS:\n\t\terr = iscsi_set_iface_params(transport, ev,\n\t\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_PING:\n\t\terr = iscsi_send_ping(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_CHAP:\n\t\terr = iscsi_get_chap(transport, nlh);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DELETE_CHAP:\n\t\terr = iscsi_delete_chap(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_FLASHNODE_PARAMS:\n\t\terr = iscsi_set_flashnode_param(transport, ev,\n\t\t\t\t\t\tnlmsg_attrlen(nlh,\n\t\t\t\t\t\t\t sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_NEW_FLASHNODE:\n\t\terr = iscsi_new_flashnode(transport, ev,\n\t\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_DEL_FLASHNODE:\n\t\terr = iscsi_del_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGIN_FLASHNODE:\n\t\terr = iscsi_login_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGOUT_FLASHNODE:\n\t\terr = iscsi_logout_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGOUT_FLASHNODE_SID:\n\t\terr = iscsi_logout_flashnode_sid(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_CHAP:\n\t\terr = iscsi_set_chap(transport, ev,\n\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_HOST_STATS:\n\t\terr = iscsi_get_host_stats(transport, nlh);\n\t\tbreak;\n\tdefault:\n\t\terr = -ENOSYS;\n\t\tbreak;\n\t}\n", "project": "linux", "hash": 165207676572058765527022757443722292191, "size": 225, "commit_id": "f9dbdf97a5bd92b1a49cee3d591b55b11fd7a6d5", "message": "scsi: iscsi: Verify lengths on passthrough PDUs\n\nOpen-iSCSI sends passthrough PDUs over netlink, but the kernel should be\nverifying that the provided PDU header and data lengths fall within the\nnetlink message to prevent accessing beyond that in memory.\n\nCc: stable@vger.kernel.org\nReported-by: Adam Nichols \nReviewed-by: Lee Duncan \nReviewed-by: Mike Christie \nSigned-off-by: Chris Leech \nSigned-off-by: Martin K. Petersen ", "target": 1, "dataset": "other", "idx": 206293} {"func": "\n\nstatic int\niscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group)\n{\n\tint err = 0;\n\tu32 portid;\n\tu32 pdu_len;\n\tstruct iscsi_uevent *ev = nlmsg_data(nlh);\n\tstruct iscsi_transport *transport = NULL;\n\tstruct iscsi_internal *priv;\n\tstruct iscsi_cls_session *session;\n\tstruct iscsi_cls_conn *conn;\n\tstruct iscsi_endpoint *ep = NULL;\n\n\tif (!netlink_capable(skb, CAP_SYS_ADMIN))\n\t\treturn -EPERM;\n\n\tif (nlh->nlmsg_type == ISCSI_UEVENT_PATH_UPDATE)\n\t\t*group = ISCSI_NL_GRP_UIP;\n\telse\n\t\t*group = ISCSI_NL_GRP_ISCSID;\n\n\tpriv = iscsi_if_transport_lookup(iscsi_ptr(ev->transport_handle));\n\tif (!priv)\n\t\treturn -EINVAL;\n\ttransport = priv->iscsi_transport;\n\n\tif (!try_module_get(transport->owner))\n\t\treturn -EINVAL;\n\n\tportid = NETLINK_CB(skb).portid;\n\n\tswitch (nlh->nlmsg_type) {\n\tcase ISCSI_UEVENT_CREATE_SESSION:\n\t\terr = iscsi_if_create_session(priv, ep, ev,\n\t\t\t\t\t portid,\n\t\t\t\t\t ev->u.c_session.initial_cmdsn,\n\t\t\t\t\t ev->u.c_session.cmds_max,\n\t\t\t\t\t ev->u.c_session.queue_depth);\n\t\tbreak;\n\tcase ISCSI_UEVENT_CREATE_BOUND_SESSION:\n\t\tep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle);\n\t\tif (!ep) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\terr = iscsi_if_create_session(priv, ep, ev,\n\t\t\t\t\tportid,\n\t\t\t\t\tev->u.c_bound_session.initial_cmdsn,\n\t\t\t\t\tev->u.c_bound_session.cmds_max,\n\t\t\t\t\tev->u.c_bound_session.queue_depth);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_SESSION:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (!session)\n\t\t\terr = -EINVAL;\n\t\telse if (iscsi_session_has_conns(ev->u.d_session.sid))\n\t\t\terr = -EBUSY;\n\t\telse\n\t\t\ttransport->destroy_session(session);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_SESSION_ASYNC:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (!session)\n\t\t\terr = -EINVAL;\n\t\telse if (iscsi_session_has_conns(ev->u.d_session.sid))\n\t\t\terr = -EBUSY;\n\t\telse {\n\t\t\tunsigned long flags;\n\n\t\t\t/* Prevent this session from being found again */\n\t\t\tspin_lock_irqsave(&sesslock, flags);\n\t\t\tlist_del_init(&session->sess_list);\n\t\t\tspin_unlock_irqrestore(&sesslock, flags);\n\n\t\t\tqueue_work(iscsi_destroy_workq, &session->destroy_work);\n\t\t}\n\t\tbreak;\n\tcase ISCSI_UEVENT_UNBIND_SESSION:\n\t\tsession = iscsi_session_lookup(ev->u.d_session.sid);\n\t\tif (session)\n\t\t\tscsi_queue_work(iscsi_session_to_shost(session),\n\t\t\t\t\t&session->unbind_work);\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_CREATE_CONN:\n\t\terr = iscsi_if_create_conn(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DESTROY_CONN:\n\t\terr = iscsi_if_destroy_conn(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_BIND_CONN:\n\t\tsession = iscsi_session_lookup(ev->u.b_conn.sid);\n\t\tconn = iscsi_conn_lookup(ev->u.b_conn.sid, ev->u.b_conn.cid);\n\n\t\tif (conn && conn->ep)\n\t\t\tiscsi_if_ep_disconnect(transport, conn->ep->id);\n\n\t\tif (!session || !conn) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\tmutex_lock(&conn_mutex);\n\t\tev->r.retcode =\ttransport->bind_conn(session, conn,\n\t\t\t\t\t\tev->u.b_conn.transport_eph,\n\t\t\t\t\t\tev->u.b_conn.is_leading);\n\t\tmutex_unlock(&conn_mutex);\n\n\t\tif (ev->r.retcode || !transport->ep_connect)\n\t\t\tbreak;\n\n\t\tep = iscsi_lookup_endpoint(ev->u.b_conn.transport_eph);\n\t\tif (ep) {\n\t\t\tep->conn = conn;\n\n\t\t\tmutex_lock(&conn->ep_mutex);\n\t\t\tconn->ep = ep;\n\t\t\tmutex_unlock(&conn->ep_mutex);\n\t\t} else\n\t\t\tiscsi_cls_conn_printk(KERN_ERR, conn,\n\t\t\t\t\t \"Could not set ep conn \"\n\t\t\t\t\t \"binding\\n\");\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_PARAM:\n\t\terr = iscsi_set_param(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_START_CONN:\n\t\tconn = iscsi_conn_lookup(ev->u.start_conn.sid, ev->u.start_conn.cid);\n\t\tif (conn) {\n\t\t\tmutex_lock(&conn_mutex);\n\t\t\tev->r.retcode = transport->start_conn(conn);\n\t\t\tif (!ev->r.retcode)\n\t\t\t\tconn->state = ISCSI_CONN_UP;\n\t\t\tmutex_unlock(&conn_mutex);\n\t\t}\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_STOP_CONN:\n\t\tconn = iscsi_conn_lookup(ev->u.stop_conn.sid, ev->u.stop_conn.cid);\n\t\tif (conn)\n\t\t\tiscsi_if_stop_conn(conn, ev->u.stop_conn.flag);\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_SEND_PDU:\n\t\tpdu_len = nlh->nlmsg_len - sizeof(*nlh) - sizeof(*ev);\n\n\t\tif ((ev->u.send_pdu.hdr_size > pdu_len) ||\n\t\t (ev->u.send_pdu.data_size > (pdu_len - ev->u.send_pdu.hdr_size))) {\n\t\t\terr = -EINVAL;\n\t\t\tbreak;\n\t\t}\n\n\t\tconn = iscsi_conn_lookup(ev->u.send_pdu.sid, ev->u.send_pdu.cid);\n\t\tif (conn) {\n\t\t\tmutex_lock(&conn_mutex);\n\t\t\tev->r.retcode =\ttransport->send_pdu(conn,\n\t\t\t\t(struct iscsi_hdr*)((char*)ev + sizeof(*ev)),\n\t\t\t\t(char*)ev + sizeof(*ev) + ev->u.send_pdu.hdr_size,\n\t\t\t\tev->u.send_pdu.data_size);\n\t\t\tmutex_unlock(&conn_mutex);\n\t\t}\n\t\telse\n\t\t\terr = -EINVAL;\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_STATS:\n\t\terr = iscsi_if_get_stats(transport, nlh);\n\t\tbreak;\n\tcase ISCSI_UEVENT_TRANSPORT_EP_CONNECT:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_POLL:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_DISCONNECT:\n\tcase ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST:\n\t\terr = iscsi_if_transport_ep(transport, ev, nlh->nlmsg_type);\n\t\tbreak;\n\tcase ISCSI_UEVENT_TGT_DSCVR:\n\t\terr = iscsi_tgt_dscvr(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_HOST_PARAM:\n\t\terr = iscsi_set_host_param(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_PATH_UPDATE:\n\t\terr = iscsi_set_path(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_IFACE_PARAMS:\n\t\terr = iscsi_set_iface_params(transport, ev,\n\t\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_PING:\n\t\terr = iscsi_send_ping(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_CHAP:\n\t\terr = iscsi_get_chap(transport, nlh);\n\t\tbreak;\n\tcase ISCSI_UEVENT_DELETE_CHAP:\n\t\terr = iscsi_delete_chap(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_FLASHNODE_PARAMS:\n\t\terr = iscsi_set_flashnode_param(transport, ev,\n\t\t\t\t\t\tnlmsg_attrlen(nlh,\n\t\t\t\t\t\t\t sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_NEW_FLASHNODE:\n\t\terr = iscsi_new_flashnode(transport, ev,\n\t\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_DEL_FLASHNODE:\n\t\terr = iscsi_del_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGIN_FLASHNODE:\n\t\terr = iscsi_login_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGOUT_FLASHNODE:\n\t\terr = iscsi_logout_flashnode(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_LOGOUT_FLASHNODE_SID:\n\t\terr = iscsi_logout_flashnode_sid(transport, ev);\n\t\tbreak;\n\tcase ISCSI_UEVENT_SET_CHAP:\n\t\terr = iscsi_set_chap(transport, ev,\n\t\t\t\t nlmsg_attrlen(nlh, sizeof(*ev)));\n\t\tbreak;\n\tcase ISCSI_UEVENT_GET_HOST_STATS:\n\t\terr = iscsi_get_host_stats(transport, nlh);\n\t\tbreak;\n\tdefault:\n\t\terr = -ENOSYS;\n\t\tbreak;\n\t}\n", "project": "linux", "hash": 290280226689808529758982123621457114455, "size": 234, "commit_id": "f9dbdf97a5bd92b1a49cee3d591b55b11fd7a6d5", "message": "scsi: iscsi: Verify lengths on passthrough PDUs\n\nOpen-iSCSI sends passthrough PDUs over netlink, but the kernel should be\nverifying that the provided PDU header and data lengths fall within the\nnetlink message to prevent accessing beyond that in memory.\n\nCc: stable@vger.kernel.org\nReported-by: Adam Nichols \nReviewed-by: Lee Duncan \nReviewed-by: Mike Christie \nSigned-off-by: Chris Leech \nSigned-off-by: Martin K. Petersen ", "target": 0, "dataset": "other", "idx": 380003} {"func": "static struct property *dlpar_parse_cc_property(struct cc_workarea *ccwa)\n{\n\tstruct property *prop;\n\tchar *name;\n\tchar *value;\n\n\tprop = kzalloc(sizeof(*prop), GFP_KERNEL);\n\tif (!prop)\n\t\treturn NULL;\n\n\tname = (char *)ccwa + be32_to_cpu(ccwa->name_offset);\n\tprop->name = kstrdup(name, GFP_KERNEL);\n\n\tprop->length = be32_to_cpu(ccwa->prop_length);\n\tvalue = (char *)ccwa + be32_to_cpu(ccwa->prop_offset);\n\tprop->value = kmemdup(value, prop->length, GFP_KERNEL);\n\tif (!prop->value) {\n\t\tdlpar_free_cc_property(prop);\n\t\treturn NULL;\n\t}\n\n\treturn prop;\n}", "project": "linux", "hash": 112920879356861496445414674726809319128, "size": 23, "commit_id": "efa9ace68e487ddd29c2b4d6dd23242158f1f607", "message": "powerpc/pseries/dlpar: Fix a missing check in dlpar_parse_cc_property()\n\nIn dlpar_parse_cc_property(), 'prop->name' is allocated by kstrdup().\nkstrdup() may return NULL, so it should be checked and handle error.\nAnd prop should be freed if 'prop->name' is NULL.\n\nSigned-off-by: Gen Zhang \nSigned-off-by: Michael Ellerman ", "target": 1, "dataset": "other", "idx": 206300} {"func": "static struct property *dlpar_parse_cc_property(struct cc_workarea *ccwa)\n{\n\tstruct property *prop;\n\tchar *name;\n\tchar *value;\n\n\tprop = kzalloc(sizeof(*prop), GFP_KERNEL);\n\tif (!prop)\n\t\treturn NULL;\n\n\tname = (char *)ccwa + be32_to_cpu(ccwa->name_offset);\n\tprop->name = kstrdup(name, GFP_KERNEL);\n\tif (!prop->name) {\n\t\tdlpar_free_cc_property(prop);\n\t\treturn NULL;\n\t}\n\n\tprop->length = be32_to_cpu(ccwa->prop_length);\n\tvalue = (char *)ccwa + be32_to_cpu(ccwa->prop_offset);\n\tprop->value = kmemdup(value, prop->length, GFP_KERNEL);\n\tif (!prop->value) {\n\t\tdlpar_free_cc_property(prop);\n\t\treturn NULL;\n\t}\n\n\treturn prop;\n}", "project": "linux", "hash": 307975532274501928757324716654129527375, "size": 27, "commit_id": "efa9ace68e487ddd29c2b4d6dd23242158f1f607", "message": "powerpc/pseries/dlpar: Fix a missing check in dlpar_parse_cc_property()\n\nIn dlpar_parse_cc_property(), 'prop->name' is allocated by kstrdup().\nkstrdup() may return NULL, so it should be checked and handle error.\nAnd prop should be freed if 'prop->name' is NULL.\n\nSigned-off-by: Gen Zhang \nSigned-off-by: Michael Ellerman ", "target": 0, "dataset": "other", "idx": 380132} {"func": "static Image *ReadHEICImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n const char\n *option;\n\n const StringInfo\n *profile;\n\n heif_item_id\n exif_id;\n\n Image\n *image;\n\n int\n count,\n stride_y,\n stride_cb,\n stride_cr;\n\n MagickBooleanType\n status;\n\n size_t\n length;\n\n ssize_t\n y;\n\n struct heif_context\n *heif_context;\n\n struct heif_decoding_options\n *decode_options;\n\n struct heif_error\n error;\n\n struct heif_image\n *heif_image;\n\n struct heif_image_handle\n *image_handle;\n\n const uint8_t\n *p_y,\n *p_cb,\n *p_cr;\n\n void\n *file_data;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n if (GetBlobSize(image) > (MagickSizeType) SSIZE_MAX)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n length=(size_t) GetBlobSize(image);\n file_data=AcquireMagickMemory(length);\n if (file_data == (void *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (ReadBlob(image,length,(unsigned char *) file_data) != (ssize_t) length)\n {\n file_data=RelinquishMagickMemory(file_data);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n /*\n Decode HEIF file\n */\n heif_context=heif_context_alloc();\n error=heif_context_read_from_memory_without_copy(heif_context,file_data,\n length,NULL);\n if (IsHeifSuccess(&error,image) == MagickFalse)\n {\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n image_handle=(struct heif_image_handle *) NULL;\n error=heif_context_get_primary_image_handle(heif_context,&image_handle);\n if (IsHeifSuccess(&error,image) == MagickFalse)\n {\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n#if LIBHEIF_NUMERIC_VERSION >= 0x01040000\n length=heif_image_handle_get_raw_color_profile_size(image_handle);\n if (length > 0)\n {\n unsigned char\n *color_buffer;\n\n /*\n Read color profile.\n */ \n if ((MagickSizeType) length > GetBlobSize(image))\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n color_buffer=(unsigned char *) AcquireMagickMemory(length);\n if (color_buffer != (unsigned char *) NULL)\n {\n error=heif_image_handle_get_raw_color_profile(image_handle,\n color_buffer);\n if (error.code == 0)\n {\n StringInfo\n *profile;\n\n profile=BlobToStringInfo(color_buffer,length);\n if (profile != (StringInfo*) NULL)\n {\n (void) SetImageProfile(image,\"icc\",profile);\n profile=DestroyStringInfo(profile);\n }\n }\n }\n color_buffer=(unsigned char *) RelinquishMagickMemory(color_buffer);\n }\n#endif\n count=heif_image_handle_get_list_of_metadata_block_IDs(image_handle,\"Exif\",\n &exif_id,1);\n if (count > 0)\n {\n size_t\n exif_size;\n\n unsigned char\n *exif_buffer;\n\n /*\n Read Exif profile.\n */\n exif_size=heif_image_handle_get_metadata_size(image_handle,exif_id);\n if ((MagickSizeType) exif_size > GetBlobSize(image))\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n exif_buffer=(unsigned char*) AcquireMagickMemory(exif_size);\n if (exif_buffer != (unsigned char*) NULL)\n {\n error=heif_image_handle_get_metadata(image_handle,\n exif_id,exif_buffer);\n if (error.code == 0)\n {\n StringInfo\n *profile;\n\n /*\n The first 4 byte should be skipped since they indicate the\n offset to the start of the TIFF header of the Exif data.\n */\n profile=(StringInfo*) NULL;\n if (exif_size > 8)\n profile=BlobToStringInfo(exif_buffer+4,(size_t) exif_size-4);\n if (profile != (StringInfo*) NULL)\n {\n (void) SetImageProfile(image,\"exif\",profile);\n profile=DestroyStringInfo(profile);\n }\n }\n }\n exif_buffer=(unsigned char *) RelinquishMagickMemory(exif_buffer);\n }\n /*\n Set image size.\n */\n image->depth=8;\n image->columns=(size_t) heif_image_handle_get_width(image_handle);\n image->rows=(size_t) heif_image_handle_get_height(image_handle);\n if (image_info->ping != MagickFalse)\n {\n image->colorspace=YCbCrColorspace;\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n /*\n Copy HEIF image into ImageMagick data structures\n */\n (void) SetImageColorspace(image,YCbCrColorspace);\n decode_options=(struct heif_decoding_options *) NULL;\n option=GetImageOption(image_info,\"heic:preserve-orientation\");\n if (IsStringTrue(option) == MagickTrue)\n {\n decode_options=heif_decoding_options_alloc();\n decode_options->ignore_transformations=1;\n }\n else\n (void) SetImageProperty(image,\"exif:Orientation\",\"1\");\n error=heif_decode_image(image_handle,&heif_image,heif_colorspace_YCbCr,\n heif_chroma_420,NULL);\n if (IsHeifSuccess(&error,image) == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n if (decode_options != (struct heif_decoding_options *) NULL)\n {\n /*\n Correct the width and height of the image.\n */\n image->columns=(size_t) heif_image_get_width(heif_image,heif_channel_Y);\n image->rows=(size_t) heif_image_get_height(heif_image,heif_channel_Y);\n status=SetImageExtent(image,image->columns,image->rows);\n heif_decoding_options_free(decode_options);\n if (status == MagickFalse)\n {\n heif_image_release(heif_image);\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n }\n p_y=heif_image_get_plane_readonly(heif_image,heif_channel_Y,&stride_y);\n p_cb=heif_image_get_plane_readonly(heif_image,heif_channel_Cb,&stride_cb);\n p_cr=heif_image_get_plane_readonly(heif_image,heif_channel_Cr,&stride_cr);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n PixelPacket\n *q;\n\n register ssize_t\n x;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,ScaleCharToQuantum((unsigned char) p_y[y*\n stride_y+x]));\n SetPixelGreen(q,ScaleCharToQuantum((unsigned char) p_cb[(y/2)*\n stride_cb+x/2]));\n SetPixelBlue(q,ScaleCharToQuantum((unsigned char) p_cr[(y/2)*\n stride_cr+x/2]));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n heif_image_release(heif_image);\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n profile=GetImageProfile(image,\"icc\");\n if (profile != (const StringInfo *) NULL)\n (void) TransformImageColorspace(image,sRGBColorspace);\n return(GetFirstImageInList(image));\n}", "project": "ImageMagick6", "hash": 126205623246026879854304189328903106802, "size": 281, "commit_id": "3456724dff047db5adb32f8cf70c903c1b7d16d4", "message": "Always correct the width and height of the image.", "target": 1, "dataset": "other", "idx": 206422} {"func": "static Image *ReadHEICImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n const char\n *option;\n\n const StringInfo\n *profile;\n\n heif_item_id\n exif_id;\n\n Image\n *image;\n\n int\n count,\n stride_y,\n stride_cb,\n stride_cr;\n\n MagickBooleanType\n status;\n\n size_t\n length;\n\n ssize_t\n y;\n\n struct heif_context\n *heif_context;\n\n struct heif_decoding_options\n *decode_options;\n\n struct heif_error\n error;\n\n struct heif_image\n *heif_image;\n\n struct heif_image_handle\n *image_handle;\n\n const uint8_t\n *p_y,\n *p_cb,\n *p_cr;\n\n void\n *file_data;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n if (GetBlobSize(image) > (MagickSizeType) SSIZE_MAX)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n length=(size_t) GetBlobSize(image);\n file_data=AcquireMagickMemory(length);\n if (file_data == (void *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (ReadBlob(image,length,(unsigned char *) file_data) != (ssize_t) length)\n {\n file_data=RelinquishMagickMemory(file_data);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n /*\n Decode HEIF file\n */\n heif_context=heif_context_alloc();\n error=heif_context_read_from_memory_without_copy(heif_context,file_data,\n length,NULL);\n if (IsHeifSuccess(&error,image) == MagickFalse)\n {\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n image_handle=(struct heif_image_handle *) NULL;\n error=heif_context_get_primary_image_handle(heif_context,&image_handle);\n if (IsHeifSuccess(&error,image) == MagickFalse)\n {\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n#if LIBHEIF_NUMERIC_VERSION >= 0x01040000\n length=heif_image_handle_get_raw_color_profile_size(image_handle);\n if (length > 0)\n {\n unsigned char\n *color_buffer;\n\n /*\n Read color profile.\n */ \n if ((MagickSizeType) length > GetBlobSize(image))\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n color_buffer=(unsigned char *) AcquireMagickMemory(length);\n if (color_buffer != (unsigned char *) NULL)\n {\n error=heif_image_handle_get_raw_color_profile(image_handle,\n color_buffer);\n if (error.code == 0)\n {\n StringInfo\n *profile;\n\n profile=BlobToStringInfo(color_buffer,length);\n if (profile != (StringInfo*) NULL)\n {\n (void) SetImageProfile(image,\"icc\",profile);\n profile=DestroyStringInfo(profile);\n }\n }\n }\n color_buffer=(unsigned char *) RelinquishMagickMemory(color_buffer);\n }\n#endif\n count=heif_image_handle_get_list_of_metadata_block_IDs(image_handle,\"Exif\",\n &exif_id,1);\n if (count > 0)\n {\n size_t\n exif_size;\n\n unsigned char\n *exif_buffer;\n\n /*\n Read Exif profile.\n */\n exif_size=heif_image_handle_get_metadata_size(image_handle,exif_id);\n if ((MagickSizeType) exif_size > GetBlobSize(image))\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n exif_buffer=(unsigned char*) AcquireMagickMemory(exif_size);\n if (exif_buffer != (unsigned char*) NULL)\n {\n error=heif_image_handle_get_metadata(image_handle,\n exif_id,exif_buffer);\n if (error.code == 0)\n {\n StringInfo\n *profile;\n\n /*\n The first 4 byte should be skipped since they indicate the\n offset to the start of the TIFF header of the Exif data.\n */\n profile=(StringInfo*) NULL;\n if (exif_size > 8)\n profile=BlobToStringInfo(exif_buffer+4,(size_t) exif_size-4);\n if (profile != (StringInfo*) NULL)\n {\n (void) SetImageProfile(image,\"exif\",profile);\n profile=DestroyStringInfo(profile);\n }\n }\n }\n exif_buffer=(unsigned char *) RelinquishMagickMemory(exif_buffer);\n }\n /*\n Set image size.\n */\n image->depth=8;\n image->columns=(size_t) heif_image_handle_get_width(image_handle);\n image->rows=(size_t) heif_image_handle_get_height(image_handle);\n if (image_info->ping != MagickFalse)\n {\n image->colorspace=YCbCrColorspace;\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n /*\n Copy HEIF image into ImageMagick data structures\n */\n (void) SetImageColorspace(image,YCbCrColorspace);\n decode_options=(struct heif_decoding_options *) NULL;\n option=GetImageOption(image_info,\"heic:preserve-orientation\");\n if (IsStringTrue(option) == MagickTrue)\n {\n decode_options=heif_decoding_options_alloc();\n decode_options->ignore_transformations=1;\n }\n else\n (void) SetImageProperty(image,\"exif:Orientation\",\"1\");\n error=heif_decode_image(image_handle,&heif_image,heif_colorspace_YCbCr,\n heif_chroma_420,decode_options);\n if (decode_options != (struct heif_decoding_options *) NULL)\n heif_decoding_options_free(decode_options);\n if (IsHeifSuccess(&error,image) == MagickFalse)\n {\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n /*\n Correct the width and height of the image.\n */\n image->columns=(size_t) heif_image_get_width(heif_image,heif_channel_Y);\n image->rows=(size_t) heif_image_get_height(heif_image,heif_channel_Y);\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n heif_image_release(heif_image);\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n return(DestroyImageList(image));\n }\n p_y=heif_image_get_plane_readonly(heif_image,heif_channel_Y,&stride_y);\n p_cb=heif_image_get_plane_readonly(heif_image,heif_channel_Cb,&stride_cb);\n p_cr=heif_image_get_plane_readonly(heif_image,heif_channel_Cr,&stride_cr);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n PixelPacket\n *q;\n\n register ssize_t\n x;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,ScaleCharToQuantum((unsigned char) p_y[y*\n stride_y+x]));\n SetPixelGreen(q,ScaleCharToQuantum((unsigned char) p_cb[(y/2)*\n stride_cb+x/2]));\n SetPixelBlue(q,ScaleCharToQuantum((unsigned char) p_cr[(y/2)*\n stride_cr+x/2]));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n heif_image_release(heif_image);\n heif_image_handle_release(image_handle);\n heif_context_free(heif_context);\n file_data=RelinquishMagickMemory(file_data);\n profile=GetImageProfile(image,\"icc\");\n if (profile != (const StringInfo *) NULL)\n (void) TransformImageColorspace(image,sRGBColorspace);\n return(GetFirstImageInList(image));\n}", "project": "ImageMagick6", "hash": 223412021839106218981699163268333438881, "size": 279, "commit_id": "3456724dff047db5adb32f8cf70c903c1b7d16d4", "message": "Always correct the width and height of the image.", "target": 0, "dataset": "other", "idx": 381036} {"func": "int pci_piix3_xen_ide_unplug(DeviceState *dev)\n{\n PCIIDEState *pci_ide;\n DriveInfo *di;\n int i;\n\n pci_ide = PCI_IDE(dev);\n\n for (i = 0; i < 4; i++) {\n di = drive_get_by_index(IF_IDE, i);\n if (di != NULL && !di->media_cd) {\n BlockBackend *blk = blk_by_legacy_dinfo(di);\n DeviceState *ds = blk_get_attached_dev(blk);\n if (ds) {\n blk_detach_dev(blk, ds);\n }\n pci_ide->bus[di->bus].ifs[di->unit].blk = NULL;\n blk_unref(blk);\n }\n }\n qdev_reset_all(DEVICE(dev));\n return 0;\n}", "project": "qemu", "hash": 24920103150571267488054332955141284957, "size": 23, "commit_id": "6cd387833d05e8ad31829d97e474dc420625aed9", "message": "Fix release_drive on unplugged devices (pci_piix3_xen_ide_unplug)\n\npci_piix3_xen_ide_unplug should completely unhook the unplugged\nIDEDevice from the corresponding BlockBackend, otherwise the next call\nto release_drive will try to detach the drive again.\n\nSuggested-by: Kevin Wolf \nSigned-off-by: Stefano Stabellini ", "target": 1, "dataset": "other", "idx": 206467} {"func": "int pci_piix3_xen_ide_unplug(DeviceState *dev)\n{\n PCIIDEState *pci_ide;\n DriveInfo *di;\n int i;\n IDEDevice *idedev;\n\n pci_ide = PCI_IDE(dev);\n\n for (i = 0; i < 4; i++) {\n di = drive_get_by_index(IF_IDE, i);\n if (di != NULL && !di->media_cd) {\n BlockBackend *blk = blk_by_legacy_dinfo(di);\n DeviceState *ds = blk_get_attached_dev(blk);\n if (ds) {\n blk_detach_dev(blk, ds);\n }\n pci_ide->bus[di->bus].ifs[di->unit].blk = NULL;\n if (!(i % 2)) {\n idedev = pci_ide->bus[di->bus].master;\n } else {\n idedev = pci_ide->bus[di->bus].slave;\n }\n idedev->conf.blk = NULL;\n blk_unref(blk);\n }\n }\n qdev_reset_all(DEVICE(dev));\n return 0;\n}", "project": "qemu", "hash": 50331044897901214962169569223095064355, "size": 30, "commit_id": "6cd387833d05e8ad31829d97e474dc420625aed9", "message": "Fix release_drive on unplugged devices (pci_piix3_xen_ide_unplug)\n\npci_piix3_xen_ide_unplug should completely unhook the unplugged\nIDEDevice from the corresponding BlockBackend, otherwise the next call\nto release_drive will try to detach the drive again.\n\nSuggested-by: Kevin Wolf \nSigned-off-by: Stefano Stabellini ", "target": 0, "dataset": "other", "idx": 381410} {"func": "video_usercopy(struct file *file, unsigned int orig_cmd, unsigned long arg,\n\t v4l2_kioctl func)\n{\n\tchar\tsbuf[128];\n\tvoid *mbuf = NULL;\n\tvoid\t*parg = (void *)arg;\n\tlong\terr = -EINVAL;\n\tbool\thas_array_args;\n\tbool\talways_copy = false;\n\tsize_t array_size = 0;\n\tvoid __user *user_ptr = NULL;\n\tvoid\t**kernel_ptr = NULL;\n\tunsigned int cmd = video_translate_cmd(orig_cmd);\n\tconst size_t ioc_size = _IOC_SIZE(cmd);\n\n\t/* Copy arguments into temp kernel buffer */\n\tif (_IOC_DIR(cmd) != _IOC_NONE) {\n\t\tif (ioc_size <= sizeof(sbuf)) {\n\t\t\tparg = sbuf;\n\t\t} else {\n\t\t\t/* too big to allocate from stack */\n\t\t\tmbuf = kvmalloc(ioc_size, GFP_KERNEL);\n\t\t\tif (NULL == mbuf)\n\t\t\t\treturn -ENOMEM;\n\t\t\tparg = mbuf;\n\t\t}\n\n\t\terr = video_get_user((void __user *)arg, parg, cmd,\n\t\t\t\t orig_cmd, &always_copy);\n\t\tif (err)\n\t\t\tgoto out;\n\t}\n\n\terr = check_array_args(cmd, parg, &array_size, &user_ptr, &kernel_ptr);\n\tif (err < 0)\n\t\tgoto out;\n\thas_array_args = err;\n\n\tif (has_array_args) {\n\t\t/*\n\t\t * When adding new types of array args, make sure that the\n\t\t * parent argument to ioctl (which contains the pointer to the\n\t\t * array) fits into sbuf (so that mbuf will still remain\n\t\t * unused up to here).\n\t\t */\n\t\tmbuf = kvmalloc(array_size, GFP_KERNEL);\n\t\terr = -ENOMEM;\n\t\tif (NULL == mbuf)\n\t\t\tgoto out_array_args;\n\t\terr = -EFAULT;\n\t\tif (in_compat_syscall())\n\t\t\terr = v4l2_compat_get_array_args(file, mbuf, user_ptr,\n\t\t\t\t\t\t\t array_size, orig_cmd,\n\t\t\t\t\t\t\t parg);\n\t\telse\n\t\t\terr = copy_from_user(mbuf, user_ptr, array_size) ?\n\t\t\t\t\t\t\t\t-EFAULT : 0;\n\t\tif (err)\n\t\t\tgoto out_array_args;\n\t\t*kernel_ptr = mbuf;\n\t}\n\n\t/* Handles IOCTL */\n\terr = func(file, cmd, parg);\n\tif (err == -ENOTTY || err == -ENOIOCTLCMD) {\n\t\terr = -ENOTTY;\n\t\tgoto out;\n\t}\n\n\tif (err == 0) {\n\t\tif (cmd == VIDIOC_DQBUF)\n\t\t\ttrace_v4l2_dqbuf(video_devdata(file)->minor, parg);\n\t\telse if (cmd == VIDIOC_QBUF)\n\t\t\ttrace_v4l2_qbuf(video_devdata(file)->minor, parg);\n\t}\n\n\tif (has_array_args) {\n\t\t*kernel_ptr = (void __force *)user_ptr;\n\t\tif (in_compat_syscall()) {\n\t\t\tint put_err;\n\n\t\t\tput_err = v4l2_compat_put_array_args(file, user_ptr, mbuf,\n\t\t\t\t\t\t\t array_size, orig_cmd,\n\t\t\t\t\t\t\t parg);\n\t\t\tif (put_err)\n\t\t\t\terr = put_err;\n\t\t} else if (copy_to_user(user_ptr, mbuf, array_size)) {\n\t\t\terr = -EFAULT;\n\t\t}\n\t\tgoto out_array_args;\n\t}\n\t/*\n\t * Some ioctls can return an error, but still have valid\n\t * results that must be returned.\n\t */\n\tif (err < 0 && !always_copy)\n\t\tgoto out;\n\nout_array_args:\n\tif (video_put_user((void __user *)arg, parg, cmd, orig_cmd))\n\t\terr = -EFAULT;\nout:\n\tkvfree(mbuf);\n\treturn err;\n}", "project": "linux", "hash": 335168946814517336955071454206732269952, "size": 105, "commit_id": "fb18802a338b36f675a388fc03d2aa504a0d0899", "message": "media: v4l: ioctl: Fix memory leak in video_usercopy\n\nWhen an IOCTL with argument size larger than 128 that also used array\narguments were handled, two memory allocations were made but alas, only\nthe latter one of them was released. This happened because there was only\na single local variable to hold such a temporary allocation.\n\nFix this by adding separate variables to hold the pointers to the\ntemporary allocations.\n\nReported-by: Arnd Bergmann \nReported-by: syzbot+1115e79c8df6472c612b@syzkaller.appspotmail.com\nFixes: d14e6d76ebf7 (\"[media] v4l: Add multi-planar ioctl handling code\")\nCc: stable@vger.kernel.org\nSigned-off-by: Sakari Ailus \nAcked-by: Arnd Bergmann \nAcked-by: Hans Verkuil \nReviewed-by: Laurent Pinchart \nSigned-off-by: Mauro Carvalho Chehab ", "target": 1, "dataset": "other", "idx": 206468} {"func": "video_usercopy(struct file *file, unsigned int orig_cmd, unsigned long arg,\n\t v4l2_kioctl func)\n{\n\tchar\tsbuf[128];\n\tvoid *mbuf = NULL, *array_buf = NULL;\n\tvoid\t*parg = (void *)arg;\n\tlong\terr = -EINVAL;\n\tbool\thas_array_args;\n\tbool\talways_copy = false;\n\tsize_t array_size = 0;\n\tvoid __user *user_ptr = NULL;\n\tvoid\t**kernel_ptr = NULL;\n\tunsigned int cmd = video_translate_cmd(orig_cmd);\n\tconst size_t ioc_size = _IOC_SIZE(cmd);\n\n\t/* Copy arguments into temp kernel buffer */\n\tif (_IOC_DIR(cmd) != _IOC_NONE) {\n\t\tif (ioc_size <= sizeof(sbuf)) {\n\t\t\tparg = sbuf;\n\t\t} else {\n\t\t\t/* too big to allocate from stack */\n\t\t\tmbuf = kvmalloc(ioc_size, GFP_KERNEL);\n\t\t\tif (NULL == mbuf)\n\t\t\t\treturn -ENOMEM;\n\t\t\tparg = mbuf;\n\t\t}\n\n\t\terr = video_get_user((void __user *)arg, parg, cmd,\n\t\t\t\t orig_cmd, &always_copy);\n\t\tif (err)\n\t\t\tgoto out;\n\t}\n\n\terr = check_array_args(cmd, parg, &array_size, &user_ptr, &kernel_ptr);\n\tif (err < 0)\n\t\tgoto out;\n\thas_array_args = err;\n\n\tif (has_array_args) {\n\t\tarray_buf = kvmalloc(array_size, GFP_KERNEL);\n\t\terr = -ENOMEM;\n\t\tif (array_buf == NULL)\n\t\t\tgoto out_array_args;\n\t\terr = -EFAULT;\n\t\tif (in_compat_syscall())\n\t\t\terr = v4l2_compat_get_array_args(file, array_buf,\n\t\t\t\t\t\t\t user_ptr, array_size,\n\t\t\t\t\t\t\t orig_cmd, parg);\n\t\telse\n\t\t\terr = copy_from_user(array_buf, user_ptr, array_size) ?\n\t\t\t\t\t\t\t\t-EFAULT : 0;\n\t\tif (err)\n\t\t\tgoto out_array_args;\n\t\t*kernel_ptr = array_buf;\n\t}\n\n\t/* Handles IOCTL */\n\terr = func(file, cmd, parg);\n\tif (err == -ENOTTY || err == -ENOIOCTLCMD) {\n\t\terr = -ENOTTY;\n\t\tgoto out;\n\t}\n\n\tif (err == 0) {\n\t\tif (cmd == VIDIOC_DQBUF)\n\t\t\ttrace_v4l2_dqbuf(video_devdata(file)->minor, parg);\n\t\telse if (cmd == VIDIOC_QBUF)\n\t\t\ttrace_v4l2_qbuf(video_devdata(file)->minor, parg);\n\t}\n\n\tif (has_array_args) {\n\t\t*kernel_ptr = (void __force *)user_ptr;\n\t\tif (in_compat_syscall()) {\n\t\t\tint put_err;\n\n\t\t\tput_err = v4l2_compat_put_array_args(file, user_ptr,\n\t\t\t\t\t\t\t array_buf,\n\t\t\t\t\t\t\t array_size,\n\t\t\t\t\t\t\t orig_cmd, parg);\n\t\t\tif (put_err)\n\t\t\t\terr = put_err;\n\t\t} else if (copy_to_user(user_ptr, array_buf, array_size)) {\n\t\t\terr = -EFAULT;\n\t\t}\n\t\tgoto out_array_args;\n\t}\n\t/*\n\t * Some ioctls can return an error, but still have valid\n\t * results that must be returned.\n\t */\n\tif (err < 0 && !always_copy)\n\t\tgoto out;\n\nout_array_args:\n\tif (video_put_user((void __user *)arg, parg, cmd, orig_cmd))\n\t\terr = -EFAULT;\nout:\n\tkvfree(array_buf);\n\tkvfree(mbuf);\n\treturn err;\n}", "project": "linux", "hash": 111009062421503165995091383541572390268, "size": 101, "commit_id": "fb18802a338b36f675a388fc03d2aa504a0d0899", "message": "media: v4l: ioctl: Fix memory leak in video_usercopy\n\nWhen an IOCTL with argument size larger than 128 that also used array\narguments were handled, two memory allocations were made but alas, only\nthe latter one of them was released. This happened because there was only\na single local variable to hold such a temporary allocation.\n\nFix this by adding separate variables to hold the pointers to the\ntemporary allocations.\n\nReported-by: Arnd Bergmann \nReported-by: syzbot+1115e79c8df6472c612b@syzkaller.appspotmail.com\nFixes: d14e6d76ebf7 (\"[media] v4l: Add multi-planar ioctl handling code\")\nCc: stable@vger.kernel.org\nSigned-off-by: Sakari Ailus \nAcked-by: Arnd Bergmann \nAcked-by: Hans Verkuil \nReviewed-by: Laurent Pinchart \nSigned-off-by: Mauro Carvalho Chehab ", "target": 0, "dataset": "other", "idx": 381516} {"func": "static long evdev_do_ioctl(struct file *file, unsigned int cmd,\n\t\t\t void __user *p, int compat_mode)\n{\n\tstruct evdev_client *client = file->private_data;\n\tstruct evdev *evdev = client->evdev;\n\tstruct input_dev *dev = evdev->handle.dev;\n\tstruct input_absinfo abs;\n\tstruct ff_effect effect;\n\tint __user *ip = (int __user *)p;\n\tunsigned int i, t, u, v;\n\tunsigned int size;\n\tint error;\n\n\t/* First we check for fixed-length commands */\n\tswitch (cmd) {\n\n\tcase EVIOCGVERSION:\n\t\treturn put_user(EV_VERSION, ip);\n\n\tcase EVIOCGID:\n\t\tif (copy_to_user(p, &dev->id, sizeof(struct input_id)))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\n\tcase EVIOCGREP:\n\t\tif (!test_bit(EV_REP, dev->evbit))\n\t\t\treturn -ENOSYS;\n\t\tif (put_user(dev->rep[REP_DELAY], ip))\n\t\t\treturn -EFAULT;\n\t\tif (put_user(dev->rep[REP_PERIOD], ip + 1))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\n\tcase EVIOCSREP:\n\t\tif (!test_bit(EV_REP, dev->evbit))\n\t\t\treturn -ENOSYS;\n\t\tif (get_user(u, ip))\n\t\t\treturn -EFAULT;\n\t\tif (get_user(v, ip + 1))\n\t\t\treturn -EFAULT;\n\n\t\tinput_inject_event(&evdev->handle, EV_REP, REP_DELAY, u);\n\t\tinput_inject_event(&evdev->handle, EV_REP, REP_PERIOD, v);\n\n\t\treturn 0;\n\n\tcase EVIOCRMFF:\n\t\treturn input_ff_erase(dev, (int)(unsigned long) p, file);\n\n\tcase EVIOCGEFFECTS:\n\t\ti = test_bit(EV_FF, dev->evbit) ?\n\t\t\t\tdev->ff->max_effects : 0;\n\t\tif (put_user(i, ip))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\n\tcase EVIOCGRAB:\n\t\tif (p)\n\t\t\treturn evdev_grab(evdev, client);\n\t\telse\n\t\t\treturn evdev_ungrab(evdev, client);\n\n\tcase EVIOCSCLOCKID:\n\t\tif (copy_from_user(&i, p, sizeof(unsigned int)))\n\t\t\treturn -EFAULT;\n\t\tif (i != CLOCK_MONOTONIC && i != CLOCK_REALTIME)\n\t\t\treturn -EINVAL;\n\t\tclient->clkid = i;\n\t\treturn 0;\n\n\tcase EVIOCGKEYCODE:\n\t\treturn evdev_handle_get_keycode(dev, p);\n\n\tcase EVIOCSKEYCODE:\n\t\treturn evdev_handle_set_keycode(dev, p);\n\n\tcase EVIOCGKEYCODE_V2:\n\t\treturn evdev_handle_get_keycode_v2(dev, p);\n\n\tcase EVIOCSKEYCODE_V2:\n\t\treturn evdev_handle_set_keycode_v2(dev, p);\n\t}\n\n\tsize = _IOC_SIZE(cmd);\n\n\t/* Now check variable-length commands */\n#define EVIOC_MASK_SIZE(nr)\t((nr) & ~(_IOC_SIZEMASK << _IOC_SIZESHIFT))\n\tswitch (EVIOC_MASK_SIZE(cmd)) {\n\n\tcase EVIOCGPROP(0):\n\t\treturn bits_to_user(dev->propbit, INPUT_PROP_MAX,\n\t\t\t\t size, p, compat_mode);\n\n\tcase EVIOCGMTSLOTS(0):\n\t\treturn evdev_handle_mt_request(dev, size, ip);\n\n\tcase EVIOCGKEY(0):\n\t\treturn bits_to_user(dev->key, KEY_MAX, size, p, compat_mode);\n\n\tcase EVIOCGLED(0):\n\t\treturn bits_to_user(dev->led, LED_MAX, size, p, compat_mode);\n\n\tcase EVIOCGSND(0):\n\t\treturn bits_to_user(dev->snd, SND_MAX, size, p, compat_mode);\n\n\tcase EVIOCGSW(0):\n\t\treturn bits_to_user(dev->sw, SW_MAX, size, p, compat_mode);\n\n\tcase EVIOCGNAME(0):\n\t\treturn str_to_user(dev->name, size, p);\n\n\tcase EVIOCGPHYS(0):\n\t\treturn str_to_user(dev->phys, size, p);\n\n\tcase EVIOCGUNIQ(0):\n\t\treturn str_to_user(dev->uniq, size, p);\n\n\tcase EVIOC_MASK_SIZE(EVIOCSFF):\n\t\tif (input_ff_effect_from_user(p, size, &effect))\n\t\t\treturn -EFAULT;\n\n\t\terror = input_ff_upload(dev, &effect, file);\n\n\t\tif (put_user(effect.id, &(((struct ff_effect __user *)p)->id)))\n\t\t\treturn -EFAULT;\n\n\t\treturn error;\n\t}\n\n\t/* Multi-number variable-length handlers */\n\tif (_IOC_TYPE(cmd) != 'E')\n\t\treturn -EINVAL;\n\n\tif (_IOC_DIR(cmd) == _IOC_READ) {\n\n\t\tif ((_IOC_NR(cmd) & ~EV_MAX) == _IOC_NR(EVIOCGBIT(0, 0)))\n\t\t\treturn handle_eviocgbit(dev,\n\t\t\t\t\t\t_IOC_NR(cmd) & EV_MAX, size,\n\t\t\t\t\t\tp, compat_mode);\n\n\t\tif ((_IOC_NR(cmd) & ~ABS_MAX) == _IOC_NR(EVIOCGABS(0))) {\n\n\t\t\tif (!dev->absinfo)\n\t\t\t\treturn -EINVAL;\n\n\t\t\tt = _IOC_NR(cmd) & ABS_MAX;\n\t\t\tabs = dev->absinfo[t];\n\n\t\t\tif (copy_to_user(p, &abs, min_t(size_t,\n\t\t\t\t\tsize, sizeof(struct input_absinfo))))\n\t\t\t\treturn -EFAULT;\n\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tif (_IOC_DIR(cmd) == _IOC_WRITE) {\n\n\t\tif ((_IOC_NR(cmd) & ~ABS_MAX) == _IOC_NR(EVIOCSABS(0))) {\n\n\t\t\tif (!dev->absinfo)\n\t\t\t\treturn -EINVAL;\n\n\t\t\tt = _IOC_NR(cmd) & ABS_MAX;\n\n\t\t\tif (copy_from_user(&abs, p, min_t(size_t,\n\t\t\t\t\tsize, sizeof(struct input_absinfo))))\n\t\t\t\treturn -EFAULT;\n\n\t\t\tif (size < sizeof(struct input_absinfo))\n\t\t\t\tabs.resolution = 0;\n\n\t\t\t/* We can't change number of reserved MT slots */\n\t\t\tif (t == ABS_MT_SLOT)\n\t\t\t\treturn -EINVAL;\n\n\t\t\t/*\n\t\t\t * Take event lock to ensure that we are not\n\t\t\t * changing device parameters in the middle\n\t\t\t * of event.\n\t\t\t */\n\t\t\tspin_lock_irq(&dev->event_lock);\n\t\t\tdev->absinfo[t] = abs;\n\t\t\tspin_unlock_irq(&dev->event_lock);\n\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\treturn -EINVAL;\n}", "project": "linux", "hash": 58772209716728897872783601375559144047, "size": 191, "commit_id": "483180281f0ac60d1138710eb21f4b9961901294", "message": "Input: evdev - flush queues during EVIOCGKEY-like ioctls\n\nIf userspace requests current KEY-state, they very likely assume that no\nsuch events are pending in the output queue of the evdev device.\nOtherwise, they will parse events which they already handled via\nEVIOCGKEY(). For XKB applications this can cause irreversible keyboard\nstates if a modifier is locked multiple times because a CTRL-DOWN event is\nhandled once via EVIOCGKEY() and once from the queue via read(), even\nthough it should handle it only once.\n\nTherefore, lets do the only logical thing and flush the evdev queue\natomically during this ioctl. We only flush events that are affected by\nthe given ioctl.\n\nThis only affects boolean events like KEY, SND, SW and LED. ABS, REL and\nothers are not affected as duplicate events can be handled gracefully by\nuser-space.\n\nNote: This actually breaks semantics of the evdev ABI. However,\ninvestigations showed that userspace already expects the new semantics and\nwe end up fixing at least all XKB applications.\nAll applications that are aware of this race-condition mirror the KEY\nstate for each open-file and detect/drop duplicate events. Hence, they do\nnot care whether duplicates are posted or not and work fine with this fix.\n\nAlso note that we need proper locking to guarantee atomicity and avoid\ndead-locks. event_lock must be locked before queue_lock (see input-core).\nHowever, we can safely release event_lock while flushing the queue. This\nallows the input-core to proceed with pending events and only stop if it\nneeds our queue_lock to post new events.\nThis should guarantee that we don't block event-dispatching for too long\nwhile flushing a single event queue.\n\nSigned-off-by: David Herrmann \nAcked-by: Peter Hutterer \nSigned-off-by: Dmitry Torokhov ", "target": 1, "dataset": "other", "idx": 206492} {"func": "static long evdev_do_ioctl(struct file *file, unsigned int cmd,\n\t\t\t void __user *p, int compat_mode)\n{\n\tstruct evdev_client *client = file->private_data;\n\tstruct evdev *evdev = client->evdev;\n\tstruct input_dev *dev = evdev->handle.dev;\n\tstruct input_absinfo abs;\n\tstruct ff_effect effect;\n\tint __user *ip = (int __user *)p;\n\tunsigned int i, t, u, v;\n\tunsigned int size;\n\tint error;\n\n\t/* First we check for fixed-length commands */\n\tswitch (cmd) {\n\n\tcase EVIOCGVERSION:\n\t\treturn put_user(EV_VERSION, ip);\n\n\tcase EVIOCGID:\n\t\tif (copy_to_user(p, &dev->id, sizeof(struct input_id)))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\n\tcase EVIOCGREP:\n\t\tif (!test_bit(EV_REP, dev->evbit))\n\t\t\treturn -ENOSYS;\n\t\tif (put_user(dev->rep[REP_DELAY], ip))\n\t\t\treturn -EFAULT;\n\t\tif (put_user(dev->rep[REP_PERIOD], ip + 1))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\n\tcase EVIOCSREP:\n\t\tif (!test_bit(EV_REP, dev->evbit))\n\t\t\treturn -ENOSYS;\n\t\tif (get_user(u, ip))\n\t\t\treturn -EFAULT;\n\t\tif (get_user(v, ip + 1))\n\t\t\treturn -EFAULT;\n\n\t\tinput_inject_event(&evdev->handle, EV_REP, REP_DELAY, u);\n\t\tinput_inject_event(&evdev->handle, EV_REP, REP_PERIOD, v);\n\n\t\treturn 0;\n\n\tcase EVIOCRMFF:\n\t\treturn input_ff_erase(dev, (int)(unsigned long) p, file);\n\n\tcase EVIOCGEFFECTS:\n\t\ti = test_bit(EV_FF, dev->evbit) ?\n\t\t\t\tdev->ff->max_effects : 0;\n\t\tif (put_user(i, ip))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\n\tcase EVIOCGRAB:\n\t\tif (p)\n\t\t\treturn evdev_grab(evdev, client);\n\t\telse\n\t\t\treturn evdev_ungrab(evdev, client);\n\n\tcase EVIOCSCLOCKID:\n\t\tif (copy_from_user(&i, p, sizeof(unsigned int)))\n\t\t\treturn -EFAULT;\n\t\tif (i != CLOCK_MONOTONIC && i != CLOCK_REALTIME)\n\t\t\treturn -EINVAL;\n\t\tclient->clkid = i;\n\t\treturn 0;\n\n\tcase EVIOCGKEYCODE:\n\t\treturn evdev_handle_get_keycode(dev, p);\n\n\tcase EVIOCSKEYCODE:\n\t\treturn evdev_handle_set_keycode(dev, p);\n\n\tcase EVIOCGKEYCODE_V2:\n\t\treturn evdev_handle_get_keycode_v2(dev, p);\n\n\tcase EVIOCSKEYCODE_V2:\n\t\treturn evdev_handle_set_keycode_v2(dev, p);\n\t}\n\n\tsize = _IOC_SIZE(cmd);\n\n\t/* Now check variable-length commands */\n#define EVIOC_MASK_SIZE(nr)\t((nr) & ~(_IOC_SIZEMASK << _IOC_SIZESHIFT))\n\tswitch (EVIOC_MASK_SIZE(cmd)) {\n\n\tcase EVIOCGPROP(0):\n\t\treturn bits_to_user(dev->propbit, INPUT_PROP_MAX,\n\t\t\t\t size, p, compat_mode);\n\n\tcase EVIOCGMTSLOTS(0):\n\t\treturn evdev_handle_mt_request(dev, size, ip);\n\n\tcase EVIOCGKEY(0):\n\t\treturn evdev_handle_get_val(client, dev, EV_KEY, dev->key,\n\t\t\t\t\t KEY_MAX, size, p, compat_mode);\n\n\tcase EVIOCGLED(0):\n\t\treturn evdev_handle_get_val(client, dev, EV_LED, dev->led,\n\t\t\t\t\t LED_MAX, size, p, compat_mode);\n\n\tcase EVIOCGSND(0):\n\t\treturn evdev_handle_get_val(client, dev, EV_SND, dev->snd,\n\t\t\t\t\t SND_MAX, size, p, compat_mode);\n\n\tcase EVIOCGSW(0):\n\t\treturn evdev_handle_get_val(client, dev, EV_SW, dev->sw,\n\t\t\t\t\t SW_MAX, size, p, compat_mode);\n\n\tcase EVIOCGNAME(0):\n\t\treturn str_to_user(dev->name, size, p);\n\n\tcase EVIOCGPHYS(0):\n\t\treturn str_to_user(dev->phys, size, p);\n\n\tcase EVIOCGUNIQ(0):\n\t\treturn str_to_user(dev->uniq, size, p);\n\n\tcase EVIOC_MASK_SIZE(EVIOCSFF):\n\t\tif (input_ff_effect_from_user(p, size, &effect))\n\t\t\treturn -EFAULT;\n\n\t\terror = input_ff_upload(dev, &effect, file);\n\n\t\tif (put_user(effect.id, &(((struct ff_effect __user *)p)->id)))\n\t\t\treturn -EFAULT;\n\n\t\treturn error;\n\t}\n\n\t/* Multi-number variable-length handlers */\n\tif (_IOC_TYPE(cmd) != 'E')\n\t\treturn -EINVAL;\n\n\tif (_IOC_DIR(cmd) == _IOC_READ) {\n\n\t\tif ((_IOC_NR(cmd) & ~EV_MAX) == _IOC_NR(EVIOCGBIT(0, 0)))\n\t\t\treturn handle_eviocgbit(dev,\n\t\t\t\t\t\t_IOC_NR(cmd) & EV_MAX, size,\n\t\t\t\t\t\tp, compat_mode);\n\n\t\tif ((_IOC_NR(cmd) & ~ABS_MAX) == _IOC_NR(EVIOCGABS(0))) {\n\n\t\t\tif (!dev->absinfo)\n\t\t\t\treturn -EINVAL;\n\n\t\t\tt = _IOC_NR(cmd) & ABS_MAX;\n\t\t\tabs = dev->absinfo[t];\n\n\t\t\tif (copy_to_user(p, &abs, min_t(size_t,\n\t\t\t\t\tsize, sizeof(struct input_absinfo))))\n\t\t\t\treturn -EFAULT;\n\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tif (_IOC_DIR(cmd) == _IOC_WRITE) {\n\n\t\tif ((_IOC_NR(cmd) & ~ABS_MAX) == _IOC_NR(EVIOCSABS(0))) {\n\n\t\t\tif (!dev->absinfo)\n\t\t\t\treturn -EINVAL;\n\n\t\t\tt = _IOC_NR(cmd) & ABS_MAX;\n\n\t\t\tif (copy_from_user(&abs, p, min_t(size_t,\n\t\t\t\t\tsize, sizeof(struct input_absinfo))))\n\t\t\t\treturn -EFAULT;\n\n\t\t\tif (size < sizeof(struct input_absinfo))\n\t\t\t\tabs.resolution = 0;\n\n\t\t\t/* We can't change number of reserved MT slots */\n\t\t\tif (t == ABS_MT_SLOT)\n\t\t\t\treturn -EINVAL;\n\n\t\t\t/*\n\t\t\t * Take event lock to ensure that we are not\n\t\t\t * changing device parameters in the middle\n\t\t\t * of event.\n\t\t\t */\n\t\t\tspin_lock_irq(&dev->event_lock);\n\t\t\tdev->absinfo[t] = abs;\n\t\t\tspin_unlock_irq(&dev->event_lock);\n\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\treturn -EINVAL;\n}", "project": "linux", "hash": 17942239882540888408053190104002056298, "size": 195, "commit_id": "483180281f0ac60d1138710eb21f4b9961901294", "message": "Input: evdev - flush queues during EVIOCGKEY-like ioctls\n\nIf userspace requests current KEY-state, they very likely assume that no\nsuch events are pending in the output queue of the evdev device.\nOtherwise, they will parse events which they already handled via\nEVIOCGKEY(). For XKB applications this can cause irreversible keyboard\nstates if a modifier is locked multiple times because a CTRL-DOWN event is\nhandled once via EVIOCGKEY() and once from the queue via read(), even\nthough it should handle it only once.\n\nTherefore, lets do the only logical thing and flush the evdev queue\natomically during this ioctl. We only flush events that are affected by\nthe given ioctl.\n\nThis only affects boolean events like KEY, SND, SW and LED. ABS, REL and\nothers are not affected as duplicate events can be handled gracefully by\nuser-space.\n\nNote: This actually breaks semantics of the evdev ABI. However,\ninvestigations showed that userspace already expects the new semantics and\nwe end up fixing at least all XKB applications.\nAll applications that are aware of this race-condition mirror the KEY\nstate for each open-file and detect/drop duplicate events. Hence, they do\nnot care whether duplicates are posted or not and work fine with this fix.\n\nAlso note that we need proper locking to guarantee atomicity and avoid\ndead-locks. event_lock must be locked before queue_lock (see input-core).\nHowever, we can safely release event_lock while flushing the queue. This\nallows the input-core to proceed with pending events and only stop if it\nneeds our queue_lock to post new events.\nThis should guarantee that we don't block event-dispatching for too long\nwhile flushing a single event queue.\n\nSigned-off-by: David Herrmann \nAcked-by: Peter Hutterer \nSigned-off-by: Dmitry Torokhov ", "target": 0, "dataset": "other", "idx": 381731} {"func": "int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID)\n{\n\tCNetChunk Packet;\n\tif(!pMsg)\n\t\treturn -1;\n\n\t// drop packet to dummy client\n\tif(0 <= ClientID && ClientID < MAX_CLIENTS && GameServer()->IsClientBot(ClientID))\n\t\treturn 0;\n\n\tmem_zero(&Packet, sizeof(CNetChunk));\n\tPacket.m_ClientID = ClientID;\n\tPacket.m_pData = pMsg->Data();\n\tPacket.m_DataSize = pMsg->Size();\n\n\tif(Flags&MSGFLAG_VITAL)\n\t\tPacket.m_Flags |= NETSENDFLAG_VITAL;\n\tif(Flags&MSGFLAG_FLUSH)\n\t\tPacket.m_Flags |= NETSENDFLAG_FLUSH;\n\n\t// write message to demo recorder\n\tif(!(Flags&MSGFLAG_NORECORD))\n\t\tm_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size());\n\n\tif(!(Flags&MSGFLAG_NOSEND))\n\t{\n\t\tif(ClientID == -1)\n\t\t{\n\t\t\t// broadcast\n\t\t\tint i;\n\t\t\tfor(i = 0; i < MAX_CLIENTS; i++)\n\t\t\t\tif(m_aClients[i].m_State == CClient::STATE_INGAME && !m_aClients[i].m_Quitting)\n\t\t\t\t{\n\t\t\t\t\tPacket.m_ClientID = i;\n\t\t\t\t\tm_NetServer.Send(&Packet);\n\t\t\t\t}\n\t\t}\n\t\telse\n\t\t\tm_NetServer.Send(&Packet);\n\t}\n\treturn 0;\n}", "project": "teeworlds", "hash": 145582132599251035090290965422339038739, "size": 42, "commit_id": "c68402fa7e279d42886d5951d1ea8ac2facc1ea5", "message": "changed a check", "target": 1, "dataset": "other", "idx": 206517} {"func": "int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID)\n{\n\tCNetChunk Packet;\n\tif(!pMsg)\n\t\treturn -1;\n\n\t// drop invalid packet\n\tif(ClientID != -1 && (ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CClient::STATE_EMPTY || m_aClients[ClientID].m_Quitting))\n\t\treturn 0;\n\n\tmem_zero(&Packet, sizeof(CNetChunk));\n\tPacket.m_ClientID = ClientID;\n\tPacket.m_pData = pMsg->Data();\n\tPacket.m_DataSize = pMsg->Size();\n\n\tif(Flags&MSGFLAG_VITAL)\n\t\tPacket.m_Flags |= NETSENDFLAG_VITAL;\n\tif(Flags&MSGFLAG_FLUSH)\n\t\tPacket.m_Flags |= NETSENDFLAG_FLUSH;\n\n\t// write message to demo recorder\n\tif(!(Flags&MSGFLAG_NORECORD))\n\t\tm_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size());\n\n\tif(!(Flags&MSGFLAG_NOSEND))\n\t{\n\t\tif(ClientID == -1)\n\t\t{\n\t\t\t// broadcast\n\t\t\tint i;\n\t\t\tfor(i = 0; i < MAX_CLIENTS; i++)\n\t\t\t\tif(m_aClients[i].m_State == CClient::STATE_INGAME && !m_aClients[i].m_Quitting)\n\t\t\t\t{\n\t\t\t\t\tPacket.m_ClientID = i;\n\t\t\t\t\tm_NetServer.Send(&Packet);\n\t\t\t\t}\n\t\t}\n\t\telse\n\t\t\tm_NetServer.Send(&Packet);\n\t}\n\treturn 0;\n}", "project": "teeworlds", "hash": 329487471777399300626475999293740358602, "size": 42, "commit_id": "c68402fa7e279d42886d5951d1ea8ac2facc1ea5", "message": "changed a check", "target": 0, "dataset": "other", "idx": 381986} {"func": "static php_iconv_err_t _php_iconv_mime_decode(smart_str *pretval, const char *str, size_t str_nbytes, const char *enc, const char **next_pos, int mode)\n{\n\tphp_iconv_err_t err = PHP_ICONV_ERR_SUCCESS;\n\n\ticonv_t cd = (iconv_t)(-1), cd_pl = (iconv_t)(-1);\n\n\tconst char *p1;\n\tsize_t str_left;\n\tunsigned int scan_stat = 0;\n\tconst char *csname = NULL;\n\tsize_t csname_len;\n\tconst char *encoded_text = NULL;\n\tsize_t encoded_text_len = 0;\n\tconst char *encoded_word = NULL;\n\tconst char *spaces = NULL;\n\n\tphp_iconv_enc_scheme_t enc_scheme = PHP_ICONV_ENC_SCHEME_BASE64;\n\n\tif (next_pos != NULL) {\n\t\t*next_pos = NULL;\n\t}\n\n\tcd_pl = iconv_open(enc, ICONV_ASCII_ENCODING);\n\n\tif (cd_pl == (iconv_t)(-1)) {\n#if ICONV_SUPPORTS_ERRNO\n\t\tif (errno == EINVAL) {\n\t\t\terr = PHP_ICONV_ERR_WRONG_CHARSET;\n\t\t} else {\n\t\t\terr = PHP_ICONV_ERR_CONVERTER;\n\t\t}\n#else\n\t\terr = PHP_ICONV_ERR_UNKNOWN;\n#endif\n\t\tgoto out;\n\t}\n\n\tp1 = str;\n\tfor (str_left = str_nbytes; str_left > 0; str_left--, p1++) {\n\t\tint eos = 0;\n\n\t\tswitch (scan_stat) {\n\t\t\tcase 0: /* expecting any character */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\tencoded_word = p1;\n\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ' ': case '\\t': /* a chunk of whitespaces */\n\t\t\t\t\t\tspaces = p1;\n\t\t\t\t\t\tscan_stat = 11;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault: /* first letter of a non-encoded word */\n\t\t\t\t\t\terr = _php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tif (mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR) {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_SUCCESS;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 1: /* expecting a delimiter */\n\t\t\t\tif (*p1 != '?') {\n\t\t\t\t\tif (*p1 == '\\r' || *p1 == '\\n') {\n\t\t\t\t\t\t--p1;\n\t\t\t\t\t}\n\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcsname = p1 + 1;\n\t\t\t\tscan_stat = 2;\n\t\t\t\tbreak;\n\n\t\t\tcase 2: /* expecting a charset name */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '?': /* normal delimiter: encoding scheme follows */\n\t\t\t\t\t\tscan_stat = 3;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '*': /* new style delimiter: locale id follows */\n\t\t\t\t\t\tscan_stat = 10;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\r': case '\\n': /* not an encoded-word */\n\t\t\t\t\t\t--p1;\n\t\t\t\t\t\t_php_iconv_appendc(pretval, '=', cd_pl);\n\t\t\t\t\t\t_php_iconv_appendc(pretval, '?', cd_pl);\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, csname, (size_t)((p1 + 1) - csname), cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcsname = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (scan_stat != 2) {\n\t\t\t\t\tchar tmpbuf[80];\n\n\t\t\t\t\tif (csname == NULL) {\n\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\n\t\t\t\t\tcsname_len = (size_t)(p1 - csname);\n\n\t\t\t\t\tif (csname_len > sizeof(tmpbuf) - 1) {\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tmemcpy(tmpbuf, csname, csname_len);\n\t\t\t\t\ttmpbuf[csname_len] = '\\0';\n\n\t\t\t\t\tif (cd != (iconv_t)(-1)) {\n\t\t\t\t\t\ticonv_close(cd);\n\t\t\t\t\t}\n\n\t\t\t\t\tcd = iconv_open(enc, tmpbuf);\n\n\t\t\t\t\tif (cd == (iconv_t)(-1)) {\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\t/* Bad character set, but the user wants us to\n\t\t\t\t\t\t\t * press on. In this case, we'll just insert the\n\t\t\t\t\t\t\t * undecoded encoded word, since there isn't really\n\t\t\t\t\t\t\t * a more sensible behaviour available; the only\n\t\t\t\t\t\t\t * other options are to swallow the encoded word\n\t\t\t\t\t\t\t * entirely or decode it with an arbitrarily chosen\n\t\t\t\t\t\t\t * single byte encoding, both of which seem to have\n\t\t\t\t\t\t\t * a higher WTF factor than leaving it undecoded.\n\t\t\t\t\t\t\t *\n\t\t\t\t\t\t\t * Given this approach, we need to skip ahead to\n\t\t\t\t\t\t\t * the end of the encoded word. */\n\t\t\t\t\t\t\tint qmarks = 2;\n\t\t\t\t\t\t\twhile (qmarks > 0 && str_left > 1) {\n\t\t\t\t\t\t\t\tif (*(++p1) == '?') {\n\t\t\t\t\t\t\t\t\t--qmarks;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t--str_left;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t/* Look ahead to check for the terminating = that\n\t\t\t\t\t\t\t * should be there as well; if it's there, we'll\n\t\t\t\t\t\t\t * also include that. If it's not, there isn't much\n\t\t\t\t\t\t\t * we can do at this point. */\n\t\t\t\t\t\t\tif (*(p1 + 1) == '=') {\n\t\t\t\t\t\t\t\t++p1;\n\t\t\t\t\t\t\t\t--str_left;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t/* Let's go back and see if there are further\n\t\t\t\t\t\t\t * encoded words or bare content, and hope they\n\t\t\t\t\t\t\t * might actually have a valid character set. */\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n#if ICONV_SUPPORTS_ERRNO\n\t\t\t\t\t\t\tif (errno == EINVAL) {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_WRONG_CHARSET;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_CONVERTER;\n\t\t\t\t\t\t\t}\n#else\n\t\t\t\t\t\t\terr = PHP_ICONV_ERR_UNKNOWN;\n#endif\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 3: /* expecting a encoding scheme specifier */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase 'b':\n\t\t\t\t\tcase 'B':\n\t\t\t\t\t\tenc_scheme = PHP_ICONV_ENC_SCHEME_BASE64;\n\t\t\t\t\t\tscan_stat = 4;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'q':\n\t\t\t\t\tcase 'Q':\n\t\t\t\t\t\tenc_scheme = PHP_ICONV_ENC_SCHEME_QPRINT;\n\t\t\t\t\t\tscan_stat = 4;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 4: /* expecting a delimiter */\n\t\t\t\tif (*p1 != '?') {\n\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tencoded_text = p1 + 1;\n\t\t\t\tscan_stat = 5;\n\t\t\t\tbreak;\n\n\t\t\tcase 5: /* expecting an encoded portion */\n\t\t\t\tif (*p1 == '?') {\n\t\t\t\t\tencoded_text_len = (size_t)(p1 - encoded_text);\n\t\t\t\t\tscan_stat = 6;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 7: /* expecting a \"\\n\" character */\n\t\t\t\tif (*p1 == '\\n') {\n\t\t\t\t\tscan_stat = 8;\n\t\t\t\t} else {\n\t\t\t\t\t/* bare CR */\n\t\t\t\t\t_php_iconv_appendc(pretval, '\\r', cd_pl);\n\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\tscan_stat = 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 8: /* checking whether the following line is part of a\n\t\t\t\t\t folded header */\n\t\t\t\tif (*p1 != ' ' && *p1 != '\\t') {\n\t\t\t\t\t--p1;\n\t\t\t\t\tstr_left = 1; /* quit_loop */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (encoded_word == NULL) {\n\t\t\t\t\t_php_iconv_appendc(pretval, ' ', cd_pl);\n\t\t\t\t}\n\t\t\t\tspaces = NULL;\n\t\t\t\tscan_stat = 11;\n\t\t\t\tbreak;\n\n\t\t\tcase 6: /* expecting a End-Of-Chunk character \"=\" */\n\t\t\t\tif (*p1 != '=') {\n\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tscan_stat = 9;\n\t\t\t\tif (str_left == 1) {\n\t\t\t\t\teos = 1;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tcase 9: /* choice point, seeing what to do next.*/\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t/* Handle non-RFC-compliant formats\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * RFC2047 requires the character that comes right\n\t\t\t\t\t\t * after an encoded word (chunk) to be a whitespace,\n\t\t\t\t\t\t * while there are lots of broken implementations that\n\t\t\t\t\t\t * generate such malformed headers that don't fulfill\n\t\t\t\t\t\t * that requirement.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (!eos) {\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* break is omitted intentionally */\n\n\t\t\t\t\tcase '\\r': case '\\n': case ' ': case '\\t': {\n\t\t\t\t\t\tzend_string *decoded_text;\n\n\t\t\t\t\t\tswitch (enc_scheme) {\n\t\t\t\t\t\t\tcase PHP_ICONV_ENC_SCHEME_BASE64:\n\t\t\t\t\t\t\t\tdecoded_text = php_base64_decode((unsigned char*)encoded_text, encoded_text_len);\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase PHP_ICONV_ENC_SCHEME_QPRINT:\n\t\t\t\t\t\t\t\tdecoded_text = php_quot_print_decode((unsigned char*)encoded_text, encoded_text_len, 1);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tdecoded_text = NULL;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (decoded_text == NULL) {\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_UNKNOWN;\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, ZSTR_VAL(decoded_text), ZSTR_LEN(decoded_text), cd);\n\t\t\t\t\t\tzend_string_release(decoded_text);\n\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)(p1 - encoded_word), cd_pl);\n\t\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (eos) { /* reached end-of-string. done. */\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tswitch (*p1) {\n\t\t\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase ' ': case '\\t': /* medial whitespaces */\n\t\t\t\t\t\t\t\tspaces = p1;\n\t\t\t\t\t\t\t\tscan_stat = 11;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tdefault: /* first letter of a non-encoded word */\n\t\t\t\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} break;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 10: /* expects a language specifier. dismiss it for now */\n\t\t\t\tif (*p1 == '?') {\n\t\t\t\t\tscan_stat = 3;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 11: /* expecting a chunk of whitespaces */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\tif (spaces != NULL && encoded_word == NULL) {\n\t\t\t\t\t\t\t_php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl);\n\t\t\t\t\t\t\tspaces = NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = p1;\n\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ' ': case '\\t':\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault: /* first letter of a non-encoded word */\n\t\t\t\t\t\tif (spaces != NULL) {\n\t\t\t\t\t\t\t_php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl);\n\t\t\t\t\t\t\tspaces = NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 12: /* expecting a non-encoded word */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ' ': case '\\t':\n\t\t\t\t\t\tspaces = p1;\n\t\t\t\t\t\tscan_stat = 11;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\tif (!(mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tencoded_word = p1;\n\t\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* break is omitted intentionally */\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tswitch (scan_stat) {\n\t\tcase 0: case 8: case 11: case 12:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\tif (scan_stat == 1) {\n\t\t\t\t\t_php_iconv_appendc(pretval, '=', cd_pl);\n\t\t\t\t}\n\t\t\t\terr = PHP_ICONV_ERR_SUCCESS;\n\t\t\t} else {\n\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\tgoto out;\n\t\t\t}\n\t}\n\n\tif (next_pos != NULL) {\n\t\t*next_pos = p1;\n\t}\n\n\tsmart_str_0(pretval);\nout:\n\tif (cd != (iconv_t)(-1)) {\n\t\ticonv_close(cd);\n\t}\n\tif (cd_pl != (iconv_t)(-1)) {\n\t\ticonv_close(cd_pl);\n\t}\n\treturn err;\n}", "project": "php-src", "hash": 252711754502941885197887607368897836371, "size": 549, "commit_id": "7cf7148a8f8f4f55fb04de2a517d740bb6253eac", "message": "Fix bug #78069 - Out-of-bounds read in iconv.c:_php_iconv_mime_decode() due to integer overflow", "target": 1, "dataset": "other", "idx": 206554} {"func": "static php_iconv_err_t _php_iconv_mime_decode(smart_str *pretval, const char *str, size_t str_nbytes, const char *enc, const char **next_pos, int mode)\n{\n\tphp_iconv_err_t err = PHP_ICONV_ERR_SUCCESS;\n\n\ticonv_t cd = (iconv_t)(-1), cd_pl = (iconv_t)(-1);\n\n\tconst char *p1;\n\tsize_t str_left;\n\tunsigned int scan_stat = 0;\n\tconst char *csname = NULL;\n\tsize_t csname_len;\n\tconst char *encoded_text = NULL;\n\tsize_t encoded_text_len = 0;\n\tconst char *encoded_word = NULL;\n\tconst char *spaces = NULL;\n\n\tphp_iconv_enc_scheme_t enc_scheme = PHP_ICONV_ENC_SCHEME_BASE64;\n\n\tif (next_pos != NULL) {\n\t\t*next_pos = NULL;\n\t}\n\n\tcd_pl = iconv_open(enc, ICONV_ASCII_ENCODING);\n\n\tif (cd_pl == (iconv_t)(-1)) {\n#if ICONV_SUPPORTS_ERRNO\n\t\tif (errno == EINVAL) {\n\t\t\terr = PHP_ICONV_ERR_WRONG_CHARSET;\n\t\t} else {\n\t\t\terr = PHP_ICONV_ERR_CONVERTER;\n\t\t}\n#else\n\t\terr = PHP_ICONV_ERR_UNKNOWN;\n#endif\n\t\tgoto out;\n\t}\n\n\tp1 = str;\n\tfor (str_left = str_nbytes; str_left > 0; str_left--, p1++) {\n\t\tint eos = 0;\n\n\t\tswitch (scan_stat) {\n\t\t\tcase 0: /* expecting any character */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\tencoded_word = p1;\n\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ' ': case '\\t': /* a chunk of whitespaces */\n\t\t\t\t\t\tspaces = p1;\n\t\t\t\t\t\tscan_stat = 11;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault: /* first letter of a non-encoded word */\n\t\t\t\t\t\terr = _php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tif (mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR) {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_SUCCESS;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 1: /* expecting a delimiter */\n\t\t\t\tif (*p1 != '?') {\n\t\t\t\t\tif (*p1 == '\\r' || *p1 == '\\n') {\n\t\t\t\t\t\t--p1;\n\t\t\t\t\t}\n\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcsname = p1 + 1;\n\t\t\t\tscan_stat = 2;\n\t\t\t\tbreak;\n\n\t\t\tcase 2: /* expecting a charset name */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '?': /* normal delimiter: encoding scheme follows */\n\t\t\t\t\t\tscan_stat = 3;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '*': /* new style delimiter: locale id follows */\n\t\t\t\t\t\tscan_stat = 10;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\r': case '\\n': /* not an encoded-word */\n\t\t\t\t\t\t--p1;\n\t\t\t\t\t\t_php_iconv_appendc(pretval, '=', cd_pl);\n\t\t\t\t\t\t_php_iconv_appendc(pretval, '?', cd_pl);\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, csname, (size_t)((p1 + 1) - csname), cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcsname = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (scan_stat != 2) {\n\t\t\t\t\tchar tmpbuf[80];\n\n\t\t\t\t\tif (csname == NULL) {\n\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\n\t\t\t\t\tcsname_len = (size_t)(p1 - csname);\n\n\t\t\t\t\tif (csname_len > sizeof(tmpbuf) - 1) {\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tmemcpy(tmpbuf, csname, csname_len);\n\t\t\t\t\ttmpbuf[csname_len] = '\\0';\n\n\t\t\t\t\tif (cd != (iconv_t)(-1)) {\n\t\t\t\t\t\ticonv_close(cd);\n\t\t\t\t\t}\n\n\t\t\t\t\tcd = iconv_open(enc, tmpbuf);\n\n\t\t\t\t\tif (cd == (iconv_t)(-1)) {\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\t/* Bad character set, but the user wants us to\n\t\t\t\t\t\t\t * press on. In this case, we'll just insert the\n\t\t\t\t\t\t\t * undecoded encoded word, since there isn't really\n\t\t\t\t\t\t\t * a more sensible behaviour available; the only\n\t\t\t\t\t\t\t * other options are to swallow the encoded word\n\t\t\t\t\t\t\t * entirely or decode it with an arbitrarily chosen\n\t\t\t\t\t\t\t * single byte encoding, both of which seem to have\n\t\t\t\t\t\t\t * a higher WTF factor than leaving it undecoded.\n\t\t\t\t\t\t\t *\n\t\t\t\t\t\t\t * Given this approach, we need to skip ahead to\n\t\t\t\t\t\t\t * the end of the encoded word. */\n\t\t\t\t\t\t\tint qmarks = 2;\n\t\t\t\t\t\t\twhile (qmarks > 0 && str_left > 1) {\n\t\t\t\t\t\t\t\tif (*(++p1) == '?') {\n\t\t\t\t\t\t\t\t\t--qmarks;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t--str_left;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t/* Look ahead to check for the terminating = that\n\t\t\t\t\t\t\t * should be there as well; if it's there, we'll\n\t\t\t\t\t\t\t * also include that. If it's not, there isn't much\n\t\t\t\t\t\t\t * we can do at this point. */\n\t\t\t\t\t\t\tif (*(p1 + 1) == '=') {\n\t\t\t\t\t\t\t\t++p1;\n\t\t\t\t\t\t\t\tif (str_left > 1) {\n\t\t\t\t\t\t\t\t\t--str_left;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t/* Let's go back and see if there are further\n\t\t\t\t\t\t\t * encoded words or bare content, and hope they\n\t\t\t\t\t\t\t * might actually have a valid character set. */\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n#if ICONV_SUPPORTS_ERRNO\n\t\t\t\t\t\t\tif (errno == EINVAL) {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_WRONG_CHARSET;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_CONVERTER;\n\t\t\t\t\t\t\t}\n#else\n\t\t\t\t\t\t\terr = PHP_ICONV_ERR_UNKNOWN;\n#endif\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 3: /* expecting a encoding scheme specifier */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase 'b':\n\t\t\t\t\tcase 'B':\n\t\t\t\t\t\tenc_scheme = PHP_ICONV_ENC_SCHEME_BASE64;\n\t\t\t\t\t\tscan_stat = 4;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'q':\n\t\t\t\t\tcase 'Q':\n\t\t\t\t\t\tenc_scheme = PHP_ICONV_ENC_SCHEME_QPRINT;\n\t\t\t\t\t\tscan_stat = 4;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 4: /* expecting a delimiter */\n\t\t\t\tif (*p1 != '?') {\n\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tencoded_text = p1 + 1;\n\t\t\t\tscan_stat = 5;\n\t\t\t\tbreak;\n\n\t\t\tcase 5: /* expecting an encoded portion */\n\t\t\t\tif (*p1 == '?') {\n\t\t\t\t\tencoded_text_len = (size_t)(p1 - encoded_text);\n\t\t\t\t\tscan_stat = 6;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 7: /* expecting a \"\\n\" character */\n\t\t\t\tif (*p1 == '\\n') {\n\t\t\t\t\tscan_stat = 8;\n\t\t\t\t} else {\n\t\t\t\t\t/* bare CR */\n\t\t\t\t\t_php_iconv_appendc(pretval, '\\r', cd_pl);\n\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\tscan_stat = 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 8: /* checking whether the following line is part of a\n\t\t\t\t\t folded header */\n\t\t\t\tif (*p1 != ' ' && *p1 != '\\t') {\n\t\t\t\t\t--p1;\n\t\t\t\t\tstr_left = 1; /* quit_loop */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (encoded_word == NULL) {\n\t\t\t\t\t_php_iconv_appendc(pretval, ' ', cd_pl);\n\t\t\t\t}\n\t\t\t\tspaces = NULL;\n\t\t\t\tscan_stat = 11;\n\t\t\t\tbreak;\n\n\t\t\tcase 6: /* expecting a End-Of-Chunk character \"=\" */\n\t\t\t\tif (*p1 != '=') {\n\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tscan_stat = 9;\n\t\t\t\tif (str_left == 1) {\n\t\t\t\t\teos = 1;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tcase 9: /* choice point, seeing what to do next.*/\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t/* Handle non-RFC-compliant formats\n\t\t\t\t\t\t *\n\t\t\t\t\t\t * RFC2047 requires the character that comes right\n\t\t\t\t\t\t * after an encoded word (chunk) to be a whitespace,\n\t\t\t\t\t\t * while there are lots of broken implementations that\n\t\t\t\t\t\t * generate such malformed headers that don't fulfill\n\t\t\t\t\t\t * that requirement.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (!eos) {\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* break is omitted intentionally */\n\n\t\t\t\t\tcase '\\r': case '\\n': case ' ': case '\\t': {\n\t\t\t\t\t\tzend_string *decoded_text;\n\n\t\t\t\t\t\tswitch (enc_scheme) {\n\t\t\t\t\t\t\tcase PHP_ICONV_ENC_SCHEME_BASE64:\n\t\t\t\t\t\t\t\tdecoded_text = php_base64_decode((unsigned char*)encoded_text, encoded_text_len);\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase PHP_ICONV_ENC_SCHEME_QPRINT:\n\t\t\t\t\t\t\t\tdecoded_text = php_quot_print_decode((unsigned char*)encoded_text, encoded_text_len, 1);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tdecoded_text = NULL;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (decoded_text == NULL) {\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl);\n\t\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\terr = PHP_ICONV_ERR_UNKNOWN;\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\terr = _php_iconv_appendl(pretval, ZSTR_VAL(decoded_text), ZSTR_LEN(decoded_text), cd);\n\t\t\t\t\t\tzend_string_release(decoded_text);\n\n\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\t\t\t\t\t/* pass the entire chunk through the converter */\n\t\t\t\t\t\t\t\terr = _php_iconv_appendl(pretval, encoded_word, (size_t)(p1 - encoded_word), cd_pl);\n\t\t\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\t\t\tif (err != PHP_ICONV_ERR_SUCCESS) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (eos) { /* reached end-of-string. done. */\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tswitch (*p1) {\n\t\t\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase ' ': case '\\t': /* medial whitespaces */\n\t\t\t\t\t\t\t\tspaces = p1;\n\t\t\t\t\t\t\t\tscan_stat = 11;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tdefault: /* first letter of a non-encoded word */\n\t\t\t\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} break;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 10: /* expects a language specifier. dismiss it for now */\n\t\t\t\tif (*p1 == '?') {\n\t\t\t\t\tscan_stat = 3;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 11: /* expecting a chunk of whitespaces */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\tif (spaces != NULL && encoded_word == NULL) {\n\t\t\t\t\t\t\t_php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl);\n\t\t\t\t\t\t\tspaces = NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tencoded_word = p1;\n\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ' ': case '\\t':\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault: /* first letter of a non-encoded word */\n\t\t\t\t\t\tif (spaces != NULL) {\n\t\t\t\t\t\t\t_php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl);\n\t\t\t\t\t\t\tspaces = NULL;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\tencoded_word = NULL;\n\t\t\t\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tscan_stat = 12;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tscan_stat = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 12: /* expecting a non-encoded word */\n\t\t\t\tswitch (*p1) {\n\t\t\t\t\tcase '\\r': /* part of an EOL sequence? */\n\t\t\t\t\t\tscan_stat = 7;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\n':\n\t\t\t\t\t\tscan_stat = 8;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ' ': case '\\t':\n\t\t\t\t\t\tspaces = p1;\n\t\t\t\t\t\tscan_stat = 11;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '=': /* first letter of an encoded chunk */\n\t\t\t\t\t\tif (!(mode & PHP_ICONV_MIME_DECODE_STRICT)) {\n\t\t\t\t\t\t\tencoded_word = p1;\n\t\t\t\t\t\t\tscan_stat = 1;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/* break is omitted intentionally */\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t_php_iconv_appendc(pretval, *p1, cd_pl);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tswitch (scan_stat) {\n\t\tcase 0: case 8: case 11: case 12:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) {\n\t\t\t\tif (scan_stat == 1) {\n\t\t\t\t\t_php_iconv_appendc(pretval, '=', cd_pl);\n\t\t\t\t}\n\t\t\t\terr = PHP_ICONV_ERR_SUCCESS;\n\t\t\t} else {\n\t\t\t\terr = PHP_ICONV_ERR_MALFORMED;\n\t\t\t\tgoto out;\n\t\t\t}\n\t}\n\n\tif (next_pos != NULL) {\n\t\t*next_pos = p1;\n\t}\n\n\tsmart_str_0(pretval);\nout:\n\tif (cd != (iconv_t)(-1)) {\n\t\ticonv_close(cd);\n\t}\n\tif (cd_pl != (iconv_t)(-1)) {\n\t\ticonv_close(cd_pl);\n\t}\n\treturn err;\n}", "project": "php-src", "hash": 218325121010366491134849590402382438328, "size": 551, "commit_id": "7cf7148a8f8f4f55fb04de2a517d740bb6253eac", "message": "Fix bug #78069 - Out-of-bounds read in iconv.c:_php_iconv_mime_decode() due to integer overflow", "target": 0, "dataset": "other", "idx": 382780} {"func": "static void *gp_worker_main(void *pvt)\n{\n struct gp_thread *t = (struct gp_thread *)pvt;\n struct gp_query *q = NULL;\n char dummy = 0;\n int ret;\n\n while (!t->pool->shutdown) {\n\n /* initialize debug client id to 0 until work is scheduled */\n gp_debug_set_conn_id(0);\n\n /* ======> COND_MUTEX */\n pthread_mutex_lock(&t->cond_mutex);\n while (t->query == NULL) {\n /* wait for next query */\n pthread_cond_wait(&t->cond_wakeup, &t->cond_mutex);\n if (t->pool->shutdown) {\n pthread_exit(NULL);\n }\n }\n\n /* grab the query off the shared pointer */\n q = t->query;\n t->query = NULL;\n\n /* <====== COND_MUTEX */\n pthread_mutex_unlock(&t->cond_mutex);\n\n /* set client id before hndling requests */\n gp_debug_set_conn_id(gp_conn_get_cid(q->conn));\n\n /* handle the client request */\n GPDEBUGN(3, \"[status] Handling query input: %p (%zu)\\n\", q->buffer,\n q->buflen);\n gp_handle_query(t->pool, q);\n GPDEBUGN(3 ,\"[status] Handling query output: %p (%zu)\\n\", q->buffer,\n q->buflen);\n\n /* now get lock on main queue, to play with the reply list */\n /* ======> POOL LOCK */\n pthread_mutex_lock(&t->pool->lock);\n\n /* put back query so that dispatcher can send reply */\n q->next = t->pool->reply_list;\n t->pool->reply_list = q;\n\n /* add us back to the free list but only if we are not\n * shutting down */\n if (!t->pool->shutdown) {\n LIST_DEL(t->pool->busy_list, t);\n LIST_ADD(t->pool->free_list, t);\n }\n\n /* <====== POOL LOCK */\n pthread_mutex_unlock(&t->pool->lock);\n\n /* and wake up dispatcher so it will handle it */\n ret = write(t->pool->sig_pipe[1], &dummy, 1);\n if (ret == -1) {\n GPERROR(\"Failed to signal dispatcher!\");\n }\n }\n\n pthread_exit(NULL);\n}", "project": "gssproxy", "hash": 78285020008400258286650992522334327753, "size": 66, "commit_id": "cb761412e299ef907f22cd7c4146d50c8a792003", "message": "Unlock cond_mutex before pthread exit in gp_worker_main()\n\nSigned-off-by: GuiYao \n[rharwood@redhat.com: whitespace, tweak commit message]\nReviewed-by: Robbie Harwood ", "target": 1, "dataset": "other", "idx": 206559} {"func": "static void *gp_worker_main(void *pvt)\n{\n struct gp_thread *t = (struct gp_thread *)pvt;\n struct gp_query *q = NULL;\n char dummy = 0;\n int ret;\n\n while (!t->pool->shutdown) {\n\n /* initialize debug client id to 0 until work is scheduled */\n gp_debug_set_conn_id(0);\n\n /* ======> COND_MUTEX */\n pthread_mutex_lock(&t->cond_mutex);\n while (t->query == NULL) {\n /* wait for next query */\n pthread_cond_wait(&t->cond_wakeup, &t->cond_mutex);\n if (t->pool->shutdown) {\n pthread_mutex_unlock(&t->cond_mutex);\n pthread_exit(NULL);\n }\n }\n\n /* grab the query off the shared pointer */\n q = t->query;\n t->query = NULL;\n\n /* <====== COND_MUTEX */\n pthread_mutex_unlock(&t->cond_mutex);\n\n /* set client id before hndling requests */\n gp_debug_set_conn_id(gp_conn_get_cid(q->conn));\n\n /* handle the client request */\n GPDEBUGN(3, \"[status] Handling query input: %p (%zu)\\n\", q->buffer,\n q->buflen);\n gp_handle_query(t->pool, q);\n GPDEBUGN(3 ,\"[status] Handling query output: %p (%zu)\\n\", q->buffer,\n q->buflen);\n\n /* now get lock on main queue, to play with the reply list */\n /* ======> POOL LOCK */\n pthread_mutex_lock(&t->pool->lock);\n\n /* put back query so that dispatcher can send reply */\n q->next = t->pool->reply_list;\n t->pool->reply_list = q;\n\n /* add us back to the free list but only if we are not\n * shutting down */\n if (!t->pool->shutdown) {\n LIST_DEL(t->pool->busy_list, t);\n LIST_ADD(t->pool->free_list, t);\n }\n\n /* <====== POOL LOCK */\n pthread_mutex_unlock(&t->pool->lock);\n\n /* and wake up dispatcher so it will handle it */\n ret = write(t->pool->sig_pipe[1], &dummy, 1);\n if (ret == -1) {\n GPERROR(\"Failed to signal dispatcher!\");\n }\n }\n\n pthread_exit(NULL);\n}", "project": "gssproxy", "hash": 4842314628500364921745841145573401402, "size": 67, "commit_id": "cb761412e299ef907f22cd7c4146d50c8a792003", "message": "Unlock cond_mutex before pthread exit in gp_worker_main()\n\nSigned-off-by: GuiYao \n[rharwood@redhat.com: whitespace, tweak commit message]\nReviewed-by: Robbie Harwood ", "target": 0, "dataset": "other", "idx": 382874} {"func": "MagickExport Image *DistortImage(const Image *image, DistortMethod method,\n const size_t number_arguments,const double *arguments,\n MagickBooleanType bestfit,ExceptionInfo *exception)\n{\n#define DistortImageTag \"Distort/Image\"\n\n double\n *coeff,\n output_scaling;\n\n Image\n *distort_image;\n\n RectangleInfo\n geometry; /* geometry of the distorted space viewport */\n\n MagickBooleanType\n viewport_given;\n\n PixelInfo\n invalid; /* the color to assign when distort result is invalid */\n\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n\n /*\n Handle Special Compound Distortions\n */\n if ( method == ResizeDistortion )\n {\n if ( number_arguments != 2 )\n {\n (void) ThrowMagickException(exception,GetMagickModule(),OptionError,\n \"InvalidArgument\",\"%s : '%s'\",\"Resize\",\n \"Invalid number of args: 2 only\");\n return((Image *) NULL);\n }\n distort_image=DistortResizeImage(image,(size_t)arguments[0],\n (size_t)arguments[1], exception);\n return(distort_image);\n }\n\n /*\n Convert input arguments (usually as control points for reverse mapping)\n into mapping coefficients to apply the distortion.\n\n Note that some distortions are mapped to other distortions,\n and as such do not require specific code after this point.\n */\n coeff = GenerateCoefficients(image, &method, number_arguments,\n arguments, 0, exception);\n if ( coeff == (double *) NULL )\n return((Image *) NULL);\n\n /*\n Determine the size and offset for a 'bestfit' destination.\n Usally the four corners of the source image is enough.\n */\n\n /* default output image bounds, when no 'bestfit' is requested */\n geometry.width=image->columns;\n geometry.height=image->rows;\n geometry.x=0;\n geometry.y=0;\n\n if ( method == ArcDistortion ) {\n bestfit = MagickTrue; /* always calculate a 'best fit' viewport */\n }\n\n /* Work out the 'best fit', (required for ArcDistortion) */\n if ( bestfit ) {\n PointInfo\n s,d,min,max; /* source, dest coords --mapping--> min, max coords */\n\n MagickBooleanType\n fix_bounds = MagickTrue; /* enlarge bounds for VP handling */\n\n s.x=s.y=min.x=max.x=min.y=max.y=0.0; /* keep compiler happy */\n\n/* defines to figure out the bounds of the distorted image */\n#define InitalBounds(p) \\\n{ \\\n /* printf(\"%lg,%lg -> %lg,%lg\\n\", s.x,s.y, d.x,d.y); */ \\\n min.x = max.x = p.x; \\\n min.y = max.y = p.y; \\\n}\n#define ExpandBounds(p) \\\n{ \\\n /* printf(\"%lg,%lg -> %lg,%lg\\n\", s.x,s.y, d.x,d.y); */ \\\n min.x = MagickMin(min.x,p.x); \\\n max.x = MagickMax(max.x,p.x); \\\n min.y = MagickMin(min.y,p.y); \\\n max.y = MagickMax(max.y,p.y); \\\n}\n\n switch (method)\n {\n case AffineDistortion:\n case RigidAffineDistortion:\n { double inverse[6];\n InvertAffineCoefficients(coeff, inverse);\n s.x = (double) image->page.x;\n s.y = (double) image->page.y;\n d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2];\n d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5];\n InitalBounds(d);\n s.x = (double) image->page.x+image->columns;\n s.y = (double) image->page.y;\n d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2];\n d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5];\n ExpandBounds(d);\n s.x = (double) image->page.x;\n s.y = (double) image->page.y+image->rows;\n d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2];\n d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5];\n ExpandBounds(d);\n s.x = (double) image->page.x+image->columns;\n s.y = (double) image->page.y+image->rows;\n d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2];\n d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5];\n ExpandBounds(d);\n break;\n }\n case PerspectiveDistortion:\n { double inverse[8], scale;\n InvertPerspectiveCoefficients(coeff, inverse);\n s.x = (double) image->page.x;\n s.y = (double) image->page.y;\n scale=inverse[6]*s.x+inverse[7]*s.y+1.0;\n scale=PerceptibleReciprocal(scale);\n d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]);\n d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]);\n InitalBounds(d);\n s.x = (double) image->page.x+image->columns;\n s.y = (double) image->page.y;\n scale=inverse[6]*s.x+inverse[7]*s.y+1.0;\n scale=PerceptibleReciprocal(scale);\n d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]);\n d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]);\n ExpandBounds(d);\n s.x = (double) image->page.x;\n s.y = (double) image->page.y+image->rows;\n scale=inverse[6]*s.x+inverse[7]*s.y+1.0;\n scale=PerceptibleReciprocal(scale);\n d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]);\n d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]);\n ExpandBounds(d);\n s.x = (double) image->page.x+image->columns;\n s.y = (double) image->page.y+image->rows;\n scale=inverse[6]*s.x+inverse[7]*s.y+1.0;\n scale=PerceptibleReciprocal(scale);\n d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]);\n d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]);\n ExpandBounds(d);\n break;\n }\n case ArcDistortion:\n { double a, ca, sa;\n /* Forward Map Corners */\n a = coeff[0]-coeff[1]/2; ca = cos(a); sa = sin(a);\n d.x = coeff[2]*ca;\n d.y = coeff[2]*sa;\n InitalBounds(d);\n d.x = (coeff[2]-coeff[3])*ca;\n d.y = (coeff[2]-coeff[3])*sa;\n ExpandBounds(d);\n a = coeff[0]+coeff[1]/2; ca = cos(a); sa = sin(a);\n d.x = coeff[2]*ca;\n d.y = coeff[2]*sa;\n ExpandBounds(d);\n d.x = (coeff[2]-coeff[3])*ca;\n d.y = (coeff[2]-coeff[3])*sa;\n ExpandBounds(d);\n /* Orthogonal points along top of arc */\n for( a=(double) (ceil((double) ((coeff[0]-coeff[1]/2.0)/MagickPI2))*MagickPI2);\n a<(coeff[0]+coeff[1]/2.0); a+=MagickPI2 ) {\n ca = cos(a); sa = sin(a);\n d.x = coeff[2]*ca;\n d.y = coeff[2]*sa;\n ExpandBounds(d);\n }\n /*\n Convert the angle_to_width and radius_to_height\n to appropriate scaling factors, to allow faster processing\n in the mapping function.\n */\n coeff[1] = (double) (Magick2PI*image->columns/coeff[1]);\n coeff[3] = (double)image->rows/coeff[3];\n break;\n }\n case PolarDistortion:\n {\n if (number_arguments < 2)\n coeff[2] = coeff[3] = 0.0;\n min.x = coeff[2]-coeff[0];\n max.x = coeff[2]+coeff[0];\n min.y = coeff[3]-coeff[0];\n max.y = coeff[3]+coeff[0];\n /* should be about 1.0 if Rmin = 0 */\n coeff[7]=(double) geometry.height/(coeff[0]-coeff[1]);\n break;\n }\n case DePolarDistortion:\n {\n /* direct calculation as it needs to tile correctly\n * for reversibility in a DePolar-Polar cycle */\n fix_bounds = MagickFalse;\n geometry.x = geometry.y = 0;\n geometry.height = (size_t) ceil(coeff[0]-coeff[1]);\n geometry.width = (size_t)\n ceil((coeff[0]-coeff[1])*(coeff[5]-coeff[4])*0.5);\n /* correct scaling factors relative to new size */\n coeff[6]=(coeff[5]-coeff[4])/geometry.width; /* changed width */\n coeff[7]=(coeff[0]-coeff[1])/geometry.height; /* should be about 1.0 */\n break;\n }\n case Cylinder2PlaneDistortion:\n {\n /* direct calculation so center of distortion is either a pixel\n * center, or pixel edge. This allows for reversibility of the\n * distortion */\n geometry.x = geometry.y = 0;\n geometry.width = (size_t) ceil( 2.0*coeff[1]*tan(coeff[0]/2.0) );\n geometry.height = (size_t) ceil( 2.0*coeff[3]/cos(coeff[0]/2.0) );\n /* correct center of distortion relative to new size */\n coeff[4] = (double) geometry.width/2.0;\n coeff[5] = (double) geometry.height/2.0;\n fix_bounds = MagickFalse;\n break;\n }\n case Plane2CylinderDistortion:\n {\n /* direct calculation center is either pixel center, or pixel edge\n * so as to allow reversibility of the image distortion */\n geometry.x = geometry.y = 0;\n geometry.width = (size_t) ceil(coeff[0]*coeff[1]); /* FOV * radius */\n geometry.height = (size_t) (2*coeff[3]); /* input image height */\n /* correct center of distortion relative to new size */\n coeff[4] = (double) geometry.width/2.0;\n coeff[5] = (double) geometry.height/2.0;\n fix_bounds = MagickFalse;\n break;\n }\n case ShepardsDistortion:\n case BilinearForwardDistortion:\n case BilinearReverseDistortion:\n#if 0\n case QuadrilateralDistortion:\n#endif\n case PolynomialDistortion:\n case BarrelDistortion:\n case BarrelInverseDistortion:\n default:\n /* no calculated bestfit available for these distortions */\n bestfit = MagickFalse;\n fix_bounds = MagickFalse;\n break;\n }\n\n /* Set the output image geometry to calculated 'bestfit'.\n Yes this tends to 'over do' the file image size, ON PURPOSE!\n Do not do this for DePolar which needs to be exact for virtual tiling.\n */\n if ( fix_bounds ) {\n geometry.x = (ssize_t) floor(min.x-0.5);\n geometry.y = (ssize_t) floor(min.y-0.5);\n geometry.width=(size_t) ceil(max.x-geometry.x+0.5);\n geometry.height=(size_t) ceil(max.y-geometry.y+0.5);\n }\n\n } /* end bestfit destination image calculations */\n\n /* The user provided a 'viewport' expert option which may\n overrides some parts of the current output image geometry.\n This also overrides its default 'bestfit' setting.\n */\n { const char *artifact=GetImageArtifact(image,\"distort:viewport\");\n viewport_given = MagickFalse;\n if ( artifact != (const char *) NULL ) {\n MagickStatusType flags=ParseAbsoluteGeometry(artifact,&geometry);\n if (flags==NoValue)\n (void) ThrowMagickException(exception,GetMagickModule(),\n OptionWarning,\"InvalidSetting\",\"'%s' '%s'\",\n \"distort:viewport\",artifact);\n else\n viewport_given = MagickTrue;\n }\n }\n\n /* Verbose output */\n if (IsStringTrue(GetImageArtifact(image,\"verbose\")) != MagickFalse) {\n ssize_t\n i;\n char image_gen[MagickPathExtent];\n const char *lookup;\n\n /* Set destination image size and virtual offset */\n if ( bestfit || viewport_given ) {\n (void) FormatLocaleString(image_gen,MagickPathExtent,\n \" -size %.20gx%.20g -page %+.20g%+.20g xc: +insert \\\\\\n\",\n (double) geometry.width,(double) geometry.height,(double) geometry.x,\n (double) geometry.y);\n lookup=\"v.p{xx-v.page.x-0.5,yy-v.page.y-0.5}\";\n }\n else {\n image_gen[0] = '\\0'; /* no destination to generate */\n lookup = \"p{xx-page.x-0.5,yy-page.y-0.5}\"; /* simplify lookup */\n }\n\n switch (method)\n {\n case AffineDistortion:\n case RigidAffineDistortion:\n {\n double\n *inverse;\n\n inverse=(double *) AcquireQuantumMemory(6,sizeof(*inverse));\n if (inverse == (double *) NULL)\n {\n coeff=(double *) RelinquishMagickMemory(coeff);\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"%s\",\"DistortImages\");\n return((Image *) NULL);\n }\n InvertAffineCoefficients(coeff, inverse);\n CoefficientsToAffineArgs(inverse);\n (void) FormatLocaleFile(stderr, \"Affine projection:\\n\");\n (void) FormatLocaleFile(stderr,\n \" -distort AffineProjection \\\\\\n '\");\n for (i=0; i < 5; i++)\n (void) FormatLocaleFile(stderr, \"%.*g,\",GetMagickPrecision(),\n inverse[i]);\n (void) FormatLocaleFile(stderr, \"%.*g'\\n\",GetMagickPrecision(),\n inverse[5]);\n (void) FormatLocaleFile(stderr,\n \"Equivalent scale, rotation(deg), translation:\\n\");\n (void) FormatLocaleFile(stderr,\" %.*g,%.*g,%.*g,%.*g\\n\",\n GetMagickPrecision(),sqrt(inverse[0]*inverse[0]+\n inverse[1]*inverse[1]),GetMagickPrecision(),\n RadiansToDegrees(atan2(inverse[1],inverse[0])),\n GetMagickPrecision(),inverse[4],GetMagickPrecision(),inverse[5]);\n inverse=(double *) RelinquishMagickMemory(inverse);\n (void) FormatLocaleFile(stderr,\"Affine distort, FX equivalent:\\n\");\n (void) FormatLocaleFile(stderr, \"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\\n\");\n (void) FormatLocaleFile(stderr,\" xx=%+.*g*ii %+.*g*jj %+.*g;\\n\",\n GetMagickPrecision(),coeff[0],GetMagickPrecision(),coeff[1],\n GetMagickPrecision(),coeff[2]);\n (void) FormatLocaleFile(stderr,\" yy=%+.*g*ii %+.*g*jj %+.*g;\\n\",\n GetMagickPrecision(),coeff[3],GetMagickPrecision(),coeff[4],\n GetMagickPrecision(),coeff[5]);\n (void) FormatLocaleFile(stderr,\" %s' \\\\\\n\",lookup);\n break;\n }\n case PerspectiveDistortion:\n {\n double\n *inverse;\n\n inverse=(double *) AcquireQuantumMemory(8,sizeof(*inverse));\n if (inverse == (double *) NULL)\n {\n coeff=(double *) RelinquishMagickMemory(coeff);\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"%s\",\n \"DistortCoefficients\");\n return((Image *) NULL);\n }\n InvertPerspectiveCoefficients(coeff, inverse);\n (void) FormatLocaleFile(stderr,\"Perspective Projection:\\n\");\n (void) FormatLocaleFile(stderr,\n \" -distort PerspectiveProjection \\\\\\n '\");\n for (i=0; i < 4; i++)\n (void) FormatLocaleFile(stderr, \"%.*g, \",GetMagickPrecision(),\n inverse[i]);\n (void) FormatLocaleFile(stderr, \"\\n \");\n for ( ; i < 7; i++)\n (void) FormatLocaleFile(stderr, \"%.*g, \",GetMagickPrecision(),\n inverse[i]);\n (void) FormatLocaleFile(stderr, \"%.*g'\\n\",GetMagickPrecision(),\n inverse[7]);\n inverse=(double *) RelinquishMagickMemory(inverse);\n (void) FormatLocaleFile(stderr,\"Perspective Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%.1024s\",image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\\n\");\n (void) FormatLocaleFile(stderr,\" rr=%+.*g*ii %+.*g*jj + 1;\\n\",\n GetMagickPrecision(),coeff[6],GetMagickPrecision(),coeff[7]);\n (void) FormatLocaleFile(stderr,\n \" xx=(%+.*g*ii %+.*g*jj %+.*g)/rr;\\n\",\n GetMagickPrecision(),coeff[0],GetMagickPrecision(),coeff[1],\n GetMagickPrecision(),coeff[2]);\n (void) FormatLocaleFile(stderr,\n \" yy=(%+.*g*ii %+.*g*jj %+.*g)/rr;\\n\",\n GetMagickPrecision(),coeff[3],GetMagickPrecision(),coeff[4],\n GetMagickPrecision(),coeff[5]);\n (void) FormatLocaleFile(stderr,\" rr%s0 ? %s : blue' \\\\\\n\",\n coeff[8] < 0.0 ? \"<\" : \">\", lookup);\n break;\n }\n case BilinearForwardDistortion:\n {\n (void) FormatLocaleFile(stderr,\"BilinearForward Mapping Equations:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\" i = %+lf*x %+lf*y %+lf*x*y %+lf;\\n\",\n coeff[0],coeff[1],coeff[2],coeff[3]);\n (void) FormatLocaleFile(stderr,\" j = %+lf*x %+lf*y %+lf*x*y %+lf;\\n\",\n coeff[4],coeff[5],coeff[6],coeff[7]);\n#if 0\n /* for debugging */\n (void) FormatLocaleFile(stderr, \" c8 = %+lf c9 = 2*a = %+lf;\\n\",\n coeff[8], coeff[9]);\n#endif\n (void) FormatLocaleFile(stderr,\n \"BilinearForward Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x%+lf; jj=j+page.y%+lf;\\n\",0.5-coeff[3],0.5-\n coeff[7]);\n (void) FormatLocaleFile(stderr,\" bb=%lf*ii %+lf*jj %+lf;\\n\",\n coeff[6], -coeff[2], coeff[8]);\n /* Handle Special degenerate (non-quadratic) or trapezoidal case */\n if (coeff[9] != 0)\n {\n (void) FormatLocaleFile(stderr,\n \" rt=bb*bb %+lf*(%lf*ii%+lf*jj);\\n\",-2*coeff[9],coeff[4],\n -coeff[0]);\n (void) FormatLocaleFile(stderr,\n \" yy=( -bb + sqrt(rt) ) / %lf;\\n\",coeff[9]);\n }\n else\n (void) FormatLocaleFile(stderr,\" yy=(%lf*ii%+lf*jj)/bb;\\n\",\n -coeff[4],coeff[0]);\n (void) FormatLocaleFile(stderr,\n \" xx=(ii %+lf*yy)/(%lf %+lf*yy);\\n\",-coeff[1],coeff[0],\n coeff[2]);\n if ( coeff[9] != 0 )\n (void) FormatLocaleFile(stderr,\" (rt < 0 ) ? red : %s'\\n\",\n lookup);\n else\n (void) FormatLocaleFile(stderr,\" %s' \\\\\\n\", lookup);\n break;\n }\n case BilinearReverseDistortion:\n {\n#if 0\n (void) FormatLocaleFile(stderr, \"Polynomial Projection Distort:\\n\");\n (void) FormatLocaleFile(stderr, \" -distort PolynomialProjection \\\\\\n\");\n (void) FormatLocaleFile(stderr, \" '1.5, %lf, %lf, %lf, %lf,\\n\",\n coeff[3], coeff[0], coeff[1], coeff[2]);\n (void) FormatLocaleFile(stderr, \" %lf, %lf, %lf, %lf'\\n\",\n coeff[7], coeff[4], coeff[5], coeff[6]);\n#endif\n (void) FormatLocaleFile(stderr,\n \"BilinearReverse Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\\n\");\n (void) FormatLocaleFile(stderr,\n \" xx=%+lf*ii %+lf*jj %+lf*ii*jj %+lf;\\n\",coeff[0],coeff[1],\n coeff[2], coeff[3]);\n (void) FormatLocaleFile(stderr,\n \" yy=%+lf*ii %+lf*jj %+lf*ii*jj %+lf;\\n\",coeff[4],coeff[5],\n coeff[6], coeff[7]);\n (void) FormatLocaleFile(stderr,\" %s' \\\\\\n\", lookup);\n break;\n }\n case PolynomialDistortion:\n {\n size_t nterms = (size_t) coeff[1];\n (void) FormatLocaleFile(stderr,\n \"Polynomial (order %lg, terms %lu), FX Equivelent\\n\",coeff[0],\n (unsigned long) nterms);\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\\n\");\n (void) FormatLocaleFile(stderr, \" xx =\");\n for (i=0; i < (ssize_t) nterms; i++)\n {\n if ((i != 0) && (i%4 == 0))\n (void) FormatLocaleFile(stderr, \"\\n \");\n (void) FormatLocaleFile(stderr,\" %+lf%s\",coeff[2+i],\n poly_basis_str(i));\n }\n (void) FormatLocaleFile(stderr,\";\\n yy =\");\n for (i=0; i < (ssize_t) nterms; i++)\n {\n if ((i != 0) && (i%4 == 0))\n (void) FormatLocaleFile(stderr,\"\\n \");\n (void) FormatLocaleFile(stderr,\" %+lf%s\",coeff[2+i+nterms],\n poly_basis_str(i));\n }\n (void) FormatLocaleFile(stderr,\";\\n %s' \\\\\\n\", lookup);\n break;\n }\n case ArcDistortion:\n {\n (void) FormatLocaleFile(stderr,\"Arc Distort, Internal Coefficients:\\n\");\n for (i=0; i < 5; i++)\n (void) FormatLocaleFile(stderr,\n \" c%.20g = %+lf\\n\",(double) i,coeff[i]);\n (void) FormatLocaleFile(stderr,\"Arc Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\" -fx 'ii=i+page.x; jj=j+page.y;\\n\");\n (void) FormatLocaleFile(stderr,\" xx=(atan2(jj,ii)%+lf)/(2*pi);\\n\",\n -coeff[0]);\n (void) FormatLocaleFile(stderr,\" xx=xx-round(xx);\\n\");\n (void) FormatLocaleFile(stderr,\" xx=xx*%lf %+lf;\\n\",coeff[1],\n coeff[4]);\n (void) FormatLocaleFile(stderr,\n \" yy=(%lf - hypot(ii,jj)) * %lf;\\n\",coeff[2],coeff[3]);\n (void) FormatLocaleFile(stderr,\" v.p{xx-.5,yy-.5}' \\\\\\n\");\n break;\n }\n case PolarDistortion:\n {\n (void) FormatLocaleFile(stderr,\"Polar Distort, Internal Coefficents\\n\");\n for (i=0; i < 8; i++)\n (void) FormatLocaleFile(stderr,\" c%.20g = %+lf\\n\",(double) i,\n coeff[i]);\n (void) FormatLocaleFile(stderr,\"Polar Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x%+lf; jj=j+page.y%+lf;\\n\",-coeff[2],-coeff[3]);\n (void) FormatLocaleFile(stderr,\" xx=(atan2(ii,jj)%+lf)/(2*pi);\\n\",\n -(coeff[4]+coeff[5])/2 );\n (void) FormatLocaleFile(stderr,\" xx=xx-round(xx);\\n\");\n (void) FormatLocaleFile(stderr,\" xx=xx*2*pi*%lf + v.w/2;\\n\",\n coeff[6] );\n (void) FormatLocaleFile(stderr,\" yy=(hypot(ii,jj)%+lf)*%lf;\\n\",\n -coeff[1],coeff[7] );\n (void) FormatLocaleFile(stderr,\" v.p{xx-.5,yy-.5}' \\\\\\n\");\n break;\n }\n case DePolarDistortion:\n {\n (void) FormatLocaleFile(stderr,\n \"DePolar Distort, Internal Coefficents\\n\");\n for (i=0; i < 8; i++)\n (void) FormatLocaleFile(stderr,\" c%.20g = %+lf\\n\",(double) i,\n coeff[i]);\n (void) FormatLocaleFile(stderr,\"DePolar Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\" -fx 'aa=(i+.5)*%lf %+lf;\\n\",\n coeff[6],+coeff[4]);\n (void) FormatLocaleFile(stderr,\" rr=(j+.5)*%lf %+lf;\\n\",\n coeff[7],+coeff[1]);\n (void) FormatLocaleFile(stderr,\" xx=rr*sin(aa) %+lf;\\n\",\n coeff[2]);\n (void) FormatLocaleFile(stderr,\" yy=rr*cos(aa) %+lf;\\n\",\n coeff[3]);\n (void) FormatLocaleFile(stderr,\" v.p{xx-.5,yy-.5}' \\\\\\n\");\n break;\n }\n case Cylinder2PlaneDistortion:\n {\n (void) FormatLocaleFile(stderr,\n \"Cylinder to Plane Distort, Internal Coefficents\\n\");\n (void) FormatLocaleFile(stderr,\" cylinder_radius = %+lf\\n\",coeff[1]);\n (void) FormatLocaleFile(stderr,\n \"Cylinder to Plane Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr, \"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x%+lf+0.5; jj=j+page.y%+lf+0.5;\\n\",-coeff[4],\n -coeff[5]);\n (void) FormatLocaleFile(stderr,\" aa=atan(ii/%+lf);\\n\",coeff[1]);\n (void) FormatLocaleFile(stderr,\" xx=%lf*aa%+lf;\\n\",\n coeff[1],coeff[2]);\n (void) FormatLocaleFile(stderr,\" yy=jj*cos(aa)%+lf;\\n\",coeff[3]);\n (void) FormatLocaleFile(stderr,\" %s' \\\\\\n\", lookup);\n break;\n }\n case Plane2CylinderDistortion:\n {\n (void) FormatLocaleFile(stderr,\n \"Plane to Cylinder Distort, Internal Coefficents\\n\");\n (void) FormatLocaleFile(stderr,\" cylinder_radius = %+lf\\n\",coeff[1]);\n (void) FormatLocaleFile(stderr,\n \"Plane to Cylinder Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x%+lf+0.5; jj=j+page.y%+lf+0.5;\\n\",-coeff[4],\n -coeff[5]);\n (void) FormatLocaleFile(stderr,\" ii=ii/%+lf;\\n\",coeff[1]);\n (void) FormatLocaleFile(stderr,\" xx=%lf*tan(ii)%+lf;\\n\",coeff[1],\n coeff[2] );\n (void) FormatLocaleFile(stderr,\" yy=jj/cos(ii)%+lf;\\n\",coeff[3]);\n (void) FormatLocaleFile(stderr,\" %s' \\\\\\n\", lookup);\n break;\n }\n case BarrelDistortion:\n case BarrelInverseDistortion:\n {\n double\n xc,\n yc;\n\n /*\n NOTE: This does the barrel roll in pixel coords not image coords\n The internal distortion must do it in image coordinates,\n so that is what the center coeff (8,9) is given in.\n */\n xc=((double)image->columns-1.0)/2.0+image->page.x;\n yc=((double)image->rows-1.0)/2.0+image->page.y;\n (void) FormatLocaleFile(stderr, \"Barrel%s Distort, FX Equivelent:\\n\",\n method == BarrelDistortion ? \"\" : \"Inv\");\n (void) FormatLocaleFile(stderr, \"%s\", image_gen);\n if ( fabs(coeff[8]-xc-0.5) < 0.1 && fabs(coeff[9]-yc-0.5) < 0.1 )\n (void) FormatLocaleFile(stderr,\" -fx 'xc=(w-1)/2; yc=(h-1)/2;\\n\");\n else\n (void) FormatLocaleFile(stderr,\" -fx 'xc=%lf; yc=%lf;\\n\",coeff[8]-\n 0.5,coeff[9]-0.5);\n (void) FormatLocaleFile(stderr,\n \" ii=i-xc; jj=j-yc; rr=hypot(ii,jj);\\n\");\n (void) FormatLocaleFile(stderr,\n \" ii=ii%s(%lf*rr*rr*rr %+lf*rr*rr %+lf*rr %+lf);\\n\",\n method == BarrelDistortion ? \"*\" : \"/\",coeff[0],coeff[1],coeff[2],\n coeff[3]);\n (void) FormatLocaleFile(stderr,\n \" jj=jj%s(%lf*rr*rr*rr %+lf*rr*rr %+lf*rr %+lf);\\n\",\n method == BarrelDistortion ? \"*\" : \"/\",coeff[4],coeff[5],coeff[6],\n coeff[7]);\n (void) FormatLocaleFile(stderr,\" v.p{fx*ii+xc,fy*jj+yc}' \\\\\\n\");\n }\n default:\n break;\n }\n }\n /*\n The user provided a 'scale' expert option will scale the output image size,\n by the factor given allowing for super-sampling of the distorted image\n space. Any scaling factors must naturally be halved as a result.\n */\n { const char *artifact;\n artifact=GetImageArtifact(image,\"distort:scale\");\n output_scaling = 1.0;\n if (artifact != (const char *) NULL) {\n output_scaling = fabs(StringToDouble(artifact,(char **) NULL));\n geometry.width=(size_t) (output_scaling*geometry.width+0.5);\n geometry.height=(size_t) (output_scaling*geometry.height+0.5);\n geometry.x=(ssize_t) (output_scaling*geometry.x+0.5);\n geometry.y=(ssize_t) (output_scaling*geometry.y+0.5);\n if ( output_scaling < 0.1 ) {\n coeff = (double *) RelinquishMagickMemory(coeff);\n (void) ThrowMagickException(exception,GetMagickModule(),OptionError,\n \"InvalidArgument\",\"%s\", \"-set option:distort:scale\" );\n return((Image *) NULL);\n }\n output_scaling = 1/output_scaling;\n }\n }\n#define ScaleFilter(F,A,B,C,D) \\\n ScaleResampleFilter( (F), \\\n output_scaling*(A), output_scaling*(B), \\\n output_scaling*(C), output_scaling*(D) )\n\n /*\n Initialize the distort image attributes.\n */\n distort_image=CloneImage(image,geometry.width,geometry.height,MagickTrue,\n exception);\n if (distort_image == (Image *) NULL)\n {\n coeff=(double *) RelinquishMagickMemory(coeff);\n return((Image *) NULL);\n }\n /* if image is ColorMapped - change it to DirectClass */\n if (SetImageStorageClass(distort_image,DirectClass,exception) == MagickFalse)\n {\n coeff=(double *) RelinquishMagickMemory(coeff);\n distort_image=DestroyImage(distort_image);\n return((Image *) NULL);\n }\n if ((IsPixelInfoGray(&distort_image->background_color) == MagickFalse) &&\n (IsGrayColorspace(distort_image->colorspace) != MagickFalse))\n (void) SetImageColorspace(distort_image,sRGBColorspace,exception);\n if (distort_image->background_color.alpha_trait != UndefinedPixelTrait)\n distort_image->alpha_trait=BlendPixelTrait;\n distort_image->page.x=geometry.x;\n distort_image->page.y=geometry.y;\n ConformPixelInfo(distort_image,&distort_image->matte_color,&invalid,\n exception);\n\n { /* ----- MAIN CODE -----\n Sample the source image to each pixel in the distort image.\n */\n CacheView\n *distort_view;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n PixelInfo\n zero;\n\n ResampleFilter\n **magick_restrict resample_filter;\n\n ssize_t\n j;\n\n status=MagickTrue;\n progress=0;\n GetPixelInfo(distort_image,&zero);\n resample_filter=AcquireResampleFilterThreadSet(image,\n UndefinedVirtualPixelMethod,MagickFalse,exception);\n distort_view=AcquireAuthenticCacheView(distort_image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(image,distort_image,distort_image->rows,1)\n#endif\n for (j=0; j < (ssize_t) distort_image->rows; j++)\n {\n const int\n id = GetOpenMPThreadId();\n\n double\n validity; /* how mathematically valid is this the mapping */\n\n MagickBooleanType\n sync;\n\n PixelInfo\n pixel; /* pixel color to assign to distorted image */\n\n PointInfo\n d,\n s; /* transform destination image x,y to source image x,y */\n\n ssize_t\n i;\n\n Quantum\n *magick_restrict q;\n\n q=QueueCacheViewAuthenticPixels(distort_view,0,j,distort_image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n pixel=zero;\n\n /* Define constant scaling vectors for Affine Distortions\n Other methods are either variable, or use interpolated lookup\n */\n switch (method)\n {\n case AffineDistortion:\n case RigidAffineDistortion:\n ScaleFilter( resample_filter[id],\n coeff[0], coeff[1],\n coeff[3], coeff[4] );\n break;\n default:\n break;\n }\n\n /* Initialize default pixel validity\n * negative: pixel is invalid output 'matte_color'\n * 0.0 to 1.0: antialiased, mix with resample output\n * 1.0 or greater: use resampled output.\n */\n validity = 1.0;\n\n for (i=0; i < (ssize_t) distort_image->columns; i++)\n {\n /* map pixel coordinate to distortion space coordinate */\n d.x = (double) (geometry.x+i+0.5)*output_scaling;\n d.y = (double) (geometry.y+j+0.5)*output_scaling;\n s = d; /* default is a no-op mapping */\n switch (method)\n {\n case AffineDistortion:\n case RigidAffineDistortion:\n {\n s.x=coeff[0]*d.x+coeff[1]*d.y+coeff[2];\n s.y=coeff[3]*d.x+coeff[4]*d.y+coeff[5];\n /* Affine partial derivitives are constant -- set above */\n break;\n }\n case PerspectiveDistortion:\n {\n double\n p,q,r,abs_r,abs_c6,abs_c7,scale;\n /* perspective is a ratio of affines */\n p=coeff[0]*d.x+coeff[1]*d.y+coeff[2];\n q=coeff[3]*d.x+coeff[4]*d.y+coeff[5];\n r=coeff[6]*d.x+coeff[7]*d.y+1.0;\n /* Pixel Validity -- is it a 'sky' or 'ground' pixel */\n validity = (r*coeff[8] < 0.0) ? 0.0 : 1.0;\n /* Determine horizon anti-alias blending */\n abs_r = fabs(r)*2;\n abs_c6 = fabs(coeff[6]);\n abs_c7 = fabs(coeff[7]);\n if ( abs_c6 > abs_c7 ) {\n if ( abs_r < abs_c6*output_scaling )\n validity = 0.5 - coeff[8]*r/(coeff[6]*output_scaling);\n }\n else if ( abs_r < abs_c7*output_scaling )\n validity = 0.5 - coeff[8]*r/(coeff[7]*output_scaling);\n /* Perspective Sampling Point (if valid) */\n if ( validity > 0.0 ) {\n /* divide by r affine, for perspective scaling */\n scale = 1.0/r;\n s.x = p*scale;\n s.y = q*scale;\n /* Perspective Partial Derivatives or Scaling Vectors */\n scale *= scale;\n ScaleFilter( resample_filter[id],\n (r*coeff[0] - p*coeff[6])*scale,\n (r*coeff[1] - p*coeff[7])*scale,\n (r*coeff[3] - q*coeff[6])*scale,\n (r*coeff[4] - q*coeff[7])*scale );\n }\n break;\n }\n case BilinearReverseDistortion:\n {\n /* Reversed Mapped is just a simple polynomial */\n s.x=coeff[0]*d.x+coeff[1]*d.y+coeff[2]*d.x*d.y+coeff[3];\n s.y=coeff[4]*d.x+coeff[5]*d.y\n +coeff[6]*d.x*d.y+coeff[7];\n /* Bilinear partial derivitives of scaling vectors */\n ScaleFilter( resample_filter[id],\n coeff[0] + coeff[2]*d.y,\n coeff[1] + coeff[2]*d.x,\n coeff[4] + coeff[6]*d.y,\n coeff[5] + coeff[6]*d.x );\n break;\n }\n case BilinearForwardDistortion:\n {\n /* Forward mapped needs reversed polynomial equations\n * which unfortunatally requires a square root! */\n double b,c;\n d.x -= coeff[3]; d.y -= coeff[7];\n b = coeff[6]*d.x - coeff[2]*d.y + coeff[8];\n c = coeff[4]*d.x - coeff[0]*d.y;\n\n validity = 1.0;\n /* Handle Special degenerate (non-quadratic) case\n * Currently without horizon anti-alising */\n if ( fabs(coeff[9]) < MagickEpsilon )\n s.y = -c/b;\n else {\n c = b*b - 2*coeff[9]*c;\n if ( c < 0.0 )\n validity = 0.0;\n else\n s.y = ( -b + sqrt(c) )/coeff[9];\n }\n if ( validity > 0.0 )\n s.x = ( d.x - coeff[1]*s.y) / ( coeff[0] + coeff[2]*s.y );\n\n /* NOTE: the sign of the square root should be -ve for parts\n where the source image becomes 'flipped' or 'mirrored'.\n FUTURE: Horizon handling\n FUTURE: Scaling factors or Deritives (how?)\n */\n break;\n }\n#if 0\n case BilinearDistortion:\n /* Bilinear mapping of any Quadrilateral to any Quadrilateral */\n /* UNDER DEVELOPMENT */\n break;\n#endif\n case PolynomialDistortion:\n {\n /* multi-ordered polynomial */\n ssize_t\n k;\n\n ssize_t\n nterms=(ssize_t)coeff[1];\n\n PointInfo\n du,dv; /* the du,dv vectors from unit dx,dy -- derivatives */\n\n s.x=s.y=du.x=du.y=dv.x=dv.y=0.0;\n for(k=0; k < nterms; k++) {\n s.x += poly_basis_fn(k,d.x,d.y)*coeff[2+k];\n du.x += poly_basis_dx(k,d.x,d.y)*coeff[2+k];\n du.y += poly_basis_dy(k,d.x,d.y)*coeff[2+k];\n s.y += poly_basis_fn(k,d.x,d.y)*coeff[2+k+nterms];\n dv.x += poly_basis_dx(k,d.x,d.y)*coeff[2+k+nterms];\n dv.y += poly_basis_dy(k,d.x,d.y)*coeff[2+k+nterms];\n }\n ScaleFilter( resample_filter[id], du.x,du.y,dv.x,dv.y );\n break;\n }\n case ArcDistortion:\n {\n /* what is the angle and radius in the destination image */\n s.x = (double) ((atan2(d.y,d.x) - coeff[0])/Magick2PI);\n s.x -= MagickRound(s.x); /* angle */\n s.y = hypot(d.x,d.y); /* radius */\n\n /* Arc Distortion Partial Scaling Vectors\n Are derived by mapping the perpendicular unit vectors\n dR and dA*R*2PI rather than trying to map dx and dy\n The results is a very simple orthogonal aligned ellipse.\n */\n if ( s.y > MagickEpsilon )\n ScaleFilter( resample_filter[id],\n (double) (coeff[1]/(Magick2PI*s.y)), 0, 0, coeff[3] );\n else\n ScaleFilter( resample_filter[id],\n distort_image->columns*2, 0, 0, coeff[3] );\n\n /* now scale the angle and radius for source image lookup point */\n s.x = s.x*coeff[1] + coeff[4] + image->page.x +0.5;\n s.y = (coeff[2] - s.y) * coeff[3] + image->page.y;\n break;\n }\n case PolarDistortion:\n { /* 2D Cartesain to Polar View */\n d.x -= coeff[2];\n d.y -= coeff[3];\n s.x = atan2(d.x,d.y) - (coeff[4]+coeff[5])/2;\n s.x /= Magick2PI;\n s.x -= MagickRound(s.x);\n s.x *= Magick2PI; /* angle - relative to centerline */\n s.y = hypot(d.x,d.y); /* radius */\n\n /* Polar Scaling vectors are based on mapping dR and dA vectors\n This results in very simple orthogonal scaling vectors\n */\n if ( s.y > MagickEpsilon )\n ScaleFilter( resample_filter[id],\n (double) (coeff[6]/(Magick2PI*s.y)), 0, 0, coeff[7] );\n else\n ScaleFilter( resample_filter[id],\n distort_image->columns*2, 0, 0, coeff[7] );\n\n /* now finish mapping radius/angle to source x,y coords */\n s.x = s.x*coeff[6] + (double)image->columns/2.0 + image->page.x;\n s.y = (s.y-coeff[1])*coeff[7] + image->page.y;\n break;\n }\n case DePolarDistortion:\n { /* @D Polar to Carteasain */\n /* ignore all destination virtual offsets */\n d.x = ((double)i+0.5)*output_scaling*coeff[6]+coeff[4];\n d.y = ((double)j+0.5)*output_scaling*coeff[7]+coeff[1];\n s.x = d.y*sin(d.x) + coeff[2];\n s.y = d.y*cos(d.x) + coeff[3];\n /* derivatives are usless - better to use SuperSampling */\n break;\n }\n case Cylinder2PlaneDistortion:\n { /* 3D Cylinder to Tangential Plane */\n double ax, cx;\n /* relative to center of distortion */\n d.x -= coeff[4]; d.y -= coeff[5];\n d.x /= coeff[1]; /* x' = x/r */\n ax=atan(d.x); /* aa = atan(x/r) = u/r */\n cx=cos(ax); /* cx = cos(atan(x/r)) = 1/sqrt(x^2+u^2) */\n s.x = coeff[1]*ax; /* u = r*atan(x/r) */\n s.y = d.y*cx; /* v = y*cos(u/r) */\n /* derivatives... (see personnal notes) */\n ScaleFilter( resample_filter[id],\n 1.0/(1.0+d.x*d.x), 0.0, -d.x*s.y*cx*cx/coeff[1], s.y/d.y );\n#if 0\nif ( i == 0 && j == 0 ) {\n fprintf(stderr, \"x=%lf y=%lf u=%lf v=%lf\\n\", d.x*coeff[1], d.y, s.x, s.y);\n fprintf(stderr, \"phi = %lf\\n\", (double)(ax * 180.0/MagickPI) );\n fprintf(stderr, \"du/dx=%lf du/dx=%lf dv/dx=%lf dv/dy=%lf\\n\",\n 1.0/(1.0+d.x*d.x), 0.0, -d.x*s.y*cx*cx/coeff[1], s.y/d.y );\n fflush(stderr); }\n#endif\n /* add center of distortion in source */\n s.x += coeff[2]; s.y += coeff[3];\n break;\n }\n case Plane2CylinderDistortion:\n { /* 3D Cylinder to Tangential Plane */\n /* relative to center of distortion */\n d.x -= coeff[4]; d.y -= coeff[5];\n\n /* is pixel valid - horizon of a infinite Virtual-Pixel Plane\n * (see Anthony Thyssen's personal note) */\n validity = (double) (coeff[1]*MagickPI2 - fabs(d.x))/output_scaling + 0.5;\n\n if ( validity > 0.0 ) {\n double cx,tx;\n d.x /= coeff[1]; /* x'= x/r */\n cx = 1/cos(d.x); /* cx = 1/cos(x/r) */\n tx = tan(d.x); /* tx = tan(x/r) */\n s.x = coeff[1]*tx; /* u = r * tan(x/r) */\n s.y = d.y*cx; /* v = y / cos(x/r) */\n /* derivatives... (see Anthony Thyssen's personal notes) */\n ScaleFilter( resample_filter[id],\n cx*cx, 0.0, s.y*cx/coeff[1], cx );\n#if 0\n/*if ( i == 0 && j == 0 )*/\nif ( d.x == 0.5 && d.y == 0.5 ) {\n fprintf(stderr, \"x=%lf y=%lf u=%lf v=%lf\\n\", d.x*coeff[1], d.y, s.x, s.y);\n fprintf(stderr, \"radius = %lf phi = %lf validity = %lf\\n\",\n coeff[1], (double)(d.x * 180.0/MagickPI), validity );\n fprintf(stderr, \"du/dx=%lf du/dx=%lf dv/dx=%lf dv/dy=%lf\\n\",\n cx*cx, 0.0, s.y*cx/coeff[1], cx);\n fflush(stderr); }\n#endif\n }\n /* add center of distortion in source */\n s.x += coeff[2]; s.y += coeff[3];\n break;\n }\n case BarrelDistortion:\n case BarrelInverseDistortion:\n { /* Lens Barrel Distionion Correction */\n double r,fx,fy,gx,gy;\n /* Radial Polynomial Distortion (de-normalized) */\n d.x -= coeff[8];\n d.y -= coeff[9];\n r = sqrt(d.x*d.x+d.y*d.y);\n if ( r > MagickEpsilon ) {\n fx = ((coeff[0]*r + coeff[1])*r + coeff[2])*r + coeff[3];\n fy = ((coeff[4]*r + coeff[5])*r + coeff[6])*r + coeff[7];\n gx = ((3*coeff[0]*r + 2*coeff[1])*r + coeff[2])/r;\n gy = ((3*coeff[4]*r + 2*coeff[5])*r + coeff[6])/r;\n /* adjust functions and scaling for 'inverse' form */\n if ( method == BarrelInverseDistortion ) {\n fx = 1/fx; fy = 1/fy;\n gx *= -fx*fx; gy *= -fy*fy;\n }\n /* Set the source pixel to lookup and EWA derivative vectors */\n s.x = d.x*fx + coeff[8];\n s.y = d.y*fy + coeff[9];\n ScaleFilter( resample_filter[id],\n gx*d.x*d.x + fx, gx*d.x*d.y,\n gy*d.x*d.y, gy*d.y*d.y + fy );\n }\n else {\n /* Special handling to avoid divide by zero when r==0\n **\n ** The source and destination pixels match in this case\n ** which was set at the top of the loop using s = d;\n ** otherwise... s.x=coeff[8]; s.y=coeff[9];\n */\n if ( method == BarrelDistortion )\n ScaleFilter( resample_filter[id],\n coeff[3], 0, 0, coeff[7] );\n else /* method == BarrelInverseDistortion */\n /* FUTURE, trap for D==0 causing division by zero */\n ScaleFilter( resample_filter[id],\n 1.0/coeff[3], 0, 0, 1.0/coeff[7] );\n }\n break;\n }\n case ShepardsDistortion:\n { /* Shepards Method, or Inverse Weighted Distance for\n displacement around the destination image control points\n The input arguments are the coefficents to the function.\n This is more of a 'displacement' function rather than an\n absolute distortion function.\n\n Note: We can not determine derivatives using shepards method\n so only a point sample interpolatation can be used.\n */\n size_t\n i;\n double\n denominator;\n\n denominator = s.x = s.y = 0;\n for(i=0; ipage.x;\n s.y -= image->page.y;\n }\n s.x -= 0.5;\n s.y -= 0.5;\n\n if ( validity <= 0.0 ) {\n /* result of distortion is an invalid pixel - don't resample */\n SetPixelViaPixelInfo(distort_image,&invalid,q);\n }\n else {\n /* resample the source image to find its correct color */\n (void) ResamplePixelColor(resample_filter[id],s.x,s.y,&pixel,\n exception);\n /* if validity between 0.0 and 1.0 mix result with invalid pixel */\n if ( validity < 1.0 ) {\n /* Do a blend of sample color and invalid pixel */\n /* should this be a 'Blend', or an 'Over' compose */\n CompositePixelInfoBlend(&pixel,validity,&invalid,(1.0-validity),\n &pixel);\n }\n SetPixelViaPixelInfo(distort_image,&pixel,q);\n }\n q+=GetPixelChannels(distort_image);\n }\n sync=SyncCacheViewAuthenticPixels(distort_view,exception);\n if (sync == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,DistortImageTag,progress,image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n distort_view=DestroyCacheView(distort_view);\n resample_filter=DestroyResampleFilterThreadSet(resample_filter);\n\n if (status == MagickFalse)\n distort_image=DestroyImage(distort_image);\n }\n\n /* Arc does not return an offset unless 'bestfit' is in effect\n And the user has not provided an overriding 'viewport'.\n */\n if ( method == ArcDistortion && !bestfit && !viewport_given ) {\n distort_image->page.x = 0;\n distort_image->page.y = 0;\n }\n coeff=(double *) RelinquishMagickMemory(coeff);\n return(distort_image);\n}", "project": "ImageMagick", "hash": 171104629152982557161712032261784795609, "size": 1159, "commit_id": "f8e8535bc821f24a30beee0030ff21ee3a2deedc", "message": "https://github.com/ImageMagick/ImageMagick/issues/3331", "target": 1, "dataset": "other", "idx": 206584} {"func": "MagickExport Image *DistortImage(const Image *image, DistortMethod method,\n const size_t number_arguments,const double *arguments,\n MagickBooleanType bestfit,ExceptionInfo *exception)\n{\n#define DistortImageTag \"Distort/Image\"\n\n double\n *coeff,\n output_scaling;\n\n Image\n *distort_image;\n\n RectangleInfo\n geometry; /* geometry of the distorted space viewport */\n\n MagickBooleanType\n viewport_given;\n\n PixelInfo\n invalid; /* the color to assign when distort result is invalid */\n\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n\n /*\n Handle Special Compound Distortions\n */\n if ( method == ResizeDistortion )\n {\n if ( number_arguments != 2 )\n {\n (void) ThrowMagickException(exception,GetMagickModule(),OptionError,\n \"InvalidArgument\",\"%s : '%s'\",\"Resize\",\n \"Invalid number of args: 2 only\");\n return((Image *) NULL);\n }\n distort_image=DistortResizeImage(image,(size_t)arguments[0],\n (size_t)arguments[1], exception);\n return(distort_image);\n }\n\n /*\n Convert input arguments (usually as control points for reverse mapping)\n into mapping coefficients to apply the distortion.\n\n Note that some distortions are mapped to other distortions,\n and as such do not require specific code after this point.\n */\n coeff = GenerateCoefficients(image, &method, number_arguments,\n arguments, 0, exception);\n if ( coeff == (double *) NULL )\n return((Image *) NULL);\n\n /*\n Determine the size and offset for a 'bestfit' destination.\n Usally the four corners of the source image is enough.\n */\n\n /* default output image bounds, when no 'bestfit' is requested */\n geometry.width=image->columns;\n geometry.height=image->rows;\n geometry.x=0;\n geometry.y=0;\n\n if ( method == ArcDistortion ) {\n bestfit = MagickTrue; /* always calculate a 'best fit' viewport */\n }\n\n /* Work out the 'best fit', (required for ArcDistortion) */\n if ( bestfit ) {\n PointInfo\n s,d,min,max; /* source, dest coords --mapping--> min, max coords */\n\n MagickBooleanType\n fix_bounds = MagickTrue; /* enlarge bounds for VP handling */\n\n s.x=s.y=min.x=max.x=min.y=max.y=0.0; /* keep compiler happy */\n\n/* defines to figure out the bounds of the distorted image */\n#define InitalBounds(p) \\\n{ \\\n /* printf(\"%lg,%lg -> %lg,%lg\\n\", s.x,s.y, d.x,d.y); */ \\\n min.x = max.x = p.x; \\\n min.y = max.y = p.y; \\\n}\n#define ExpandBounds(p) \\\n{ \\\n /* printf(\"%lg,%lg -> %lg,%lg\\n\", s.x,s.y, d.x,d.y); */ \\\n min.x = MagickMin(min.x,p.x); \\\n max.x = MagickMax(max.x,p.x); \\\n min.y = MagickMin(min.y,p.y); \\\n max.y = MagickMax(max.y,p.y); \\\n}\n\n switch (method)\n {\n case AffineDistortion:\n case RigidAffineDistortion:\n { double inverse[6];\n InvertAffineCoefficients(coeff, inverse);\n s.x = (double) image->page.x;\n s.y = (double) image->page.y;\n d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2];\n d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5];\n InitalBounds(d);\n s.x = (double) image->page.x+image->columns;\n s.y = (double) image->page.y;\n d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2];\n d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5];\n ExpandBounds(d);\n s.x = (double) image->page.x;\n s.y = (double) image->page.y+image->rows;\n d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2];\n d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5];\n ExpandBounds(d);\n s.x = (double) image->page.x+image->columns;\n s.y = (double) image->page.y+image->rows;\n d.x = inverse[0]*s.x+inverse[1]*s.y+inverse[2];\n d.y = inverse[3]*s.x+inverse[4]*s.y+inverse[5];\n ExpandBounds(d);\n break;\n }\n case PerspectiveDistortion:\n { double inverse[8], scale;\n InvertPerspectiveCoefficients(coeff, inverse);\n s.x = (double) image->page.x;\n s.y = (double) image->page.y;\n scale=inverse[6]*s.x+inverse[7]*s.y+1.0;\n scale=PerceptibleReciprocal(scale);\n d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]);\n d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]);\n InitalBounds(d);\n s.x = (double) image->page.x+image->columns;\n s.y = (double) image->page.y;\n scale=inverse[6]*s.x+inverse[7]*s.y+1.0;\n scale=PerceptibleReciprocal(scale);\n d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]);\n d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]);\n ExpandBounds(d);\n s.x = (double) image->page.x;\n s.y = (double) image->page.y+image->rows;\n scale=inverse[6]*s.x+inverse[7]*s.y+1.0;\n scale=PerceptibleReciprocal(scale);\n d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]);\n d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]);\n ExpandBounds(d);\n s.x = (double) image->page.x+image->columns;\n s.y = (double) image->page.y+image->rows;\n scale=inverse[6]*s.x+inverse[7]*s.y+1.0;\n scale=PerceptibleReciprocal(scale);\n d.x = scale*(inverse[0]*s.x+inverse[1]*s.y+inverse[2]);\n d.y = scale*(inverse[3]*s.x+inverse[4]*s.y+inverse[5]);\n ExpandBounds(d);\n break;\n }\n case ArcDistortion:\n { double a, ca, sa;\n /* Forward Map Corners */\n a = coeff[0]-coeff[1]/2; ca = cos(a); sa = sin(a);\n d.x = coeff[2]*ca;\n d.y = coeff[2]*sa;\n InitalBounds(d);\n d.x = (coeff[2]-coeff[3])*ca;\n d.y = (coeff[2]-coeff[3])*sa;\n ExpandBounds(d);\n a = coeff[0]+coeff[1]/2; ca = cos(a); sa = sin(a);\n d.x = coeff[2]*ca;\n d.y = coeff[2]*sa;\n ExpandBounds(d);\n d.x = (coeff[2]-coeff[3])*ca;\n d.y = (coeff[2]-coeff[3])*sa;\n ExpandBounds(d);\n /* Orthogonal points along top of arc */\n for( a=(double) (ceil((double) ((coeff[0]-coeff[1]/2.0)/MagickPI2))*MagickPI2);\n a<(coeff[0]+coeff[1]/2.0); a+=MagickPI2 ) {\n ca = cos(a); sa = sin(a);\n d.x = coeff[2]*ca;\n d.y = coeff[2]*sa;\n ExpandBounds(d);\n }\n /*\n Convert the angle_to_width and radius_to_height\n to appropriate scaling factors, to allow faster processing\n in the mapping function.\n */\n coeff[1] = (double) (Magick2PI*image->columns/coeff[1]);\n coeff[3] = (double)image->rows/coeff[3];\n break;\n }\n case PolarDistortion:\n {\n if (number_arguments < 2)\n coeff[2] = coeff[3] = 0.0;\n min.x = coeff[2]-coeff[0];\n max.x = coeff[2]+coeff[0];\n min.y = coeff[3]-coeff[0];\n max.y = coeff[3]+coeff[0];\n /* should be about 1.0 if Rmin = 0 */\n coeff[7]=(double) geometry.height/(coeff[0]-coeff[1]);\n break;\n }\n case DePolarDistortion:\n {\n /* direct calculation as it needs to tile correctly\n * for reversibility in a DePolar-Polar cycle */\n fix_bounds = MagickFalse;\n geometry.x = geometry.y = 0;\n geometry.height = (size_t) ceil(coeff[0]-coeff[1]);\n geometry.width = (size_t) ceil((coeff[0]-coeff[1])*\n (coeff[5]-coeff[4])*0.5);\n /* correct scaling factors relative to new size */\n coeff[6]=(coeff[5]-coeff[4])*PerceptibleReciprocal(geometry.width); /* changed width */\n coeff[7]=(coeff[0]-coeff[1])*PerceptibleReciprocal(geometry.height); /* should be about 1.0 */\n break;\n }\n case Cylinder2PlaneDistortion:\n {\n /* direct calculation so center of distortion is either a pixel\n * center, or pixel edge. This allows for reversibility of the\n * distortion */\n geometry.x = geometry.y = 0;\n geometry.width = (size_t) ceil( 2.0*coeff[1]*tan(coeff[0]/2.0) );\n geometry.height = (size_t) ceil( 2.0*coeff[3]/cos(coeff[0]/2.0) );\n /* correct center of distortion relative to new size */\n coeff[4] = (double) geometry.width/2.0;\n coeff[5] = (double) geometry.height/2.0;\n fix_bounds = MagickFalse;\n break;\n }\n case Plane2CylinderDistortion:\n {\n /* direct calculation center is either pixel center, or pixel edge\n * so as to allow reversibility of the image distortion */\n geometry.x = geometry.y = 0;\n geometry.width = (size_t) ceil(coeff[0]*coeff[1]); /* FOV * radius */\n geometry.height = (size_t) (2*coeff[3]); /* input image height */\n /* correct center of distortion relative to new size */\n coeff[4] = (double) geometry.width/2.0;\n coeff[5] = (double) geometry.height/2.0;\n fix_bounds = MagickFalse;\n break;\n }\n case ShepardsDistortion:\n case BilinearForwardDistortion:\n case BilinearReverseDistortion:\n#if 0\n case QuadrilateralDistortion:\n#endif\n case PolynomialDistortion:\n case BarrelDistortion:\n case BarrelInverseDistortion:\n default:\n /* no calculated bestfit available for these distortions */\n bestfit = MagickFalse;\n fix_bounds = MagickFalse;\n break;\n }\n\n /* Set the output image geometry to calculated 'bestfit'.\n Yes this tends to 'over do' the file image size, ON PURPOSE!\n Do not do this for DePolar which needs to be exact for virtual tiling.\n */\n if ( fix_bounds ) {\n geometry.x = (ssize_t) floor(min.x-0.5);\n geometry.y = (ssize_t) floor(min.y-0.5);\n geometry.width=(size_t) ceil(max.x-geometry.x+0.5);\n geometry.height=(size_t) ceil(max.y-geometry.y+0.5);\n }\n\n } /* end bestfit destination image calculations */\n\n /* The user provided a 'viewport' expert option which may\n overrides some parts of the current output image geometry.\n This also overrides its default 'bestfit' setting.\n */\n { const char *artifact=GetImageArtifact(image,\"distort:viewport\");\n viewport_given = MagickFalse;\n if ( artifact != (const char *) NULL ) {\n MagickStatusType flags=ParseAbsoluteGeometry(artifact,&geometry);\n if (flags==NoValue)\n (void) ThrowMagickException(exception,GetMagickModule(),\n OptionWarning,\"InvalidSetting\",\"'%s' '%s'\",\n \"distort:viewport\",artifact);\n else\n viewport_given = MagickTrue;\n }\n }\n\n /* Verbose output */\n if (IsStringTrue(GetImageArtifact(image,\"verbose\")) != MagickFalse) {\n ssize_t\n i;\n char image_gen[MagickPathExtent];\n const char *lookup;\n\n /* Set destination image size and virtual offset */\n if ( bestfit || viewport_given ) {\n (void) FormatLocaleString(image_gen,MagickPathExtent,\n \" -size %.20gx%.20g -page %+.20g%+.20g xc: +insert \\\\\\n\",\n (double) geometry.width,(double) geometry.height,(double) geometry.x,\n (double) geometry.y);\n lookup=\"v.p{xx-v.page.x-0.5,yy-v.page.y-0.5}\";\n }\n else {\n image_gen[0] = '\\0'; /* no destination to generate */\n lookup = \"p{xx-page.x-0.5,yy-page.y-0.5}\"; /* simplify lookup */\n }\n\n switch (method)\n {\n case AffineDistortion:\n case RigidAffineDistortion:\n {\n double\n *inverse;\n\n inverse=(double *) AcquireQuantumMemory(6,sizeof(*inverse));\n if (inverse == (double *) NULL)\n {\n coeff=(double *) RelinquishMagickMemory(coeff);\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"%s\",\"DistortImages\");\n return((Image *) NULL);\n }\n InvertAffineCoefficients(coeff, inverse);\n CoefficientsToAffineArgs(inverse);\n (void) FormatLocaleFile(stderr, \"Affine projection:\\n\");\n (void) FormatLocaleFile(stderr,\n \" -distort AffineProjection \\\\\\n '\");\n for (i=0; i < 5; i++)\n (void) FormatLocaleFile(stderr, \"%.*g,\",GetMagickPrecision(),\n inverse[i]);\n (void) FormatLocaleFile(stderr, \"%.*g'\\n\",GetMagickPrecision(),\n inverse[5]);\n (void) FormatLocaleFile(stderr,\n \"Equivalent scale, rotation(deg), translation:\\n\");\n (void) FormatLocaleFile(stderr,\" %.*g,%.*g,%.*g,%.*g\\n\",\n GetMagickPrecision(),sqrt(inverse[0]*inverse[0]+\n inverse[1]*inverse[1]),GetMagickPrecision(),\n RadiansToDegrees(atan2(inverse[1],inverse[0])),\n GetMagickPrecision(),inverse[4],GetMagickPrecision(),inverse[5]);\n inverse=(double *) RelinquishMagickMemory(inverse);\n (void) FormatLocaleFile(stderr,\"Affine distort, FX equivalent:\\n\");\n (void) FormatLocaleFile(stderr, \"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\\n\");\n (void) FormatLocaleFile(stderr,\" xx=%+.*g*ii %+.*g*jj %+.*g;\\n\",\n GetMagickPrecision(),coeff[0],GetMagickPrecision(),coeff[1],\n GetMagickPrecision(),coeff[2]);\n (void) FormatLocaleFile(stderr,\" yy=%+.*g*ii %+.*g*jj %+.*g;\\n\",\n GetMagickPrecision(),coeff[3],GetMagickPrecision(),coeff[4],\n GetMagickPrecision(),coeff[5]);\n (void) FormatLocaleFile(stderr,\" %s' \\\\\\n\",lookup);\n break;\n }\n case PerspectiveDistortion:\n {\n double\n *inverse;\n\n inverse=(double *) AcquireQuantumMemory(8,sizeof(*inverse));\n if (inverse == (double *) NULL)\n {\n coeff=(double *) RelinquishMagickMemory(coeff);\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"%s\",\n \"DistortCoefficients\");\n return((Image *) NULL);\n }\n InvertPerspectiveCoefficients(coeff, inverse);\n (void) FormatLocaleFile(stderr,\"Perspective Projection:\\n\");\n (void) FormatLocaleFile(stderr,\n \" -distort PerspectiveProjection \\\\\\n '\");\n for (i=0; i < 4; i++)\n (void) FormatLocaleFile(stderr, \"%.*g, \",GetMagickPrecision(),\n inverse[i]);\n (void) FormatLocaleFile(stderr, \"\\n \");\n for ( ; i < 7; i++)\n (void) FormatLocaleFile(stderr, \"%.*g, \",GetMagickPrecision(),\n inverse[i]);\n (void) FormatLocaleFile(stderr, \"%.*g'\\n\",GetMagickPrecision(),\n inverse[7]);\n inverse=(double *) RelinquishMagickMemory(inverse);\n (void) FormatLocaleFile(stderr,\"Perspective Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%.1024s\",image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\\n\");\n (void) FormatLocaleFile(stderr,\" rr=%+.*g*ii %+.*g*jj + 1;\\n\",\n GetMagickPrecision(),coeff[6],GetMagickPrecision(),coeff[7]);\n (void) FormatLocaleFile(stderr,\n \" xx=(%+.*g*ii %+.*g*jj %+.*g)/rr;\\n\",\n GetMagickPrecision(),coeff[0],GetMagickPrecision(),coeff[1],\n GetMagickPrecision(),coeff[2]);\n (void) FormatLocaleFile(stderr,\n \" yy=(%+.*g*ii %+.*g*jj %+.*g)/rr;\\n\",\n GetMagickPrecision(),coeff[3],GetMagickPrecision(),coeff[4],\n GetMagickPrecision(),coeff[5]);\n (void) FormatLocaleFile(stderr,\" rr%s0 ? %s : blue' \\\\\\n\",\n coeff[8] < 0.0 ? \"<\" : \">\", lookup);\n break;\n }\n case BilinearForwardDistortion:\n {\n (void) FormatLocaleFile(stderr,\"BilinearForward Mapping Equations:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\" i = %+lf*x %+lf*y %+lf*x*y %+lf;\\n\",\n coeff[0],coeff[1],coeff[2],coeff[3]);\n (void) FormatLocaleFile(stderr,\" j = %+lf*x %+lf*y %+lf*x*y %+lf;\\n\",\n coeff[4],coeff[5],coeff[6],coeff[7]);\n#if 0\n /* for debugging */\n (void) FormatLocaleFile(stderr, \" c8 = %+lf c9 = 2*a = %+lf;\\n\",\n coeff[8], coeff[9]);\n#endif\n (void) FormatLocaleFile(stderr,\n \"BilinearForward Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x%+lf; jj=j+page.y%+lf;\\n\",0.5-coeff[3],0.5-\n coeff[7]);\n (void) FormatLocaleFile(stderr,\" bb=%lf*ii %+lf*jj %+lf;\\n\",\n coeff[6], -coeff[2], coeff[8]);\n /* Handle Special degenerate (non-quadratic) or trapezoidal case */\n if (coeff[9] != 0)\n {\n (void) FormatLocaleFile(stderr,\n \" rt=bb*bb %+lf*(%lf*ii%+lf*jj);\\n\",-2*coeff[9],coeff[4],\n -coeff[0]);\n (void) FormatLocaleFile(stderr,\n \" yy=( -bb + sqrt(rt) ) / %lf;\\n\",coeff[9]);\n }\n else\n (void) FormatLocaleFile(stderr,\" yy=(%lf*ii%+lf*jj)/bb;\\n\",\n -coeff[4],coeff[0]);\n (void) FormatLocaleFile(stderr,\n \" xx=(ii %+lf*yy)/(%lf %+lf*yy);\\n\",-coeff[1],coeff[0],\n coeff[2]);\n if ( coeff[9] != 0 )\n (void) FormatLocaleFile(stderr,\" (rt < 0 ) ? red : %s'\\n\",\n lookup);\n else\n (void) FormatLocaleFile(stderr,\" %s' \\\\\\n\", lookup);\n break;\n }\n case BilinearReverseDistortion:\n {\n#if 0\n (void) FormatLocaleFile(stderr, \"Polynomial Projection Distort:\\n\");\n (void) FormatLocaleFile(stderr, \" -distort PolynomialProjection \\\\\\n\");\n (void) FormatLocaleFile(stderr, \" '1.5, %lf, %lf, %lf, %lf,\\n\",\n coeff[3], coeff[0], coeff[1], coeff[2]);\n (void) FormatLocaleFile(stderr, \" %lf, %lf, %lf, %lf'\\n\",\n coeff[7], coeff[4], coeff[5], coeff[6]);\n#endif\n (void) FormatLocaleFile(stderr,\n \"BilinearReverse Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\\n\");\n (void) FormatLocaleFile(stderr,\n \" xx=%+lf*ii %+lf*jj %+lf*ii*jj %+lf;\\n\",coeff[0],coeff[1],\n coeff[2], coeff[3]);\n (void) FormatLocaleFile(stderr,\n \" yy=%+lf*ii %+lf*jj %+lf*ii*jj %+lf;\\n\",coeff[4],coeff[5],\n coeff[6], coeff[7]);\n (void) FormatLocaleFile(stderr,\" %s' \\\\\\n\", lookup);\n break;\n }\n case PolynomialDistortion:\n {\n size_t nterms = (size_t) coeff[1];\n (void) FormatLocaleFile(stderr,\n \"Polynomial (order %lg, terms %lu), FX Equivelent\\n\",coeff[0],\n (unsigned long) nterms);\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x+0.5; jj=j+page.y+0.5;\\n\");\n (void) FormatLocaleFile(stderr, \" xx =\");\n for (i=0; i < (ssize_t) nterms; i++)\n {\n if ((i != 0) && (i%4 == 0))\n (void) FormatLocaleFile(stderr, \"\\n \");\n (void) FormatLocaleFile(stderr,\" %+lf%s\",coeff[2+i],\n poly_basis_str(i));\n }\n (void) FormatLocaleFile(stderr,\";\\n yy =\");\n for (i=0; i < (ssize_t) nterms; i++)\n {\n if ((i != 0) && (i%4 == 0))\n (void) FormatLocaleFile(stderr,\"\\n \");\n (void) FormatLocaleFile(stderr,\" %+lf%s\",coeff[2+i+nterms],\n poly_basis_str(i));\n }\n (void) FormatLocaleFile(stderr,\";\\n %s' \\\\\\n\", lookup);\n break;\n }\n case ArcDistortion:\n {\n (void) FormatLocaleFile(stderr,\"Arc Distort, Internal Coefficients:\\n\");\n for (i=0; i < 5; i++)\n (void) FormatLocaleFile(stderr,\n \" c%.20g = %+lf\\n\",(double) i,coeff[i]);\n (void) FormatLocaleFile(stderr,\"Arc Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\" -fx 'ii=i+page.x; jj=j+page.y;\\n\");\n (void) FormatLocaleFile(stderr,\" xx=(atan2(jj,ii)%+lf)/(2*pi);\\n\",\n -coeff[0]);\n (void) FormatLocaleFile(stderr,\" xx=xx-round(xx);\\n\");\n (void) FormatLocaleFile(stderr,\" xx=xx*%lf %+lf;\\n\",coeff[1],\n coeff[4]);\n (void) FormatLocaleFile(stderr,\n \" yy=(%lf - hypot(ii,jj)) * %lf;\\n\",coeff[2],coeff[3]);\n (void) FormatLocaleFile(stderr,\" v.p{xx-.5,yy-.5}' \\\\\\n\");\n break;\n }\n case PolarDistortion:\n {\n (void) FormatLocaleFile(stderr,\"Polar Distort, Internal Coefficents\\n\");\n for (i=0; i < 8; i++)\n (void) FormatLocaleFile(stderr,\" c%.20g = %+lf\\n\",(double) i,\n coeff[i]);\n (void) FormatLocaleFile(stderr,\"Polar Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x%+lf; jj=j+page.y%+lf;\\n\",-coeff[2],-coeff[3]);\n (void) FormatLocaleFile(stderr,\" xx=(atan2(ii,jj)%+lf)/(2*pi);\\n\",\n -(coeff[4]+coeff[5])/2 );\n (void) FormatLocaleFile(stderr,\" xx=xx-round(xx);\\n\");\n (void) FormatLocaleFile(stderr,\" xx=xx*2*pi*%lf + v.w/2;\\n\",\n coeff[6] );\n (void) FormatLocaleFile(stderr,\" yy=(hypot(ii,jj)%+lf)*%lf;\\n\",\n -coeff[1],coeff[7] );\n (void) FormatLocaleFile(stderr,\" v.p{xx-.5,yy-.5}' \\\\\\n\");\n break;\n }\n case DePolarDistortion:\n {\n (void) FormatLocaleFile(stderr,\n \"DePolar Distort, Internal Coefficents\\n\");\n for (i=0; i < 8; i++)\n (void) FormatLocaleFile(stderr,\" c%.20g = %+lf\\n\",(double) i,\n coeff[i]);\n (void) FormatLocaleFile(stderr,\"DePolar Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\" -fx 'aa=(i+.5)*%lf %+lf;\\n\",\n coeff[6],+coeff[4]);\n (void) FormatLocaleFile(stderr,\" rr=(j+.5)*%lf %+lf;\\n\",\n coeff[7],+coeff[1]);\n (void) FormatLocaleFile(stderr,\" xx=rr*sin(aa) %+lf;\\n\",\n coeff[2]);\n (void) FormatLocaleFile(stderr,\" yy=rr*cos(aa) %+lf;\\n\",\n coeff[3]);\n (void) FormatLocaleFile(stderr,\" v.p{xx-.5,yy-.5}' \\\\\\n\");\n break;\n }\n case Cylinder2PlaneDistortion:\n {\n (void) FormatLocaleFile(stderr,\n \"Cylinder to Plane Distort, Internal Coefficents\\n\");\n (void) FormatLocaleFile(stderr,\" cylinder_radius = %+lf\\n\",coeff[1]);\n (void) FormatLocaleFile(stderr,\n \"Cylinder to Plane Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr, \"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x%+lf+0.5; jj=j+page.y%+lf+0.5;\\n\",-coeff[4],\n -coeff[5]);\n (void) FormatLocaleFile(stderr,\" aa=atan(ii/%+lf);\\n\",coeff[1]);\n (void) FormatLocaleFile(stderr,\" xx=%lf*aa%+lf;\\n\",\n coeff[1],coeff[2]);\n (void) FormatLocaleFile(stderr,\" yy=jj*cos(aa)%+lf;\\n\",coeff[3]);\n (void) FormatLocaleFile(stderr,\" %s' \\\\\\n\", lookup);\n break;\n }\n case Plane2CylinderDistortion:\n {\n (void) FormatLocaleFile(stderr,\n \"Plane to Cylinder Distort, Internal Coefficents\\n\");\n (void) FormatLocaleFile(stderr,\" cylinder_radius = %+lf\\n\",coeff[1]);\n (void) FormatLocaleFile(stderr,\n \"Plane to Cylinder Distort, FX Equivelent:\\n\");\n (void) FormatLocaleFile(stderr,\"%s\", image_gen);\n (void) FormatLocaleFile(stderr,\n \" -fx 'ii=i+page.x%+lf+0.5; jj=j+page.y%+lf+0.5;\\n\",-coeff[4],\n -coeff[5]);\n (void) FormatLocaleFile(stderr,\" ii=ii/%+lf;\\n\",coeff[1]);\n (void) FormatLocaleFile(stderr,\" xx=%lf*tan(ii)%+lf;\\n\",coeff[1],\n coeff[2] );\n (void) FormatLocaleFile(stderr,\" yy=jj/cos(ii)%+lf;\\n\",coeff[3]);\n (void) FormatLocaleFile(stderr,\" %s' \\\\\\n\", lookup);\n break;\n }\n case BarrelDistortion:\n case BarrelInverseDistortion:\n {\n double\n xc,\n yc;\n\n /*\n NOTE: This does the barrel roll in pixel coords not image coords\n The internal distortion must do it in image coordinates,\n so that is what the center coeff (8,9) is given in.\n */\n xc=((double)image->columns-1.0)/2.0+image->page.x;\n yc=((double)image->rows-1.0)/2.0+image->page.y;\n (void) FormatLocaleFile(stderr, \"Barrel%s Distort, FX Equivelent:\\n\",\n method == BarrelDistortion ? \"\" : \"Inv\");\n (void) FormatLocaleFile(stderr, \"%s\", image_gen);\n if ( fabs(coeff[8]-xc-0.5) < 0.1 && fabs(coeff[9]-yc-0.5) < 0.1 )\n (void) FormatLocaleFile(stderr,\" -fx 'xc=(w-1)/2; yc=(h-1)/2;\\n\");\n else\n (void) FormatLocaleFile(stderr,\" -fx 'xc=%lf; yc=%lf;\\n\",coeff[8]-\n 0.5,coeff[9]-0.5);\n (void) FormatLocaleFile(stderr,\n \" ii=i-xc; jj=j-yc; rr=hypot(ii,jj);\\n\");\n (void) FormatLocaleFile(stderr,\n \" ii=ii%s(%lf*rr*rr*rr %+lf*rr*rr %+lf*rr %+lf);\\n\",\n method == BarrelDistortion ? \"*\" : \"/\",coeff[0],coeff[1],coeff[2],\n coeff[3]);\n (void) FormatLocaleFile(stderr,\n \" jj=jj%s(%lf*rr*rr*rr %+lf*rr*rr %+lf*rr %+lf);\\n\",\n method == BarrelDistortion ? \"*\" : \"/\",coeff[4],coeff[5],coeff[6],\n coeff[7]);\n (void) FormatLocaleFile(stderr,\" v.p{fx*ii+xc,fy*jj+yc}' \\\\\\n\");\n }\n default:\n break;\n }\n }\n /*\n The user provided a 'scale' expert option will scale the output image size,\n by the factor given allowing for super-sampling of the distorted image\n space. Any scaling factors must naturally be halved as a result.\n */\n { const char *artifact;\n artifact=GetImageArtifact(image,\"distort:scale\");\n output_scaling = 1.0;\n if (artifact != (const char *) NULL) {\n output_scaling = fabs(StringToDouble(artifact,(char **) NULL));\n geometry.width=(size_t) (output_scaling*geometry.width+0.5);\n geometry.height=(size_t) (output_scaling*geometry.height+0.5);\n geometry.x=(ssize_t) (output_scaling*geometry.x+0.5);\n geometry.y=(ssize_t) (output_scaling*geometry.y+0.5);\n if ( output_scaling < 0.1 ) {\n coeff = (double *) RelinquishMagickMemory(coeff);\n (void) ThrowMagickException(exception,GetMagickModule(),OptionError,\n \"InvalidArgument\",\"%s\", \"-set option:distort:scale\" );\n return((Image *) NULL);\n }\n output_scaling = 1/output_scaling;\n }\n }\n#define ScaleFilter(F,A,B,C,D) \\\n ScaleResampleFilter( (F), \\\n output_scaling*(A), output_scaling*(B), \\\n output_scaling*(C), output_scaling*(D) )\n\n /*\n Initialize the distort image attributes.\n */\n distort_image=CloneImage(image,geometry.width,geometry.height,MagickTrue,\n exception);\n if (distort_image == (Image *) NULL)\n {\n coeff=(double *) RelinquishMagickMemory(coeff);\n return((Image *) NULL);\n }\n /* if image is ColorMapped - change it to DirectClass */\n if (SetImageStorageClass(distort_image,DirectClass,exception) == MagickFalse)\n {\n coeff=(double *) RelinquishMagickMemory(coeff);\n distort_image=DestroyImage(distort_image);\n return((Image *) NULL);\n }\n if ((IsPixelInfoGray(&distort_image->background_color) == MagickFalse) &&\n (IsGrayColorspace(distort_image->colorspace) != MagickFalse))\n (void) SetImageColorspace(distort_image,sRGBColorspace,exception);\n if (distort_image->background_color.alpha_trait != UndefinedPixelTrait)\n distort_image->alpha_trait=BlendPixelTrait;\n distort_image->page.x=geometry.x;\n distort_image->page.y=geometry.y;\n ConformPixelInfo(distort_image,&distort_image->matte_color,&invalid,\n exception);\n\n { /* ----- MAIN CODE -----\n Sample the source image to each pixel in the distort image.\n */\n CacheView\n *distort_view;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n PixelInfo\n zero;\n\n ResampleFilter\n **magick_restrict resample_filter;\n\n ssize_t\n j;\n\n status=MagickTrue;\n progress=0;\n GetPixelInfo(distort_image,&zero);\n resample_filter=AcquireResampleFilterThreadSet(image,\n UndefinedVirtualPixelMethod,MagickFalse,exception);\n distort_view=AcquireAuthenticCacheView(distort_image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(image,distort_image,distort_image->rows,1)\n#endif\n for (j=0; j < (ssize_t) distort_image->rows; j++)\n {\n const int\n id = GetOpenMPThreadId();\n\n double\n validity; /* how mathematically valid is this the mapping */\n\n MagickBooleanType\n sync;\n\n PixelInfo\n pixel; /* pixel color to assign to distorted image */\n\n PointInfo\n d,\n s; /* transform destination image x,y to source image x,y */\n\n ssize_t\n i;\n\n Quantum\n *magick_restrict q;\n\n q=QueueCacheViewAuthenticPixels(distort_view,0,j,distort_image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n pixel=zero;\n\n /* Define constant scaling vectors for Affine Distortions\n Other methods are either variable, or use interpolated lookup\n */\n switch (method)\n {\n case AffineDistortion:\n case RigidAffineDistortion:\n ScaleFilter( resample_filter[id],\n coeff[0], coeff[1],\n coeff[3], coeff[4] );\n break;\n default:\n break;\n }\n\n /* Initialize default pixel validity\n * negative: pixel is invalid output 'matte_color'\n * 0.0 to 1.0: antialiased, mix with resample output\n * 1.0 or greater: use resampled output.\n */\n validity = 1.0;\n\n for (i=0; i < (ssize_t) distort_image->columns; i++)\n {\n /* map pixel coordinate to distortion space coordinate */\n d.x = (double) (geometry.x+i+0.5)*output_scaling;\n d.y = (double) (geometry.y+j+0.5)*output_scaling;\n s = d; /* default is a no-op mapping */\n switch (method)\n {\n case AffineDistortion:\n case RigidAffineDistortion:\n {\n s.x=coeff[0]*d.x+coeff[1]*d.y+coeff[2];\n s.y=coeff[3]*d.x+coeff[4]*d.y+coeff[5];\n /* Affine partial derivitives are constant -- set above */\n break;\n }\n case PerspectiveDistortion:\n {\n double\n p,q,r,abs_r,abs_c6,abs_c7,scale;\n /* perspective is a ratio of affines */\n p=coeff[0]*d.x+coeff[1]*d.y+coeff[2];\n q=coeff[3]*d.x+coeff[4]*d.y+coeff[5];\n r=coeff[6]*d.x+coeff[7]*d.y+1.0;\n /* Pixel Validity -- is it a 'sky' or 'ground' pixel */\n validity = (r*coeff[8] < 0.0) ? 0.0 : 1.0;\n /* Determine horizon anti-alias blending */\n abs_r = fabs(r)*2;\n abs_c6 = fabs(coeff[6]);\n abs_c7 = fabs(coeff[7]);\n if ( abs_c6 > abs_c7 ) {\n if ( abs_r < abs_c6*output_scaling )\n validity = 0.5 - coeff[8]*r/(coeff[6]*output_scaling);\n }\n else if ( abs_r < abs_c7*output_scaling )\n validity = 0.5 - coeff[8]*r/(coeff[7]*output_scaling);\n /* Perspective Sampling Point (if valid) */\n if ( validity > 0.0 ) {\n /* divide by r affine, for perspective scaling */\n scale = 1.0/r;\n s.x = p*scale;\n s.y = q*scale;\n /* Perspective Partial Derivatives or Scaling Vectors */\n scale *= scale;\n ScaleFilter( resample_filter[id],\n (r*coeff[0] - p*coeff[6])*scale,\n (r*coeff[1] - p*coeff[7])*scale,\n (r*coeff[3] - q*coeff[6])*scale,\n (r*coeff[4] - q*coeff[7])*scale );\n }\n break;\n }\n case BilinearReverseDistortion:\n {\n /* Reversed Mapped is just a simple polynomial */\n s.x=coeff[0]*d.x+coeff[1]*d.y+coeff[2]*d.x*d.y+coeff[3];\n s.y=coeff[4]*d.x+coeff[5]*d.y\n +coeff[6]*d.x*d.y+coeff[7];\n /* Bilinear partial derivitives of scaling vectors */\n ScaleFilter( resample_filter[id],\n coeff[0] + coeff[2]*d.y,\n coeff[1] + coeff[2]*d.x,\n coeff[4] + coeff[6]*d.y,\n coeff[5] + coeff[6]*d.x );\n break;\n }\n case BilinearForwardDistortion:\n {\n /* Forward mapped needs reversed polynomial equations\n * which unfortunatally requires a square root! */\n double b,c;\n d.x -= coeff[3]; d.y -= coeff[7];\n b = coeff[6]*d.x - coeff[2]*d.y + coeff[8];\n c = coeff[4]*d.x - coeff[0]*d.y;\n\n validity = 1.0;\n /* Handle Special degenerate (non-quadratic) case\n * Currently without horizon anti-alising */\n if ( fabs(coeff[9]) < MagickEpsilon )\n s.y = -c/b;\n else {\n c = b*b - 2*coeff[9]*c;\n if ( c < 0.0 )\n validity = 0.0;\n else\n s.y = ( -b + sqrt(c) )/coeff[9];\n }\n if ( validity > 0.0 )\n s.x = ( d.x - coeff[1]*s.y) / ( coeff[0] + coeff[2]*s.y );\n\n /* NOTE: the sign of the square root should be -ve for parts\n where the source image becomes 'flipped' or 'mirrored'.\n FUTURE: Horizon handling\n FUTURE: Scaling factors or Deritives (how?)\n */\n break;\n }\n#if 0\n case BilinearDistortion:\n /* Bilinear mapping of any Quadrilateral to any Quadrilateral */\n /* UNDER DEVELOPMENT */\n break;\n#endif\n case PolynomialDistortion:\n {\n /* multi-ordered polynomial */\n ssize_t\n k;\n\n ssize_t\n nterms=(ssize_t)coeff[1];\n\n PointInfo\n du,dv; /* the du,dv vectors from unit dx,dy -- derivatives */\n\n s.x=s.y=du.x=du.y=dv.x=dv.y=0.0;\n for(k=0; k < nterms; k++) {\n s.x += poly_basis_fn(k,d.x,d.y)*coeff[2+k];\n du.x += poly_basis_dx(k,d.x,d.y)*coeff[2+k];\n du.y += poly_basis_dy(k,d.x,d.y)*coeff[2+k];\n s.y += poly_basis_fn(k,d.x,d.y)*coeff[2+k+nterms];\n dv.x += poly_basis_dx(k,d.x,d.y)*coeff[2+k+nterms];\n dv.y += poly_basis_dy(k,d.x,d.y)*coeff[2+k+nterms];\n }\n ScaleFilter( resample_filter[id], du.x,du.y,dv.x,dv.y );\n break;\n }\n case ArcDistortion:\n {\n /* what is the angle and radius in the destination image */\n s.x = (double) ((atan2(d.y,d.x) - coeff[0])/Magick2PI);\n s.x -= MagickRound(s.x); /* angle */\n s.y = hypot(d.x,d.y); /* radius */\n\n /* Arc Distortion Partial Scaling Vectors\n Are derived by mapping the perpendicular unit vectors\n dR and dA*R*2PI rather than trying to map dx and dy\n The results is a very simple orthogonal aligned ellipse.\n */\n if ( s.y > MagickEpsilon )\n ScaleFilter( resample_filter[id],\n (double) (coeff[1]/(Magick2PI*s.y)), 0, 0, coeff[3] );\n else\n ScaleFilter( resample_filter[id],\n distort_image->columns*2, 0, 0, coeff[3] );\n\n /* now scale the angle and radius for source image lookup point */\n s.x = s.x*coeff[1] + coeff[4] + image->page.x +0.5;\n s.y = (coeff[2] - s.y) * coeff[3] + image->page.y;\n break;\n }\n case PolarDistortion:\n { /* 2D Cartesain to Polar View */\n d.x -= coeff[2];\n d.y -= coeff[3];\n s.x = atan2(d.x,d.y) - (coeff[4]+coeff[5])/2;\n s.x /= Magick2PI;\n s.x -= MagickRound(s.x);\n s.x *= Magick2PI; /* angle - relative to centerline */\n s.y = hypot(d.x,d.y); /* radius */\n\n /* Polar Scaling vectors are based on mapping dR and dA vectors\n This results in very simple orthogonal scaling vectors\n */\n if ( s.y > MagickEpsilon )\n ScaleFilter( resample_filter[id],\n (double) (coeff[6]/(Magick2PI*s.y)), 0, 0, coeff[7] );\n else\n ScaleFilter( resample_filter[id],\n distort_image->columns*2, 0, 0, coeff[7] );\n\n /* now finish mapping radius/angle to source x,y coords */\n s.x = s.x*coeff[6] + (double)image->columns/2.0 + image->page.x;\n s.y = (s.y-coeff[1])*coeff[7] + image->page.y;\n break;\n }\n case DePolarDistortion:\n { /* @D Polar to Carteasain */\n /* ignore all destination virtual offsets */\n d.x = ((double)i+0.5)*output_scaling*coeff[6]+coeff[4];\n d.y = ((double)j+0.5)*output_scaling*coeff[7]+coeff[1];\n s.x = d.y*sin(d.x) + coeff[2];\n s.y = d.y*cos(d.x) + coeff[3];\n /* derivatives are usless - better to use SuperSampling */\n break;\n }\n case Cylinder2PlaneDistortion:\n { /* 3D Cylinder to Tangential Plane */\n double ax, cx;\n /* relative to center of distortion */\n d.x -= coeff[4]; d.y -= coeff[5];\n d.x /= coeff[1]; /* x' = x/r */\n ax=atan(d.x); /* aa = atan(x/r) = u/r */\n cx=cos(ax); /* cx = cos(atan(x/r)) = 1/sqrt(x^2+u^2) */\n s.x = coeff[1]*ax; /* u = r*atan(x/r) */\n s.y = d.y*cx; /* v = y*cos(u/r) */\n /* derivatives... (see personnal notes) */\n ScaleFilter( resample_filter[id],\n 1.0/(1.0+d.x*d.x), 0.0, -d.x*s.y*cx*cx/coeff[1], s.y/d.y );\n#if 0\nif ( i == 0 && j == 0 ) {\n fprintf(stderr, \"x=%lf y=%lf u=%lf v=%lf\\n\", d.x*coeff[1], d.y, s.x, s.y);\n fprintf(stderr, \"phi = %lf\\n\", (double)(ax * 180.0/MagickPI) );\n fprintf(stderr, \"du/dx=%lf du/dx=%lf dv/dx=%lf dv/dy=%lf\\n\",\n 1.0/(1.0+d.x*d.x), 0.0, -d.x*s.y*cx*cx/coeff[1], s.y/d.y );\n fflush(stderr); }\n#endif\n /* add center of distortion in source */\n s.x += coeff[2]; s.y += coeff[3];\n break;\n }\n case Plane2CylinderDistortion:\n { /* 3D Cylinder to Tangential Plane */\n /* relative to center of distortion */\n d.x -= coeff[4]; d.y -= coeff[5];\n\n /* is pixel valid - horizon of a infinite Virtual-Pixel Plane\n * (see Anthony Thyssen's personal note) */\n validity = (double) (coeff[1]*MagickPI2 - fabs(d.x))/output_scaling + 0.5;\n\n if ( validity > 0.0 ) {\n double cx,tx;\n d.x /= coeff[1]; /* x'= x/r */\n cx = 1/cos(d.x); /* cx = 1/cos(x/r) */\n tx = tan(d.x); /* tx = tan(x/r) */\n s.x = coeff[1]*tx; /* u = r * tan(x/r) */\n s.y = d.y*cx; /* v = y / cos(x/r) */\n /* derivatives... (see Anthony Thyssen's personal notes) */\n ScaleFilter( resample_filter[id],\n cx*cx, 0.0, s.y*cx/coeff[1], cx );\n#if 0\n/*if ( i == 0 && j == 0 )*/\nif ( d.x == 0.5 && d.y == 0.5 ) {\n fprintf(stderr, \"x=%lf y=%lf u=%lf v=%lf\\n\", d.x*coeff[1], d.y, s.x, s.y);\n fprintf(stderr, \"radius = %lf phi = %lf validity = %lf\\n\",\n coeff[1], (double)(d.x * 180.0/MagickPI), validity );\n fprintf(stderr, \"du/dx=%lf du/dx=%lf dv/dx=%lf dv/dy=%lf\\n\",\n cx*cx, 0.0, s.y*cx/coeff[1], cx);\n fflush(stderr); }\n#endif\n }\n /* add center of distortion in source */\n s.x += coeff[2]; s.y += coeff[3];\n break;\n }\n case BarrelDistortion:\n case BarrelInverseDistortion:\n { /* Lens Barrel Distionion Correction */\n double r,fx,fy,gx,gy;\n /* Radial Polynomial Distortion (de-normalized) */\n d.x -= coeff[8];\n d.y -= coeff[9];\n r = sqrt(d.x*d.x+d.y*d.y);\n if ( r > MagickEpsilon ) {\n fx = ((coeff[0]*r + coeff[1])*r + coeff[2])*r + coeff[3];\n fy = ((coeff[4]*r + coeff[5])*r + coeff[6])*r + coeff[7];\n gx = ((3*coeff[0]*r + 2*coeff[1])*r + coeff[2])/r;\n gy = ((3*coeff[4]*r + 2*coeff[5])*r + coeff[6])/r;\n /* adjust functions and scaling for 'inverse' form */\n if ( method == BarrelInverseDistortion ) {\n fx = 1/fx; fy = 1/fy;\n gx *= -fx*fx; gy *= -fy*fy;\n }\n /* Set the source pixel to lookup and EWA derivative vectors */\n s.x = d.x*fx + coeff[8];\n s.y = d.y*fy + coeff[9];\n ScaleFilter( resample_filter[id],\n gx*d.x*d.x + fx, gx*d.x*d.y,\n gy*d.x*d.y, gy*d.y*d.y + fy );\n }\n else {\n /* Special handling to avoid divide by zero when r==0\n **\n ** The source and destination pixels match in this case\n ** which was set at the top of the loop using s = d;\n ** otherwise... s.x=coeff[8]; s.y=coeff[9];\n */\n if ( method == BarrelDistortion )\n ScaleFilter( resample_filter[id],\n coeff[3], 0, 0, coeff[7] );\n else /* method == BarrelInverseDistortion */\n /* FUTURE, trap for D==0 causing division by zero */\n ScaleFilter( resample_filter[id],\n 1.0/coeff[3], 0, 0, 1.0/coeff[7] );\n }\n break;\n }\n case ShepardsDistortion:\n { /* Shepards Method, or Inverse Weighted Distance for\n displacement around the destination image control points\n The input arguments are the coefficents to the function.\n This is more of a 'displacement' function rather than an\n absolute distortion function.\n\n Note: We can not determine derivatives using shepards method\n so only a point sample interpolatation can be used.\n */\n size_t\n i;\n double\n denominator;\n\n denominator = s.x = s.y = 0;\n for(i=0; ipage.x;\n s.y -= image->page.y;\n }\n s.x -= 0.5;\n s.y -= 0.5;\n\n if ( validity <= 0.0 ) {\n /* result of distortion is an invalid pixel - don't resample */\n SetPixelViaPixelInfo(distort_image,&invalid,q);\n }\n else {\n /* resample the source image to find its correct color */\n (void) ResamplePixelColor(resample_filter[id],s.x,s.y,&pixel,\n exception);\n /* if validity between 0.0 and 1.0 mix result with invalid pixel */\n if ( validity < 1.0 ) {\n /* Do a blend of sample color and invalid pixel */\n /* should this be a 'Blend', or an 'Over' compose */\n CompositePixelInfoBlend(&pixel,validity,&invalid,(1.0-validity),\n &pixel);\n }\n SetPixelViaPixelInfo(distort_image,&pixel,q);\n }\n q+=GetPixelChannels(distort_image);\n }\n sync=SyncCacheViewAuthenticPixels(distort_view,exception);\n if (sync == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,DistortImageTag,progress,image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n distort_view=DestroyCacheView(distort_view);\n resample_filter=DestroyResampleFilterThreadSet(resample_filter);\n\n if (status == MagickFalse)\n distort_image=DestroyImage(distort_image);\n }\n\n /* Arc does not return an offset unless 'bestfit' is in effect\n And the user has not provided an overriding 'viewport'.\n */\n if ( method == ArcDistortion && !bestfit && !viewport_given ) {\n distort_image->page.x = 0;\n distort_image->page.y = 0;\n }\n coeff=(double *) RelinquishMagickMemory(coeff);\n return(distort_image);\n}", "project": "ImageMagick", "hash": 325010277995776734256210799163273736372, "size": 1159, "commit_id": "f8e8535bc821f24a30beee0030ff21ee3a2deedc", "message": "https://github.com/ImageMagick/ImageMagick/issues/3331", "target": 0, "dataset": "other", "idx": 383186} {"func": "static int llcp_sock_bind(struct socket *sock, struct sockaddr *addr, int alen)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);\n\tstruct nfc_llcp_local *local;\n\tstruct nfc_dev *dev;\n\tstruct sockaddr_nfc_llcp llcp_addr;\n\tint len, ret = 0;\n\n\tif (!addr || alen < offsetofend(struct sockaddr, sa_family) ||\n\t addr->sa_family != AF_NFC)\n\t\treturn -EINVAL;\n\n\tpr_debug(\"sk %p addr %p family %d\\n\", sk, addr, addr->sa_family);\n\n\tmemset(&llcp_addr, 0, sizeof(llcp_addr));\n\tlen = min_t(unsigned int, sizeof(llcp_addr), alen);\n\tmemcpy(&llcp_addr, addr, len);\n\n\t/* This is going to be a listening socket, dsap must be 0 */\n\tif (llcp_addr.dsap != 0)\n\t\treturn -EINVAL;\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state != LLCP_CLOSED) {\n\t\tret = -EBADFD;\n\t\tgoto error;\n\t}\n\n\tdev = nfc_get_device(llcp_addr.dev_idx);\n\tif (dev == NULL) {\n\t\tret = -ENODEV;\n\t\tgoto error;\n\t}\n\n\tlocal = nfc_llcp_find_local(dev);\n\tif (local == NULL) {\n\t\tret = -ENODEV;\n\t\tgoto put_dev;\n\t}\n\n\tllcp_sock->dev = dev;\n\tllcp_sock->local = nfc_llcp_local_get(local);\n\tllcp_sock->nfc_protocol = llcp_addr.nfc_protocol;\n\tllcp_sock->service_name_len = min_t(unsigned int,\n\t\t\t\t\t llcp_addr.service_name_len,\n\t\t\t\t\t NFC_LLCP_MAX_SERVICE_NAME);\n\tllcp_sock->service_name = kmemdup(llcp_addr.service_name,\n\t\t\t\t\t llcp_sock->service_name_len,\n\t\t\t\t\t GFP_KERNEL);\n\tif (!llcp_sock->service_name) {\n\t\tnfc_llcp_local_put(llcp_sock->local);\n\t\tllcp_sock->local = NULL;\n\t\tret = -ENOMEM;\n\t\tgoto put_dev;\n\t}\n\tllcp_sock->ssap = nfc_llcp_get_sdp_ssap(local, llcp_sock);\n\tif (llcp_sock->ssap == LLCP_SAP_MAX) {\n\t\tnfc_llcp_local_put(llcp_sock->local);\n\t\tllcp_sock->local = NULL;\n\t\tkfree(llcp_sock->service_name);\n\t\tllcp_sock->service_name = NULL;\n\t\tret = -EADDRINUSE;\n\t\tgoto put_dev;\n\t}\n\n\tllcp_sock->reserved_ssap = llcp_sock->ssap;\n\n\tnfc_llcp_sock_link(&local->sockets, sk);\n\n\tpr_debug(\"Socket bound to SAP %d\\n\", llcp_sock->ssap);\n\n\tsk->sk_state = LLCP_BOUND;\n\nput_dev:\n\tnfc_put_device(dev);\n\nerror:\n\trelease_sock(sk);\n\treturn ret;\n}", "project": "linux", "hash": 318436817421404573454745290139407660076, "size": 82, "commit_id": "4ac06a1e013cf5fdd963317ffd3b968560f33bba", "message": "nfc: fix NULL ptr dereference in llcp_sock_getname() after failed connect\n\nIt's possible to trigger NULL pointer dereference by local unprivileged\nuser, when calling getsockname() after failed bind() (e.g. the bind\nfails because LLCP_SAP_MAX used as SAP):\n\n BUG: kernel NULL pointer dereference, address: 0000000000000000\n CPU: 1 PID: 426 Comm: llcp_sock_getna Not tainted 5.13.0-rc2-next-20210521+ #9\n Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-1 04/01/2014\n Call Trace:\n llcp_sock_getname+0xb1/0xe0\n __sys_getpeername+0x95/0xc0\n ? lockdep_hardirqs_on_prepare+0xd5/0x180\n ? syscall_enter_from_user_mode+0x1c/0x40\n __x64_sys_getpeername+0x11/0x20\n do_syscall_64+0x36/0x70\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nThis can be reproduced with Syzkaller C repro (bind followed by\ngetpeername):\nhttps://syzkaller.appspot.com/x/repro.c?x=14def446e00000\n\nCc: \nFixes: d646960f7986 (\"NFC: Initial LLCP support\")\nReported-by: syzbot+80fb126e7f7d8b1a5914@syzkaller.appspotmail.com\nReported-by: butt3rflyh4ck \nSigned-off-by: Krzysztof Kozlowski \nLink: https://lore.kernel.org/r/20210531072138.5219-1-krzysztof.kozlowski@canonical.com\nSigned-off-by: Jakub Kicinski ", "target": 1, "dataset": "other", "idx": 206589} {"func": "static int llcp_sock_bind(struct socket *sock, struct sockaddr *addr, int alen)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk);\n\tstruct nfc_llcp_local *local;\n\tstruct nfc_dev *dev;\n\tstruct sockaddr_nfc_llcp llcp_addr;\n\tint len, ret = 0;\n\n\tif (!addr || alen < offsetofend(struct sockaddr, sa_family) ||\n\t addr->sa_family != AF_NFC)\n\t\treturn -EINVAL;\n\n\tpr_debug(\"sk %p addr %p family %d\\n\", sk, addr, addr->sa_family);\n\n\tmemset(&llcp_addr, 0, sizeof(llcp_addr));\n\tlen = min_t(unsigned int, sizeof(llcp_addr), alen);\n\tmemcpy(&llcp_addr, addr, len);\n\n\t/* This is going to be a listening socket, dsap must be 0 */\n\tif (llcp_addr.dsap != 0)\n\t\treturn -EINVAL;\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state != LLCP_CLOSED) {\n\t\tret = -EBADFD;\n\t\tgoto error;\n\t}\n\n\tdev = nfc_get_device(llcp_addr.dev_idx);\n\tif (dev == NULL) {\n\t\tret = -ENODEV;\n\t\tgoto error;\n\t}\n\n\tlocal = nfc_llcp_find_local(dev);\n\tif (local == NULL) {\n\t\tret = -ENODEV;\n\t\tgoto put_dev;\n\t}\n\n\tllcp_sock->dev = dev;\n\tllcp_sock->local = nfc_llcp_local_get(local);\n\tllcp_sock->nfc_protocol = llcp_addr.nfc_protocol;\n\tllcp_sock->service_name_len = min_t(unsigned int,\n\t\t\t\t\t llcp_addr.service_name_len,\n\t\t\t\t\t NFC_LLCP_MAX_SERVICE_NAME);\n\tllcp_sock->service_name = kmemdup(llcp_addr.service_name,\n\t\t\t\t\t llcp_sock->service_name_len,\n\t\t\t\t\t GFP_KERNEL);\n\tif (!llcp_sock->service_name) {\n\t\tnfc_llcp_local_put(llcp_sock->local);\n\t\tllcp_sock->local = NULL;\n\t\tllcp_sock->dev = NULL;\n\t\tret = -ENOMEM;\n\t\tgoto put_dev;\n\t}\n\tllcp_sock->ssap = nfc_llcp_get_sdp_ssap(local, llcp_sock);\n\tif (llcp_sock->ssap == LLCP_SAP_MAX) {\n\t\tnfc_llcp_local_put(llcp_sock->local);\n\t\tllcp_sock->local = NULL;\n\t\tkfree(llcp_sock->service_name);\n\t\tllcp_sock->service_name = NULL;\n\t\tllcp_sock->dev = NULL;\n\t\tret = -EADDRINUSE;\n\t\tgoto put_dev;\n\t}\n\n\tllcp_sock->reserved_ssap = llcp_sock->ssap;\n\n\tnfc_llcp_sock_link(&local->sockets, sk);\n\n\tpr_debug(\"Socket bound to SAP %d\\n\", llcp_sock->ssap);\n\n\tsk->sk_state = LLCP_BOUND;\n\nput_dev:\n\tnfc_put_device(dev);\n\nerror:\n\trelease_sock(sk);\n\treturn ret;\n}", "project": "linux", "hash": 198293030880834049287684601516018080299, "size": 84, "commit_id": "4ac06a1e013cf5fdd963317ffd3b968560f33bba", "message": "nfc: fix NULL ptr dereference in llcp_sock_getname() after failed connect\n\nIt's possible to trigger NULL pointer dereference by local unprivileged\nuser, when calling getsockname() after failed bind() (e.g. the bind\nfails because LLCP_SAP_MAX used as SAP):\n\n BUG: kernel NULL pointer dereference, address: 0000000000000000\n CPU: 1 PID: 426 Comm: llcp_sock_getna Not tainted 5.13.0-rc2-next-20210521+ #9\n Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.14.0-1 04/01/2014\n Call Trace:\n llcp_sock_getname+0xb1/0xe0\n __sys_getpeername+0x95/0xc0\n ? lockdep_hardirqs_on_prepare+0xd5/0x180\n ? syscall_enter_from_user_mode+0x1c/0x40\n __x64_sys_getpeername+0x11/0x20\n do_syscall_64+0x36/0x70\n entry_SYSCALL_64_after_hwframe+0x44/0xae\n\nThis can be reproduced with Syzkaller C repro (bind followed by\ngetpeername):\nhttps://syzkaller.appspot.com/x/repro.c?x=14def446e00000\n\nCc: \nFixes: d646960f7986 (\"NFC: Initial LLCP support\")\nReported-by: syzbot+80fb126e7f7d8b1a5914@syzkaller.appspotmail.com\nReported-by: butt3rflyh4ck \nSigned-off-by: Krzysztof Kozlowski \nLink: https://lore.kernel.org/r/20210531072138.5219-1-krzysztof.kozlowski@canonical.com\nSigned-off-by: Jakub Kicinski ", "target": 0, "dataset": "other", "idx": 383386} {"func": "start_input_gif(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)\n{\n gif_source_ptr source = (gif_source_ptr)sinfo;\n U_CHAR hdrbuf[10]; /* workspace for reading control blocks */\n unsigned int width, height; /* image dimensions */\n int colormaplen, aspectRatio;\n int c;\n\n /* Read and verify GIF Header */\n if (!ReadOK(source->pub.input_file, hdrbuf, 6))\n ERREXIT(cinfo, JERR_GIF_NOT);\n if (hdrbuf[0] != 'G' || hdrbuf[1] != 'I' || hdrbuf[2] != 'F')\n ERREXIT(cinfo, JERR_GIF_NOT);\n /* Check for expected version numbers.\n * If unknown version, give warning and try to process anyway;\n * this is per recommendation in GIF89a standard.\n */\n if ((hdrbuf[3] != '8' || hdrbuf[4] != '7' || hdrbuf[5] != 'a') &&\n (hdrbuf[3] != '8' || hdrbuf[4] != '9' || hdrbuf[5] != 'a'))\n TRACEMS3(cinfo, 1, JTRC_GIF_BADVERSION, hdrbuf[3], hdrbuf[4], hdrbuf[5]);\n\n /* Read and decipher Logical Screen Descriptor */\n if (!ReadOK(source->pub.input_file, hdrbuf, 7))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n width = LM_to_uint(hdrbuf, 0);\n height = LM_to_uint(hdrbuf, 2);\n /* we ignore the color resolution, sort flag, and background color index */\n aspectRatio = UCH(hdrbuf[6]);\n if (aspectRatio != 0 && aspectRatio != 49)\n TRACEMS(cinfo, 1, JTRC_GIF_NONSQUARE);\n\n /* Allocate space to store the colormap */\n source->colormap = (*cinfo->mem->alloc_sarray)\n ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)MAXCOLORMAPSIZE,\n (JDIMENSION)NUMCOLORS);\n colormaplen = 0; /* indicate initialization */\n\n /* Read global colormap if header indicates it is present */\n if (BitSet(hdrbuf[4], COLORMAPFLAG)) {\n colormaplen = 2 << (hdrbuf[4] & 0x07);\n ReadColorMap(source, colormaplen, source->colormap);\n }\n\n /* Scan until we reach start of desired image.\n * We don't currently support skipping images, but could add it easily.\n */\n for (;;) {\n c = ReadByte(source);\n\n if (c == ';') /* GIF terminator?? */\n ERREXIT(cinfo, JERR_GIF_IMAGENOTFOUND);\n\n if (c == '!') { /* Extension */\n DoExtension(source);\n continue;\n }\n\n if (c != ',') { /* Not an image separator? */\n WARNMS1(cinfo, JWRN_GIF_CHAR, c);\n continue;\n }\n\n /* Read and decipher Local Image Descriptor */\n if (!ReadOK(source->pub.input_file, hdrbuf, 9))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n /* we ignore top/left position info, also sort flag */\n width = LM_to_uint(hdrbuf, 4);\n height = LM_to_uint(hdrbuf, 6);\n source->is_interlaced = (BitSet(hdrbuf[8], INTERLACE) != 0);\n\n /* Read local colormap if header indicates it is present */\n /* Note: if we wanted to support skipping images, */\n /* we'd need to skip rather than read colormap for ignored images */\n if (BitSet(hdrbuf[8], COLORMAPFLAG)) {\n colormaplen = 2 << (hdrbuf[8] & 0x07);\n ReadColorMap(source, colormaplen, source->colormap);\n }\n\n source->input_code_size = ReadByte(source); /* get min-code-size byte */\n if (source->input_code_size < 2 || source->input_code_size > 8)\n ERREXIT1(cinfo, JERR_GIF_CODESIZE, source->input_code_size);\n\n /* Reached desired image, so break out of loop */\n /* If we wanted to skip this image, */\n /* we'd call SkipDataBlocks and then continue the loop */\n break;\n }\n\n /* Prepare to read selected image: first initialize LZW decompressor */\n source->symbol_head = (UINT16 *)\n (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n LZW_TABLE_SIZE * sizeof(UINT16));\n source->symbol_tail = (UINT8 *)\n (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n LZW_TABLE_SIZE * sizeof(UINT8));\n source->symbol_stack = (UINT8 *)\n (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n LZW_TABLE_SIZE * sizeof(UINT8));\n InitLZWCode(source);\n\n /*\n * If image is interlaced, we read it into a full-size sample array,\n * decompressing as we go; then get_interlaced_row selects rows from the\n * sample array in the proper order.\n */\n if (source->is_interlaced) {\n /* We request the virtual array now, but can't access it until virtual\n * arrays have been allocated. Hence, the actual work of reading the\n * image is postponed until the first call to get_pixel_rows.\n */\n source->interlaced_image = (*cinfo->mem->request_virt_sarray)\n ((j_common_ptr)cinfo, JPOOL_IMAGE, FALSE,\n (JDIMENSION)width, (JDIMENSION)height, (JDIMENSION)1);\n if (cinfo->progress != NULL) {\n cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress;\n progress->total_extra_passes++; /* count file input as separate pass */\n }\n source->pub.get_pixel_rows = load_interlaced_image;\n } else {\n source->pub.get_pixel_rows = get_pixel_rows;\n }\n\n /* Create compressor input buffer. */\n source->pub.buffer = (*cinfo->mem->alloc_sarray)\n ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)width * NUMCOLORS,\n (JDIMENSION)1);\n source->pub.buffer_height = 1;\n\n /* Pad colormap for safety. */\n for (c = colormaplen; c < source->clear_code; c++) {\n source->colormap[CM_RED][c] =\n source->colormap[CM_GREEN][c] =\n source->colormap[CM_BLUE][c] = CENTERJSAMPLE;\n }\n\n /* Return info about the image. */\n cinfo->in_color_space = JCS_RGB;\n cinfo->input_components = NUMCOLORS;\n cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */\n cinfo->image_width = width;\n cinfo->image_height = height;\n\n TRACEMS3(cinfo, 1, JTRC_GIF, width, height, colormaplen);\n}", "project": "libjpeg-turbo", "hash": 201180578183398097843040932663132682779, "size": 144, "commit_id": "1719d12e51641cce5c77e259516649ba5ef6303c", "message": "cjpeg: Fix FPE when compressing 0-width GIF\n\nFixes #493", "target": 1, "dataset": "other", "idx": 206616} {"func": "start_input_gif(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)\n{\n gif_source_ptr source = (gif_source_ptr)sinfo;\n U_CHAR hdrbuf[10]; /* workspace for reading control blocks */\n unsigned int width, height; /* image dimensions */\n int colormaplen, aspectRatio;\n int c;\n\n /* Read and verify GIF Header */\n if (!ReadOK(source->pub.input_file, hdrbuf, 6))\n ERREXIT(cinfo, JERR_GIF_NOT);\n if (hdrbuf[0] != 'G' || hdrbuf[1] != 'I' || hdrbuf[2] != 'F')\n ERREXIT(cinfo, JERR_GIF_NOT);\n /* Check for expected version numbers.\n * If unknown version, give warning and try to process anyway;\n * this is per recommendation in GIF89a standard.\n */\n if ((hdrbuf[3] != '8' || hdrbuf[4] != '7' || hdrbuf[5] != 'a') &&\n (hdrbuf[3] != '8' || hdrbuf[4] != '9' || hdrbuf[5] != 'a'))\n TRACEMS3(cinfo, 1, JTRC_GIF_BADVERSION, hdrbuf[3], hdrbuf[4], hdrbuf[5]);\n\n /* Read and decipher Logical Screen Descriptor */\n if (!ReadOK(source->pub.input_file, hdrbuf, 7))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n width = LM_to_uint(hdrbuf, 0);\n height = LM_to_uint(hdrbuf, 2);\n if (width == 0 || height == 0)\n ERREXIT(cinfo, JERR_GIF_EMPTY);\n /* we ignore the color resolution, sort flag, and background color index */\n aspectRatio = UCH(hdrbuf[6]);\n if (aspectRatio != 0 && aspectRatio != 49)\n TRACEMS(cinfo, 1, JTRC_GIF_NONSQUARE);\n\n /* Allocate space to store the colormap */\n source->colormap = (*cinfo->mem->alloc_sarray)\n ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)MAXCOLORMAPSIZE,\n (JDIMENSION)NUMCOLORS);\n colormaplen = 0; /* indicate initialization */\n\n /* Read global colormap if header indicates it is present */\n if (BitSet(hdrbuf[4], COLORMAPFLAG)) {\n colormaplen = 2 << (hdrbuf[4] & 0x07);\n ReadColorMap(source, colormaplen, source->colormap);\n }\n\n /* Scan until we reach start of desired image.\n * We don't currently support skipping images, but could add it easily.\n */\n for (;;) {\n c = ReadByte(source);\n\n if (c == ';') /* GIF terminator?? */\n ERREXIT(cinfo, JERR_GIF_IMAGENOTFOUND);\n\n if (c == '!') { /* Extension */\n DoExtension(source);\n continue;\n }\n\n if (c != ',') { /* Not an image separator? */\n WARNMS1(cinfo, JWRN_GIF_CHAR, c);\n continue;\n }\n\n /* Read and decipher Local Image Descriptor */\n if (!ReadOK(source->pub.input_file, hdrbuf, 9))\n ERREXIT(cinfo, JERR_INPUT_EOF);\n /* we ignore top/left position info, also sort flag */\n width = LM_to_uint(hdrbuf, 4);\n height = LM_to_uint(hdrbuf, 6);\n if (width == 0 || height == 0)\n ERREXIT(cinfo, JERR_GIF_EMPTY);\n source->is_interlaced = (BitSet(hdrbuf[8], INTERLACE) != 0);\n\n /* Read local colormap if header indicates it is present */\n /* Note: if we wanted to support skipping images, */\n /* we'd need to skip rather than read colormap for ignored images */\n if (BitSet(hdrbuf[8], COLORMAPFLAG)) {\n colormaplen = 2 << (hdrbuf[8] & 0x07);\n ReadColorMap(source, colormaplen, source->colormap);\n }\n\n source->input_code_size = ReadByte(source); /* get min-code-size byte */\n if (source->input_code_size < 2 || source->input_code_size > 8)\n ERREXIT1(cinfo, JERR_GIF_CODESIZE, source->input_code_size);\n\n /* Reached desired image, so break out of loop */\n /* If we wanted to skip this image, */\n /* we'd call SkipDataBlocks and then continue the loop */\n break;\n }\n\n /* Prepare to read selected image: first initialize LZW decompressor */\n source->symbol_head = (UINT16 *)\n (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n LZW_TABLE_SIZE * sizeof(UINT16));\n source->symbol_tail = (UINT8 *)\n (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n LZW_TABLE_SIZE * sizeof(UINT8));\n source->symbol_stack = (UINT8 *)\n (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,\n LZW_TABLE_SIZE * sizeof(UINT8));\n InitLZWCode(source);\n\n /*\n * If image is interlaced, we read it into a full-size sample array,\n * decompressing as we go; then get_interlaced_row selects rows from the\n * sample array in the proper order.\n */\n if (source->is_interlaced) {\n /* We request the virtual array now, but can't access it until virtual\n * arrays have been allocated. Hence, the actual work of reading the\n * image is postponed until the first call to get_pixel_rows.\n */\n source->interlaced_image = (*cinfo->mem->request_virt_sarray)\n ((j_common_ptr)cinfo, JPOOL_IMAGE, FALSE,\n (JDIMENSION)width, (JDIMENSION)height, (JDIMENSION)1);\n if (cinfo->progress != NULL) {\n cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress;\n progress->total_extra_passes++; /* count file input as separate pass */\n }\n source->pub.get_pixel_rows = load_interlaced_image;\n } else {\n source->pub.get_pixel_rows = get_pixel_rows;\n }\n\n /* Create compressor input buffer. */\n source->pub.buffer = (*cinfo->mem->alloc_sarray)\n ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)width * NUMCOLORS,\n (JDIMENSION)1);\n source->pub.buffer_height = 1;\n\n /* Pad colormap for safety. */\n for (c = colormaplen; c < source->clear_code; c++) {\n source->colormap[CM_RED][c] =\n source->colormap[CM_GREEN][c] =\n source->colormap[CM_BLUE][c] = CENTERJSAMPLE;\n }\n\n /* Return info about the image. */\n cinfo->in_color_space = JCS_RGB;\n cinfo->input_components = NUMCOLORS;\n cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */\n cinfo->image_width = width;\n cinfo->image_height = height;\n\n TRACEMS3(cinfo, 1, JTRC_GIF, width, height, colormaplen);\n}", "project": "libjpeg-turbo", "hash": 121557664873555763939551225581936916025, "size": 148, "commit_id": "1719d12e51641cce5c77e259516649ba5ef6303c", "message": "cjpeg: Fix FPE when compressing 0-width GIF\n\nFixes #493", "target": 0, "dataset": "other", "idx": 383920} {"func": "exif_entry_get_value (ExifEntry *e, char *val, unsigned int maxlen)\n{\n\tunsigned int i, j, k;\n\tExifShort v_short, v_short2, v_short3, v_short4;\n\tExifByte v_byte;\n\tExifRational v_rat;\n\tExifSRational v_srat;\n\tchar b[64];\n\tconst char *c;\n\tExifByteOrder o;\n\tdouble d;\n\tExifEntry *entry;\n\tstatic const struct {\n\t\tchar label[5];\n\t\tchar major, minor;\n\t} versions[] = {\n\t\t{\"0110\", 1, 1},\n\t\t{\"0120\", 1, 2},\n\t\t{\"0200\", 2, 0},\n\t\t{\"0210\", 2, 1},\n\t\t{\"0220\", 2, 2},\n\t\t{\"0221\", 2, 21},\n\t\t{\"0230\", 2, 3},\n\t\t{\"\" , 0, 0}\n\t};\n\n\t(void) bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);\n\n\tif (!e || !e->parent || !e->parent->parent || !maxlen || !val)\n\t\treturn val;\n\n\t/* make sure the returned string is zero terminated */\n\t/* FIXME: this is inefficient in the case of long buffers and should\n\t * instead be taken care of on each write instead. */\n\tmemset (val, 0, maxlen);\n\n\t/* We need the byte order */\n\to = exif_data_get_byte_order (e->parent->parent);\n\n\t/* Sanity check */\n\tif (e->size != e->components * exif_format_get_size (e->format)) {\n\t\tsnprintf (val, maxlen, _(\"Invalid size of entry (%i, \"\n\t\t\t\"expected %li x %i).\"), e->size, e->components,\n\t\t\t\texif_format_get_size (e->format));\n\t\treturn val;\n\t}\n\n\tswitch (e->tag) {\n\tcase EXIF_TAG_USER_COMMENT:\n\n\t\t/*\n\t\t * The specification says UNDEFINED, but some\n\t\t * manufacturers don't care and use ASCII. If this is the\n\t\t * case here, only refuse to read it if there is no chance\n\t\t * of finding readable data.\n\t\t */\n\t\tif ((e->format != EXIF_FORMAT_ASCII) || \n\t\t (e->size <= 8) ||\n\t\t ( memcmp (e->data, \"ASCII\\0\\0\\0\" , 8) &&\n\t\t memcmp (e->data, \"UNICODE\\0\" , 8) &&\n\t\t memcmp (e->data, \"JIS\\0\\0\\0\\0\\0\", 8) &&\n\t\t memcmp (e->data, \"\\0\\0\\0\\0\\0\\0\\0\\0\", 8)))\n\t\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\n\t\t/*\n\t\t * Note that, according to the specification (V2.1, p 40),\n\t\t * the user comment field does not have to be \n\t\t * NULL terminated.\n\t\t */\n\t\tif ((e->size >= 8) && !memcmp (e->data, \"ASCII\\0\\0\\0\", 8)) {\n\t\t\tstrncpy (val, (char *) e->data + 8, MIN (e->size - 8, maxlen-1));\n\t\t\tbreak;\n\t\t}\n\t\tif ((e->size >= 8) && !memcmp (e->data, \"UNICODE\\0\", 8)) {\n\t\t\tstrncpy (val, _(\"Unsupported UNICODE string\"), maxlen-1);\n\t\t/* FIXME: use iconv to convert into the locale encoding.\n\t\t * EXIF 2.2 implies (but does not say) that this encoding is\n\t\t * UCS-2.\n\t\t */\n\t\t\tbreak;\n\t\t}\n\t\tif ((e->size >= 8) && !memcmp (e->data, \"JIS\\0\\0\\0\\0\\0\", 8)) {\n\t\t\tstrncpy (val, _(\"Unsupported JIS string\"), maxlen-1);\n\t\t/* FIXME: use iconv to convert into the locale encoding */\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Check if there is really some information in the tag. */\n\t\tfor (i = 0; (i < e->size) &&\n\t\t\t (!e->data[i] || (e->data[i] == ' ')); i++);\n\t\tif (i == e->size) break;\n\n\t\t/*\n\t\t * If we reach this point, the tag does not\n \t\t * comply with the standard but seems to contain data.\n\t\t * Print as much as possible.\n\t\t * Note: make sure we do not overwrite the final \\0 at maxlen-1\n\t\t */\n\t\texif_entry_log (e, EXIF_LOG_CODE_DEBUG,\n\t\t\t_(\"Tag UserComment contains data but is \"\n\t\t\t \"against specification.\"));\n \t\tfor (j = 0; (i < e->size) && (j < maxlen-1); i++, j++) {\n\t\t\texif_entry_log (e, EXIF_LOG_CODE_DEBUG,\n\t\t\t\t_(\"Byte at position %i: 0x%02x\"), i, e->data[i]);\n \t\t\tval[j] = isprint (e->data[i]) ? e->data[i] : '.';\n\t\t}\n\t\tbreak;\n\n\tcase EXIF_TAG_EXIF_VERSION:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tstrncpy (val, _(\"Unknown Exif Version\"), maxlen-1);\n\t\tfor (i = 0; *versions[i].label; i++) {\n\t\t\tif (!memcmp (e->data, versions[i].label, 4)) {\n \t\t\t\tsnprintf (val, maxlen,\n\t\t\t\t\t_(\"Exif Version %d.%d\"),\n\t\t\t\t\tversions[i].major,\n\t\t\t\t\tversions[i].minor);\n \t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_FLASH_PIX_VERSION:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tif (!memcmp (e->data, \"0100\", 4))\n\t\t\tstrncpy (val, _(\"FlashPix Version 1.0\"), maxlen-1);\n\t\telse if (!memcmp (e->data, \"0101\", 4))\n\t\t\tstrncpy (val, _(\"FlashPix Version 1.01\"), maxlen-1);\n\t\telse\n\t\t\tstrncpy (val, _(\"Unknown FlashPix Version\"), maxlen-1);\n\t\tbreak;\n\tcase EXIF_TAG_COPYRIGHT:\n\t\tCF (e, EXIF_FORMAT_ASCII, val, maxlen);\n\n\t\t/*\n\t\t * First part: Photographer.\n\t\t * Some cameras store a string like \" \" here. Ignore it.\n\t\t * Remember that a corrupted tag might not be NUL-terminated\n\t\t */\n\t\tif (e->size && e->data && match_repeated_char(e->data, ' ', e->size))\n\t\t\tstrncpy (val, (char *) e->data, MIN (maxlen-1, e->size));\n\t\telse\n\t\t\tstrncpy (val, _(\"[None]\"), maxlen-1);\n\t\tstrncat (val, \" \", maxlen-1 - strlen (val));\n\t\tstrncat (val, _(\"(Photographer)\"), maxlen-1 - strlen (val));\n\n\t\t/* Second part: Editor. */\n\t\tstrncat (val, \" - \", maxlen-1 - strlen (val));\n\t\tk = 0;\n\t\tif (e->size && e->data) {\n\t\t\tconst unsigned char *tagdata = memchr(e->data, 0, e->size);\n\t\t\tif (tagdata++) {\n\t\t\t\tunsigned int editor_ofs = tagdata - e->data;\n\t\t\t\tunsigned int remaining = e->size - editor_ofs;\n\t\t\t\tif (match_repeated_char(tagdata, ' ', remaining)) {\n\t\t\t\t\tstrncat (val, (const char*)tagdata, MIN (maxlen-1 - strlen (val), remaining));\n\t\t\t\t\t++k;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!k)\n\t\t\tstrncat (val, _(\"[None]\"), maxlen-1 - strlen (val));\n\t\tstrncat (val, \" \", maxlen-1 - strlen (val));\n\t\tstrncat (val, _(\"(Editor)\"), maxlen-1 - strlen (val));\n\n\t\tbreak;\n\tcase EXIF_TAG_FNUMBER:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"f/%.01f\", d);\n\t\tbreak;\n\tcase EXIF_TAG_APERTURE_VALUE:\n\tcase EXIF_TAG_MAX_APERTURE_VALUE:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator || (0x80000000 == v_rat.numerator)) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tsnprintf (b, sizeof (b), _(\" (f/%.01f)\"), pow (2, d / 2.));\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_FOCAL_LENGTH:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * For calculation of the 35mm equivalent,\n\t\t * Minolta cameras need a multiplier that depends on the\n\t\t * camera model.\n\t\t */\n\t\td = 0.;\n\t\tentry = exif_content_get_entry (\n\t\t\te->parent->parent->ifd[EXIF_IFD_0], EXIF_TAG_MAKE);\n\t\tif (entry && entry->data && entry->size >= 7 &&\n\t\t !strncmp ((char *)entry->data, \"Minolta\", 7)) {\n\t\t\tentry = exif_content_get_entry (\n\t\t\t\t\te->parent->parent->ifd[EXIF_IFD_0],\n\t\t\t\t\tEXIF_TAG_MODEL);\n\t\t\tif (entry && entry->data && entry->size >= 8) {\n\t\t\t\tif (!strncmp ((char *)entry->data, \"DiMAGE 7\", 8))\n\t\t\t\t\td = 3.9;\n\t\t\t\telse if (!strncmp ((char *)entry->data, \"DiMAGE 5\", 8))\n\t\t\t\t\td = 4.9;\n\t\t\t}\n\t\t}\n\t\tif (d)\n\t\t\tsnprintf (b, sizeof (b), _(\" (35 equivalent: %.0f mm)\"),\n\t\t\t\t (d * (double) v_rat.numerator /\n\t\t\t\t (double) v_rat.denominator));\n\t\telse\n\t\t\tb[0] = 0;\n\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"%.1f mm\", d);\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_SUBJECT_DISTANCE:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"%.1f m\", d);\n\t\tbreak;\n\tcase EXIF_TAG_EXPOSURE_TIME:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tif (d < 1 && d)\n\t\t\tsnprintf (val, maxlen, _(\"1/%.0f\"), 1. / d);\n\t\telse\n\t\t\tsnprintf (val, maxlen, \"%.0f\", d);\n\t\tstrncat (val, _(\" sec.\"), maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_SHUTTER_SPEED_VALUE:\n\t\tCF (e, EXIF_FORMAT_SRATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_srat = exif_get_srational (e->data, o);\n\t\tif (!v_srat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_srat.numerator / (double) v_srat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tif (pow (2, d))\n\t\t\td = 1. / pow (2, d);\n\t\tif (d < 1 && d)\n\t\t snprintf (b, sizeof (b), _(\" (1/%.0f sec.)\"), 1. / d);\n\t\telse\n\t\t snprintf (b, sizeof (b), _(\" (%.0f sec.)\"), d);\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_BRIGHTNESS_VALUE:\n\t\tCF (e, EXIF_FORMAT_SRATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_srat = exif_get_srational (e->data, o);\n\t\tif (!v_srat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_srat.numerator / (double) v_srat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tsnprintf (b, sizeof (b), _(\" (%.02f cd/m^2)\"),\n\t\t\t1. / (M_PI * 0.3048 * 0.3048) * pow (2, d));\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_FILE_SOURCE:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tif (v_byte == 3)\n\t\t\tstrncpy (val, _(\"DSC\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_byte);\n\t\tbreak;\n\tcase EXIF_TAG_COMPONENTS_CONFIGURATION:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tfor (i = 0; i < 4; i++) {\n\t\t\tswitch (e->data[i]) {\n\t\t\tcase 0: c = _(\"-\"); break;\n\t\t\tcase 1: c = _(\"Y\"); break;\n\t\t\tcase 2: c = _(\"Cb\"); break;\n\t\t\tcase 3: c = _(\"Cr\"); break;\n\t\t\tcase 4: c = _(\"R\"); break;\n\t\t\tcase 5: c = _(\"G\"); break;\n\t\t\tcase 6: c = _(\"B\"); break;\n\t\t\tdefault: c = _(\"Reserved\"); break;\n\t\t\t}\n\t\t\tstrncat (val, c, maxlen-1 - strlen (val));\n\t\t\tif (i < 3)\n\t\t\t\tstrncat (val, \" \", maxlen-1 - strlen (val));\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_EXPOSURE_BIAS_VALUE:\n\t\tCF (e, EXIF_FORMAT_SRATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_srat = exif_get_srational (e->data, o);\n\t\tif (!v_srat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_srat.numerator / (double) v_srat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tbreak;\n\tcase EXIF_TAG_SCENE_TYPE:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tif (v_byte == 1)\n\t\t\tstrncpy (val, _(\"Directly photographed\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_byte);\n\t\tbreak;\n\tcase EXIF_TAG_YCBCR_SUB_SAMPLING:\n\t\tCF (e, EXIF_FORMAT_SHORT, val, maxlen);\n\t\tCC (e, 2, val, maxlen);\n\t\tv_short = exif_get_short (e->data, o);\n\t\tv_short2 = exif_get_short (\n\t\t\te->data + exif_format_get_size (e->format),\n\t\t\to);\n\t\tif ((v_short == 2) && (v_short2 == 1))\n\t\t\tstrncpy (val, _(\"YCbCr4:2:2\"), maxlen-1);\n\t\telse if ((v_short == 2) && (v_short2 == 2))\n\t\t\tstrncpy (val, _(\"YCbCr4:2:0\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, \"%u, %u\", v_short, v_short2);\n\t\tbreak;\n\tcase EXIF_TAG_SUBJECT_AREA:\n\t\tCF (e, EXIF_FORMAT_SHORT, val, maxlen);\n\t\tswitch (e->components) {\n\t\tcase 2:\n\t\t\tv_short = exif_get_short (e->data, o);\n\t\t\tv_short2 = exif_get_short (e->data + 2, o);\n\t\t\tsnprintf (val, maxlen, \"(x,y) = (%i,%i)\",\n\t\t\t\t v_short, v_short2);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tv_short = exif_get_short (e->data, o);\n\t\t\tv_short2 = exif_get_short (e->data + 2, o);\n\t\t\tv_short3 = exif_get_short (e->data + 4, o);\n\t\t\tsnprintf (val, maxlen, _(\"Within distance %i of \"\n\t\t\t\t\"(x,y) = (%i,%i)\"), v_short3, v_short,\n\t\t\t\tv_short2);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tv_short = exif_get_short (e->data, o);\n\t\t\tv_short2 = exif_get_short (e->data + 2, o);\n\t\t\tv_short3 = exif_get_short (e->data + 4, o);\n\t\t\tv_short4 = exif_get_short (e->data + 6, o);\n\t\t\tsnprintf (val, maxlen, _(\"Within rectangle \"\n\t\t\t\t\"(width %i, height %i) around \"\n\t\t\t\t\"(x,y) = (%i,%i)\"), v_short3, v_short4,\n\t\t\t\tv_short, v_short2);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tsnprintf (val, maxlen, _(\"Unexpected number \"\n\t\t\t\t\"of components (%li, expected 2, 3, or 4).\"),\n\t\t\t\te->components);\t\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_GPS_VERSION_ID:\n\t\t/* This is only valid in the GPS IFD */\n\t\tCF (e, EXIF_FORMAT_BYTE, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tsnprintf (val, maxlen, \"%u\", v_byte);\n\t\tfor (i = 1; i < e->components; i++) {\n\t\t\tv_byte = e->data[i];\n\t\t\tsnprintf (b, sizeof (b), \".%u\", v_byte);\n\t\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_INTEROPERABILITY_VERSION:\n\t/* a.k.a. case EXIF_TAG_GPS_LATITUDE: */\n\t\t/* This tag occurs in EXIF_IFD_INTEROPERABILITY */\n\t\tif (e->format == EXIF_FORMAT_UNDEFINED) {\n\t\t\tstrncpy (val, (char *) e->data, MIN (maxlen-1, e->size));\n\t\t\tbreak;\n\t\t}\n\t\t/* EXIF_TAG_GPS_LATITUDE is the same numerically as\n\t\t * EXIF_TAG_INTEROPERABILITY_VERSION but in EXIF_IFD_GPS\n\t\t */\n\t\texif_entry_format_value(e, val, maxlen);\n\t\tbreak;\n\tcase EXIF_TAG_GPS_ALTITUDE_REF:\n\t\t/* This is only valid in the GPS IFD */\n\t\tCF (e, EXIF_FORMAT_BYTE, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tif (v_byte == 0)\n\t\t\tstrncpy (val, _(\"Sea level\"), maxlen-1);\n\t\telse if (v_byte == 1)\n\t\t\tstrncpy (val, _(\"Sea level reference\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_byte);\n\t\tbreak;\n\tcase EXIF_TAG_GPS_TIME_STAMP:\n\t\t/* This is only valid in the GPS IFD */\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 3, val, maxlen);\n\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\ti = v_rat.numerator / v_rat.denominator;\n\n\t\tv_rat = exif_get_rational (e->data +\n\t\t\t\t\t exif_format_get_size (e->format),\n\t\t\t\t\t o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\tj = v_rat.numerator / v_rat.denominator;\n\n\t\tv_rat = exif_get_rational (e->data +\n\t\t\t\t\t 2*exif_format_get_size (e->format),\n\t\t\t\t\t o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"%02u:%02u:%05.2f\", i, j, d);\n\t\tbreak;\n\n\tcase EXIF_TAG_METERING_MODE:\n\tcase EXIF_TAG_COMPRESSION:\n\tcase EXIF_TAG_LIGHT_SOURCE:\n\tcase EXIF_TAG_FOCAL_PLANE_RESOLUTION_UNIT:\n\tcase EXIF_TAG_RESOLUTION_UNIT:\n\tcase EXIF_TAG_EXPOSURE_PROGRAM:\n\tcase EXIF_TAG_FLASH:\n\tcase EXIF_TAG_SUBJECT_DISTANCE_RANGE:\n\tcase EXIF_TAG_COLOR_SPACE:\n\t\tCF (e,EXIF_FORMAT_SHORT, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_short = exif_get_short (e->data, o);\n\n\t\t/* Search the tag */\n\t\tfor (i = 0; list2[i].tag && (list2[i].tag != e->tag); i++);\n\t\tif (!list2[i].tag) {\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_short);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find the value */\n\t\tfor (j = 0; list2[i].elem[j].values[0] &&\n\t\t\t (list2[i].elem[j].index < v_short); j++);\n\t\tif (list2[i].elem[j].index != v_short) {\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_short);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find a short enough value */\n\t\tmemset (val, 0, maxlen);\n\t\tfor (k = 0; list2[i].elem[j].values[k]; k++) {\n\t\t\tsize_t l = strlen (_(list2[i].elem[j].values[k]));\n\t\t\tif ((maxlen > l) && (strlen (val) < l))\n\t\t\t\tstrncpy (val, _(list2[i].elem[j].values[k]), maxlen-1);\n\t\t}\n\t\tif (!val[0]) snprintf (val, maxlen, \"%i\", v_short);\n\n\t\tbreak;\n\n\tcase EXIF_TAG_PLANAR_CONFIGURATION:\n\tcase EXIF_TAG_SENSING_METHOD:\n\tcase EXIF_TAG_ORIENTATION:\n\tcase EXIF_TAG_YCBCR_POSITIONING:\n\tcase EXIF_TAG_PHOTOMETRIC_INTERPRETATION:\n\tcase EXIF_TAG_CUSTOM_RENDERED:\n\tcase EXIF_TAG_EXPOSURE_MODE:\n\tcase EXIF_TAG_WHITE_BALANCE:\n\tcase EXIF_TAG_SCENE_CAPTURE_TYPE:\n\tcase EXIF_TAG_GAIN_CONTROL:\n\tcase EXIF_TAG_SATURATION:\n\tcase EXIF_TAG_CONTRAST:\n\tcase EXIF_TAG_SHARPNESS:\n\t\tCF (e, EXIF_FORMAT_SHORT, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_short = exif_get_short (e->data, o);\n\n\t\t/* Search the tag */\n\t\tfor (i = 0; list[i].tag && (list[i].tag != e->tag); i++);\n\t\tif (!list[i].tag) {\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_short);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find the value */\n\t\tfor (j = 0; list[i].strings[j] && (j < v_short); j++);\n\t\tif (!list[i].strings[j])\n\t\t\tsnprintf (val, maxlen, \"%i\", v_short);\n\t\telse if (!*list[i].strings[j])\n\t\t\tsnprintf (val, maxlen, _(\"Unknown value %i\"), v_short);\n\t\telse\n\t\t\tstrncpy (val, _(list[i].strings[j]), maxlen-1);\n\t\tbreak;\n\n\tcase EXIF_TAG_XP_TITLE:\n\tcase EXIF_TAG_XP_COMMENT:\n\tcase EXIF_TAG_XP_AUTHOR:\n\tcase EXIF_TAG_XP_KEYWORDS:\n\tcase EXIF_TAG_XP_SUBJECT:\n\t{\n\t\tunsigned char *utf16;\n\n\t\t/* Sanity check the size to prevent overflow */\n\t\tif (e->size+sizeof(uint16_t)+1 < e->size) break;\n\n\t\t/* The tag may not be U+0000-terminated , so make a local\n\t\t U+0000-terminated copy before converting it */\n\t\tutf16 = exif_mem_alloc (e->priv->mem, e->size+sizeof(uint16_t)+1);\n\t\tif (!utf16) break;\n\t\tmemcpy(utf16, e->data, e->size);\n\n\t\t/* NUL terminate the string. If the size is odd (which isn't possible\n\t\t * for a valid UTF16 string), then this will overwrite the high byte of\n\t\t * the final half word, plus add a full zero NUL word at the end.\n\t\t */\n\t\tutf16[e->size] = 0;\n\t\tutf16[e->size+1] = 0;\n\t\tutf16[e->size+2] = 0;\n\n\t\t/* Warning! The texts are converted from UTF16 to UTF8 */\n\t\t/* FIXME: use iconv to convert into the locale encoding */\n\t\texif_convert_utf16_to_utf8(val, utf16, maxlen);\n\t\texif_mem_free(e->priv->mem, utf16);\n\t\tbreak;\n\t}\n\n\tdefault:\n\t\t/* Use a generic value formatting */\n\t\texif_entry_format_value(e, val, maxlen);\n\t}\n\n\treturn val;\n}", "project": "libexif", "hash": 41736839540103750314907754428693931445, "size": 571, "commit_id": "9266d14b5ca4e29b970fa03272318e5f99386e06", "message": "fixed a incorrect overflow check that could be optimized away.\n\ninspired by:\nhttps://android.googlesource.com/platform/external/libexif/+/8e7345f3bc0bad06ac369d6cbc1124c8ceaf7d4b\n\nhttps://source.android.com/security/bulletin/2020-11-01\n\nCVE-2020-0452", "target": 1, "dataset": "other", "idx": 206645} {"func": "exif_entry_get_value (ExifEntry *e, char *val, unsigned int maxlen)\n{\n\tunsigned int i, j, k;\n\tExifShort v_short, v_short2, v_short3, v_short4;\n\tExifByte v_byte;\n\tExifRational v_rat;\n\tExifSRational v_srat;\n\tchar b[64];\n\tconst char *c;\n\tExifByteOrder o;\n\tdouble d;\n\tExifEntry *entry;\n\tstatic const struct {\n\t\tchar label[5];\n\t\tchar major, minor;\n\t} versions[] = {\n\t\t{\"0110\", 1, 1},\n\t\t{\"0120\", 1, 2},\n\t\t{\"0200\", 2, 0},\n\t\t{\"0210\", 2, 1},\n\t\t{\"0220\", 2, 2},\n\t\t{\"0221\", 2, 21},\n\t\t{\"0230\", 2, 3},\n\t\t{\"\" , 0, 0}\n\t};\n\n\t(void) bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);\n\n\tif (!e || !e->parent || !e->parent->parent || !maxlen || !val)\n\t\treturn val;\n\n\t/* make sure the returned string is zero terminated */\n\t/* FIXME: this is inefficient in the case of long buffers and should\n\t * instead be taken care of on each write instead. */\n\tmemset (val, 0, maxlen);\n\n\t/* We need the byte order */\n\to = exif_data_get_byte_order (e->parent->parent);\n\n\t/* Sanity check */\n\tif (e->size != e->components * exif_format_get_size (e->format)) {\n\t\tsnprintf (val, maxlen, _(\"Invalid size of entry (%i, \"\n\t\t\t\"expected %li x %i).\"), e->size, e->components,\n\t\t\t\texif_format_get_size (e->format));\n\t\treturn val;\n\t}\n\n\tswitch (e->tag) {\n\tcase EXIF_TAG_USER_COMMENT:\n\n\t\t/*\n\t\t * The specification says UNDEFINED, but some\n\t\t * manufacturers don't care and use ASCII. If this is the\n\t\t * case here, only refuse to read it if there is no chance\n\t\t * of finding readable data.\n\t\t */\n\t\tif ((e->format != EXIF_FORMAT_ASCII) || \n\t\t (e->size <= 8) ||\n\t\t ( memcmp (e->data, \"ASCII\\0\\0\\0\" , 8) &&\n\t\t memcmp (e->data, \"UNICODE\\0\" , 8) &&\n\t\t memcmp (e->data, \"JIS\\0\\0\\0\\0\\0\", 8) &&\n\t\t memcmp (e->data, \"\\0\\0\\0\\0\\0\\0\\0\\0\", 8)))\n\t\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\n\t\t/*\n\t\t * Note that, according to the specification (V2.1, p 40),\n\t\t * the user comment field does not have to be \n\t\t * NULL terminated.\n\t\t */\n\t\tif ((e->size >= 8) && !memcmp (e->data, \"ASCII\\0\\0\\0\", 8)) {\n\t\t\tstrncpy (val, (char *) e->data + 8, MIN (e->size - 8, maxlen-1));\n\t\t\tbreak;\n\t\t}\n\t\tif ((e->size >= 8) && !memcmp (e->data, \"UNICODE\\0\", 8)) {\n\t\t\tstrncpy (val, _(\"Unsupported UNICODE string\"), maxlen-1);\n\t\t/* FIXME: use iconv to convert into the locale encoding.\n\t\t * EXIF 2.2 implies (but does not say) that this encoding is\n\t\t * UCS-2.\n\t\t */\n\t\t\tbreak;\n\t\t}\n\t\tif ((e->size >= 8) && !memcmp (e->data, \"JIS\\0\\0\\0\\0\\0\", 8)) {\n\t\t\tstrncpy (val, _(\"Unsupported JIS string\"), maxlen-1);\n\t\t/* FIXME: use iconv to convert into the locale encoding */\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Check if there is really some information in the tag. */\n\t\tfor (i = 0; (i < e->size) &&\n\t\t\t (!e->data[i] || (e->data[i] == ' ')); i++);\n\t\tif (i == e->size) break;\n\n\t\t/*\n\t\t * If we reach this point, the tag does not\n \t\t * comply with the standard but seems to contain data.\n\t\t * Print as much as possible.\n\t\t * Note: make sure we do not overwrite the final \\0 at maxlen-1\n\t\t */\n\t\texif_entry_log (e, EXIF_LOG_CODE_DEBUG,\n\t\t\t_(\"Tag UserComment contains data but is \"\n\t\t\t \"against specification.\"));\n \t\tfor (j = 0; (i < e->size) && (j < maxlen-1); i++, j++) {\n\t\t\texif_entry_log (e, EXIF_LOG_CODE_DEBUG,\n\t\t\t\t_(\"Byte at position %i: 0x%02x\"), i, e->data[i]);\n \t\t\tval[j] = isprint (e->data[i]) ? e->data[i] : '.';\n\t\t}\n\t\tbreak;\n\n\tcase EXIF_TAG_EXIF_VERSION:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tstrncpy (val, _(\"Unknown Exif Version\"), maxlen-1);\n\t\tfor (i = 0; *versions[i].label; i++) {\n\t\t\tif (!memcmp (e->data, versions[i].label, 4)) {\n \t\t\t\tsnprintf (val, maxlen,\n\t\t\t\t\t_(\"Exif Version %d.%d\"),\n\t\t\t\t\tversions[i].major,\n\t\t\t\t\tversions[i].minor);\n \t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_FLASH_PIX_VERSION:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tif (!memcmp (e->data, \"0100\", 4))\n\t\t\tstrncpy (val, _(\"FlashPix Version 1.0\"), maxlen-1);\n\t\telse if (!memcmp (e->data, \"0101\", 4))\n\t\t\tstrncpy (val, _(\"FlashPix Version 1.01\"), maxlen-1);\n\t\telse\n\t\t\tstrncpy (val, _(\"Unknown FlashPix Version\"), maxlen-1);\n\t\tbreak;\n\tcase EXIF_TAG_COPYRIGHT:\n\t\tCF (e, EXIF_FORMAT_ASCII, val, maxlen);\n\n\t\t/*\n\t\t * First part: Photographer.\n\t\t * Some cameras store a string like \" \" here. Ignore it.\n\t\t * Remember that a corrupted tag might not be NUL-terminated\n\t\t */\n\t\tif (e->size && e->data && match_repeated_char(e->data, ' ', e->size))\n\t\t\tstrncpy (val, (char *) e->data, MIN (maxlen-1, e->size));\n\t\telse\n\t\t\tstrncpy (val, _(\"[None]\"), maxlen-1);\n\t\tstrncat (val, \" \", maxlen-1 - strlen (val));\n\t\tstrncat (val, _(\"(Photographer)\"), maxlen-1 - strlen (val));\n\n\t\t/* Second part: Editor. */\n\t\tstrncat (val, \" - \", maxlen-1 - strlen (val));\n\t\tk = 0;\n\t\tif (e->size && e->data) {\n\t\t\tconst unsigned char *tagdata = memchr(e->data, 0, e->size);\n\t\t\tif (tagdata++) {\n\t\t\t\tunsigned int editor_ofs = tagdata - e->data;\n\t\t\t\tunsigned int remaining = e->size - editor_ofs;\n\t\t\t\tif (match_repeated_char(tagdata, ' ', remaining)) {\n\t\t\t\t\tstrncat (val, (const char*)tagdata, MIN (maxlen-1 - strlen (val), remaining));\n\t\t\t\t\t++k;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!k)\n\t\t\tstrncat (val, _(\"[None]\"), maxlen-1 - strlen (val));\n\t\tstrncat (val, \" \", maxlen-1 - strlen (val));\n\t\tstrncat (val, _(\"(Editor)\"), maxlen-1 - strlen (val));\n\n\t\tbreak;\n\tcase EXIF_TAG_FNUMBER:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"f/%.01f\", d);\n\t\tbreak;\n\tcase EXIF_TAG_APERTURE_VALUE:\n\tcase EXIF_TAG_MAX_APERTURE_VALUE:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator || (0x80000000 == v_rat.numerator)) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tsnprintf (b, sizeof (b), _(\" (f/%.01f)\"), pow (2, d / 2.));\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_FOCAL_LENGTH:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\n\t\t/*\n\t\t * For calculation of the 35mm equivalent,\n\t\t * Minolta cameras need a multiplier that depends on the\n\t\t * camera model.\n\t\t */\n\t\td = 0.;\n\t\tentry = exif_content_get_entry (\n\t\t\te->parent->parent->ifd[EXIF_IFD_0], EXIF_TAG_MAKE);\n\t\tif (entry && entry->data && entry->size >= 7 &&\n\t\t !strncmp ((char *)entry->data, \"Minolta\", 7)) {\n\t\t\tentry = exif_content_get_entry (\n\t\t\t\t\te->parent->parent->ifd[EXIF_IFD_0],\n\t\t\t\t\tEXIF_TAG_MODEL);\n\t\t\tif (entry && entry->data && entry->size >= 8) {\n\t\t\t\tif (!strncmp ((char *)entry->data, \"DiMAGE 7\", 8))\n\t\t\t\t\td = 3.9;\n\t\t\t\telse if (!strncmp ((char *)entry->data, \"DiMAGE 5\", 8))\n\t\t\t\t\td = 4.9;\n\t\t\t}\n\t\t}\n\t\tif (d)\n\t\t\tsnprintf (b, sizeof (b), _(\" (35 equivalent: %.0f mm)\"),\n\t\t\t\t (d * (double) v_rat.numerator /\n\t\t\t\t (double) v_rat.denominator));\n\t\telse\n\t\t\tb[0] = 0;\n\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"%.1f mm\", d);\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_SUBJECT_DISTANCE:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"%.1f m\", d);\n\t\tbreak;\n\tcase EXIF_TAG_EXPOSURE_TIME:\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tif (d < 1 && d)\n\t\t\tsnprintf (val, maxlen, _(\"1/%.0f\"), 1. / d);\n\t\telse\n\t\t\tsnprintf (val, maxlen, \"%.0f\", d);\n\t\tstrncat (val, _(\" sec.\"), maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_SHUTTER_SPEED_VALUE:\n\t\tCF (e, EXIF_FORMAT_SRATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_srat = exif_get_srational (e->data, o);\n\t\tif (!v_srat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_srat.numerator / (double) v_srat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tif (pow (2, d))\n\t\t\td = 1. / pow (2, d);\n\t\tif (d < 1 && d)\n\t\t snprintf (b, sizeof (b), _(\" (1/%.0f sec.)\"), 1. / d);\n\t\telse\n\t\t snprintf (b, sizeof (b), _(\" (%.0f sec.)\"), d);\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_BRIGHTNESS_VALUE:\n\t\tCF (e, EXIF_FORMAT_SRATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_srat = exif_get_srational (e->data, o);\n\t\tif (!v_srat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_srat.numerator / (double) v_srat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tsnprintf (b, sizeof (b), _(\" (%.02f cd/m^2)\"),\n\t\t\t1. / (M_PI * 0.3048 * 0.3048) * pow (2, d));\n\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\tbreak;\n\tcase EXIF_TAG_FILE_SOURCE:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tif (v_byte == 3)\n\t\t\tstrncpy (val, _(\"DSC\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_byte);\n\t\tbreak;\n\tcase EXIF_TAG_COMPONENTS_CONFIGURATION:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tfor (i = 0; i < 4; i++) {\n\t\t\tswitch (e->data[i]) {\n\t\t\tcase 0: c = _(\"-\"); break;\n\t\t\tcase 1: c = _(\"Y\"); break;\n\t\t\tcase 2: c = _(\"Cb\"); break;\n\t\t\tcase 3: c = _(\"Cr\"); break;\n\t\t\tcase 4: c = _(\"R\"); break;\n\t\t\tcase 5: c = _(\"G\"); break;\n\t\t\tcase 6: c = _(\"B\"); break;\n\t\t\tdefault: c = _(\"Reserved\"); break;\n\t\t\t}\n\t\t\tstrncat (val, c, maxlen-1 - strlen (val));\n\t\t\tif (i < 3)\n\t\t\t\tstrncat (val, \" \", maxlen-1 - strlen (val));\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_EXPOSURE_BIAS_VALUE:\n\t\tCF (e, EXIF_FORMAT_SRATIONAL, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_srat = exif_get_srational (e->data, o);\n\t\tif (!v_srat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_srat.numerator / (double) v_srat.denominator;\n\t\tsnprintf (val, maxlen, _(\"%.02f EV\"), d);\n\t\tbreak;\n\tcase EXIF_TAG_SCENE_TYPE:\n\t\tCF (e, EXIF_FORMAT_UNDEFINED, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tif (v_byte == 1)\n\t\t\tstrncpy (val, _(\"Directly photographed\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_byte);\n\t\tbreak;\n\tcase EXIF_TAG_YCBCR_SUB_SAMPLING:\n\t\tCF (e, EXIF_FORMAT_SHORT, val, maxlen);\n\t\tCC (e, 2, val, maxlen);\n\t\tv_short = exif_get_short (e->data, o);\n\t\tv_short2 = exif_get_short (\n\t\t\te->data + exif_format_get_size (e->format),\n\t\t\to);\n\t\tif ((v_short == 2) && (v_short2 == 1))\n\t\t\tstrncpy (val, _(\"YCbCr4:2:2\"), maxlen-1);\n\t\telse if ((v_short == 2) && (v_short2 == 2))\n\t\t\tstrncpy (val, _(\"YCbCr4:2:0\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, \"%u, %u\", v_short, v_short2);\n\t\tbreak;\n\tcase EXIF_TAG_SUBJECT_AREA:\n\t\tCF (e, EXIF_FORMAT_SHORT, val, maxlen);\n\t\tswitch (e->components) {\n\t\tcase 2:\n\t\t\tv_short = exif_get_short (e->data, o);\n\t\t\tv_short2 = exif_get_short (e->data + 2, o);\n\t\t\tsnprintf (val, maxlen, \"(x,y) = (%i,%i)\",\n\t\t\t\t v_short, v_short2);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tv_short = exif_get_short (e->data, o);\n\t\t\tv_short2 = exif_get_short (e->data + 2, o);\n\t\t\tv_short3 = exif_get_short (e->data + 4, o);\n\t\t\tsnprintf (val, maxlen, _(\"Within distance %i of \"\n\t\t\t\t\"(x,y) = (%i,%i)\"), v_short3, v_short,\n\t\t\t\tv_short2);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tv_short = exif_get_short (e->data, o);\n\t\t\tv_short2 = exif_get_short (e->data + 2, o);\n\t\t\tv_short3 = exif_get_short (e->data + 4, o);\n\t\t\tv_short4 = exif_get_short (e->data + 6, o);\n\t\t\tsnprintf (val, maxlen, _(\"Within rectangle \"\n\t\t\t\t\"(width %i, height %i) around \"\n\t\t\t\t\"(x,y) = (%i,%i)\"), v_short3, v_short4,\n\t\t\t\tv_short, v_short2);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tsnprintf (val, maxlen, _(\"Unexpected number \"\n\t\t\t\t\"of components (%li, expected 2, 3, or 4).\"),\n\t\t\t\te->components);\t\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_GPS_VERSION_ID:\n\t\t/* This is only valid in the GPS IFD */\n\t\tCF (e, EXIF_FORMAT_BYTE, val, maxlen);\n\t\tCC (e, 4, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tsnprintf (val, maxlen, \"%u\", v_byte);\n\t\tfor (i = 1; i < e->components; i++) {\n\t\t\tv_byte = e->data[i];\n\t\t\tsnprintf (b, sizeof (b), \".%u\", v_byte);\n\t\t\tstrncat (val, b, maxlen-1 - strlen (val));\n\t\t}\n\t\tbreak;\n\tcase EXIF_TAG_INTEROPERABILITY_VERSION:\n\t/* a.k.a. case EXIF_TAG_GPS_LATITUDE: */\n\t\t/* This tag occurs in EXIF_IFD_INTEROPERABILITY */\n\t\tif (e->format == EXIF_FORMAT_UNDEFINED) {\n\t\t\tstrncpy (val, (char *) e->data, MIN (maxlen-1, e->size));\n\t\t\tbreak;\n\t\t}\n\t\t/* EXIF_TAG_GPS_LATITUDE is the same numerically as\n\t\t * EXIF_TAG_INTEROPERABILITY_VERSION but in EXIF_IFD_GPS\n\t\t */\n\t\texif_entry_format_value(e, val, maxlen);\n\t\tbreak;\n\tcase EXIF_TAG_GPS_ALTITUDE_REF:\n\t\t/* This is only valid in the GPS IFD */\n\t\tCF (e, EXIF_FORMAT_BYTE, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_byte = e->data[0];\n\t\tif (v_byte == 0)\n\t\t\tstrncpy (val, _(\"Sea level\"), maxlen-1);\n\t\telse if (v_byte == 1)\n\t\t\tstrncpy (val, _(\"Sea level reference\"), maxlen-1);\n\t\telse\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_byte);\n\t\tbreak;\n\tcase EXIF_TAG_GPS_TIME_STAMP:\n\t\t/* This is only valid in the GPS IFD */\n\t\tCF (e, EXIF_FORMAT_RATIONAL, val, maxlen);\n\t\tCC (e, 3, val, maxlen);\n\n\t\tv_rat = exif_get_rational (e->data, o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\ti = v_rat.numerator / v_rat.denominator;\n\n\t\tv_rat = exif_get_rational (e->data +\n\t\t\t\t\t exif_format_get_size (e->format),\n\t\t\t\t\t o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\tj = v_rat.numerator / v_rat.denominator;\n\n\t\tv_rat = exif_get_rational (e->data +\n\t\t\t\t\t 2*exif_format_get_size (e->format),\n\t\t\t\t\t o);\n\t\tif (!v_rat.denominator) {\n\t\t\texif_entry_format_value(e, val, maxlen);\n\t\t\tbreak;\n\t\t}\n\t\td = (double) v_rat.numerator / (double) v_rat.denominator;\n\t\tsnprintf (val, maxlen, \"%02u:%02u:%05.2f\", i, j, d);\n\t\tbreak;\n\n\tcase EXIF_TAG_METERING_MODE:\n\tcase EXIF_TAG_COMPRESSION:\n\tcase EXIF_TAG_LIGHT_SOURCE:\n\tcase EXIF_TAG_FOCAL_PLANE_RESOLUTION_UNIT:\n\tcase EXIF_TAG_RESOLUTION_UNIT:\n\tcase EXIF_TAG_EXPOSURE_PROGRAM:\n\tcase EXIF_TAG_FLASH:\n\tcase EXIF_TAG_SUBJECT_DISTANCE_RANGE:\n\tcase EXIF_TAG_COLOR_SPACE:\n\t\tCF (e,EXIF_FORMAT_SHORT, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_short = exif_get_short (e->data, o);\n\n\t\t/* Search the tag */\n\t\tfor (i = 0; list2[i].tag && (list2[i].tag != e->tag); i++);\n\t\tif (!list2[i].tag) {\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_short);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find the value */\n\t\tfor (j = 0; list2[i].elem[j].values[0] &&\n\t\t\t (list2[i].elem[j].index < v_short); j++);\n\t\tif (list2[i].elem[j].index != v_short) {\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_short);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find a short enough value */\n\t\tmemset (val, 0, maxlen);\n\t\tfor (k = 0; list2[i].elem[j].values[k]; k++) {\n\t\t\tsize_t l = strlen (_(list2[i].elem[j].values[k]));\n\t\t\tif ((maxlen > l) && (strlen (val) < l))\n\t\t\t\tstrncpy (val, _(list2[i].elem[j].values[k]), maxlen-1);\n\t\t}\n\t\tif (!val[0]) snprintf (val, maxlen, \"%i\", v_short);\n\n\t\tbreak;\n\n\tcase EXIF_TAG_PLANAR_CONFIGURATION:\n\tcase EXIF_TAG_SENSING_METHOD:\n\tcase EXIF_TAG_ORIENTATION:\n\tcase EXIF_TAG_YCBCR_POSITIONING:\n\tcase EXIF_TAG_PHOTOMETRIC_INTERPRETATION:\n\tcase EXIF_TAG_CUSTOM_RENDERED:\n\tcase EXIF_TAG_EXPOSURE_MODE:\n\tcase EXIF_TAG_WHITE_BALANCE:\n\tcase EXIF_TAG_SCENE_CAPTURE_TYPE:\n\tcase EXIF_TAG_GAIN_CONTROL:\n\tcase EXIF_TAG_SATURATION:\n\tcase EXIF_TAG_CONTRAST:\n\tcase EXIF_TAG_SHARPNESS:\n\t\tCF (e, EXIF_FORMAT_SHORT, val, maxlen);\n\t\tCC (e, 1, val, maxlen);\n\t\tv_short = exif_get_short (e->data, o);\n\n\t\t/* Search the tag */\n\t\tfor (i = 0; list[i].tag && (list[i].tag != e->tag); i++);\n\t\tif (!list[i].tag) {\n\t\t\tsnprintf (val, maxlen, _(\"Internal error (unknown \"\n\t\t\t\t \"value %i)\"), v_short);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Find the value */\n\t\tfor (j = 0; list[i].strings[j] && (j < v_short); j++);\n\t\tif (!list[i].strings[j])\n\t\t\tsnprintf (val, maxlen, \"%i\", v_short);\n\t\telse if (!*list[i].strings[j])\n\t\t\tsnprintf (val, maxlen, _(\"Unknown value %i\"), v_short);\n\t\telse\n\t\t\tstrncpy (val, _(list[i].strings[j]), maxlen-1);\n\t\tbreak;\n\n\tcase EXIF_TAG_XP_TITLE:\n\tcase EXIF_TAG_XP_COMMENT:\n\tcase EXIF_TAG_XP_AUTHOR:\n\tcase EXIF_TAG_XP_KEYWORDS:\n\tcase EXIF_TAG_XP_SUBJECT:\n\t{\n\t\tunsigned char *utf16;\n\n\t\t/* Sanity check the size to prevent overflow. Note EXIF files are 64kb at most. */\n\t\tif (e->size >= 65536 - sizeof(uint16_t)*2) break;\n\n\t\t/* The tag may not be U+0000-terminated , so make a local\n\t\t U+0000-terminated copy before converting it */\n\t\tutf16 = exif_mem_alloc (e->priv->mem, e->size+sizeof(uint16_t)+1);\n\t\tif (!utf16) break;\n\t\tmemcpy(utf16, e->data, e->size);\n\n\t\t/* NUL terminate the string. If the size is odd (which isn't possible\n\t\t * for a valid UTF16 string), then this will overwrite the high byte of\n\t\t * the final half word, plus add a full zero NUL word at the end.\n\t\t */\n\t\tutf16[e->size] = 0;\n\t\tutf16[e->size+1] = 0;\n\t\tutf16[e->size+2] = 0;\n\n\t\t/* Warning! The texts are converted from UTF16 to UTF8 */\n\t\t/* FIXME: use iconv to convert into the locale encoding */\n\t\texif_convert_utf16_to_utf8(val, utf16, maxlen);\n\t\texif_mem_free(e->priv->mem, utf16);\n\t\tbreak;\n\t}\n\n\tdefault:\n\t\t/* Use a generic value formatting */\n\t\texif_entry_format_value(e, val, maxlen);\n\t}\n\n\treturn val;\n}", "project": "libexif", "hash": 96196385413825038531426685586673546332, "size": 571, "commit_id": "9266d14b5ca4e29b970fa03272318e5f99386e06", "message": "fixed a incorrect overflow check that could be optimized away.\n\ninspired by:\nhttps://android.googlesource.com/platform/external/libexif/+/8e7345f3bc0bad06ac369d6cbc1124c8ceaf7d4b\n\nhttps://source.android.com/security/bulletin/2020-11-01\n\nCVE-2020-0452", "target": 0, "dataset": "other", "idx": 384338} {"func": "static struct scatterlist *alloc_sgtable(int size)\n{\n\tint alloc_size, nents, i;\n\tstruct page *new_page;\n\tstruct scatterlist *iter;\n\tstruct scatterlist *table;\n\n\tnents = DIV_ROUND_UP(size, PAGE_SIZE);\n\ttable = kcalloc(nents, sizeof(*table), GFP_KERNEL);\n\tif (!table)\n\t\treturn NULL;\n\tsg_init_table(table, nents);\n\titer = table;\n\tfor_each_sg(table, iter, sg_nents(table), i) {\n\t\tnew_page = alloc_page(GFP_KERNEL);\n\t\tif (!new_page) {\n\t\t\t/* release all previous allocated pages in the table */\n\t\t\titer = table;\n\t\t\tfor_each_sg(table, iter, sg_nents(table), i) {\n\t\t\t\tnew_page = sg_page(iter);\n\t\t\t\tif (new_page)\n\t\t\t\t\t__free_page(new_page);\n\t\t\t}\n\t\t\treturn NULL;\n\t\t}\n\t\talloc_size = min_t(int, size, PAGE_SIZE);\n\t\tsize -= PAGE_SIZE;\n\t\tsg_set_page(iter, new_page, alloc_size, 0);\n\t}\n\treturn table;\n}", "project": "linux", "hash": 155226500233023096269286137238523446812, "size": 31, "commit_id": "b4b814fec1a5a849383f7b3886b654a13abbda7d", "message": "iwlwifi: dbg_ini: fix memory leak in alloc_sgtable\n\nIn alloc_sgtable if alloc_page fails, the alocated table should be\nreleased.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Luca Coelho ", "target": 1, "dataset": "other", "idx": 206661} {"func": "static struct scatterlist *alloc_sgtable(int size)\n{\n\tint alloc_size, nents, i;\n\tstruct page *new_page;\n\tstruct scatterlist *iter;\n\tstruct scatterlist *table;\n\n\tnents = DIV_ROUND_UP(size, PAGE_SIZE);\n\ttable = kcalloc(nents, sizeof(*table), GFP_KERNEL);\n\tif (!table)\n\t\treturn NULL;\n\tsg_init_table(table, nents);\n\titer = table;\n\tfor_each_sg(table, iter, sg_nents(table), i) {\n\t\tnew_page = alloc_page(GFP_KERNEL);\n\t\tif (!new_page) {\n\t\t\t/* release all previous allocated pages in the table */\n\t\t\titer = table;\n\t\t\tfor_each_sg(table, iter, sg_nents(table), i) {\n\t\t\t\tnew_page = sg_page(iter);\n\t\t\t\tif (new_page)\n\t\t\t\t\t__free_page(new_page);\n\t\t\t}\n\t\t\tkfree(table);\n\t\t\treturn NULL;\n\t\t}\n\t\talloc_size = min_t(int, size, PAGE_SIZE);\n\t\tsize -= PAGE_SIZE;\n\t\tsg_set_page(iter, new_page, alloc_size, 0);\n\t}\n\treturn table;\n}", "project": "linux", "hash": 158159015289832357782514537392354870835, "size": 32, "commit_id": "b4b814fec1a5a849383f7b3886b654a13abbda7d", "message": "iwlwifi: dbg_ini: fix memory leak in alloc_sgtable\n\nIn alloc_sgtable if alloc_page fails, the alocated table should be\nreleased.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Luca Coelho ", "target": 0, "dataset": "other", "idx": 384469} {"func": " size_t recv_body(char* buf, size_t max) override {\n auto& message = parser.get();\n auto& body_remaining = message.body();\n body_remaining.data = buf;\n body_remaining.size = max;\n\n while (body_remaining.size && !parser.is_done()) {\n boost::system::error_code ec;\n http::async_read_some(stream, buffer, parser, yield[ec]);\n if (ec == http::error::partial_message ||\n ec == http::error::need_buffer) {\n break;\n }\n if (ec) {\n ldout(cct, 4) << \"failed to read body: \" << ec.message() << dendl;\n throw rgw::io::Exception(ec.value(), std::system_category());\n }\n }\n return max - body_remaining.size;\n }", "project": "ceph", "hash": 239302242093544263117469919869262423971, "size": 20, "commit_id": "ff72c50a2c43c57aead933eb4903ad1ca6d1748a", "message": "rgw: improve beast\n\nAvoid leaking connections that had partially-consumed\nclient data on unexpected disconnect.\n\nResolves CVE-2020-1700 (moderate impact flaw).\n\nFixes: https://tracker.ceph.com/issues/42531\n\nSigned-off-by: Or Friedmann \nSigned-off-by: Matt Benjamin ", "target": 1, "dataset": "other", "idx": 206666} {"func": " size_t recv_body(char* buf, size_t max) override {\n auto& message = parser.get();\n auto& body_remaining = message.body();\n body_remaining.data = buf;\n body_remaining.size = max;\n\n while (body_remaining.size && !parser.is_done()) {\n boost::system::error_code ec;\n http::async_read_some(stream, buffer, parser, yield[ec]);\n if (ec == http::error::need_buffer) {\n break;\n }\n if (ec) {\n ldout(cct, 4) << \"failed to read body: \" << ec.message() << dendl;\n throw rgw::io::Exception(ec.value(), std::system_category());\n }\n }\n return max - body_remaining.size;\n }", "project": "ceph", "hash": 297732611702424956920389637575646123237, "size": 19, "commit_id": "ff72c50a2c43c57aead933eb4903ad1ca6d1748a", "message": "rgw: improve beast\n\nAvoid leaking connections that had partially-consumed\nclient data on unexpected disconnect.\n\nResolves CVE-2020-1700 (moderate impact flaw).\n\nFixes: https://tracker.ceph.com/issues/42531\n\nSigned-off-by: Or Friedmann \nSigned-off-by: Matt Benjamin ", "target": 0, "dataset": "other", "idx": 384543} {"func": "dissect_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)\n{\n guint8 th_off_x2; /* combines th_off and th_x2 */\n guint16 th_sum;\n guint32 th_urp;\n proto_tree *tcp_tree = NULL, *field_tree = NULL;\n proto_item *ti = NULL, *tf, *hidden_item;\n proto_item *options_item;\n proto_tree *options_tree;\n int offset = 0;\n const char *flags_str, *flags_str_first_letter;\n guint optlen;\n guint32 nxtseq = 0;\n guint reported_len;\n vec_t cksum_vec[4];\n guint32 phdr[2];\n guint16 computed_cksum;\n guint16 real_window;\n guint captured_length_remaining;\n gboolean desegment_ok;\n struct tcpinfo tcpinfo;\n struct tcpheader *tcph;\n proto_item *tf_syn = NULL, *tf_fin = NULL, *tf_rst = NULL, *scaled_pi;\n conversation_t *conv=NULL, *other_conv;\n guint32 save_last_frame = 0;\n struct tcp_analysis *tcpd=NULL;\n struct tcp_per_packet_data_t *tcppd=NULL;\n proto_item *item;\n proto_tree *checksum_tree;\n gboolean icmp_ip = FALSE;\n\n tcph = wmem_new0(wmem_packet_scope(), struct tcpheader);\n tcph->th_sport = tvb_get_ntohs(tvb, offset);\n tcph->th_dport = tvb_get_ntohs(tvb, offset + 2);\n copy_address_shallow(&tcph->ip_src, &pinfo->src);\n copy_address_shallow(&tcph->ip_dst, &pinfo->dst);\n\n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"TCP\");\n col_clear(pinfo->cinfo, COL_INFO);\n col_append_ports(pinfo->cinfo, COL_INFO, PT_TCP, tcph->th_sport, tcph->th_dport);\n\n if (tree) {\n ti = proto_tree_add_item(tree, proto_tcp, tvb, 0, -1, ENC_NA);\n if (tcp_summary_in_tree) {\n proto_item_append_text(ti, \", Src Port: %s, Dst Port: %s\",\n port_with_resolution_to_str(wmem_packet_scope(), PT_TCP, tcph->th_sport),\n port_with_resolution_to_str(wmem_packet_scope(), PT_TCP, tcph->th_dport));\n }\n tcp_tree = proto_item_add_subtree(ti, ett_tcp);\n p_add_proto_data(pinfo->pool, pinfo, proto_tcp, pinfo->curr_layer_num, tcp_tree);\n\n proto_tree_add_item(tcp_tree, hf_tcp_srcport, tvb, offset, 2, ENC_BIG_ENDIAN);\n proto_tree_add_item(tcp_tree, hf_tcp_dstport, tvb, offset + 2, 2, ENC_BIG_ENDIAN);\n hidden_item = proto_tree_add_item(tcp_tree, hf_tcp_port, tvb, offset, 2, ENC_BIG_ENDIAN);\n PROTO_ITEM_SET_HIDDEN(hidden_item);\n hidden_item = proto_tree_add_item(tcp_tree, hf_tcp_port, tvb, offset + 2, 2, ENC_BIG_ENDIAN);\n PROTO_ITEM_SET_HIDDEN(hidden_item);\n\n /* If we're dissecting the headers of a TCP packet in an ICMP packet\n * then go ahead and put the sequence numbers in the tree now (because\n * they won't be put in later because the ICMP packet only contains up\n * to the sequence number).\n * We should only need to do this for IPv4 since IPv6 will hopefully\n * carry enough TCP payload for this dissector to put the sequence\n * numbers in via the regular code path.\n */\n {\n wmem_list_frame_t *frame;\n frame = wmem_list_frame_prev(wmem_list_tail(pinfo->layers));\n if (proto_ip == (gint) GPOINTER_TO_UINT(wmem_list_frame_data(frame))) {\n frame = wmem_list_frame_prev(frame);\n if (proto_icmp == (gint) GPOINTER_TO_UINT(wmem_list_frame_data(frame))) {\n proto_tree_add_item(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, ENC_BIG_ENDIAN);\n icmp_ip = TRUE;\n }\n }\n }\n }\n\n /* Set the source and destination port numbers as soon as we get them,\n so that they're available to the \"Follow TCP Stream\" code even if\n we throw an exception dissecting the rest of the TCP header. */\n pinfo->ptype = PT_TCP;\n pinfo->srcport = tcph->th_sport;\n pinfo->destport = tcph->th_dport;\n\n p_add_proto_data(pinfo->pool, pinfo, hf_tcp_srcport, pinfo->curr_layer_num, GUINT_TO_POINTER(tcph->th_sport));\n p_add_proto_data(pinfo->pool, pinfo, hf_tcp_dstport, pinfo->curr_layer_num, GUINT_TO_POINTER(tcph->th_dport));\n\n tcph->th_rawseq = tvb_get_ntohl(tvb, offset + 4);\n tcph->th_seq = tcph->th_rawseq;\n tcph->th_ack = tvb_get_ntohl(tvb, offset + 8);\n th_off_x2 = tvb_get_guint8(tvb, offset + 12);\n tcpinfo.flags = tcph->th_flags = tvb_get_ntohs(tvb, offset + 12) & TH_MASK;\n tcph->th_win = tvb_get_ntohs(tvb, offset + 14);\n real_window = tcph->th_win;\n tcph->th_hlen = hi_nibble(th_off_x2) * 4; /* TCP header length, in bytes */\n\n /* find(or create if needed) the conversation for this tcp session\n * This is a slight deviation from find_or_create_conversation so it's\n * done manually. This is done to save the last frame of the conversation\n * in case a new conversation is found and the previous conversation needs\n * to be adjusted,\n */\n if((conv = find_conversation_pinfo(pinfo, 0)) != NULL) {\n /* Update how far the conversation reaches */\n if (pinfo->num > conv->last_frame) {\n save_last_frame = conv->last_frame;\n conv->last_frame = pinfo->num;\n }\n }\n else {\n conv = conversation_new(pinfo->num, &pinfo->src,\n &pinfo->dst, ENDPOINT_TCP,\n pinfo->srcport, pinfo->destport, 0);\n }\n tcpd=get_tcp_conversation_data(conv,pinfo);\n\n /* If this is a SYN packet, then check if its seq-nr is different\n * from the base_seq of the retrieved conversation. If this is the\n * case, create a new conversation with the same addresses and ports\n * and set the TA_PORTS_REUSED flag. If the seq-nr is the same as\n * the base_seq, then do nothing so it will be marked as a retrans-\n * mission later.\n * XXX - Is this affected by MPTCP which can use multiple SYNs?\n */\n if(tcpd && ((tcph->th_flags&(TH_SYN|TH_ACK))==TH_SYN) &&\n (tcpd->fwd->static_flags & TCP_S_BASE_SEQ_SET) &&\n (tcph->th_seq!=tcpd->fwd->base_seq) ) {\n if (!(pinfo->fd->visited)) {\n /* Reset the last frame seen in the conversation */\n if (save_last_frame > 0)\n conv->last_frame = save_last_frame;\n\n conv=conversation_new(pinfo->num, &pinfo->src, &pinfo->dst, ENDPOINT_TCP, pinfo->srcport, pinfo->destport, 0);\n tcpd=get_tcp_conversation_data(conv,pinfo);\n }\n if(!tcpd->ta)\n tcp_analyze_get_acked_struct(pinfo->num, tcph->th_seq, tcph->th_ack, TRUE, tcpd);\n tcpd->ta->flags|=TCP_A_REUSED_PORTS;\n }\n /* If this is a SYN/ACK packet, then check if its seq-nr is different\n * from the base_seq of the retrieved conversation. If this is the\n * case, try to find a conversation with the same addresses and ports\n * and set the TA_PORTS_REUSED flag. If the seq-nr is the same as\n * the base_seq, then do nothing so it will be marked as a retrans-\n * mission later.\n * XXX - Is this affected by MPTCP which can use multiple SYNs?\n */\n if(tcpd && ((tcph->th_flags&(TH_SYN|TH_ACK))==(TH_SYN|TH_ACK)) &&\n (tcpd->fwd->static_flags & TCP_S_BASE_SEQ_SET) &&\n (tcph->th_seq!=tcpd->fwd->base_seq) ) {\n if (!(pinfo->fd->visited)) {\n /* Reset the last frame seen in the conversation */\n if (save_last_frame > 0)\n conv->last_frame = save_last_frame;\n }\n\n other_conv = find_conversation(pinfo->num, &pinfo->dst, &pinfo->src, ENDPOINT_TCP, pinfo->destport, pinfo->srcport, 0);\n if (other_conv != NULL)\n {\n conv = other_conv;\n tcpd=get_tcp_conversation_data(conv,pinfo);\n }\n\n if(!tcpd->ta)\n tcp_analyze_get_acked_struct(pinfo->num, tcph->th_seq, tcph->th_ack, TRUE, tcpd);\n tcpd->ta->flags|=TCP_A_REUSED_PORTS;\n }\n\n if (tcpd) {\n item = proto_tree_add_uint(tcp_tree, hf_tcp_stream, tvb, offset, 0, tcpd->stream);\n PROTO_ITEM_SET_GENERATED(item);\n\n /* Copy the stream index into the header as well to make it available\n * to tap listeners.\n */\n tcph->th_stream = tcpd->stream;\n }\n\n /* Do we need to calculate timestamps relative to the tcp-stream? */\n if (tcp_calculate_ts) {\n tcppd = (struct tcp_per_packet_data_t *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tcp, pinfo->curr_layer_num);\n\n /*\n * Calculate the timestamps relative to this conversation (but only on the\n * first run when frames are accessed sequentially)\n */\n if (!(pinfo->fd->visited))\n tcp_calculate_timestamps(pinfo, tcpd, tcppd);\n }\n\n /*\n * If we've been handed an IP fragment, we don't know how big the TCP\n * segment is, so don't do anything that requires that we know that.\n *\n * The same applies if we're part of an error packet. (XXX - if the\n * ICMP and ICMPv6 dissectors could set a \"this is how big the IP\n * header says it is\" length in the tvbuff, we could use that; such\n * a length might also be useful for handling packets where the IP\n * length is bigger than the actual data available in the frame; the\n * dissectors should trust that length, and then throw a\n * ReportedBoundsError exception when they go past the end of the frame.)\n *\n * We also can't determine the segment length if the reported length\n * of the TCP packet is less than the TCP header length.\n */\n reported_len = tvb_reported_length(tvb);\n\n if (!pinfo->fragmented && !pinfo->flags.in_error_pkt) {\n if (reported_len < tcph->th_hlen) {\n proto_tree_add_expert_format(tcp_tree, pinfo, &ei_tcp_short_segment, tvb, offset, 0,\n \"Short segment. Segment/fragment does not contain a full TCP header\"\n \" (might be NMAP or someone else deliberately sending unusual packets)\");\n tcph->th_have_seglen = FALSE;\n } else {\n proto_item *pi;\n\n /* Compute the length of data in this segment. */\n tcph->th_seglen = reported_len - tcph->th_hlen;\n tcph->th_have_seglen = TRUE;\n\n pi = proto_tree_add_uint(ti, hf_tcp_len, tvb, offset+12, 1, tcph->th_seglen);\n PROTO_ITEM_SET_GENERATED(pi);\n\n /* handle TCP seq# analysis parse all new segments we see */\n if(tcp_analyze_seq) {\n if(!(pinfo->fd->visited)) {\n tcp_analyze_sequence_number(pinfo, tcph->th_seq, tcph->th_ack, tcph->th_seglen, tcph->th_flags, tcph->th_win, tcpd);\n }\n if(tcpd && tcp_relative_seq) {\n (tcph->th_seq) -= tcpd->fwd->base_seq;\n if (tcph->th_flags & TH_ACK) {\n (tcph->th_ack) -= tcpd->rev->base_seq;\n }\n }\n }\n\n /* re-calculate window size, based on scaling factor */\n if (!(tcph->th_flags&TH_SYN)) { /* SYNs are never scaled */\n if (tcpd && (tcpd->fwd->win_scale>=0)) {\n (tcph->th_win)<<=tcpd->fwd->win_scale;\n }\n else {\n /* Don't have it stored, so use preference setting instead! */\n if (tcp_default_window_scaling>=0) {\n (tcph->th_win)<<=tcp_default_window_scaling;\n }\n }\n }\n\n /* Compute the sequence number of next octet after this segment. */\n nxtseq = tcph->th_seq + tcph->th_seglen;\n if ((tcph->th_flags&(TH_SYN|TH_FIN)) && (tcph->th_seglen > 0)) {\n nxtseq += 1;\n }\n }\n } else\n tcph->th_have_seglen = FALSE;\n\n flags_str = tcp_flags_to_str(wmem_packet_scope(), tcph);\n flags_str_first_letter = tcp_flags_to_str_first_letter(tcph);\n\n col_append_lstr(pinfo->cinfo, COL_INFO,\n \" [\", flags_str, \"]\",\n COL_ADD_LSTR_TERMINATOR);\n tcp_info_append_uint(pinfo, \"Seq\", tcph->th_seq);\n if (tcph->th_flags&TH_ACK)\n tcp_info_append_uint(pinfo, \"Ack\", tcph->th_ack);\n\n tcp_info_append_uint(pinfo, \"Win\", tcph->th_win);\n\n if (tcp_summary_in_tree) {\n proto_item_append_text(ti, \", Seq: %u\", tcph->th_seq);\n }\n\n if (!icmp_ip) {\n if(tcp_relative_seq && tcp_analyze_seq) {\n proto_tree_add_uint_format_value(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, tcph->th_seq, \"%u (relative sequence number)\", tcph->th_seq);\n } else {\n proto_tree_add_uint(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, tcph->th_seq);\n }\n }\n\n if (tcph->th_hlen < TCPH_MIN_LEN) {\n /* Give up at this point; we put the source and destination port in\n the tree, before fetching the header length, so that they'll\n show up if this is in the failing packet in an ICMP error packet,\n but it's now time to give up if the header length is bogus. */\n col_append_fstr(pinfo->cinfo, COL_INFO, \", bogus TCP header length (%u, must be at least %u)\",\n tcph->th_hlen, TCPH_MIN_LEN);\n if (tree) {\n tf = proto_tree_add_uint_bits_format_value(tcp_tree, hf_tcp_hdr_len, tvb, (offset + 12) << 3, 4, tcph->th_hlen,\n \"%u bytes (%u)\", tcph->th_hlen, tcph->th_hlen >> 2);\n expert_add_info_format(pinfo, tf, &ei_tcp_bogus_header_length,\n \"Bogus TCP header length (%u, must be at least %u)\", tcph->th_hlen, TCPH_MIN_LEN);\n }\n return offset+12;\n }\n\n if (tcp_summary_in_tree) {\n if(tcph->th_flags&TH_ACK) {\n proto_item_append_text(ti, \", Ack: %u\", tcph->th_ack);\n }\n if (tcph->th_have_seglen)\n proto_item_append_text(ti, \", Len: %u\", tcph->th_seglen);\n }\n proto_item_set_len(ti, tcph->th_hlen);\n if (tcph->th_have_seglen) {\n if(tcp_relative_seq && tcp_analyze_seq) {\n tf=proto_tree_add_uint_format_value(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq, \"%u (relative sequence number)\", nxtseq);\n } else {\n tf=proto_tree_add_uint(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq);\n }\n PROTO_ITEM_SET_GENERATED(tf);\n }\n\n tf = proto_tree_add_uint(tcp_tree, hf_tcp_ack, tvb, offset + 8, 4, tcph->th_ack);\n if (tcph->th_flags & TH_ACK) {\n if (tcp_relative_seq && tcp_analyze_seq) {\n proto_item_append_text(tf, \" (relative ack number)\");\n }\n } else {\n /* Note if the ACK field is non-zero */\n if (tvb_get_ntohl(tvb, offset+8) != 0) {\n expert_add_info(pinfo, tf, &ei_tcp_ack_nonzero);\n }\n }\n\n if (tree) {\n // This should be consistent with ip.hdr_len.\n proto_tree_add_uint_bits_format_value(tcp_tree, hf_tcp_hdr_len, tvb, (offset + 12) << 3, 4, tcph->th_hlen,\n \"%u bytes (%u)\", tcph->th_hlen, tcph->th_hlen>>2);\n tf = proto_tree_add_uint_format(tcp_tree, hf_tcp_flags, tvb, offset + 12, 2,\n tcph->th_flags, \"Flags: 0x%03x (%s)\", tcph->th_flags, flags_str);\n field_tree = proto_item_add_subtree(tf, ett_tcp_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_res, tvb, offset + 12, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_ns, tvb, offset + 12, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_cwr, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_ecn, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_urg, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_ack, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_push, tvb, offset + 13, 1, tcph->th_flags);\n tf_rst = proto_tree_add_boolean(field_tree, hf_tcp_flags_reset, tvb, offset + 13, 1, tcph->th_flags);\n tf_syn = proto_tree_add_boolean(field_tree, hf_tcp_flags_syn, tvb, offset + 13, 1, tcph->th_flags);\n tf_fin = proto_tree_add_boolean(field_tree, hf_tcp_flags_fin, tvb, offset + 13, 1, tcph->th_flags);\n\n tf = proto_tree_add_string(field_tree, hf_tcp_flags_str, tvb, offset + 12, 2, flags_str_first_letter);\n PROTO_ITEM_SET_GENERATED(tf);\n /* As discussed in bug 5541, it is better to use two separate\n * fields for the real and calculated window size.\n */\n proto_tree_add_uint(tcp_tree, hf_tcp_window_size_value, tvb, offset + 14, 2, real_window);\n scaled_pi = proto_tree_add_uint(tcp_tree, hf_tcp_window_size, tvb, offset + 14, 2, tcph->th_win);\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n\n if( !(tcph->th_flags&TH_SYN) && tcpd ) {\n switch (tcpd->fwd->win_scale) {\n\n case -1:\n {\n gint16 win_scale = tcpd->fwd->win_scale;\n gboolean override_with_pref = FALSE;\n\n /* Use preference setting (if set) */\n if (tcp_default_window_scaling != WindowScaling_NotKnown) {\n win_scale = tcp_default_window_scaling;\n override_with_pref = TRUE;\n }\n\n scaled_pi = proto_tree_add_int_format_value(tcp_tree, hf_tcp_window_size_scalefactor, tvb, offset + 14, 2,\n win_scale, \"%d (%s)\",\n win_scale,\n (override_with_pref) ? \"missing - taken from preference\" : \"unknown\");\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n }\n break;\n\n case -2:\n scaled_pi = proto_tree_add_int_format_value(tcp_tree, hf_tcp_window_size_scalefactor, tvb, offset + 14, 2, tcpd->fwd->win_scale, \"%d (no window scaling used)\", tcpd->fwd->win_scale);\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n break;\n\n default:\n scaled_pi = proto_tree_add_int_format_value(tcp_tree, hf_tcp_window_size_scalefactor, tvb, offset + 14, 2, 1<fwd->win_scale, \"%d\", 1<fwd->win_scale);\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n }\n }\n }\n\n if(tcph->th_flags & TH_SYN) {\n if(tcph->th_flags & TH_ACK) {\n expert_add_info_format(pinfo, tf_syn, &ei_tcp_connection_sack,\n \"Connection establish acknowledge (SYN+ACK): server port %u\", tcph->th_sport);\n /* Save the server port to help determine dissector used */\n tcpd->server_port = tcph->th_sport;\n }\n else {\n expert_add_info_format(pinfo, tf_syn, &ei_tcp_connection_syn,\n \"Connection establish request (SYN): server port %u\", tcph->th_dport);\n /* Save the server port to help determine dissector used */\n tcpd->server_port = tcph->th_dport;\n tcpd->ts_mru_syn = pinfo->abs_ts;\n }\n /* Remember where the next segment will start. */\n if (tcp_desegment && tcp_reassemble_out_of_order && tcpd && !PINFO_FD_VISITED(pinfo)) {\n if (tcpd->fwd->maxnextseq == 0) {\n tcpd->fwd->maxnextseq = tcph->th_seq + 1;\n }\n }\n }\n if(tcph->th_flags & TH_FIN) {\n /* XXX - find a way to know the server port and output only that one */\n expert_add_info(pinfo, tf_fin, &ei_tcp_connection_fin);\n }\n if(tcph->th_flags & TH_RST)\n /* XXX - find a way to know the server port and output only that one */\n expert_add_info(pinfo, tf_rst, &ei_tcp_connection_rst);\n\n if(tcp_analyze_seq\n && (tcph->th_flags & (TH_SYN|TH_ACK)) == TH_ACK\n && !nstime_is_zero(&tcpd->ts_mru_syn)\n && nstime_is_zero(&tcpd->ts_first_rtt)) {\n /* If all of the following:\n * - we care (the pref is set)\n * - this is a pure ACK\n * - we have a timestamp for the most-recently-transmitted SYN\n * - we haven't seen a pure ACK yet (no ts_first_rtt stored)\n * then assume it's the last part of the handshake and store the initial\n * RTT time\n */\n nstime_delta(&(tcpd->ts_first_rtt), &(pinfo->abs_ts), &(tcpd->ts_mru_syn));\n }\n\n /* Supply the sequence number of the first byte and of the first byte\n after the segment. */\n tcpinfo.seq = tcph->th_seq;\n tcpinfo.nxtseq = nxtseq;\n tcpinfo.lastackseq = tcph->th_ack;\n\n /* Assume we'll pass un-reassembled data to subdissectors. */\n tcpinfo.is_reassembled = FALSE;\n\n /*\n * Assume, initially, that we can't desegment.\n */\n pinfo->can_desegment = 0;\n th_sum = tvb_get_ntohs(tvb, offset + 16);\n if (!pinfo->fragmented && tvb_bytes_exist(tvb, 0, reported_len)) {\n /* The packet isn't part of an un-reassembled fragmented datagram\n and isn't truncated. This means we have all the data, and thus\n can checksum it and, unless it's being returned in an error\n packet, are willing to allow subdissectors to request reassembly\n on it. */\n\n if (tcp_check_checksum) {\n /* We haven't turned checksum checking off; checksum it. */\n\n /* Set up the fields of the pseudo-header. */\n SET_CKSUM_VEC_PTR(cksum_vec[0], (const guint8 *)pinfo->src.data, pinfo->src.len);\n SET_CKSUM_VEC_PTR(cksum_vec[1], (const guint8 *)pinfo->dst.data, pinfo->dst.len);\n switch (pinfo->src.type) {\n\n case AT_IPv4:\n phdr[0] = g_htonl((IP_PROTO_TCP<<16) + reported_len);\n SET_CKSUM_VEC_PTR(cksum_vec[2], (const guint8 *)phdr, 4);\n break;\n\n case AT_IPv6:\n phdr[0] = g_htonl(reported_len);\n phdr[1] = g_htonl(IP_PROTO_TCP);\n SET_CKSUM_VEC_PTR(cksum_vec[2], (const guint8 *)phdr, 8);\n break;\n\n default:\n /* TCP runs only atop IPv4 and IPv6.... */\n DISSECTOR_ASSERT_NOT_REACHED();\n break;\n }\n SET_CKSUM_VEC_TVB(cksum_vec[3], tvb, offset, reported_len);\n computed_cksum = in_cksum(cksum_vec, 4);\n if (computed_cksum == 0 && th_sum == 0xffff) {\n item = proto_tree_add_uint_format_value(tcp_tree, hf_tcp_checksum, tvb,\n offset + 16, 2, th_sum,\n \"0x%04x [should be 0x0000 (see RFC 1624)]\", th_sum);\n\n checksum_tree = proto_item_add_subtree(item, ett_tcp_checksum);\n item = proto_tree_add_uint(checksum_tree, hf_tcp_checksum_calculated, tvb,\n offset + 16, 2, 0x0000);\n PROTO_ITEM_SET_GENERATED(item);\n /* XXX - What should this special status be? */\n item = proto_tree_add_uint(checksum_tree, hf_tcp_checksum_status, tvb,\n offset + 16, 0, 4);\n PROTO_ITEM_SET_GENERATED(item);\n expert_add_info(pinfo, item, &ei_tcp_checksum_ffff);\n\n col_append_str(pinfo->cinfo, COL_INFO, \" [TCP CHECKSUM 0xFFFF]\");\n\n /* Checksum is treated as valid on most systems, so we're willing to desegment it. */\n desegment_ok = TRUE;\n } else {\n proto_item* calc_item;\n item = proto_tree_add_checksum(tcp_tree, tvb, offset+16, hf_tcp_checksum, hf_tcp_checksum_status, &ei_tcp_checksum_bad, pinfo, computed_cksum,\n ENC_BIG_ENDIAN, PROTO_CHECKSUM_VERIFY|PROTO_CHECKSUM_IN_CKSUM);\n\n calc_item = proto_tree_add_uint(tcp_tree, hf_tcp_checksum_calculated, tvb,\n offset + 16, 2, in_cksum_shouldbe(th_sum, computed_cksum));\n PROTO_ITEM_SET_GENERATED(calc_item);\n\n /* Checksum is valid, so we're willing to desegment it. */\n if (computed_cksum == 0) {\n desegment_ok = TRUE;\n } else {\n proto_item_append_text(item, \"(maybe caused by \\\"TCP checksum offload\\\"?)\");\n\n /* Checksum is invalid, so we're not willing to desegment it. */\n desegment_ok = FALSE;\n pinfo->noreassembly_reason = \" [incorrect TCP checksum]\";\n col_append_str(pinfo->cinfo, COL_INFO, \" [TCP CHECKSUM INCORRECT]\");\n }\n }\n } else {\n proto_tree_add_checksum(tcp_tree, tvb, offset+16, hf_tcp_checksum, hf_tcp_checksum_status, &ei_tcp_checksum_bad, pinfo, 0,\n ENC_BIG_ENDIAN, PROTO_CHECKSUM_NO_FLAGS);\n\n /* We didn't check the checksum, and don't care if it's valid,\n so we're willing to desegment it. */\n desegment_ok = TRUE;\n }\n } else {\n /* We don't have all the packet data, so we can't checksum it... */\n proto_tree_add_checksum(tcp_tree, tvb, offset+16, hf_tcp_checksum, hf_tcp_checksum_status, &ei_tcp_checksum_bad, pinfo, 0,\n ENC_BIG_ENDIAN, PROTO_CHECKSUM_NO_FLAGS);\n\n /* ...and aren't willing to desegment it. */\n desegment_ok = FALSE;\n }\n\n if (desegment_ok) {\n /* We're willing to desegment this. Is desegmentation enabled? */\n if (tcp_desegment) {\n /* Yes - is this segment being returned in an error packet? */\n if (!pinfo->flags.in_error_pkt) {\n /* No - indicate that we will desegment.\n We do NOT want to desegment segments returned in error\n packets, as they're not part of a TCP connection. */\n pinfo->can_desegment = 2;\n }\n }\n }\n\n item = proto_tree_add_item_ret_uint(tcp_tree, hf_tcp_urgent_pointer, tvb, offset + 18, 2, ENC_BIG_ENDIAN, &th_urp);\n\n if (IS_TH_URG(tcph->th_flags)) {\n /* Export the urgent pointer, for the benefit of protocols such as\n rlogin. */\n tcpinfo.urgent_pointer = (guint16)th_urp;\n tcp_info_append_uint(pinfo, \"Urg\", th_urp);\n } else {\n if (th_urp) {\n /* Note if the urgent pointer field is non-zero */\n expert_add_info(pinfo, item, &ei_tcp_urgent_pointer_non_zero);\n }\n }\n\n if (tcph->th_have_seglen)\n tcp_info_append_uint(pinfo, \"Len\", tcph->th_seglen);\n\n /* If there's more than just the fixed-length header (20 bytes), create\n a protocol tree item for the options. (We already know there's\n not less than the fixed-length header - we checked that above.)\n\n We ensure that we don't throw an exception here, so that we can\n do some analysis before we dissect the options and possibly\n throw an exception. (Trying to avoid throwing an exception when\n dissecting options is not something we should do.) */\n optlen = tcph->th_hlen - TCPH_MIN_LEN; /* length of options, in bytes */\n options_item = NULL;\n options_tree = NULL;\n if (optlen != 0) {\n guint bc = (guint)tvb_captured_length_remaining(tvb, offset + 20);\n\n if (tcp_tree != NULL) {\n options_item = proto_tree_add_item(tcp_tree, hf_tcp_options, tvb, offset + 20,\n bc < optlen ? bc : optlen, ENC_NA);\n proto_item_set_text(options_item, \"Options: (%u bytes)\", optlen);\n options_tree = proto_item_add_subtree(options_item, ett_tcp_options);\n }\n }\n\n tcph->num_sack_ranges = 0;\n\n /* handle TCP seq# analysis, print any extra SEQ/ACK data for this segment*/\n if(tcp_analyze_seq) {\n guint32 use_seq = tcph->th_seq;\n guint32 use_ack = tcph->th_ack;\n /* May need to recover absolute values here... */\n if (tcp_relative_seq) {\n use_seq += tcpd->fwd->base_seq;\n if (tcph->th_flags & TH_ACK) {\n use_ack += tcpd->rev->base_seq;\n }\n }\n tcp_print_sequence_number_analysis(pinfo, tvb, tcp_tree, tcpd, use_seq, use_ack);\n }\n\n /* handle conversation timestamps */\n if(tcp_calculate_ts) {\n tcp_print_timestamps(pinfo, tvb, tcp_tree, tcpd, tcppd);\n }\n\n /* Now dissect the options. */\n if (optlen) {\n rvbd_option_data* option_data;\n\n tcp_dissect_options(tvb, offset + 20, optlen,\n TCPOPT_EOL, pinfo, options_tree,\n options_item, tcph);\n\n /* Do some post evaluation of some Riverbed probe options in the list */\n option_data = (rvbd_option_data*)p_get_proto_data(pinfo->pool, pinfo, proto_tcp_option_rvbd_probe, pinfo->curr_layer_num);\n if (option_data != NULL)\n {\n if (option_data->valid)\n {\n /* Distinguish S+ from S+* */\n col_prepend_fstr(pinfo->cinfo, COL_INFO, \"S%s, \",\n option_data->type == PROBE_TRACE ? \"#\" :\n (option_data->probe_flags & RVBD_FLAGS_PROBE_NCFE) ? \"+*\" : \"+\");\n }\n }\n\n }\n\n if(!pinfo->fd->visited) {\n if((tcph->th_flags & TH_SYN)==TH_SYN) {\n /* Check the validity of the window scale value\n */\n verify_tcp_window_scaling((tcph->th_flags&TH_ACK)==TH_ACK,tcpd);\n }\n\n if((tcph->th_flags & (TH_SYN|TH_ACK))==(TH_SYN|TH_ACK)) {\n /* If the SYN or the SYN+ACK offered SCPS capabilities,\n * validate the flow's bidirectional scps capabilities.\n * The or protects against broken implementations offering\n * SCPS capabilities on SYN+ACK even if it wasn't offered with the SYN\n */\n if(tcpd && ((tcpd->rev->scps_capable) || (tcpd->fwd->scps_capable))) {\n verify_scps(pinfo, tf_syn, tcpd);\n }\n\n }\n }\n\n if (tcph->th_mptcp) {\n\n if (tcp_analyze_mptcp) {\n mptcp_add_analysis_subtree(pinfo, tvb, tcp_tree, tcpd, tcpd->mptcp_analysis, tcph );\n }\n }\n\n /* Skip over header + options */\n offset += tcph->th_hlen;\n\n /* Check the packet length to see if there's more data\n (it could be an ACK-only packet) */\n captured_length_remaining = tvb_captured_length_remaining(tvb, offset);\n\n if (tcph->th_have_seglen) {\n if(have_tap_listener(tcp_follow_tap)) {\n tcp_follow_tap_data_t* follow_data = wmem_new0(wmem_packet_scope(), tcp_follow_tap_data_t);\n\n follow_data->tvb = tvb_new_subset_remaining(tvb, offset);\n follow_data->tcph = tcph;\n follow_data->tcpd = tcpd;\n\n tap_queue_packet(tcp_follow_tap, pinfo, follow_data);\n }\n }\n\n tap_queue_packet(tcp_tap, pinfo, tcph);\n\n /* if it is an MPTCP packet */\n if(tcpd->mptcp_analysis) {\n tap_queue_packet(mptcp_tap, pinfo, tcpd);\n }\n\n /* If we're reassembling something whose length isn't known\n * beforehand, and that runs all the way to the end of\n * the data stream, a FIN indicates the end of the data\n * stream and thus the completion of reassembly, so we\n * need to explicitly check for that here.\n */\n if(tcph->th_have_seglen && tcpd && (tcph->th_flags & TH_FIN)\n && (tcpd->fwd->flags&TCP_FLOW_REASSEMBLE_UNTIL_FIN) ) {\n struct tcp_multisegment_pdu *msp;\n\n /* Is this the FIN that ended the data stream or is it a\n * retransmission of that FIN?\n */\n if (tcpd->fwd->fin == 0 || tcpd->fwd->fin == pinfo->num) {\n /* Either we haven't seen a FIN for this flow or we\n * have and it's this frame. Note that this is the FIN\n * for this flow, terminate reassembly and dissect the\n * results. */\n tcpd->fwd->fin = pinfo->num;\n msp=(struct tcp_multisegment_pdu *)wmem_tree_lookup32_le(tcpd->fwd->multisegment_pdus, tcph->th_seq-1);\n if(msp) {\n fragment_head *ipfd_head;\n\n ipfd_head = fragment_add(&tcp_reassembly_table, tvb, offset,\n pinfo, msp->first_frame, NULL,\n tcph->th_seq - msp->seq,\n tcph->th_seglen,\n FALSE );\n if(ipfd_head) {\n tvbuff_t *next_tvb;\n\n /* create a new TVB structure for desegmented data\n * datalen-1 to strip the dummy FIN byte off\n */\n next_tvb = tvb_new_chain(tvb, ipfd_head->tvb_data);\n\n /* add desegmented data to the data source list */\n add_new_data_source(pinfo, next_tvb, \"Reassembled TCP\");\n\n /* Show details of the reassembly */\n print_tcp_fragment_tree(ipfd_head, tree, tcp_tree, pinfo, next_tvb);\n\n /* call the payload dissector\n * but make sure we don't offer desegmentation any more\n */\n pinfo->can_desegment = 0;\n\n process_tcp_payload(next_tvb, 0, pinfo, tree, tcp_tree, tcph->th_sport, tcph->th_dport, tcph->th_seq,\n nxtseq, FALSE, tcpd, &tcpinfo);\n\n return tvb_captured_length(tvb);\n }\n }\n } else {\n /* Yes. This is a retransmission of the final FIN (or it's\n * the final FIN transmitted via a different path).\n * XXX - we need to flag retransmissions a bit better.\n */\n proto_tree_add_uint(tcp_tree, hf_tcp_fin_retransmission, tvb, 0, 0, tcpd->fwd->fin);\n }\n }\n\n if (tcp_display_process_info && tcpd && ((tcpd->fwd && tcpd->fwd->process_info && tcpd->fwd->process_info->command) ||\n (tcpd->rev && tcpd->rev->process_info && tcpd->rev->process_info->command))) {\n field_tree = proto_tree_add_subtree(tcp_tree, tvb, offset, 0, ett_tcp_process_info, &ti, \"Process Information\");\n PROTO_ITEM_SET_GENERATED(ti);\n if (tcpd->fwd && tcpd->fwd->process_info && tcpd->fwd->process_info->command) {\n proto_tree_add_uint(field_tree, hf_tcp_proc_dst_uid, tvb, 0, 0, tcpd->fwd->process_info->process_uid);\n proto_tree_add_uint(field_tree, hf_tcp_proc_dst_pid, tvb, 0, 0, tcpd->fwd->process_info->process_pid);\n proto_tree_add_string(field_tree, hf_tcp_proc_dst_uname, tvb, 0, 0, tcpd->fwd->process_info->username);\n proto_tree_add_string(field_tree, hf_tcp_proc_dst_cmd, tvb, 0, 0, tcpd->fwd->process_info->command);\n }\n if (tcpd->rev && tcpd->rev->process_info && tcpd->rev->process_info->command) {\n proto_tree_add_uint(field_tree, hf_tcp_proc_src_uid, tvb, 0, 0, tcpd->rev->process_info->process_uid);\n proto_tree_add_uint(field_tree, hf_tcp_proc_src_pid, tvb, 0, 0, tcpd->rev->process_info->process_pid);\n proto_tree_add_string(field_tree, hf_tcp_proc_src_uname, tvb, 0, 0, tcpd->rev->process_info->username);\n proto_tree_add_string(field_tree, hf_tcp_proc_src_cmd, tvb, 0, 0, tcpd->rev->process_info->command);\n }\n }\n\n /*\n * XXX - what, if any, of this should we do if this is included in an\n * error packet? It might be nice to see the details of the packet\n * that caused the ICMP error, but it might not be nice to have the\n * dissector update state based on it.\n * Also, we probably don't want to run TCP taps on those packets.\n */\n if (captured_length_remaining != 0) {\n if (tcph->th_flags & TH_RST) {\n /*\n * RFC1122 says:\n *\n * 4.2.2.12 RST Segment: RFC-793 Section 3.4\n *\n * A TCP SHOULD allow a received RST segment to include data.\n *\n * DISCUSSION\n * It has been suggested that a RST segment could contain\n * ASCII text that encoded and explained the cause of the\n * RST. No standard has yet been established for such\n * data.\n *\n * so for segments with RST we just display the data as text.\n */\n proto_tree_add_item(tcp_tree, hf_tcp_reset_cause, tvb, offset, captured_length_remaining, ENC_NA|ENC_ASCII);\n } else {\n /*\n * XXX - dissect_tcp_payload() expects the payload length, however\n * SYN and FIN increments the nxtseq by one without having\n * the data.\n */\n if ((tcph->th_flags&(TH_FIN|TH_SYN)) && (tcph->th_seglen > 0)) {\n nxtseq -= 1;\n }\n dissect_tcp_payload(tvb, pinfo, offset, tcph->th_seq, nxtseq,\n tcph->th_sport, tcph->th_dport, tree, tcp_tree, tcpd, &tcpinfo);\n }\n }\n return tvb_captured_length(tvb);\n}", "project": "wireshark", "hash": 267912446686612518591440218718898174428, "size": 807, "commit_id": "7f3fe6164a68b76d9988c4253b24d43f498f1753", "message": "TCP: do not use an unknown status when the checksum is 0xffff\n\nOtherwise it triggers an assert when adding the column as the field is\ndefined as BASE_NONE and not BASE_DEC or BASE_HEX. Thus an unknown value\n(not in proto_checksum_vals[)array) cannot be represented.\nMark the checksum as bad even if we process the packet.\nCloses #16816\n\nConflicts:\n\tepan/dissectors/packet-tcp.c", "target": 1, "dataset": "other", "idx": 206691} {"func": "dissect_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)\n{\n guint8 th_off_x2; /* combines th_off and th_x2 */\n guint16 th_sum;\n guint32 th_urp;\n proto_tree *tcp_tree = NULL, *field_tree = NULL;\n proto_item *ti = NULL, *tf, *hidden_item;\n proto_item *options_item;\n proto_tree *options_tree;\n int offset = 0;\n const char *flags_str, *flags_str_first_letter;\n guint optlen;\n guint32 nxtseq = 0;\n guint reported_len;\n vec_t cksum_vec[4];\n guint32 phdr[2];\n guint16 computed_cksum;\n guint16 real_window;\n guint captured_length_remaining;\n gboolean desegment_ok;\n struct tcpinfo tcpinfo;\n struct tcpheader *tcph;\n proto_item *tf_syn = NULL, *tf_fin = NULL, *tf_rst = NULL, *scaled_pi;\n conversation_t *conv=NULL, *other_conv;\n guint32 save_last_frame = 0;\n struct tcp_analysis *tcpd=NULL;\n struct tcp_per_packet_data_t *tcppd=NULL;\n proto_item *item;\n proto_tree *checksum_tree;\n gboolean icmp_ip = FALSE;\n\n tcph = wmem_new0(wmem_packet_scope(), struct tcpheader);\n tcph->th_sport = tvb_get_ntohs(tvb, offset);\n tcph->th_dport = tvb_get_ntohs(tvb, offset + 2);\n copy_address_shallow(&tcph->ip_src, &pinfo->src);\n copy_address_shallow(&tcph->ip_dst, &pinfo->dst);\n\n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"TCP\");\n col_clear(pinfo->cinfo, COL_INFO);\n col_append_ports(pinfo->cinfo, COL_INFO, PT_TCP, tcph->th_sport, tcph->th_dport);\n\n if (tree) {\n ti = proto_tree_add_item(tree, proto_tcp, tvb, 0, -1, ENC_NA);\n if (tcp_summary_in_tree) {\n proto_item_append_text(ti, \", Src Port: %s, Dst Port: %s\",\n port_with_resolution_to_str(wmem_packet_scope(), PT_TCP, tcph->th_sport),\n port_with_resolution_to_str(wmem_packet_scope(), PT_TCP, tcph->th_dport));\n }\n tcp_tree = proto_item_add_subtree(ti, ett_tcp);\n p_add_proto_data(pinfo->pool, pinfo, proto_tcp, pinfo->curr_layer_num, tcp_tree);\n\n proto_tree_add_item(tcp_tree, hf_tcp_srcport, tvb, offset, 2, ENC_BIG_ENDIAN);\n proto_tree_add_item(tcp_tree, hf_tcp_dstport, tvb, offset + 2, 2, ENC_BIG_ENDIAN);\n hidden_item = proto_tree_add_item(tcp_tree, hf_tcp_port, tvb, offset, 2, ENC_BIG_ENDIAN);\n PROTO_ITEM_SET_HIDDEN(hidden_item);\n hidden_item = proto_tree_add_item(tcp_tree, hf_tcp_port, tvb, offset + 2, 2, ENC_BIG_ENDIAN);\n PROTO_ITEM_SET_HIDDEN(hidden_item);\n\n /* If we're dissecting the headers of a TCP packet in an ICMP packet\n * then go ahead and put the sequence numbers in the tree now (because\n * they won't be put in later because the ICMP packet only contains up\n * to the sequence number).\n * We should only need to do this for IPv4 since IPv6 will hopefully\n * carry enough TCP payload for this dissector to put the sequence\n * numbers in via the regular code path.\n */\n {\n wmem_list_frame_t *frame;\n frame = wmem_list_frame_prev(wmem_list_tail(pinfo->layers));\n if (proto_ip == (gint) GPOINTER_TO_UINT(wmem_list_frame_data(frame))) {\n frame = wmem_list_frame_prev(frame);\n if (proto_icmp == (gint) GPOINTER_TO_UINT(wmem_list_frame_data(frame))) {\n proto_tree_add_item(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, ENC_BIG_ENDIAN);\n icmp_ip = TRUE;\n }\n }\n }\n }\n\n /* Set the source and destination port numbers as soon as we get them,\n so that they're available to the \"Follow TCP Stream\" code even if\n we throw an exception dissecting the rest of the TCP header. */\n pinfo->ptype = PT_TCP;\n pinfo->srcport = tcph->th_sport;\n pinfo->destport = tcph->th_dport;\n\n p_add_proto_data(pinfo->pool, pinfo, hf_tcp_srcport, pinfo->curr_layer_num, GUINT_TO_POINTER(tcph->th_sport));\n p_add_proto_data(pinfo->pool, pinfo, hf_tcp_dstport, pinfo->curr_layer_num, GUINT_TO_POINTER(tcph->th_dport));\n\n tcph->th_rawseq = tvb_get_ntohl(tvb, offset + 4);\n tcph->th_seq = tcph->th_rawseq;\n tcph->th_ack = tvb_get_ntohl(tvb, offset + 8);\n th_off_x2 = tvb_get_guint8(tvb, offset + 12);\n tcpinfo.flags = tcph->th_flags = tvb_get_ntohs(tvb, offset + 12) & TH_MASK;\n tcph->th_win = tvb_get_ntohs(tvb, offset + 14);\n real_window = tcph->th_win;\n tcph->th_hlen = hi_nibble(th_off_x2) * 4; /* TCP header length, in bytes */\n\n /* find(or create if needed) the conversation for this tcp session\n * This is a slight deviation from find_or_create_conversation so it's\n * done manually. This is done to save the last frame of the conversation\n * in case a new conversation is found and the previous conversation needs\n * to be adjusted,\n */\n if((conv = find_conversation_pinfo(pinfo, 0)) != NULL) {\n /* Update how far the conversation reaches */\n if (pinfo->num > conv->last_frame) {\n save_last_frame = conv->last_frame;\n conv->last_frame = pinfo->num;\n }\n }\n else {\n conv = conversation_new(pinfo->num, &pinfo->src,\n &pinfo->dst, ENDPOINT_TCP,\n pinfo->srcport, pinfo->destport, 0);\n }\n tcpd=get_tcp_conversation_data(conv,pinfo);\n\n /* If this is a SYN packet, then check if its seq-nr is different\n * from the base_seq of the retrieved conversation. If this is the\n * case, create a new conversation with the same addresses and ports\n * and set the TA_PORTS_REUSED flag. If the seq-nr is the same as\n * the base_seq, then do nothing so it will be marked as a retrans-\n * mission later.\n * XXX - Is this affected by MPTCP which can use multiple SYNs?\n */\n if(tcpd && ((tcph->th_flags&(TH_SYN|TH_ACK))==TH_SYN) &&\n (tcpd->fwd->static_flags & TCP_S_BASE_SEQ_SET) &&\n (tcph->th_seq!=tcpd->fwd->base_seq) ) {\n if (!(pinfo->fd->visited)) {\n /* Reset the last frame seen in the conversation */\n if (save_last_frame > 0)\n conv->last_frame = save_last_frame;\n\n conv=conversation_new(pinfo->num, &pinfo->src, &pinfo->dst, ENDPOINT_TCP, pinfo->srcport, pinfo->destport, 0);\n tcpd=get_tcp_conversation_data(conv,pinfo);\n }\n if(!tcpd->ta)\n tcp_analyze_get_acked_struct(pinfo->num, tcph->th_seq, tcph->th_ack, TRUE, tcpd);\n tcpd->ta->flags|=TCP_A_REUSED_PORTS;\n }\n /* If this is a SYN/ACK packet, then check if its seq-nr is different\n * from the base_seq of the retrieved conversation. If this is the\n * case, try to find a conversation with the same addresses and ports\n * and set the TA_PORTS_REUSED flag. If the seq-nr is the same as\n * the base_seq, then do nothing so it will be marked as a retrans-\n * mission later.\n * XXX - Is this affected by MPTCP which can use multiple SYNs?\n */\n if(tcpd && ((tcph->th_flags&(TH_SYN|TH_ACK))==(TH_SYN|TH_ACK)) &&\n (tcpd->fwd->static_flags & TCP_S_BASE_SEQ_SET) &&\n (tcph->th_seq!=tcpd->fwd->base_seq) ) {\n if (!(pinfo->fd->visited)) {\n /* Reset the last frame seen in the conversation */\n if (save_last_frame > 0)\n conv->last_frame = save_last_frame;\n }\n\n other_conv = find_conversation(pinfo->num, &pinfo->dst, &pinfo->src, ENDPOINT_TCP, pinfo->destport, pinfo->srcport, 0);\n if (other_conv != NULL)\n {\n conv = other_conv;\n tcpd=get_tcp_conversation_data(conv,pinfo);\n }\n\n if(!tcpd->ta)\n tcp_analyze_get_acked_struct(pinfo->num, tcph->th_seq, tcph->th_ack, TRUE, tcpd);\n tcpd->ta->flags|=TCP_A_REUSED_PORTS;\n }\n\n if (tcpd) {\n item = proto_tree_add_uint(tcp_tree, hf_tcp_stream, tvb, offset, 0, tcpd->stream);\n PROTO_ITEM_SET_GENERATED(item);\n\n /* Copy the stream index into the header as well to make it available\n * to tap listeners.\n */\n tcph->th_stream = tcpd->stream;\n }\n\n /* Do we need to calculate timestamps relative to the tcp-stream? */\n if (tcp_calculate_ts) {\n tcppd = (struct tcp_per_packet_data_t *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tcp, pinfo->curr_layer_num);\n\n /*\n * Calculate the timestamps relative to this conversation (but only on the\n * first run when frames are accessed sequentially)\n */\n if (!(pinfo->fd->visited))\n tcp_calculate_timestamps(pinfo, tcpd, tcppd);\n }\n\n /*\n * If we've been handed an IP fragment, we don't know how big the TCP\n * segment is, so don't do anything that requires that we know that.\n *\n * The same applies if we're part of an error packet. (XXX - if the\n * ICMP and ICMPv6 dissectors could set a \"this is how big the IP\n * header says it is\" length in the tvbuff, we could use that; such\n * a length might also be useful for handling packets where the IP\n * length is bigger than the actual data available in the frame; the\n * dissectors should trust that length, and then throw a\n * ReportedBoundsError exception when they go past the end of the frame.)\n *\n * We also can't determine the segment length if the reported length\n * of the TCP packet is less than the TCP header length.\n */\n reported_len = tvb_reported_length(tvb);\n\n if (!pinfo->fragmented && !pinfo->flags.in_error_pkt) {\n if (reported_len < tcph->th_hlen) {\n proto_tree_add_expert_format(tcp_tree, pinfo, &ei_tcp_short_segment, tvb, offset, 0,\n \"Short segment. Segment/fragment does not contain a full TCP header\"\n \" (might be NMAP or someone else deliberately sending unusual packets)\");\n tcph->th_have_seglen = FALSE;\n } else {\n proto_item *pi;\n\n /* Compute the length of data in this segment. */\n tcph->th_seglen = reported_len - tcph->th_hlen;\n tcph->th_have_seglen = TRUE;\n\n pi = proto_tree_add_uint(ti, hf_tcp_len, tvb, offset+12, 1, tcph->th_seglen);\n PROTO_ITEM_SET_GENERATED(pi);\n\n /* handle TCP seq# analysis parse all new segments we see */\n if(tcp_analyze_seq) {\n if(!(pinfo->fd->visited)) {\n tcp_analyze_sequence_number(pinfo, tcph->th_seq, tcph->th_ack, tcph->th_seglen, tcph->th_flags, tcph->th_win, tcpd);\n }\n if(tcpd && tcp_relative_seq) {\n (tcph->th_seq) -= tcpd->fwd->base_seq;\n if (tcph->th_flags & TH_ACK) {\n (tcph->th_ack) -= tcpd->rev->base_seq;\n }\n }\n }\n\n /* re-calculate window size, based on scaling factor */\n if (!(tcph->th_flags&TH_SYN)) { /* SYNs are never scaled */\n if (tcpd && (tcpd->fwd->win_scale>=0)) {\n (tcph->th_win)<<=tcpd->fwd->win_scale;\n }\n else {\n /* Don't have it stored, so use preference setting instead! */\n if (tcp_default_window_scaling>=0) {\n (tcph->th_win)<<=tcp_default_window_scaling;\n }\n }\n }\n\n /* Compute the sequence number of next octet after this segment. */\n nxtseq = tcph->th_seq + tcph->th_seglen;\n if ((tcph->th_flags&(TH_SYN|TH_FIN)) && (tcph->th_seglen > 0)) {\n nxtseq += 1;\n }\n }\n } else\n tcph->th_have_seglen = FALSE;\n\n flags_str = tcp_flags_to_str(wmem_packet_scope(), tcph);\n flags_str_first_letter = tcp_flags_to_str_first_letter(tcph);\n\n col_append_lstr(pinfo->cinfo, COL_INFO,\n \" [\", flags_str, \"]\",\n COL_ADD_LSTR_TERMINATOR);\n tcp_info_append_uint(pinfo, \"Seq\", tcph->th_seq);\n if (tcph->th_flags&TH_ACK)\n tcp_info_append_uint(pinfo, \"Ack\", tcph->th_ack);\n\n tcp_info_append_uint(pinfo, \"Win\", tcph->th_win);\n\n if (tcp_summary_in_tree) {\n proto_item_append_text(ti, \", Seq: %u\", tcph->th_seq);\n }\n\n if (!icmp_ip) {\n if(tcp_relative_seq && tcp_analyze_seq) {\n proto_tree_add_uint_format_value(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, tcph->th_seq, \"%u (relative sequence number)\", tcph->th_seq);\n } else {\n proto_tree_add_uint(tcp_tree, hf_tcp_seq, tvb, offset + 4, 4, tcph->th_seq);\n }\n }\n\n if (tcph->th_hlen < TCPH_MIN_LEN) {\n /* Give up at this point; we put the source and destination port in\n the tree, before fetching the header length, so that they'll\n show up if this is in the failing packet in an ICMP error packet,\n but it's now time to give up if the header length is bogus. */\n col_append_fstr(pinfo->cinfo, COL_INFO, \", bogus TCP header length (%u, must be at least %u)\",\n tcph->th_hlen, TCPH_MIN_LEN);\n if (tree) {\n tf = proto_tree_add_uint_bits_format_value(tcp_tree, hf_tcp_hdr_len, tvb, (offset + 12) << 3, 4, tcph->th_hlen,\n \"%u bytes (%u)\", tcph->th_hlen, tcph->th_hlen >> 2);\n expert_add_info_format(pinfo, tf, &ei_tcp_bogus_header_length,\n \"Bogus TCP header length (%u, must be at least %u)\", tcph->th_hlen, TCPH_MIN_LEN);\n }\n return offset+12;\n }\n\n if (tcp_summary_in_tree) {\n if(tcph->th_flags&TH_ACK) {\n proto_item_append_text(ti, \", Ack: %u\", tcph->th_ack);\n }\n if (tcph->th_have_seglen)\n proto_item_append_text(ti, \", Len: %u\", tcph->th_seglen);\n }\n proto_item_set_len(ti, tcph->th_hlen);\n if (tcph->th_have_seglen) {\n if(tcp_relative_seq && tcp_analyze_seq) {\n tf=proto_tree_add_uint_format_value(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq, \"%u (relative sequence number)\", nxtseq);\n } else {\n tf=proto_tree_add_uint(tcp_tree, hf_tcp_nxtseq, tvb, offset, 0, nxtseq);\n }\n PROTO_ITEM_SET_GENERATED(tf);\n }\n\n tf = proto_tree_add_uint(tcp_tree, hf_tcp_ack, tvb, offset + 8, 4, tcph->th_ack);\n if (tcph->th_flags & TH_ACK) {\n if (tcp_relative_seq && tcp_analyze_seq) {\n proto_item_append_text(tf, \" (relative ack number)\");\n }\n } else {\n /* Note if the ACK field is non-zero */\n if (tvb_get_ntohl(tvb, offset+8) != 0) {\n expert_add_info(pinfo, tf, &ei_tcp_ack_nonzero);\n }\n }\n\n if (tree) {\n // This should be consistent with ip.hdr_len.\n proto_tree_add_uint_bits_format_value(tcp_tree, hf_tcp_hdr_len, tvb, (offset + 12) << 3, 4, tcph->th_hlen,\n \"%u bytes (%u)\", tcph->th_hlen, tcph->th_hlen>>2);\n tf = proto_tree_add_uint_format(tcp_tree, hf_tcp_flags, tvb, offset + 12, 2,\n tcph->th_flags, \"Flags: 0x%03x (%s)\", tcph->th_flags, flags_str);\n field_tree = proto_item_add_subtree(tf, ett_tcp_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_res, tvb, offset + 12, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_ns, tvb, offset + 12, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_cwr, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_ecn, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_urg, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_ack, tvb, offset + 13, 1, tcph->th_flags);\n proto_tree_add_boolean(field_tree, hf_tcp_flags_push, tvb, offset + 13, 1, tcph->th_flags);\n tf_rst = proto_tree_add_boolean(field_tree, hf_tcp_flags_reset, tvb, offset + 13, 1, tcph->th_flags);\n tf_syn = proto_tree_add_boolean(field_tree, hf_tcp_flags_syn, tvb, offset + 13, 1, tcph->th_flags);\n tf_fin = proto_tree_add_boolean(field_tree, hf_tcp_flags_fin, tvb, offset + 13, 1, tcph->th_flags);\n\n tf = proto_tree_add_string(field_tree, hf_tcp_flags_str, tvb, offset + 12, 2, flags_str_first_letter);\n PROTO_ITEM_SET_GENERATED(tf);\n /* As discussed in bug 5541, it is better to use two separate\n * fields for the real and calculated window size.\n */\n proto_tree_add_uint(tcp_tree, hf_tcp_window_size_value, tvb, offset + 14, 2, real_window);\n scaled_pi = proto_tree_add_uint(tcp_tree, hf_tcp_window_size, tvb, offset + 14, 2, tcph->th_win);\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n\n if( !(tcph->th_flags&TH_SYN) && tcpd ) {\n switch (tcpd->fwd->win_scale) {\n\n case -1:\n {\n gint16 win_scale = tcpd->fwd->win_scale;\n gboolean override_with_pref = FALSE;\n\n /* Use preference setting (if set) */\n if (tcp_default_window_scaling != WindowScaling_NotKnown) {\n win_scale = tcp_default_window_scaling;\n override_with_pref = TRUE;\n }\n\n scaled_pi = proto_tree_add_int_format_value(tcp_tree, hf_tcp_window_size_scalefactor, tvb, offset + 14, 2,\n win_scale, \"%d (%s)\",\n win_scale,\n (override_with_pref) ? \"missing - taken from preference\" : \"unknown\");\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n }\n break;\n\n case -2:\n scaled_pi = proto_tree_add_int_format_value(tcp_tree, hf_tcp_window_size_scalefactor, tvb, offset + 14, 2, tcpd->fwd->win_scale, \"%d (no window scaling used)\", tcpd->fwd->win_scale);\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n break;\n\n default:\n scaled_pi = proto_tree_add_int_format_value(tcp_tree, hf_tcp_window_size_scalefactor, tvb, offset + 14, 2, 1<fwd->win_scale, \"%d\", 1<fwd->win_scale);\n PROTO_ITEM_SET_GENERATED(scaled_pi);\n }\n }\n }\n\n if(tcph->th_flags & TH_SYN) {\n if(tcph->th_flags & TH_ACK) {\n expert_add_info_format(pinfo, tf_syn, &ei_tcp_connection_sack,\n \"Connection establish acknowledge (SYN+ACK): server port %u\", tcph->th_sport);\n /* Save the server port to help determine dissector used */\n tcpd->server_port = tcph->th_sport;\n }\n else {\n expert_add_info_format(pinfo, tf_syn, &ei_tcp_connection_syn,\n \"Connection establish request (SYN): server port %u\", tcph->th_dport);\n /* Save the server port to help determine dissector used */\n tcpd->server_port = tcph->th_dport;\n tcpd->ts_mru_syn = pinfo->abs_ts;\n }\n /* Remember where the next segment will start. */\n if (tcp_desegment && tcp_reassemble_out_of_order && tcpd && !PINFO_FD_VISITED(pinfo)) {\n if (tcpd->fwd->maxnextseq == 0) {\n tcpd->fwd->maxnextseq = tcph->th_seq + 1;\n }\n }\n }\n if(tcph->th_flags & TH_FIN) {\n /* XXX - find a way to know the server port and output only that one */\n expert_add_info(pinfo, tf_fin, &ei_tcp_connection_fin);\n }\n if(tcph->th_flags & TH_RST)\n /* XXX - find a way to know the server port and output only that one */\n expert_add_info(pinfo, tf_rst, &ei_tcp_connection_rst);\n\n if(tcp_analyze_seq\n && (tcph->th_flags & (TH_SYN|TH_ACK)) == TH_ACK\n && !nstime_is_zero(&tcpd->ts_mru_syn)\n && nstime_is_zero(&tcpd->ts_first_rtt)) {\n /* If all of the following:\n * - we care (the pref is set)\n * - this is a pure ACK\n * - we have a timestamp for the most-recently-transmitted SYN\n * - we haven't seen a pure ACK yet (no ts_first_rtt stored)\n * then assume it's the last part of the handshake and store the initial\n * RTT time\n */\n nstime_delta(&(tcpd->ts_first_rtt), &(pinfo->abs_ts), &(tcpd->ts_mru_syn));\n }\n\n /* Supply the sequence number of the first byte and of the first byte\n after the segment. */\n tcpinfo.seq = tcph->th_seq;\n tcpinfo.nxtseq = nxtseq;\n tcpinfo.lastackseq = tcph->th_ack;\n\n /* Assume we'll pass un-reassembled data to subdissectors. */\n tcpinfo.is_reassembled = FALSE;\n\n /*\n * Assume, initially, that we can't desegment.\n */\n pinfo->can_desegment = 0;\n th_sum = tvb_get_ntohs(tvb, offset + 16);\n if (!pinfo->fragmented && tvb_bytes_exist(tvb, 0, reported_len)) {\n /* The packet isn't part of an un-reassembled fragmented datagram\n and isn't truncated. This means we have all the data, and thus\n can checksum it and, unless it's being returned in an error\n packet, are willing to allow subdissectors to request reassembly\n on it. */\n\n if (tcp_check_checksum) {\n /* We haven't turned checksum checking off; checksum it. */\n\n /* Set up the fields of the pseudo-header. */\n SET_CKSUM_VEC_PTR(cksum_vec[0], (const guint8 *)pinfo->src.data, pinfo->src.len);\n SET_CKSUM_VEC_PTR(cksum_vec[1], (const guint8 *)pinfo->dst.data, pinfo->dst.len);\n switch (pinfo->src.type) {\n\n case AT_IPv4:\n phdr[0] = g_htonl((IP_PROTO_TCP<<16) + reported_len);\n SET_CKSUM_VEC_PTR(cksum_vec[2], (const guint8 *)phdr, 4);\n break;\n\n case AT_IPv6:\n phdr[0] = g_htonl(reported_len);\n phdr[1] = g_htonl(IP_PROTO_TCP);\n SET_CKSUM_VEC_PTR(cksum_vec[2], (const guint8 *)phdr, 8);\n break;\n\n default:\n /* TCP runs only atop IPv4 and IPv6.... */\n DISSECTOR_ASSERT_NOT_REACHED();\n break;\n }\n SET_CKSUM_VEC_TVB(cksum_vec[3], tvb, offset, reported_len);\n computed_cksum = in_cksum(cksum_vec, 4);\n if (computed_cksum == 0 && th_sum == 0xffff) {\n item = proto_tree_add_uint_format_value(tcp_tree, hf_tcp_checksum, tvb,\n offset + 16, 2, th_sum,\n \"0x%04x [should be 0x0000 (see RFC 1624)]\", th_sum);\n\n checksum_tree = proto_item_add_subtree(item, ett_tcp_checksum);\n item = proto_tree_add_uint(checksum_tree, hf_tcp_checksum_calculated, tvb,\n offset + 16, 2, 0x0000);\n PROTO_ITEM_SET_GENERATED(item);\n /* XXX - What should this special status be? */\n item = proto_tree_add_uint(checksum_tree, hf_tcp_checksum_status, tvb,\n offset + 16, 0, PROTO_CHECKSUM_E_BAD);\n PROTO_ITEM_SET_GENERATED(item);\n expert_add_info(pinfo, item, &ei_tcp_checksum_ffff);\n\n col_append_str(pinfo->cinfo, COL_INFO, \" [TCP CHECKSUM 0xFFFF]\");\n\n /* Checksum is treated as valid on most systems, so we're willing to desegment it. */\n desegment_ok = TRUE;\n } else {\n proto_item* calc_item;\n item = proto_tree_add_checksum(tcp_tree, tvb, offset+16, hf_tcp_checksum, hf_tcp_checksum_status, &ei_tcp_checksum_bad, pinfo, computed_cksum,\n ENC_BIG_ENDIAN, PROTO_CHECKSUM_VERIFY|PROTO_CHECKSUM_IN_CKSUM);\n\n calc_item = proto_tree_add_uint(tcp_tree, hf_tcp_checksum_calculated, tvb,\n offset + 16, 2, in_cksum_shouldbe(th_sum, computed_cksum));\n PROTO_ITEM_SET_GENERATED(calc_item);\n\n /* Checksum is valid, so we're willing to desegment it. */\n if (computed_cksum == 0) {\n desegment_ok = TRUE;\n } else {\n proto_item_append_text(item, \"(maybe caused by \\\"TCP checksum offload\\\"?)\");\n\n /* Checksum is invalid, so we're not willing to desegment it. */\n desegment_ok = FALSE;\n pinfo->noreassembly_reason = \" [incorrect TCP checksum]\";\n col_append_str(pinfo->cinfo, COL_INFO, \" [TCP CHECKSUM INCORRECT]\");\n }\n }\n } else {\n proto_tree_add_checksum(tcp_tree, tvb, offset+16, hf_tcp_checksum, hf_tcp_checksum_status, &ei_tcp_checksum_bad, pinfo, 0,\n ENC_BIG_ENDIAN, PROTO_CHECKSUM_NO_FLAGS);\n\n /* We didn't check the checksum, and don't care if it's valid,\n so we're willing to desegment it. */\n desegment_ok = TRUE;\n }\n } else {\n /* We don't have all the packet data, so we can't checksum it... */\n proto_tree_add_checksum(tcp_tree, tvb, offset+16, hf_tcp_checksum, hf_tcp_checksum_status, &ei_tcp_checksum_bad, pinfo, 0,\n ENC_BIG_ENDIAN, PROTO_CHECKSUM_NO_FLAGS);\n\n /* ...and aren't willing to desegment it. */\n desegment_ok = FALSE;\n }\n\n if (desegment_ok) {\n /* We're willing to desegment this. Is desegmentation enabled? */\n if (tcp_desegment) {\n /* Yes - is this segment being returned in an error packet? */\n if (!pinfo->flags.in_error_pkt) {\n /* No - indicate that we will desegment.\n We do NOT want to desegment segments returned in error\n packets, as they're not part of a TCP connection. */\n pinfo->can_desegment = 2;\n }\n }\n }\n\n item = proto_tree_add_item_ret_uint(tcp_tree, hf_tcp_urgent_pointer, tvb, offset + 18, 2, ENC_BIG_ENDIAN, &th_urp);\n\n if (IS_TH_URG(tcph->th_flags)) {\n /* Export the urgent pointer, for the benefit of protocols such as\n rlogin. */\n tcpinfo.urgent_pointer = (guint16)th_urp;\n tcp_info_append_uint(pinfo, \"Urg\", th_urp);\n } else {\n if (th_urp) {\n /* Note if the urgent pointer field is non-zero */\n expert_add_info(pinfo, item, &ei_tcp_urgent_pointer_non_zero);\n }\n }\n\n if (tcph->th_have_seglen)\n tcp_info_append_uint(pinfo, \"Len\", tcph->th_seglen);\n\n /* If there's more than just the fixed-length header (20 bytes), create\n a protocol tree item for the options. (We already know there's\n not less than the fixed-length header - we checked that above.)\n\n We ensure that we don't throw an exception here, so that we can\n do some analysis before we dissect the options and possibly\n throw an exception. (Trying to avoid throwing an exception when\n dissecting options is not something we should do.) */\n optlen = tcph->th_hlen - TCPH_MIN_LEN; /* length of options, in bytes */\n options_item = NULL;\n options_tree = NULL;\n if (optlen != 0) {\n guint bc = (guint)tvb_captured_length_remaining(tvb, offset + 20);\n\n if (tcp_tree != NULL) {\n options_item = proto_tree_add_item(tcp_tree, hf_tcp_options, tvb, offset + 20,\n bc < optlen ? bc : optlen, ENC_NA);\n proto_item_set_text(options_item, \"Options: (%u bytes)\", optlen);\n options_tree = proto_item_add_subtree(options_item, ett_tcp_options);\n }\n }\n\n tcph->num_sack_ranges = 0;\n\n /* handle TCP seq# analysis, print any extra SEQ/ACK data for this segment*/\n if(tcp_analyze_seq) {\n guint32 use_seq = tcph->th_seq;\n guint32 use_ack = tcph->th_ack;\n /* May need to recover absolute values here... */\n if (tcp_relative_seq) {\n use_seq += tcpd->fwd->base_seq;\n if (tcph->th_flags & TH_ACK) {\n use_ack += tcpd->rev->base_seq;\n }\n }\n tcp_print_sequence_number_analysis(pinfo, tvb, tcp_tree, tcpd, use_seq, use_ack);\n }\n\n /* handle conversation timestamps */\n if(tcp_calculate_ts) {\n tcp_print_timestamps(pinfo, tvb, tcp_tree, tcpd, tcppd);\n }\n\n /* Now dissect the options. */\n if (optlen) {\n rvbd_option_data* option_data;\n\n tcp_dissect_options(tvb, offset + 20, optlen,\n TCPOPT_EOL, pinfo, options_tree,\n options_item, tcph);\n\n /* Do some post evaluation of some Riverbed probe options in the list */\n option_data = (rvbd_option_data*)p_get_proto_data(pinfo->pool, pinfo, proto_tcp_option_rvbd_probe, pinfo->curr_layer_num);\n if (option_data != NULL)\n {\n if (option_data->valid)\n {\n /* Distinguish S+ from S+* */\n col_prepend_fstr(pinfo->cinfo, COL_INFO, \"S%s, \",\n option_data->type == PROBE_TRACE ? \"#\" :\n (option_data->probe_flags & RVBD_FLAGS_PROBE_NCFE) ? \"+*\" : \"+\");\n }\n }\n\n }\n\n if(!pinfo->fd->visited) {\n if((tcph->th_flags & TH_SYN)==TH_SYN) {\n /* Check the validity of the window scale value\n */\n verify_tcp_window_scaling((tcph->th_flags&TH_ACK)==TH_ACK,tcpd);\n }\n\n if((tcph->th_flags & (TH_SYN|TH_ACK))==(TH_SYN|TH_ACK)) {\n /* If the SYN or the SYN+ACK offered SCPS capabilities,\n * validate the flow's bidirectional scps capabilities.\n * The or protects against broken implementations offering\n * SCPS capabilities on SYN+ACK even if it wasn't offered with the SYN\n */\n if(tcpd && ((tcpd->rev->scps_capable) || (tcpd->fwd->scps_capable))) {\n verify_scps(pinfo, tf_syn, tcpd);\n }\n\n }\n }\n\n if (tcph->th_mptcp) {\n\n if (tcp_analyze_mptcp) {\n mptcp_add_analysis_subtree(pinfo, tvb, tcp_tree, tcpd, tcpd->mptcp_analysis, tcph );\n }\n }\n\n /* Skip over header + options */\n offset += tcph->th_hlen;\n\n /* Check the packet length to see if there's more data\n (it could be an ACK-only packet) */\n captured_length_remaining = tvb_captured_length_remaining(tvb, offset);\n\n if (tcph->th_have_seglen) {\n if(have_tap_listener(tcp_follow_tap)) {\n tcp_follow_tap_data_t* follow_data = wmem_new0(wmem_packet_scope(), tcp_follow_tap_data_t);\n\n follow_data->tvb = tvb_new_subset_remaining(tvb, offset);\n follow_data->tcph = tcph;\n follow_data->tcpd = tcpd;\n\n tap_queue_packet(tcp_follow_tap, pinfo, follow_data);\n }\n }\n\n tap_queue_packet(tcp_tap, pinfo, tcph);\n\n /* if it is an MPTCP packet */\n if(tcpd->mptcp_analysis) {\n tap_queue_packet(mptcp_tap, pinfo, tcpd);\n }\n\n /* If we're reassembling something whose length isn't known\n * beforehand, and that runs all the way to the end of\n * the data stream, a FIN indicates the end of the data\n * stream and thus the completion of reassembly, so we\n * need to explicitly check for that here.\n */\n if(tcph->th_have_seglen && tcpd && (tcph->th_flags & TH_FIN)\n && (tcpd->fwd->flags&TCP_FLOW_REASSEMBLE_UNTIL_FIN) ) {\n struct tcp_multisegment_pdu *msp;\n\n /* Is this the FIN that ended the data stream or is it a\n * retransmission of that FIN?\n */\n if (tcpd->fwd->fin == 0 || tcpd->fwd->fin == pinfo->num) {\n /* Either we haven't seen a FIN for this flow or we\n * have and it's this frame. Note that this is the FIN\n * for this flow, terminate reassembly and dissect the\n * results. */\n tcpd->fwd->fin = pinfo->num;\n msp=(struct tcp_multisegment_pdu *)wmem_tree_lookup32_le(tcpd->fwd->multisegment_pdus, tcph->th_seq-1);\n if(msp) {\n fragment_head *ipfd_head;\n\n ipfd_head = fragment_add(&tcp_reassembly_table, tvb, offset,\n pinfo, msp->first_frame, NULL,\n tcph->th_seq - msp->seq,\n tcph->th_seglen,\n FALSE );\n if(ipfd_head) {\n tvbuff_t *next_tvb;\n\n /* create a new TVB structure for desegmented data\n * datalen-1 to strip the dummy FIN byte off\n */\n next_tvb = tvb_new_chain(tvb, ipfd_head->tvb_data);\n\n /* add desegmented data to the data source list */\n add_new_data_source(pinfo, next_tvb, \"Reassembled TCP\");\n\n /* Show details of the reassembly */\n print_tcp_fragment_tree(ipfd_head, tree, tcp_tree, pinfo, next_tvb);\n\n /* call the payload dissector\n * but make sure we don't offer desegmentation any more\n */\n pinfo->can_desegment = 0;\n\n process_tcp_payload(next_tvb, 0, pinfo, tree, tcp_tree, tcph->th_sport, tcph->th_dport, tcph->th_seq,\n nxtseq, FALSE, tcpd, &tcpinfo);\n\n return tvb_captured_length(tvb);\n }\n }\n } else {\n /* Yes. This is a retransmission of the final FIN (or it's\n * the final FIN transmitted via a different path).\n * XXX - we need to flag retransmissions a bit better.\n */\n proto_tree_add_uint(tcp_tree, hf_tcp_fin_retransmission, tvb, 0, 0, tcpd->fwd->fin);\n }\n }\n\n if (tcp_display_process_info && tcpd && ((tcpd->fwd && tcpd->fwd->process_info && tcpd->fwd->process_info->command) ||\n (tcpd->rev && tcpd->rev->process_info && tcpd->rev->process_info->command))) {\n field_tree = proto_tree_add_subtree(tcp_tree, tvb, offset, 0, ett_tcp_process_info, &ti, \"Process Information\");\n PROTO_ITEM_SET_GENERATED(ti);\n if (tcpd->fwd && tcpd->fwd->process_info && tcpd->fwd->process_info->command) {\n proto_tree_add_uint(field_tree, hf_tcp_proc_dst_uid, tvb, 0, 0, tcpd->fwd->process_info->process_uid);\n proto_tree_add_uint(field_tree, hf_tcp_proc_dst_pid, tvb, 0, 0, tcpd->fwd->process_info->process_pid);\n proto_tree_add_string(field_tree, hf_tcp_proc_dst_uname, tvb, 0, 0, tcpd->fwd->process_info->username);\n proto_tree_add_string(field_tree, hf_tcp_proc_dst_cmd, tvb, 0, 0, tcpd->fwd->process_info->command);\n }\n if (tcpd->rev && tcpd->rev->process_info && tcpd->rev->process_info->command) {\n proto_tree_add_uint(field_tree, hf_tcp_proc_src_uid, tvb, 0, 0, tcpd->rev->process_info->process_uid);\n proto_tree_add_uint(field_tree, hf_tcp_proc_src_pid, tvb, 0, 0, tcpd->rev->process_info->process_pid);\n proto_tree_add_string(field_tree, hf_tcp_proc_src_uname, tvb, 0, 0, tcpd->rev->process_info->username);\n proto_tree_add_string(field_tree, hf_tcp_proc_src_cmd, tvb, 0, 0, tcpd->rev->process_info->command);\n }\n }\n\n /*\n * XXX - what, if any, of this should we do if this is included in an\n * error packet? It might be nice to see the details of the packet\n * that caused the ICMP error, but it might not be nice to have the\n * dissector update state based on it.\n * Also, we probably don't want to run TCP taps on those packets.\n */\n if (captured_length_remaining != 0) {\n if (tcph->th_flags & TH_RST) {\n /*\n * RFC1122 says:\n *\n * 4.2.2.12 RST Segment: RFC-793 Section 3.4\n *\n * A TCP SHOULD allow a received RST segment to include data.\n *\n * DISCUSSION\n * It has been suggested that a RST segment could contain\n * ASCII text that encoded and explained the cause of the\n * RST. No standard has yet been established for such\n * data.\n *\n * so for segments with RST we just display the data as text.\n */\n proto_tree_add_item(tcp_tree, hf_tcp_reset_cause, tvb, offset, captured_length_remaining, ENC_NA|ENC_ASCII);\n } else {\n /*\n * XXX - dissect_tcp_payload() expects the payload length, however\n * SYN and FIN increments the nxtseq by one without having\n * the data.\n */\n if ((tcph->th_flags&(TH_FIN|TH_SYN)) && (tcph->th_seglen > 0)) {\n nxtseq -= 1;\n }\n dissect_tcp_payload(tvb, pinfo, offset, tcph->th_seq, nxtseq,\n tcph->th_sport, tcph->th_dport, tree, tcp_tree, tcpd, &tcpinfo);\n }\n }\n return tvb_captured_length(tvb);\n}", "project": "wireshark", "hash": 314637810017431195334165172811945016897, "size": 807, "commit_id": "7f3fe6164a68b76d9988c4253b24d43f498f1753", "message": "TCP: do not use an unknown status when the checksum is 0xffff\n\nOtherwise it triggers an assert when adding the column as the field is\ndefined as BASE_NONE and not BASE_DEC or BASE_HEX. Thus an unknown value\n(not in proto_checksum_vals[)array) cannot be represented.\nMark the checksum as bad even if we process the packet.\nCloses #16816\n\nConflicts:\n\tepan/dissectors/packet-tcp.c", "target": 0, "dataset": "other", "idx": 385216} {"func": "static void umd_cleanup(struct subprocess_info *info)\n{\n\tstruct umd_info *umd_info = info->data;\n\n\t/* cleanup if umh_setup() was successful but exec failed */\n\tif (info->retval) {\n\t\tfput(umd_info->pipe_to_umh);\n\t\tfput(umd_info->pipe_from_umh);\n\t\tput_pid(umd_info->tgid);\n\t\tumd_info->tgid = NULL;\n\t}\n}", "project": "linux", "hash": 202261761255865455882373619018707547027, "size": 12, "commit_id": "f60a85cad677c4f9bb4cadd764f1d106c38c7cf8", "message": "bpf: Fix umd memory leak in copy_process()\n\nThe syzbot reported a memleak as follows:\n\nBUG: memory leak\nunreferenced object 0xffff888101b41d00 (size 120):\n comm \"kworker/u4:0\", pid 8, jiffies 4294944270 (age 12.780s)\n backtrace:\n [] alloc_pid+0x66/0x560\n [] copy_process+0x1465/0x25e0\n [] kernel_clone+0xf3/0x670\n [] kernel_thread+0x61/0x80\n [] call_usermodehelper_exec_work\n [] call_usermodehelper_exec_work+0xc4/0x120\n [] process_one_work+0x2c9/0x600\n [] worker_thread+0x59/0x5d0\n [] kthread+0x178/0x1b0\n [] ret_from_fork+0x1f/0x30\n\nunreferenced object 0xffff888110ef5c00 (size 232):\n comm \"kworker/u4:0\", pid 8414, jiffies 4294944270 (age 12.780s)\n backtrace:\n [] kmem_cache_zalloc\n [] __alloc_file+0x1f/0xf0\n [] alloc_empty_file+0x69/0x120\n [] alloc_file+0x33/0x1b0\n [] alloc_file_pseudo+0xb2/0x140\n [] create_pipe_files+0x138/0x2e0\n [] umd_setup+0x33/0x220\n [] call_usermodehelper_exec_async+0xb4/0x1b0\n [] ret_from_fork+0x1f/0x30\n\nAfter the UMD process exits, the pipe_to_umh/pipe_from_umh and\ntgid need to be released.\n\nFixes: d71fa5c9763c (\"bpf: Add kernel module with user mode driver that populates bpffs.\")\nReported-by: syzbot+44908bb56d2bfe56b28e@syzkaller.appspotmail.com\nSigned-off-by: Zqiang \nSigned-off-by: Daniel Borkmann \nLink: https://lore.kernel.org/bpf/20210317030915.2865-1-qiang.zhang@windriver.com", "target": 1, "dataset": "other", "idx": 206697} {"func": "static void umd_cleanup(struct subprocess_info *info)\n{\n\tstruct umd_info *umd_info = info->data;\n\n\t/* cleanup if umh_setup() was successful but exec failed */\n\tif (info->retval)\n\t\tumd_cleanup_helper(umd_info);\n}", "project": "linux", "hash": 164239646891437415065034800136492740579, "size": 8, "commit_id": "f60a85cad677c4f9bb4cadd764f1d106c38c7cf8", "message": "bpf: Fix umd memory leak in copy_process()\n\nThe syzbot reported a memleak as follows:\n\nBUG: memory leak\nunreferenced object 0xffff888101b41d00 (size 120):\n comm \"kworker/u4:0\", pid 8, jiffies 4294944270 (age 12.780s)\n backtrace:\n [] alloc_pid+0x66/0x560\n [] copy_process+0x1465/0x25e0\n [] kernel_clone+0xf3/0x670\n [] kernel_thread+0x61/0x80\n [] call_usermodehelper_exec_work\n [] call_usermodehelper_exec_work+0xc4/0x120\n [] process_one_work+0x2c9/0x600\n [] worker_thread+0x59/0x5d0\n [] kthread+0x178/0x1b0\n [] ret_from_fork+0x1f/0x30\n\nunreferenced object 0xffff888110ef5c00 (size 232):\n comm \"kworker/u4:0\", pid 8414, jiffies 4294944270 (age 12.780s)\n backtrace:\n [] kmem_cache_zalloc\n [] __alloc_file+0x1f/0xf0\n [] alloc_empty_file+0x69/0x120\n [] alloc_file+0x33/0x1b0\n [] alloc_file_pseudo+0xb2/0x140\n [] create_pipe_files+0x138/0x2e0\n [] umd_setup+0x33/0x220\n [] call_usermodehelper_exec_async+0xb4/0x1b0\n [] ret_from_fork+0x1f/0x30\n\nAfter the UMD process exits, the pipe_to_umh/pipe_from_umh and\ntgid need to be released.\n\nFixes: d71fa5c9763c (\"bpf: Add kernel module with user mode driver that populates bpffs.\")\nReported-by: syzbot+44908bb56d2bfe56b28e@syzkaller.appspotmail.com\nSigned-off-by: Zqiang \nSigned-off-by: Daniel Borkmann \nLink: https://lore.kernel.org/bpf/20210317030915.2865-1-qiang.zhang@windriver.com", "target": 0, "dataset": "other", "idx": 385297} {"func": "\nstatic int\nxmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt,\n\t\t\t\t xmlXPathStepOpPtr op,\n\t\t\t\t xmlNodeSetPtr set,\n\t\t\t\t int contextSize,\n\t\t\t\t int minPos,\n\t\t\t\t int maxPos,\n\t\t\t\t int hasNsNodes)\n{\n if (op->ch1 != -1) {\n\txmlXPathCompExprPtr comp = ctxt->comp;\n\tif (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {\n\t /*\n\t * TODO: raise an internal error.\n\t */\n\t}\n\tcontextSize = xmlXPathCompOpEvalPredicate(ctxt,\n\t &comp->steps[op->ch1], set, contextSize, hasNsNodes);\n\tCHECK_ERROR0;\n\tif (contextSize <= 0)\n\t return(0);\n }\n /*\n * Check if the node set contains a sufficient number of nodes for\n * the requested range.\n */\n if (contextSize < minPos) {\n\txmlXPathNodeSetClear(set, hasNsNodes);\n\treturn(0);\n }\n if (op->ch2 == -1) {\n\t/*\n\t* TODO: Can this ever happen?\n\t*/\n\treturn (contextSize);\n } else {\n\txmlDocPtr oldContextDoc;\n\tint i, pos = 0, newContextSize = 0, contextPos = 0, res;\n\txmlXPathStepOpPtr exprOp;\n\txmlXPathObjectPtr contextObj = NULL, exprRes = NULL;\n\txmlNodePtr oldContextNode, contextNode = NULL;\n\txmlXPathContextPtr xpctxt = ctxt->context;\n int frame;\n\n#ifdef LIBXML_XPTR_ENABLED\n\t /*\n\t * URGENT TODO: Check the following:\n\t * We don't expect location sets if evaluating prediates, right?\n\t * Only filters should expect location sets, right?\n\t*/\n#endif /* LIBXML_XPTR_ENABLED */\n\n\t/*\n\t* Save old context.\n\t*/\n\toldContextNode = xpctxt->node;\n\toldContextDoc = xpctxt->doc;\n\t/*\n\t* Get the expression of this predicate.\n\t*/\n\texprOp = &ctxt->comp->steps[op->ch2];\n\tfor (i = 0; i < set->nodeNr; i++) {\n xmlXPathObjectPtr tmp;\n\n\t if (set->nodeTab[i] == NULL)\n\t\tcontinue;\n\n\t contextNode = set->nodeTab[i];\n\t xpctxt->node = contextNode;\n\t xpctxt->contextSize = contextSize;\n\t xpctxt->proximityPosition = ++contextPos;\n\n\t /*\n\t * Initialize the new set.\n\t * Also set the xpath document in case things like\n\t * key() evaluation are attempted on the predicate\n\t */\n\t if ((contextNode->type != XML_NAMESPACE_DECL) &&\n\t\t(contextNode->doc != NULL))\n\t\txpctxt->doc = contextNode->doc;\n\t /*\n\t * Evaluate the predicate expression with 1 context node\n\t * at a time; this node is packaged into a node set; this\n\t * node set is handed over to the evaluation mechanism.\n\t */\n\t if (contextObj == NULL)\n\t\tcontextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);\n\t else {\n\t\tif (xmlXPathNodeSetAddUnique(contextObj->nodesetval,\n\t\t contextNode) < 0) {\n\t\t ctxt->error = XPATH_MEMORY_ERROR;\n\t\t goto evaluation_exit;\n\t\t}\n\t }\n\n frame = xmlXPathSetFrame(ctxt);\n\t valuePush(ctxt, contextObj);\n\t res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);\n tmp = valuePop(ctxt);\n xmlXPathPopFrame(ctxt, frame);\n\n\t if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {\n while (tmp != contextObj) {\n /*\n * Free up the result\n * then pop off contextObj, which will be freed later\n */\n xmlXPathReleaseObject(xpctxt, tmp);\n tmp = valuePop(ctxt);\n }\n\t\tgoto evaluation_error;\n\t }\n /* push the result back onto the stack */\n valuePush(ctxt, tmp);\n\n\t if (res)\n\t\tpos++;\n\n\t if (res && (pos >= minPos) && (pos <= maxPos)) {\n\t\t/*\n\t\t* Fits in the requested range.\n\t\t*/\n\t\tnewContextSize++;\n\t\tif (minPos == maxPos) {\n\t\t /*\n\t\t * Only 1 node was requested.\n\t\t */\n\t\t if (contextNode->type == XML_NAMESPACE_DECL) {\n\t\t\t/*\n\t\t\t* As always: take care of those nasty\n\t\t\t* namespace nodes.\n\t\t\t*/\n\t\t\tset->nodeTab[i] = NULL;\n\t\t }\n\t\t xmlXPathNodeSetClear(set, hasNsNodes);\n\t\t set->nodeNr = 1;\n\t\t set->nodeTab[0] = contextNode;\n\t\t goto evaluation_exit;\n\t\t}\n\t\tif (pos == maxPos) {\n\t\t /*\n\t\t * We are done.\n\t\t */\n\t\t xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes);\n\t\t goto evaluation_exit;\n\t\t}\n\t } else {\n\t\t/*\n\t\t* Remove the entry from the initial node set.\n\t\t*/\n\t\tset->nodeTab[i] = NULL;\n\t\tif (contextNode->type == XML_NAMESPACE_DECL)\n\t\t xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);\n\t }\n\t if (exprRes != NULL) {\n\t\txmlXPathReleaseObject(ctxt->context, exprRes);\n\t\texprRes = NULL;\n\t }\n\t if (ctxt->value == contextObj) {\n\t\t/*\n\t\t* Don't free the temporary XPath object holding the\n\t\t* context node, in order to avoid massive recreation\n\t\t* inside this loop.\n\t\t*/\n\t\tvaluePop(ctxt);\n\t\txmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);\n\t } else {\n\t\t/*\n\t\t* The object was lost in the evaluation machinery.\n\t\t* Can this happen? Maybe in case of internal-errors.\n\t\t*/\n\t\tcontextObj = NULL;\n\t }\n\t}\n\tgoto evaluation_exit;\n\nevaluation_error:\n\txmlXPathNodeSetClear(set, hasNsNodes);\n\tnewContextSize = 0;\n\nevaluation_exit:\n\tif (contextObj != NULL) {\n\t if (ctxt->value == contextObj)\n\t\tvaluePop(ctxt);\n\t xmlXPathReleaseObject(xpctxt, contextObj);\n\t}\n\tif (exprRes != NULL)\n\t xmlXPathReleaseObject(ctxt->context, exprRes);\n\t/*\n\t* Reset/invalidate the context.\n\t*/\n\txpctxt->node = oldContextNode;\n\txpctxt->doc = oldContextDoc;\n\txpctxt->contextSize = -1;\n\txpctxt->proximityPosition = -1;\n\treturn(newContextSize);\n }", "project": "libxml2", "hash": 173043750179367760971490701431316800176, "size": 198, "commit_id": "0f3b843b3534784ef57a4f9b874238aa1fda5a73", "message": "Fix XPath stack frame logic\n\nMove the calls to xmlXPathSetFrame and xmlXPathPopFrame around in\nxmlXPathCompOpEvalPositionalPredicate to make sure that the context\nobject on the stack is actually protected. Otherwise, memory corruption\ncan occur when calling sloppily coded XPath extension functions.\n\nFixes bug 783160.", "target": 1, "dataset": "other", "idx": 206698} {"func": "\nstatic int\nxmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt,\n\t\t\t\t xmlXPathStepOpPtr op,\n\t\t\t\t xmlNodeSetPtr set,\n\t\t\t\t int contextSize,\n\t\t\t\t int minPos,\n\t\t\t\t int maxPos,\n\t\t\t\t int hasNsNodes)\n{\n if (op->ch1 != -1) {\n\txmlXPathCompExprPtr comp = ctxt->comp;\n\tif (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {\n\t /*\n\t * TODO: raise an internal error.\n\t */\n\t}\n\tcontextSize = xmlXPathCompOpEvalPredicate(ctxt,\n\t &comp->steps[op->ch1], set, contextSize, hasNsNodes);\n\tCHECK_ERROR0;\n\tif (contextSize <= 0)\n\t return(0);\n }\n /*\n * Check if the node set contains a sufficient number of nodes for\n * the requested range.\n */\n if (contextSize < minPos) {\n\txmlXPathNodeSetClear(set, hasNsNodes);\n\treturn(0);\n }\n if (op->ch2 == -1) {\n\t/*\n\t* TODO: Can this ever happen?\n\t*/\n\treturn (contextSize);\n } else {\n\txmlDocPtr oldContextDoc;\n\tint i, pos = 0, newContextSize = 0, contextPos = 0, res;\n\txmlXPathStepOpPtr exprOp;\n\txmlXPathObjectPtr contextObj = NULL, exprRes = NULL;\n\txmlNodePtr oldContextNode, contextNode = NULL;\n\txmlXPathContextPtr xpctxt = ctxt->context;\n int frame;\n\n#ifdef LIBXML_XPTR_ENABLED\n\t /*\n\t * URGENT TODO: Check the following:\n\t * We don't expect location sets if evaluating prediates, right?\n\t * Only filters should expect location sets, right?\n\t*/\n#endif /* LIBXML_XPTR_ENABLED */\n\n\t/*\n\t* Save old context.\n\t*/\n\toldContextNode = xpctxt->node;\n\toldContextDoc = xpctxt->doc;\n\t/*\n\t* Get the expression of this predicate.\n\t*/\n\texprOp = &ctxt->comp->steps[op->ch2];\n\tfor (i = 0; i < set->nodeNr; i++) {\n xmlXPathObjectPtr tmp;\n\n\t if (set->nodeTab[i] == NULL)\n\t\tcontinue;\n\n\t contextNode = set->nodeTab[i];\n\t xpctxt->node = contextNode;\n\t xpctxt->contextSize = contextSize;\n\t xpctxt->proximityPosition = ++contextPos;\n\n\t /*\n\t * Initialize the new set.\n\t * Also set the xpath document in case things like\n\t * key() evaluation are attempted on the predicate\n\t */\n\t if ((contextNode->type != XML_NAMESPACE_DECL) &&\n\t\t(contextNode->doc != NULL))\n\t\txpctxt->doc = contextNode->doc;\n\t /*\n\t * Evaluate the predicate expression with 1 context node\n\t * at a time; this node is packaged into a node set; this\n\t * node set is handed over to the evaluation mechanism.\n\t */\n\t if (contextObj == NULL)\n\t\tcontextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);\n\t else {\n\t\tif (xmlXPathNodeSetAddUnique(contextObj->nodesetval,\n\t\t contextNode) < 0) {\n\t\t ctxt->error = XPATH_MEMORY_ERROR;\n\t\t goto evaluation_exit;\n\t\t}\n\t }\n\n\t valuePush(ctxt, contextObj);\n frame = xmlXPathSetFrame(ctxt);\n\t res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);\n xmlXPathPopFrame(ctxt, frame);\n tmp = valuePop(ctxt);\n\n\t if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {\n while (tmp != contextObj) {\n /*\n * Free up the result\n * then pop off contextObj, which will be freed later\n */\n xmlXPathReleaseObject(xpctxt, tmp);\n tmp = valuePop(ctxt);\n }\n\t\tgoto evaluation_error;\n\t }\n /* push the result back onto the stack */\n valuePush(ctxt, tmp);\n\n\t if (res)\n\t\tpos++;\n\n\t if (res && (pos >= minPos) && (pos <= maxPos)) {\n\t\t/*\n\t\t* Fits in the requested range.\n\t\t*/\n\t\tnewContextSize++;\n\t\tif (minPos == maxPos) {\n\t\t /*\n\t\t * Only 1 node was requested.\n\t\t */\n\t\t if (contextNode->type == XML_NAMESPACE_DECL) {\n\t\t\t/*\n\t\t\t* As always: take care of those nasty\n\t\t\t* namespace nodes.\n\t\t\t*/\n\t\t\tset->nodeTab[i] = NULL;\n\t\t }\n\t\t xmlXPathNodeSetClear(set, hasNsNodes);\n\t\t set->nodeNr = 1;\n\t\t set->nodeTab[0] = contextNode;\n\t\t goto evaluation_exit;\n\t\t}\n\t\tif (pos == maxPos) {\n\t\t /*\n\t\t * We are done.\n\t\t */\n\t\t xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes);\n\t\t goto evaluation_exit;\n\t\t}\n\t } else {\n\t\t/*\n\t\t* Remove the entry from the initial node set.\n\t\t*/\n\t\tset->nodeTab[i] = NULL;\n\t\tif (contextNode->type == XML_NAMESPACE_DECL)\n\t\t xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);\n\t }\n\t if (exprRes != NULL) {\n\t\txmlXPathReleaseObject(ctxt->context, exprRes);\n\t\texprRes = NULL;\n\t }\n\t if (ctxt->value == contextObj) {\n\t\t/*\n\t\t* Don't free the temporary XPath object holding the\n\t\t* context node, in order to avoid massive recreation\n\t\t* inside this loop.\n\t\t*/\n\t\tvaluePop(ctxt);\n\t\txmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);\n\t } else {\n\t\t/*\n\t\t* The object was lost in the evaluation machinery.\n\t\t* Can this happen? Maybe in case of internal-errors.\n\t\t*/\n\t\tcontextObj = NULL;\n\t }\n\t}\n\tgoto evaluation_exit;\n\nevaluation_error:\n\txmlXPathNodeSetClear(set, hasNsNodes);\n\tnewContextSize = 0;\n\nevaluation_exit:\n\tif (contextObj != NULL) {\n\t if (ctxt->value == contextObj)\n\t\tvaluePop(ctxt);\n\t xmlXPathReleaseObject(xpctxt, contextObj);\n\t}\n\tif (exprRes != NULL)\n\t xmlXPathReleaseObject(ctxt->context, exprRes);\n\t/*\n\t* Reset/invalidate the context.\n\t*/\n\txpctxt->node = oldContextNode;\n\txpctxt->doc = oldContextDoc;\n\txpctxt->contextSize = -1;\n\txpctxt->proximityPosition = -1;\n\treturn(newContextSize);\n }", "project": "libxml2", "hash": 87079765018061420144174234477625527081, "size": 198, "commit_id": "0f3b843b3534784ef57a4f9b874238aa1fda5a73", "message": "Fix XPath stack frame logic\n\nMove the calls to xmlXPathSetFrame and xmlXPathPopFrame around in\nxmlXPathCompOpEvalPositionalPredicate to make sure that the context\nobject on the stack is actually protected. Otherwise, memory corruption\ncan occur when calling sloppily coded XPath extension functions.\n\nFixes bug 783160.", "target": 0, "dataset": "other", "idx": 385345} {"func": "void Utf8DecoderBase::WriteUtf16Slow(const uint8_t* stream,\n uint16_t* data,\n unsigned data_length) {\n while (data_length != 0) {\n unsigned cursor = 0;\n uint32_t character = Utf8::ValueOf(stream, Utf8::kMaxEncodedSize, &cursor);\n // There's a total lack of bounds checking for stream\n // as it was already done in Reset.\n stream += cursor;\n if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {\n *data++ = Utf16::LeadSurrogate(character);\n *data++ = Utf16::TrailSurrogate(character);\n DCHECK(data_length > 1);\n data_length -= 2;\n } else {\n *data++ = character;\n data_length -= 1;\n }\n }\n}", "project": "node", "hash": 252347364978872387181975652701666279871, "size": 20, "commit_id": "78b0e30954111cfaba0edbeee85450d8cbc6fdf6", "message": "deps: fix out-of-band write in utf8 decoder\n\nOriginally reported by: Kris Reeves \n\nReviewed-By: Trevor Norris ", "target": 1, "dataset": "other", "idx": 206709} {"func": "void Utf8DecoderBase::WriteUtf16Slow(const uint8_t* stream,\n unsigned stream_length,\n uint16_t* data,\n unsigned data_length) {\n while (data_length != 0) {\n unsigned cursor = 0;\n\n uint32_t character = Utf8::ValueOf(stream, stream_length, &cursor);\n // There's a total lack of bounds checking for stream\n // as it was already done in Reset.\n stream += cursor;\n stream_length -= cursor;\n if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {\n *data++ = Utf16::LeadSurrogate(character);\n *data++ = Utf16::TrailSurrogate(character);\n DCHECK(data_length > 1);\n data_length -= 2;\n } else {\n *data++ = character;\n data_length -= 1;\n }\n }\n DCHECK(stream_length >= 0);\n}", "project": "node", "hash": 108599142078622494128331469487001444691, "size": 24, "commit_id": "78b0e30954111cfaba0edbeee85450d8cbc6fdf6", "message": "deps: fix out-of-band write in utf8 decoder\n\nOriginally reported by: Kris Reeves \n\nReviewed-By: Trevor Norris ", "target": 0, "dataset": "other", "idx": 385616} {"func": "MagickExport Image *WaveImage(const Image *image,const double amplitude,\n const double wave_length,ExceptionInfo *exception)\n{\n#define WaveImageTag \"Wave/Image\"\n\n CacheView\n *image_view,\n *wave_view;\n\n float\n *sine_map;\n\n Image\n *wave_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n MagickPixelPacket\n zero;\n\n ssize_t\n i;\n\n ssize_t\n y;\n\n /*\n Initialize wave image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n wave_image=CloneImage(image,image->columns,(size_t) (image->rows+2.0*\n fabs(amplitude)),MagickTrue,exception);\n if (wave_image == (Image *) NULL)\n return((Image *) NULL);\n if (SetImageStorageClass(wave_image,DirectClass) == MagickFalse)\n {\n InheritException(exception,&wave_image->exception);\n wave_image=DestroyImage(wave_image);\n return((Image *) NULL);\n }\n if (wave_image->background_color.opacity != OpaqueOpacity)\n wave_image->matte=MagickTrue;\n /*\n Allocate sine map.\n */\n sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,\n sizeof(*sine_map));\n if (sine_map == (float *) NULL)\n {\n wave_image=DestroyImage(wave_image);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) wave_image->columns; i++)\n sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)\n ((2.0*MagickPI*i)/wave_length));\n /*\n Wave image.\n */\n status=MagickTrue;\n progress=0;\n GetMagickPixelPacket(wave_image,&zero);\n image_view=AcquireVirtualCacheView(image,exception);\n wave_view=AcquireAuthenticCacheView(wave_image,exception);\n (void) SetCacheViewVirtualPixelMethod(image_view,\n BackgroundVirtualPixelMethod);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(image,wave_image,wave_image->rows,1)\n#endif\n for (y=0; y < (ssize_t) wave_image->rows; y++)\n {\n MagickPixelPacket\n pixel;\n\n IndexPacket\n *magick_restrict indexes;\n\n PixelPacket\n *magick_restrict q;\n\n ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n indexes=GetCacheViewAuthenticIndexQueue(wave_view);\n pixel=zero;\n for (x=0; x < (ssize_t) wave_image->columns; x++)\n {\n status=InterpolateMagickPixelPacket(image,image_view,\n UndefinedInterpolatePixel,(double) x,(double) (y-sine_map[x]),&pixel,\n exception);\n if (status == MagickFalse)\n break;\n SetPixelPacket(wave_image,&pixel,q,indexes+x);\n q++;\n }\n if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,WaveImageTag,progress,image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n wave_view=DestroyCacheView(wave_view);\n image_view=DestroyCacheView(image_view);\n sine_map=(float *) RelinquishMagickMemory(sine_map);\n if (status == MagickFalse)\n wave_image=DestroyImage(wave_image);\n return(wave_image);\n}", "project": "ImageMagick6", "hash": 151042824862097823118767733345259035764, "size": 136, "commit_id": "f1e68d22d1b35459421710587a0dcbab6900b51f", "message": "https://github.com/ImageMagick/ImageMagick/issues/3296", "target": 1, "dataset": "other", "idx": 206717} {"func": "MagickExport Image *WaveImage(const Image *image,const double amplitude,\n const double wave_length,ExceptionInfo *exception)\n{\n#define WaveImageTag \"Wave/Image\"\n\n CacheView\n *image_view,\n *wave_view;\n\n float\n *sine_map;\n\n Image\n *wave_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n MagickPixelPacket\n zero;\n\n ssize_t\n i;\n\n ssize_t\n y;\n\n /*\n Initialize wave image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n wave_image=CloneImage(image,image->columns,(size_t) (image->rows+2.0*\n fabs(amplitude)),MagickTrue,exception);\n if (wave_image == (Image *) NULL)\n return((Image *) NULL);\n if (SetImageStorageClass(wave_image,DirectClass) == MagickFalse)\n {\n InheritException(exception,&wave_image->exception);\n wave_image=DestroyImage(wave_image);\n return((Image *) NULL);\n }\n if (wave_image->background_color.opacity != OpaqueOpacity)\n wave_image->matte=MagickTrue;\n /*\n Allocate sine map.\n */\n sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns,\n sizeof(*sine_map));\n if (sine_map == (float *) NULL)\n {\n wave_image=DestroyImage(wave_image);\n ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n for (i=0; i < (ssize_t) wave_image->columns; i++)\n sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double)\n ((2.0*MagickPI*i)*PerceptibleReciprocal(wave_length)));\n /*\n Wave image.\n */\n status=MagickTrue;\n progress=0;\n GetMagickPixelPacket(wave_image,&zero);\n image_view=AcquireVirtualCacheView(image,exception);\n wave_view=AcquireAuthenticCacheView(wave_image,exception);\n (void) SetCacheViewVirtualPixelMethod(image_view,\n BackgroundVirtualPixelMethod);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(image,wave_image,wave_image->rows,1)\n#endif\n for (y=0; y < (ssize_t) wave_image->rows; y++)\n {\n MagickPixelPacket\n pixel;\n\n IndexPacket\n *magick_restrict indexes;\n\n PixelPacket\n *magick_restrict q;\n\n ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,\n exception);\n if (q == (PixelPacket *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n indexes=GetCacheViewAuthenticIndexQueue(wave_view);\n pixel=zero;\n for (x=0; x < (ssize_t) wave_image->columns; x++)\n {\n status=InterpolateMagickPixelPacket(image,image_view,\n UndefinedInterpolatePixel,(double) x,(double) (y-sine_map[x]),&pixel,\n exception);\n if (status == MagickFalse)\n break;\n SetPixelPacket(wave_image,&pixel,q,indexes+x);\n q++;\n }\n if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,WaveImageTag,progress,image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n wave_view=DestroyCacheView(wave_view);\n image_view=DestroyCacheView(image_view);\n sine_map=(float *) RelinquishMagickMemory(sine_map);\n if (status == MagickFalse)\n wave_image=DestroyImage(wave_image);\n return(wave_image);\n}", "project": "ImageMagick6", "hash": 101226025493037855922393203126658342941, "size": 136, "commit_id": "f1e68d22d1b35459421710587a0dcbab6900b51f", "message": "https://github.com/ImageMagick/ImageMagick/issues/3296", "target": 0, "dataset": "other", "idx": 385763} {"func": "static int route4_change(struct net *net, struct sk_buff *in_skb,\n\t\t\t struct tcf_proto *tp, unsigned long base, u32 handle,\n\t\t\t struct nlattr **tca, void **arg, bool ovr,\n\t\t\t bool rtnl_held, struct netlink_ext_ack *extack)\n{\n\tstruct route4_head *head = rtnl_dereference(tp->root);\n\tstruct route4_filter __rcu **fp;\n\tstruct route4_filter *fold, *f1, *pfp, *f = NULL;\n\tstruct route4_bucket *b;\n\tstruct nlattr *opt = tca[TCA_OPTIONS];\n\tstruct nlattr *tb[TCA_ROUTE4_MAX + 1];\n\tunsigned int h, th;\n\tint err;\n\tbool new = true;\n\n\tif (opt == NULL)\n\t\treturn handle ? -EINVAL : 0;\n\n\terr = nla_parse_nested_deprecated(tb, TCA_ROUTE4_MAX, opt,\n\t\t\t\t\t route4_policy, NULL);\n\tif (err < 0)\n\t\treturn err;\n\n\tfold = *arg;\n\tif (fold && handle && fold->handle != handle)\n\t\t\treturn -EINVAL;\n\n\terr = -ENOBUFS;\n\tf = kzalloc(sizeof(struct route4_filter), GFP_KERNEL);\n\tif (!f)\n\t\tgoto errout;\n\n\terr = tcf_exts_init(&f->exts, net, TCA_ROUTE4_ACT, TCA_ROUTE4_POLICE);\n\tif (err < 0)\n\t\tgoto errout;\n\n\tif (fold) {\n\t\tf->id = fold->id;\n\t\tf->iif = fold->iif;\n\t\tf->res = fold->res;\n\t\tf->handle = fold->handle;\n\n\t\tf->tp = fold->tp;\n\t\tf->bkt = fold->bkt;\n\t\tnew = false;\n\t}\n\n\terr = route4_set_parms(net, tp, base, f, handle, head, tb,\n\t\t\t tca[TCA_RATE], new, ovr, extack);\n\tif (err < 0)\n\t\tgoto errout;\n\n\th = from_hash(f->handle >> 16);\n\tfp = &f->bkt->ht[h];\n\tfor (pfp = rtnl_dereference(*fp);\n\t (f1 = rtnl_dereference(*fp)) != NULL;\n\t fp = &f1->next)\n\t\tif (f->handle < f1->handle)\n\t\t\tbreak;\n\n\ttcf_block_netif_keep_dst(tp->chain->block);\n\trcu_assign_pointer(f->next, f1);\n\trcu_assign_pointer(*fp, f);\n\n\tif (fold && fold->handle && f->handle != fold->handle) {\n\t\tth = to_hash(fold->handle);\n\t\th = from_hash(fold->handle >> 16);\n\t\tb = rtnl_dereference(head->table[th]);\n\t\tif (b) {\n\t\t\tfp = &b->ht[h];\n\t\t\tfor (pfp = rtnl_dereference(*fp); pfp;\n\t\t\t fp = &pfp->next, pfp = rtnl_dereference(*fp)) {\n\t\t\t\tif (pfp == f) {\n\t\t\t\t\t*fp = f->next;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\troute4_reset_fastmap(head);\n\t*arg = f;\n\tif (fold) {\n\t\ttcf_unbind_filter(tp, &fold->res);\n\t\ttcf_exts_get_net(&fold->exts);\n\t\ttcf_queue_work(&fold->rwork, route4_delete_filter_work);\n\t}\n\treturn 0;\n\nerrout:\n\tif (f)\n\t\ttcf_exts_destroy(&f->exts);\n\tkfree(f);\n\treturn err;\n}", "project": "linux", "hash": 231199128984425325302576009574271570955, "size": 95, "commit_id": "ef299cc3fa1a9e1288665a9fdc8bff55629fd359", "message": "net_sched: cls_route: remove the right filter from hashtable\n\nroute4_change() allocates a new filter and copies values from\nthe old one. After the new filter is inserted into the hash\ntable, the old filter should be removed and freed, as the final\nstep of the update.\n\nHowever, the current code mistakenly removes the new one. This\nlooks apparently wrong to me, and it causes double \"free\" and\nuse-after-free too, as reported by syzbot.\n\nReported-and-tested-by: syzbot+f9b32aaacd60305d9687@syzkaller.appspotmail.com\nReported-and-tested-by: syzbot+2f8c233f131943d6056d@syzkaller.appspotmail.com\nReported-and-tested-by: syzbot+9c2df9fd5e9445b74e01@syzkaller.appspotmail.com\nFixes: 1109c00547fc (\"net: sched: RCU cls_route\")\nCc: Jamal Hadi Salim \nCc: Jiri Pirko \nCc: John Fastabend \nSigned-off-by: Cong Wang \nSigned-off-by: David S. Miller ", "target": 1, "dataset": "other", "idx": 206718} {"func": "static int route4_change(struct net *net, struct sk_buff *in_skb,\n\t\t\t struct tcf_proto *tp, unsigned long base, u32 handle,\n\t\t\t struct nlattr **tca, void **arg, bool ovr,\n\t\t\t bool rtnl_held, struct netlink_ext_ack *extack)\n{\n\tstruct route4_head *head = rtnl_dereference(tp->root);\n\tstruct route4_filter __rcu **fp;\n\tstruct route4_filter *fold, *f1, *pfp, *f = NULL;\n\tstruct route4_bucket *b;\n\tstruct nlattr *opt = tca[TCA_OPTIONS];\n\tstruct nlattr *tb[TCA_ROUTE4_MAX + 1];\n\tunsigned int h, th;\n\tint err;\n\tbool new = true;\n\n\tif (opt == NULL)\n\t\treturn handle ? -EINVAL : 0;\n\n\terr = nla_parse_nested_deprecated(tb, TCA_ROUTE4_MAX, opt,\n\t\t\t\t\t route4_policy, NULL);\n\tif (err < 0)\n\t\treturn err;\n\n\tfold = *arg;\n\tif (fold && handle && fold->handle != handle)\n\t\t\treturn -EINVAL;\n\n\terr = -ENOBUFS;\n\tf = kzalloc(sizeof(struct route4_filter), GFP_KERNEL);\n\tif (!f)\n\t\tgoto errout;\n\n\terr = tcf_exts_init(&f->exts, net, TCA_ROUTE4_ACT, TCA_ROUTE4_POLICE);\n\tif (err < 0)\n\t\tgoto errout;\n\n\tif (fold) {\n\t\tf->id = fold->id;\n\t\tf->iif = fold->iif;\n\t\tf->res = fold->res;\n\t\tf->handle = fold->handle;\n\n\t\tf->tp = fold->tp;\n\t\tf->bkt = fold->bkt;\n\t\tnew = false;\n\t}\n\n\terr = route4_set_parms(net, tp, base, f, handle, head, tb,\n\t\t\t tca[TCA_RATE], new, ovr, extack);\n\tif (err < 0)\n\t\tgoto errout;\n\n\th = from_hash(f->handle >> 16);\n\tfp = &f->bkt->ht[h];\n\tfor (pfp = rtnl_dereference(*fp);\n\t (f1 = rtnl_dereference(*fp)) != NULL;\n\t fp = &f1->next)\n\t\tif (f->handle < f1->handle)\n\t\t\tbreak;\n\n\ttcf_block_netif_keep_dst(tp->chain->block);\n\trcu_assign_pointer(f->next, f1);\n\trcu_assign_pointer(*fp, f);\n\n\tif (fold && fold->handle && f->handle != fold->handle) {\n\t\tth = to_hash(fold->handle);\n\t\th = from_hash(fold->handle >> 16);\n\t\tb = rtnl_dereference(head->table[th]);\n\t\tif (b) {\n\t\t\tfp = &b->ht[h];\n\t\t\tfor (pfp = rtnl_dereference(*fp); pfp;\n\t\t\t fp = &pfp->next, pfp = rtnl_dereference(*fp)) {\n\t\t\t\tif (pfp == fold) {\n\t\t\t\t\trcu_assign_pointer(*fp, fold->next);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\troute4_reset_fastmap(head);\n\t*arg = f;\n\tif (fold) {\n\t\ttcf_unbind_filter(tp, &fold->res);\n\t\ttcf_exts_get_net(&fold->exts);\n\t\ttcf_queue_work(&fold->rwork, route4_delete_filter_work);\n\t}\n\treturn 0;\n\nerrout:\n\tif (f)\n\t\ttcf_exts_destroy(&f->exts);\n\tkfree(f);\n\treturn err;\n}", "project": "linux", "hash": 37265442732800560811121149832465762697, "size": 95, "commit_id": "ef299cc3fa1a9e1288665a9fdc8bff55629fd359", "message": "net_sched: cls_route: remove the right filter from hashtable\n\nroute4_change() allocates a new filter and copies values from\nthe old one. After the new filter is inserted into the hash\ntable, the old filter should be removed and freed, as the final\nstep of the update.\n\nHowever, the current code mistakenly removes the new one. This\nlooks apparently wrong to me, and it causes double \"free\" and\nuse-after-free too, as reported by syzbot.\n\nReported-and-tested-by: syzbot+f9b32aaacd60305d9687@syzkaller.appspotmail.com\nReported-and-tested-by: syzbot+2f8c233f131943d6056d@syzkaller.appspotmail.com\nReported-and-tested-by: syzbot+9c2df9fd5e9445b74e01@syzkaller.appspotmail.com\nFixes: 1109c00547fc (\"net: sched: RCU cls_route\")\nCc: Jamal Hadi Salim \nCc: Jiri Pirko \nCc: John Fastabend \nSigned-off-by: Cong Wang \nSigned-off-by: David S. Miller ", "target": 0, "dataset": "other", "idx": 385783} {"func": "apprentice_map(struct magic_set *ms, const char *fn)\n{\n\tuint32_t *ptr;\n\tuint32_t version, entries, nentries;\n\tint needsbyteswap;\n\tchar *dbname = NULL;\n\tstruct magic_map *map;\n\tsize_t i;\n\tphp_stream *stream = NULL;\n\tphp_stream_statbuf st;\n\n\n\tTSRMLS_FETCH();\n\n\tif ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL) {\n\t\tfile_oomem(ms, sizeof(*map));\n\t\tefree(map);\n\t\tgoto error;\n\t}\n\n\tif (fn == NULL) {\n\t\tmap->p = (void *)&php_magic_database;\n\t\tgoto internal_loaded;\n\t}\n\n#ifdef PHP_WIN32\n\t/* Don't bother on windows with php_stream_open_wrapper,\n\treturn to give apprentice_load() a chance. */\n\tif (php_stream_stat_path_ex((char *)fn, 0, &st, NULL) == SUCCESS) {\n if (st.sb.st_mode & S_IFDIR) {\n goto error;\n }\n }\n#endif\n\n\tdbname = mkdbname(ms, fn, 0);\n\tif (dbname == NULL)\n\t\tgoto error;\n\n#if PHP_API_VERSION < 20100412\n\t\tstream = php_stream_open_wrapper((char *)fn, \"rb\", REPORT_ERRORS|ENFORCE_SAFE_MODE, NULL);\n#else\n\t\tstream = php_stream_open_wrapper((char *)fn, \"rb\", REPORT_ERRORS, NULL);\n#endif\n\n\tif (!stream) {\n\t\tgoto error;\n\t}\n\n\tif (php_stream_stat(stream, &st) < 0) {\n\t\tfile_error(ms, errno, \"cannot stat `%s'\", dbname);\n\t\tgoto error;\n\t}\n\n\tif (st.sb.st_size < 8) {\n\t\tfile_error(ms, 0, \"file `%s' is too small\", dbname);\n\t\tgoto error;\n\t}\n\n\tmap->len = (size_t)st.sb.st_size;\n\tif ((map->p = CAST(void *, emalloc(map->len))) == NULL) {\n\t\tfile_oomem(ms, map->len);\n\t\tgoto error;\n\t}\n\tif (php_stream_read(stream, map->p, (size_t)st.sb.st_size) != (size_t)st.sb.st_size) {\n\t\tfile_badread(ms);\n\t\tgoto error;\n\t}\n\tmap->len = 0;\n#define RET\t1\n\n\tphp_stream_close(stream);\n\tstream = NULL;\n\ninternal_loaded:\n\tptr = (uint32_t *)(void *)map->p;\n\tif (*ptr != MAGICNO) {\n\t\tif (swap4(*ptr) != MAGICNO) {\n\t\t\tfile_error(ms, 0, \"bad magic in `%s'\", dbname);\n\t\t\tgoto error;\n\t\t}\n\t\tneedsbyteswap = 1;\n\t} else\n\t\tneedsbyteswap = 0;\n\tif (needsbyteswap)\n\t\tversion = swap4(ptr[1]);\n\telse\n\t\tversion = ptr[1];\n\tif (version != VERSIONNO) {\n\t\tfile_error(ms, 0, \"File %d.%d supports only version %d magic \"\n\t\t \"files. `%s' is version %d\", FILE_VERSION_MAJOR, patchlevel,\n\t\t VERSIONNO, dbname, version);\n\t\tgoto error;\n\t}\n\n\t/* php_magic_database is a const, performing writes will segfault. This is for big-endian\n\tmachines only, PPC and Sparc specifically. Consider static variable or MINIT in\n\tfuture. */\n\tif (needsbyteswap && fn == NULL) {\n\t\tmap->p = emalloc(sizeof(php_magic_database));\n\t\tmap->p = memcpy(map->p, php_magic_database, sizeof(php_magic_database));\n\t}\n\n\tif (NULL != fn) {\n\t\tnentries = (uint32_t)(st.sb.st_size / sizeof(struct magic));\n\t\tentries = (uint32_t)(st.sb.st_size / sizeof(struct magic));\n\t\tif ((off_t)(entries * sizeof(struct magic)) != st.sb.st_size) {\n\t\t\tfile_error(ms, 0, \"Size of `%s' %llu is not a multiple of %zu\",\n\t\t\t\tdbname, (unsigned long long)st.sb.st_size,\n\t\t\t\tsizeof(struct magic));\n\t\t\tgoto error;\n\t\t}\n\t}\n\tmap->magic[0] = CAST(struct magic *, map->p) + 1;\n\tnentries = 0;\n\tfor (i = 0; i < MAGIC_SETS; i++) {\n\t\tif (needsbyteswap)\n\t\t\tmap->nmagic[i] = swap4(ptr[i + 2]);\n\t\telse\n\t\t\tmap->nmagic[i] = ptr[i + 2];\n\t\tif (i != MAGIC_SETS - 1)\n\t\t\tmap->magic[i + 1] = map->magic[i] + map->nmagic[i];\n\t\tnentries += map->nmagic[i];\n\t}\n\tif (NULL != fn && entries != nentries + 1) {\n\t\tfile_error(ms, 0, \"Inconsistent entries in `%s' %u != %u\",\n\t\t dbname, entries, nentries + 1);\n\t\tgoto error;\n\t}\n\n\tif (needsbyteswap)\n\t\tfor (i = 0; i < MAGIC_SETS; i++)\n\t\t\tbyteswap(map->magic[i], map->nmagic[i]);\n\n\tif (dbname) {\n\t\tefree(dbname);\n\t}\n\treturn map;\n\nerror:\n\tif (stream) {\n\t\tphp_stream_close(stream);\n\t}\n\tapprentice_unmap(map);\n\tif (dbname) {\n\t\tefree(dbname);\n\t}\n\treturn NULL;\n}", "project": "php-src", "hash": 251164010590167534593186953249875788485, "size": 149, "commit_id": "91aa340180eccfc15d4a143b54d47b8120f898be", "message": "Fixed bug #68827 Double free with disabled ZMM", "target": 1, "dataset": "other", "idx": 206725} {"func": "apprentice_map(struct magic_set *ms, const char *fn)\n{\n\tuint32_t *ptr;\n\tuint32_t version, entries, nentries;\n\tint needsbyteswap;\n\tchar *dbname = NULL;\n\tstruct magic_map *map;\n\tsize_t i;\n\tphp_stream *stream = NULL;\n\tphp_stream_statbuf st;\n\n\n\tTSRMLS_FETCH();\n\n\tif ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL) {\n\t\tfile_oomem(ms, sizeof(*map));\n\t\treturn NULL;\n\t}\n\n\tif (fn == NULL) {\n\t\tmap->p = (void *)&php_magic_database;\n\t\tgoto internal_loaded;\n\t}\n\n#ifdef PHP_WIN32\n\t/* Don't bother on windows with php_stream_open_wrapper,\n\treturn to give apprentice_load() a chance. */\n\tif (php_stream_stat_path_ex((char *)fn, 0, &st, NULL) == SUCCESS) {\n if (st.sb.st_mode & S_IFDIR) {\n goto error;\n }\n }\n#endif\n\n\tdbname = mkdbname(ms, fn, 0);\n\tif (dbname == NULL)\n\t\tgoto error;\n\n#if PHP_API_VERSION < 20100412\n\t\tstream = php_stream_open_wrapper((char *)fn, \"rb\", REPORT_ERRORS|ENFORCE_SAFE_MODE, NULL);\n#else\n\t\tstream = php_stream_open_wrapper((char *)fn, \"rb\", REPORT_ERRORS, NULL);\n#endif\n\n\tif (!stream) {\n\t\tgoto error;\n\t}\n\n\tif (php_stream_stat(stream, &st) < 0) {\n\t\tfile_error(ms, errno, \"cannot stat `%s'\", dbname);\n\t\tgoto error;\n\t}\n\n\tif (st.sb.st_size < 8) {\n\t\tfile_error(ms, 0, \"file `%s' is too small\", dbname);\n\t\tgoto error;\n\t}\n\n\tmap->len = (size_t)st.sb.st_size;\n\tif ((map->p = CAST(void *, emalloc(map->len))) == NULL) {\n\t\tfile_oomem(ms, map->len);\n\t\tgoto error;\n\t}\n\tif (php_stream_read(stream, map->p, (size_t)st.sb.st_size) != (size_t)st.sb.st_size) {\n\t\tfile_badread(ms);\n\t\tgoto error;\n\t}\n\tmap->len = 0;\n#define RET\t1\n\n\tphp_stream_close(stream);\n\tstream = NULL;\n\ninternal_loaded:\n\tptr = (uint32_t *)(void *)map->p;\n\tif (*ptr != MAGICNO) {\n\t\tif (swap4(*ptr) != MAGICNO) {\n\t\t\tfile_error(ms, 0, \"bad magic in `%s'\", dbname);\n\t\t\tgoto error;\n\t\t}\n\t\tneedsbyteswap = 1;\n\t} else\n\t\tneedsbyteswap = 0;\n\tif (needsbyteswap)\n\t\tversion = swap4(ptr[1]);\n\telse\n\t\tversion = ptr[1];\n\tif (version != VERSIONNO) {\n\t\tfile_error(ms, 0, \"File %d.%d supports only version %d magic \"\n\t\t \"files. `%s' is version %d\", FILE_VERSION_MAJOR, patchlevel,\n\t\t VERSIONNO, dbname, version);\n\t\tgoto error;\n\t}\n\n\t/* php_magic_database is a const, performing writes will segfault. This is for big-endian\n\tmachines only, PPC and Sparc specifically. Consider static variable or MINIT in\n\tfuture. */\n\tif (needsbyteswap && fn == NULL) {\n\t\tmap->p = emalloc(sizeof(php_magic_database));\n\t\tmap->p = memcpy(map->p, php_magic_database, sizeof(php_magic_database));\n\t}\n\n\tif (NULL != fn) {\n\t\tnentries = (uint32_t)(st.sb.st_size / sizeof(struct magic));\n\t\tentries = (uint32_t)(st.sb.st_size / sizeof(struct magic));\n\t\tif ((off_t)(entries * sizeof(struct magic)) != st.sb.st_size) {\n\t\t\tfile_error(ms, 0, \"Size of `%s' %llu is not a multiple of %zu\",\n\t\t\t\tdbname, (unsigned long long)st.sb.st_size,\n\t\t\t\tsizeof(struct magic));\n\t\t\tgoto error;\n\t\t}\n\t}\n\tmap->magic[0] = CAST(struct magic *, map->p) + 1;\n\tnentries = 0;\n\tfor (i = 0; i < MAGIC_SETS; i++) {\n\t\tif (needsbyteswap)\n\t\t\tmap->nmagic[i] = swap4(ptr[i + 2]);\n\t\telse\n\t\t\tmap->nmagic[i] = ptr[i + 2];\n\t\tif (i != MAGIC_SETS - 1)\n\t\t\tmap->magic[i + 1] = map->magic[i] + map->nmagic[i];\n\t\tnentries += map->nmagic[i];\n\t}\n\tif (NULL != fn && entries != nentries + 1) {\n\t\tfile_error(ms, 0, \"Inconsistent entries in `%s' %u != %u\",\n\t\t dbname, entries, nentries + 1);\n\t\tgoto error;\n\t}\n\n\tif (needsbyteswap)\n\t\tfor (i = 0; i < MAGIC_SETS; i++)\n\t\t\tbyteswap(map->magic[i], map->nmagic[i]);\n\n\tif (dbname) {\n\t\tefree(dbname);\n\t}\n\treturn map;\n\nerror:\n\tif (stream) {\n\t\tphp_stream_close(stream);\n\t}\n\tapprentice_unmap(map);\n\tif (dbname) {\n\t\tefree(dbname);\n\t}\n\treturn NULL;\n}", "project": "php-src", "hash": 229425420476248340719725960925505400726, "size": 148, "commit_id": "91aa340180eccfc15d4a143b54d47b8120f898be", "message": "Fixed bug #68827 Double free with disabled ZMM", "target": 0, "dataset": "other", "idx": 385969} {"func": "static int rtsx_usb_ms_drv_remove(struct platform_device *pdev)\n{\n\tstruct rtsx_usb_ms *host = platform_get_drvdata(pdev);\n\tstruct memstick_host *msh = host->msh;\n\tint err;\n\n\thost->eject = true;\n\tcancel_work_sync(&host->handle_req);\n\n\tmutex_lock(&host->host_mutex);\n\tif (host->req) {\n\t\tdev_dbg(ms_dev(host),\n\t\t\t\"%s: Controller removed during transfer\\n\",\n\t\t\tdev_name(&msh->dev));\n\t\thost->req->error = -ENOMEDIUM;\n\t\tdo {\n\t\t\terr = memstick_next_req(msh, &host->req);\n\t\t\tif (!err)\n\t\t\t\thost->req->error = -ENOMEDIUM;\n\t\t} while (!err);\n\t}\n\tmutex_unlock(&host->host_mutex);\n\n\tmemstick_remove_host(msh);\n\tmemstick_free_host(msh);\n\n\t/* Balance possible unbalanced usage count\n\t * e.g. unconditional module removal\n\t */\n\tif (pm_runtime_active(ms_dev(host)))\n\t\tpm_runtime_put(ms_dev(host));\n\n\tpm_runtime_disable(ms_dev(host));\n\tplatform_set_drvdata(pdev, NULL);\n\n\tdev_dbg(ms_dev(host),\n\t\t\": Realtek USB Memstick controller has been removed\\n\");\n\n\treturn 0;\n}", "project": "linux", "hash": 251538097616710951131117275306805038352, "size": 40, "commit_id": "42933c8aa14be1caa9eda41f65cde8a3a95d3e39", "message": "memstick: rtsx_usb_ms: fix UAF\n\nThis patch fixes the following issues:\n1. memstick_free_host() will free the host, so the use of ms_dev(host) after\nit will be a problem. To fix this, move memstick_free_host() after when we\nare done with ms_dev(host).\n2. In rtsx_usb_ms_drv_remove(), pm need to be disabled before we remove\nand free host otherwise memstick_check will be called and UAF will\nhappen.\n\n[ 11.351173] BUG: KASAN: use-after-free in rtsx_usb_ms_drv_remove+0x94/0x140 [rtsx_usb_ms]\n[ 11.357077] rtsx_usb_ms_drv_remove+0x94/0x140 [rtsx_usb_ms]\n[ 11.357376] platform_remove+0x2a/0x50\n[ 11.367531] Freed by task 298:\n[ 11.368537] kfree+0xa4/0x2a0\n[ 11.368711] device_release+0x51/0xe0\n[ 11.368905] kobject_put+0xa2/0x120\n[ 11.369090] rtsx_usb_ms_drv_remove+0x8c/0x140 [rtsx_usb_ms]\n[ 11.369386] platform_remove+0x2a/0x50\n\n[ 12.038408] BUG: KASAN: use-after-free in __mutex_lock.isra.0+0x3ec/0x7c0\n[ 12.045432] mutex_lock+0xc9/0xd0\n[ 12.046080] memstick_check+0x6a/0x578 [memstick]\n[ 12.046509] process_one_work+0x46d/0x750\n[ 12.052107] Freed by task 297:\n[ 12.053115] kfree+0xa4/0x2a0\n[ 12.053272] device_release+0x51/0xe0\n[ 12.053463] kobject_put+0xa2/0x120\n[ 12.053647] rtsx_usb_ms_drv_remove+0xc4/0x140 [rtsx_usb_ms]\n[ 12.053939] platform_remove+0x2a/0x50\n\nSigned-off-by: Tong Zhang \nCo-developed-by: Ulf Hansson \nLink: https://lore.kernel.org/r/20210511163944.1233295-1-ztong0001@gmail.com\nSigned-off-by: Ulf Hansson ", "target": 1, "dataset": "other", "idx": 206735} {"func": "static int rtsx_usb_ms_drv_remove(struct platform_device *pdev)\n{\n\tstruct rtsx_usb_ms *host = platform_get_drvdata(pdev);\n\tstruct memstick_host *msh = host->msh;\n\tint err;\n\n\thost->eject = true;\n\tcancel_work_sync(&host->handle_req);\n\n\tmutex_lock(&host->host_mutex);\n\tif (host->req) {\n\t\tdev_dbg(ms_dev(host),\n\t\t\t\"%s: Controller removed during transfer\\n\",\n\t\t\tdev_name(&msh->dev));\n\t\thost->req->error = -ENOMEDIUM;\n\t\tdo {\n\t\t\terr = memstick_next_req(msh, &host->req);\n\t\t\tif (!err)\n\t\t\t\thost->req->error = -ENOMEDIUM;\n\t\t} while (!err);\n\t}\n\tmutex_unlock(&host->host_mutex);\n\n\t/* Balance possible unbalanced usage count\n\t * e.g. unconditional module removal\n\t */\n\tif (pm_runtime_active(ms_dev(host)))\n\t\tpm_runtime_put(ms_dev(host));\n\n\tpm_runtime_disable(ms_dev(host));\n\tmemstick_remove_host(msh);\n\tdev_dbg(ms_dev(host),\n\t\t\": Realtek USB Memstick controller has been removed\\n\");\n\tmemstick_free_host(msh);\n\tplatform_set_drvdata(pdev, NULL);\n\n\treturn 0;\n}", "project": "linux", "hash": 221647974417543889059882407549025776248, "size": 38, "commit_id": "42933c8aa14be1caa9eda41f65cde8a3a95d3e39", "message": "memstick: rtsx_usb_ms: fix UAF\n\nThis patch fixes the following issues:\n1. memstick_free_host() will free the host, so the use of ms_dev(host) after\nit will be a problem. To fix this, move memstick_free_host() after when we\nare done with ms_dev(host).\n2. In rtsx_usb_ms_drv_remove(), pm need to be disabled before we remove\nand free host otherwise memstick_check will be called and UAF will\nhappen.\n\n[ 11.351173] BUG: KASAN: use-after-free in rtsx_usb_ms_drv_remove+0x94/0x140 [rtsx_usb_ms]\n[ 11.357077] rtsx_usb_ms_drv_remove+0x94/0x140 [rtsx_usb_ms]\n[ 11.357376] platform_remove+0x2a/0x50\n[ 11.367531] Freed by task 298:\n[ 11.368537] kfree+0xa4/0x2a0\n[ 11.368711] device_release+0x51/0xe0\n[ 11.368905] kobject_put+0xa2/0x120\n[ 11.369090] rtsx_usb_ms_drv_remove+0x8c/0x140 [rtsx_usb_ms]\n[ 11.369386] platform_remove+0x2a/0x50\n\n[ 12.038408] BUG: KASAN: use-after-free in __mutex_lock.isra.0+0x3ec/0x7c0\n[ 12.045432] mutex_lock+0xc9/0xd0\n[ 12.046080] memstick_check+0x6a/0x578 [memstick]\n[ 12.046509] process_one_work+0x46d/0x750\n[ 12.052107] Freed by task 297:\n[ 12.053115] kfree+0xa4/0x2a0\n[ 12.053272] device_release+0x51/0xe0\n[ 12.053463] kobject_put+0xa2/0x120\n[ 12.053647] rtsx_usb_ms_drv_remove+0xc4/0x140 [rtsx_usb_ms]\n[ 12.053939] platform_remove+0x2a/0x50\n\nSigned-off-by: Tong Zhang \nCo-developed-by: Ulf Hansson \nLink: https://lore.kernel.org/r/20210511163944.1233295-1-ztong0001@gmail.com\nSigned-off-by: Ulf Hansson ", "target": 0, "dataset": "other", "idx": 386074} {"func": "print_just_file_entry_details(Dwarf_Debug dbg,\n Dwarf_Line_Context line_context)\n{\n unsigned fiu = 0;\n Dwarf_File_Entry fe = line_context->lc_file_entries;\n Dwarf_File_Entry fe2 = fe;\n dwarfstring m3;\n\n dwarfstring_constructor_static(&m3,locallinebuf,\n sizeof(locallinebuf));\n dwarfstring_append_printf_i(&m3,\n \" file names count %d\\n\",\n line_context->lc_file_entry_count);\n _dwarf_printf(dbg,dwarfstring_string(&m3));\n dwarfstring_reset(&m3);\n for (fiu = 0 ; fe2 ; fe2 = fe->fi_next,++fiu ) {\n Dwarf_Unsigned tlm2 = 0;\n unsigned filenum = 0;\n\n fe = fe2;\n tlm2 = fe->fi_time_last_mod;\n filenum = fiu+1;\n\n /* The space character at the end of line is silly,\n but lets leave it there for the moment to avoid\n changing output. */\n if (line_context->lc_file_entry_count > 9) {\n dwarfstring_append_printf_u(&m3,\n \" file[%2u] \",fiu);\n dwarfstring_append_printf_s(&m3,\n \"%-20s \",\n (char *) fe->fi_file_name);\n dwarfstring_append_printf_u(&m3,\n \"(file-number: %u)\\n\",\n filenum);\n } else {\n dwarfstring_append_printf_u(&m3,\n \" file[%u] \", fiu);\n dwarfstring_append_printf_s(&m3,\n \"%-20s \",(char *)fe->fi_file_name);\n dwarfstring_append_printf_u(&m3,\n \"(file-number: %u)\\n\",filenum);\n }\n _dwarf_printf(dbg,dwarfstring_string(&m3));\n dwarfstring_reset(&m3);\n if (fe->fi_dir_index_present) {\n Dwarf_Unsigned di = 0;\n di = fe->fi_dir_index;\n dwarfstring_append_printf_i(&m3,\n \" dir index %d\\n\", di);\n }\n if (fe->fi_time_last_mod_present) {\n time_t tt = (time_t) tlm2;\n\n /* ctime supplies newline */\n dwarfstring_append_printf_u(&m3,\n \" last time 0x%x \",tlm2);\n dwarfstring_append(&m3,(char *)ctime(&tt));\n }\n if (fe->fi_file_length_present) {\n Dwarf_Unsigned fl = 0;\n\n fl = fe->fi_file_length;\n dwarfstring_append_printf_i(&m3,\n \" file length %ld \",fl);\n dwarfstring_append_printf_u(&m3,\n \"0x%lx\\n\",fl);\n }\n if (fe->fi_md5_present) {\n char *c = (char *)&fe->fi_md5_value;\n char *end = c+sizeof(fe->fi_md5_value);\n dwarfstring_append(&m3, \" file md5 value 0x\");\n while(c < end) {\n dwarfstring_append_printf_u(&m3,\n \"%02x\",0xff&*c);\n ++c;\n }\n dwarfstring_append(&m3,\"\\n\");\n }\n if (dwarfstring_strlen(&m3)) {\n _dwarf_printf(dbg,dwarfstring_string(&m3));\n dwarfstring_reset(&m3);\n }\n }\n dwarfstring_destructor(&m3);\n}", "project": "libdwarf-code", "hash": 305047332333399787689973899073262959948, "size": 86, "commit_id": "faf99408e3f9f706fc3809dd400e831f989778d3", "message": "modified: libdwarf/dwarf_print_lines.c\n * dwarf_print_lines.c: In case of corrupted\n DWARF5 line header the fi_file_name field\n for a file entry can be null. Now\n we print a string in that case\n to avoid passing a null to dwarfstring_append.\n Dwarfbug DW202010-003.\n Also some lines longer than libdwarf standard\n were shortened, but a few long lines really\n must remain.", "target": 1, "dataset": "other", "idx": 206765} {"func": "print_just_file_entry_details(Dwarf_Debug dbg,\n Dwarf_Line_Context line_context)\n{\n unsigned fiu = 0;\n Dwarf_File_Entry fe = line_context->lc_file_entries;\n Dwarf_File_Entry fe2 = fe;\n dwarfstring m3;\n\n dwarfstring_constructor_static(&m3,locallinebuf,\n sizeof(locallinebuf));\n dwarfstring_append_printf_i(&m3,\n \" file names count %d\\n\",\n line_context->lc_file_entry_count);\n _dwarf_printf(dbg,dwarfstring_string(&m3));\n dwarfstring_reset(&m3);\n for (fiu = 0 ; fe2 ; fe2 = fe->fi_next,++fiu ) {\n Dwarf_Unsigned tlm2 = 0;\n unsigned filenum = 0;\n\n fe = fe2;\n tlm2 = fe->fi_time_last_mod;\n filenum = fiu+1;\n\n /* The space character at the end of line is silly,\n but lets leave it there for the moment to avoid\n changing output. */\n if (line_context->lc_file_entry_count > 9) {\n dwarfstring_append_printf_u(&m3,\n \" file[%2u] \",fiu);\n } else {\n dwarfstring_append_printf_u(&m3,\n \" file[%u] \", fiu);\n }\n /* DWARF5 can have a null fi_file_name\n if the format code in the\n line table header is unknown, such\n as in a corrupt object file. */\n dwarfstring_append_printf_s(&m3,\n \"%-20s \",\n fe->fi_file_name?\n (char *) fe->fi_file_name:\n \"\");\n dwarfstring_append_printf_u(&m3,\n \"(file-number: %u)\\n\",\n filenum);\n _dwarf_printf(dbg,dwarfstring_string(&m3));\n dwarfstring_reset(&m3);\n if (fe->fi_dir_index_present) {\n Dwarf_Unsigned di = 0;\n di = fe->fi_dir_index;\n dwarfstring_append_printf_i(&m3,\n \" dir index %d\\n\", di);\n }\n if (fe->fi_time_last_mod_present) {\n time_t tt = (time_t) tlm2;\n\n /* ctime supplies newline */\n dwarfstring_append_printf_u(&m3,\n \" last time 0x%x \",tlm2);\n dwarfstring_append(&m3,(char *)ctime(&tt));\n }\n if (fe->fi_file_length_present) {\n Dwarf_Unsigned fl = 0;\n\n fl = fe->fi_file_length;\n dwarfstring_append_printf_i(&m3,\n \" file length %ld \",fl);\n dwarfstring_append_printf_u(&m3,\n \"0x%lx\\n\",fl);\n }\n if (fe->fi_md5_present) {\n char *c = (char *)&fe->fi_md5_value;\n char *end = c+sizeof(fe->fi_md5_value);\n dwarfstring_append(&m3, \" file md5 value 0x\");\n while(c < end) {\n dwarfstring_append_printf_u(&m3,\n \"%02x\",0xff&*c);\n ++c;\n }\n dwarfstring_append(&m3,\"\\n\");\n }\n if (dwarfstring_strlen(&m3)) {\n _dwarf_printf(dbg,dwarfstring_string(&m3));\n dwarfstring_reset(&m3);\n }\n }\n dwarfstring_destructor(&m3);\n}", "project": "libdwarf-code", "hash": 164570038693462174492969033994984555291, "size": 88, "commit_id": "faf99408e3f9f706fc3809dd400e831f989778d3", "message": "modified: libdwarf/dwarf_print_lines.c\n * dwarf_print_lines.c: In case of corrupted\n DWARF5 line header the fi_file_name field\n for a file entry can be null. Now\n we print a string in that case\n to avoid passing a null to dwarfstring_append.\n Dwarfbug DW202010-003.\n Also some lines longer than libdwarf standard\n were shortened, but a few long lines really\n must remain.", "target": 0, "dataset": "other", "idx": 386452} {"func": "static ssize_t acpi_table_aml_write(struct config_item *cfg,\n\t\t\t\t const void *data, size_t size)\n{\n\tconst struct acpi_table_header *header = data;\n\tstruct acpi_table *table;\n\tint ret;\n\n\ttable = container_of(cfg, struct acpi_table, cfg);\n\n\tif (table->header) {\n\t\tpr_err(\"table already loaded\\n\");\n\t\treturn -EBUSY;\n\t}\n\n\tif (header->length != size) {\n\t\tpr_err(\"invalid table length\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\tif (memcmp(header->signature, ACPI_SIG_SSDT, 4)) {\n\t\tpr_err(\"invalid table signature\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\ttable = container_of(cfg, struct acpi_table, cfg);\n\n\ttable->header = kmemdup(header, header->length, GFP_KERNEL);\n\tif (!table->header)\n\t\treturn -ENOMEM;\n\n\tret = acpi_load_table(table->header, &table->index);\n\tif (ret) {\n\t\tkfree(table->header);\n\t\ttable->header = NULL;\n\t}\n\n\treturn ret;\n}", "project": "linux", "hash": 178950288749024718434922419399845158436, "size": 38, "commit_id": "75b0cea7bf307f362057cc778efe89af4c615354", "message": "ACPI: configfs: Disallow loading ACPI tables when locked down\n\nLike other vectors already patched, this one here allows the root\nuser to load ACPI tables, which enables arbitrary physical address\nwrites, which in turn makes it possible to disable lockdown.\n\nPrevents this by checking the lockdown status before allowing a new\nACPI table to be installed. The link in the trailer shows a PoC of\nhow this might be used.\n\nLink: https://git.zx2c4.com/american-unsigned-language/tree/american-unsigned-language-2.sh\nCc: 5.4+ # 5.4+\nSigned-off-by: Jason A. Donenfeld \nSigned-off-by: Rafael J. Wysocki ", "target": 1, "dataset": "other", "idx": 206866} {"func": "static ssize_t acpi_table_aml_write(struct config_item *cfg,\n\t\t\t\t const void *data, size_t size)\n{\n\tconst struct acpi_table_header *header = data;\n\tstruct acpi_table *table;\n\tint ret = security_locked_down(LOCKDOWN_ACPI_TABLES);\n\n\tif (ret)\n\t\treturn ret;\n\n\ttable = container_of(cfg, struct acpi_table, cfg);\n\n\tif (table->header) {\n\t\tpr_err(\"table already loaded\\n\");\n\t\treturn -EBUSY;\n\t}\n\n\tif (header->length != size) {\n\t\tpr_err(\"invalid table length\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\tif (memcmp(header->signature, ACPI_SIG_SSDT, 4)) {\n\t\tpr_err(\"invalid table signature\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\ttable = container_of(cfg, struct acpi_table, cfg);\n\n\ttable->header = kmemdup(header, header->length, GFP_KERNEL);\n\tif (!table->header)\n\t\treturn -ENOMEM;\n\n\tret = acpi_load_table(table->header, &table->index);\n\tif (ret) {\n\t\tkfree(table->header);\n\t\ttable->header = NULL;\n\t}\n\n\treturn ret;\n}", "project": "linux", "hash": 23089143507537986751432919005044809927, "size": 41, "commit_id": "75b0cea7bf307f362057cc778efe89af4c615354", "message": "ACPI: configfs: Disallow loading ACPI tables when locked down\n\nLike other vectors already patched, this one here allows the root\nuser to load ACPI tables, which enables arbitrary physical address\nwrites, which in turn makes it possible to disable lockdown.\n\nPrevents this by checking the lockdown status before allowing a new\nACPI table to be installed. The link in the trailer shows a PoC of\nhow this might be used.\n\nLink: https://git.zx2c4.com/american-unsigned-language/tree/american-unsigned-language-2.sh\nCc: 5.4+ # 5.4+\nSigned-off-by: Jason A. Donenfeld \nSigned-off-by: Rafael J. Wysocki ", "target": 0, "dataset": "other", "idx": 387888} {"func": "void get_cmdln_options(int argc, char *argv[]) {\n\tint o;\n#if CONFIG_FILE && HAVE_GETPWUID\n static struct passwd *pwd_entry;\n char *str;\n#endif\n#ifdef LONG_OPTIONS\n int option_index = 0;\n static struct option long_options[] = {\n {\"timeout\", 1, 0, 't'},\n#ifdef PROC_NET_DEV\n {\"procfile\",1,0,'f'},\n#endif\n#ifdef PROC_DISKSTATS\n\t\t\t{\"diskstatsfile\",1,0,1000},\n\t\t\t{\"partitionsfile\",1,0,1001},\n#endif\t\t \n#if NETSTAT && ALLOW_NETSTATPATH\n {\"netstat\",1,0,'n'},\n#endif\n#if IOSERVICE_IN\n\t\t {\"longdisknames\",0,0,1002},\n#endif\n {\"input\",1,0,'i'},\n {\"dynamic\",1,0,'d'},\n {\"help\", 0, 0, 'h'},\n {\"version\",0,0,'V'},\n {\"allif\",1,0,'a'},\n {\"unit\",1,0,'u'},\n\t\t {\"ansiout\",0,0,'N'},\n#if EXTENDED_STATS \n {\"type\",1,0,'T'},\n {\"avglength\",1,0,'A'},\n#endif \n {\"interfaces\",1,0,'I'},\n {\"sumhidden\",1,0,'S'},\n {\"output\",1,0,'o'},\n#ifdef CSV\n {\"csvchar\",1,0,'C'},\n {\"csvfile\",1,0,'F'},\n#endif\n {\"count\",1,0,'c'},\n {\"daemon\",1,0,'D'},\n#ifdef HTML\n {\"htmlrefresh\",1,0,'R'},\n {\"htmlheader\",1,0,'H'},\n#endif\n {0,0,0,0}\n };\n#endif\n#ifdef CONFIG_FILE\n /* loop till first non option argument */\n opterr=0;\n while (1) {\n#ifdef LONG_OPTIONS\n o=getopt_long (argc,argv,SHORT_OPTIONS,long_options, &option_index);\n#else\n o=getopt (argc,argv,SHORT_OPTIONS);\n#endif\n if (o==-1) break;\n }\n opterr=1;\n if (optind < argc) {\n read_config(argv[optind]);\n } else {\n read_config(\"/etc/bwm-ng.conf\");\n#ifdef HAVE_GETPWUID \n pwd_entry=getpwuid(getuid());\n if (pwd_entry!=NULL) {\n str=(char*)malloc(strlen(pwd_entry->pw_dir)+14);\n snprintf(str,strlen(pwd_entry->pw_dir)+14,\"%s/.bwm-ng.conf\",pwd_entry->pw_dir);\n read_config(str);\n free(str);\n }\n#endif \n }\n /* reset getopt again */\n optind=1;\n#endif\n /* get command line arguments, kinda ugly, wanna rewrite it? */\n while (1) {\n#ifdef LONG_OPTIONS\n\t\to=getopt_long (argc,argv,SHORT_OPTIONS,long_options, &option_index);\n#else\n\t\to=getopt (argc,argv,SHORT_OPTIONS);\n#endif\t\t\n if (o==-1) break;\n switch (o) {\n case '?': printf(\"unknown option: %s\\n\",argv[optind-1]);\n exit(EXIT_FAILURE);\n break;\n /* ugly workaround to handle optional arguments for all platforms */ \n case ':': if (!strcmp(argv[optind-1],\"-a\") || !strcasecmp(argv[optind-1],\"--allif\")) \n show_all_if=1;\n else if (!strcmp(argv[optind-1],\"-d\") || !strcasecmp(argv[optind-1],\"--dynamic\"))\n dynamic=1;\n else if (!strcmp(argv[optind-1],\"-D\") || !strcasecmp(argv[optind-1],\"--daemon\"))\n daemonize=1;\n#ifdef HTML \n else if (!strcmp(argv[optind-1],\"-H\") || !strcasecmp(argv[optind-1],\"--htmlheader\"))\n html_header=1;\n#endif \n else if (!strcmp(argv[optind-1],\"-S\") || !strcasecmp(argv[optind-1],\"--sumhidden\"))\n sumhidden=1; \n else {\n printf(\"%s requires an argument!\\n\",argv[optind-1]);\n exit(EXIT_FAILURE);\n }\n break;\n#ifdef PROC_DISKSTATS\n\t\t\tcase 1000:\n\t\t\t\tif (strlen(optarg)0) { html_refresh=atol(optarg); }\n\t\t\t\tbreak;\n\t\t\tcase 'H':\n\t\t\t\tif (optarg) html_header=atoi(optarg);\n\t\t\t\tbreak;\n#endif\n\t\t\tcase 'c':\n\t\t\t\tif (optarg) output_count=atol(optarg);\n\t\t\t\tbreak;\n#if CSV || HTML\n case 'F':\n if (optarg) { \n if (out_file) fclose(out_file);\n out_file=fopen(optarg,\"a\"); \n if (!out_file) deinit(1, \"failed to open outfile\\n\");\n if (out_file_path) free(out_file_path);\n out_file_path=(char *)strdup(optarg);\n }\n break;\n#endif\n#ifdef CSV\n\t\t\tcase 'C':\n\t\t\t\tif (optarg) csv_char=optarg[0];\n\t\t\t\tbreak;\n#endif\n case 'h':\n cmdln_printhelp();\n break;\n#ifdef PROC_NET_DEV\n\t\t\tcase 'f':\n if (optarg && (strlen(optarg)0) { delay=atol(optarg); }\n break;\n#if EXTENDED_STATS \n case 'T':\n output_type=str2output_type(optarg);\n break;\n case 'A':\n if (optarg) avg_length=atoi(optarg)*1000;\n break;\n#endif \n case 'd':\n if (optarg) dynamic=atoi(optarg);\n break;\n case 'u':\n output_unit=str2output_unit(optarg);\n break;\n#if NETSTAT && ALLOW_NETSTATPATH\n case 'n':\n if (optarg && (strlen(optarg)=avg_length) deinit(1, \"avglength needs to be a least twice the value of timeout\\n\");\n#endif \n\t if ((output_unit==ERRORS_OUT && !net_input_method(input_method)) || \n\t\t\t (output_unit==PACKETS_OUT && input_method==LIBSTATDISK_IN)) \n\t\toutput_unit=BYTES_OUT;\n return;\n}", "project": "bwm-ng", "hash": 190610676223568420413623069094924895723, "size": 227, "commit_id": "9774f23bf78a6e6d3ae4cfe3d73bad34f2fdcd17", "message": "Fix https://github.com/vgropp/bwm-ng/issues/26", "target": 1, "dataset": "other", "idx": 206867} {"func": "void get_cmdln_options(int argc, char *argv[]) {\n\tint o;\n#if CONFIG_FILE && HAVE_GETPWUID\n static struct passwd *pwd_entry;\n char *str;\n#endif\n#ifdef LONG_OPTIONS\n int option_index = 0;\n static struct option long_options[] = {\n {\"timeout\", 1, 0, 't'},\n#ifdef PROC_NET_DEV\n {\"procfile\",1,0,'f'},\n#endif\n#ifdef PROC_DISKSTATS\n\t\t\t{\"diskstatsfile\",1,0,1000},\n\t\t\t{\"partitionsfile\",1,0,1001},\n#endif\t\t \n#if NETSTAT && ALLOW_NETSTATPATH\n {\"netstat\",1,0,'n'},\n#endif\n#if IOSERVICE_IN\n\t\t {\"longdisknames\",0,0,1002},\n#endif\n {\"input\",1,0,'i'},\n {\"dynamic\",1,0,'d'},\n {\"help\", 0, 0, 'h'},\n {\"version\",0,0,'V'},\n {\"allif\",1,0,'a'},\n {\"unit\",1,0,'u'},\n\t\t {\"ansiout\",0,0,'N'},\n#if EXTENDED_STATS \n {\"type\",1,0,'T'},\n {\"avglength\",1,0,'A'},\n#endif \n {\"interfaces\",1,0,'I'},\n {\"sumhidden\",1,0,'S'},\n {\"output\",1,0,'o'},\n#ifdef CSV\n {\"csvchar\",1,0,'C'},\n {\"csvfile\",1,0,'F'},\n#endif\n {\"count\",1,0,'c'},\n {\"daemon\",1,0,'D'},\n#ifdef HTML\n {\"htmlrefresh\",1,0,'R'},\n {\"htmlheader\",1,0,'H'},\n#endif\n {0,0,0,0}\n };\n#endif\n#ifdef CONFIG_FILE\n /* loop till first non option argument */\n opterr=0;\n while (1) {\n#ifdef LONG_OPTIONS\n o=getopt_long (argc,argv,SHORT_OPTIONS,long_options, &option_index);\n#else\n o=getopt (argc,argv,SHORT_OPTIONS);\n#endif\n if (o==-1) break;\n }\n opterr=1;\n if (optind < argc) {\n read_config(argv[optind]);\n } else {\n read_config(\"/etc/bwm-ng.conf\");\n#ifdef HAVE_GETPWUID \n pwd_entry=getpwuid(getuid());\n if (pwd_entry!=NULL) {\n str=(char*)malloc(strlen(pwd_entry->pw_dir)+14);\n if(!str) {\n printf(\"Fatal: failed to allocate %zu bytes.\\n\", strlen(pwd_entry->pw_dir)+14);\n exit(EXIT_FAILURE);\n }\n snprintf(str,strlen(pwd_entry->pw_dir)+14,\"%s/.bwm-ng.conf\",pwd_entry->pw_dir);\n read_config(str);\n free(str);\n }\n#endif \n }\n /* reset getopt again */\n optind=1;\n#endif\n /* get command line arguments, kinda ugly, wanna rewrite it? */\n while (1) {\n#ifdef LONG_OPTIONS\n\t\to=getopt_long (argc,argv,SHORT_OPTIONS,long_options, &option_index);\n#else\n\t\to=getopt (argc,argv,SHORT_OPTIONS);\n#endif\t\t\n if (o==-1) break;\n switch (o) {\n case '?': printf(\"unknown option: %s\\n\",argv[optind-1]);\n exit(EXIT_FAILURE);\n break;\n /* ugly workaround to handle optional arguments for all platforms */ \n case ':': if (!strcmp(argv[optind-1],\"-a\") || !strcasecmp(argv[optind-1],\"--allif\")) \n show_all_if=1;\n else if (!strcmp(argv[optind-1],\"-d\") || !strcasecmp(argv[optind-1],\"--dynamic\"))\n dynamic=1;\n else if (!strcmp(argv[optind-1],\"-D\") || !strcasecmp(argv[optind-1],\"--daemon\"))\n daemonize=1;\n#ifdef HTML \n else if (!strcmp(argv[optind-1],\"-H\") || !strcasecmp(argv[optind-1],\"--htmlheader\"))\n html_header=1;\n#endif \n else if (!strcmp(argv[optind-1],\"-S\") || !strcasecmp(argv[optind-1],\"--sumhidden\"))\n sumhidden=1; \n else {\n printf(\"%s requires an argument!\\n\",argv[optind-1]);\n exit(EXIT_FAILURE);\n }\n break;\n#ifdef PROC_DISKSTATS\n\t\t\tcase 1000:\n\t\t\t\tif (strlen(optarg)0) { html_refresh=atol(optarg); }\n\t\t\t\tbreak;\n\t\t\tcase 'H':\n\t\t\t\tif (optarg) html_header=atoi(optarg);\n\t\t\t\tbreak;\n#endif\n\t\t\tcase 'c':\n\t\t\t\tif (optarg) output_count=atol(optarg);\n\t\t\t\tbreak;\n#if CSV || HTML\n case 'F':\n if (optarg) { \n if (out_file) fclose(out_file);\n out_file=fopen(optarg,\"a\"); \n if (!out_file) deinit(1, \"failed to open outfile\\n\");\n if (out_file_path) free(out_file_path);\n out_file_path=(char *)strdup(optarg);\n }\n break;\n#endif\n#ifdef CSV\n\t\t\tcase 'C':\n\t\t\t\tif (optarg) csv_char=optarg[0];\n\t\t\t\tbreak;\n#endif\n case 'h':\n cmdln_printhelp();\n break;\n#ifdef PROC_NET_DEV\n\t\t\tcase 'f':\n if (optarg && (strlen(optarg)0) { delay=atol(optarg); }\n break;\n#if EXTENDED_STATS \n case 'T':\n output_type=str2output_type(optarg);\n break;\n case 'A':\n if (optarg) avg_length=atoi(optarg)*1000;\n break;\n#endif \n case 'd':\n if (optarg) dynamic=atoi(optarg);\n break;\n case 'u':\n output_unit=str2output_unit(optarg);\n break;\n#if NETSTAT && ALLOW_NETSTATPATH\n case 'n':\n if (optarg && (strlen(optarg)=avg_length) deinit(1, \"avglength needs to be a least twice the value of timeout\\n\");\n#endif \n\t if ((output_unit==ERRORS_OUT && !net_input_method(input_method)) || \n\t\t\t (output_unit==PACKETS_OUT && input_method==LIBSTATDISK_IN)) \n\t\toutput_unit=BYTES_OUT;\n return;\n}", "project": "bwm-ng", "hash": 193898408646396083666542746077666107845, "size": 231, "commit_id": "9774f23bf78a6e6d3ae4cfe3d73bad34f2fdcd17", "message": "Fix https://github.com/vgropp/bwm-ng/issues/26", "target": 0, "dataset": "other", "idx": 387905} {"func": "static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,\n const size_t number_parameters,const double *parameters,\n ExceptionInfo *exception)\n{\n double\n result;\n\n ssize_t\n i;\n\n (void) exception;\n result=0.0;\n switch (function)\n {\n case PolynomialFunction:\n {\n /*\n Polynomial: polynomial constants, highest to lowest order (e.g. c0*x^3+\n c1*x^2+c2*x+c3).\n */\n result=0.0;\n for (i=0; i < (ssize_t) number_parameters; i++)\n result=result*QuantumScale*pixel+parameters[i];\n result*=QuantumRange;\n break;\n }\n case SinusoidFunction:\n {\n double\n amplitude,\n bias,\n frequency,\n phase;\n\n /*\n Sinusoid: frequency, phase, amplitude, bias.\n */\n frequency=(number_parameters >= 1) ? parameters[0] : 1.0;\n phase=(number_parameters >= 2) ? parameters[1] : 0.0;\n amplitude=(number_parameters >= 3) ? parameters[2] : 0.5;\n bias=(number_parameters >= 4) ? parameters[3] : 0.5;\n result=(double) (QuantumRange*(amplitude*sin((double) (2.0*\n MagickPI*(frequency*QuantumScale*pixel+phase/360.0)))+bias));\n break;\n }\n case ArcsinFunction:\n {\n double\n bias,\n center,\n range,\n width;\n\n /*\n Arcsin (peged at range limits for invalid results): width, center,\n range, and bias.\n */\n width=(number_parameters >= 1) ? parameters[0] : 1.0;\n center=(number_parameters >= 2) ? parameters[1] : 0.5;\n range=(number_parameters >= 3) ? parameters[2] : 1.0;\n bias=(number_parameters >= 4) ? parameters[3] : 0.5;\n result=2.0/width*(QuantumScale*pixel-center);\n if ( result <= -1.0 )\n result=bias-range/2.0;\n else\n if (result >= 1.0)\n result=bias+range/2.0;\n else\n result=(double) (range/MagickPI*asin((double) result)+bias);\n result*=QuantumRange;\n break;\n }\n case ArctanFunction:\n {\n double\n center,\n bias,\n range,\n slope;\n\n /*\n Arctan: slope, center, range, and bias.\n */\n slope=(number_parameters >= 1) ? parameters[0] : 1.0;\n center=(number_parameters >= 2) ? parameters[1] : 0.5;\n range=(number_parameters >= 3) ? parameters[2] : 1.0;\n bias=(number_parameters >= 4) ? parameters[3] : 0.5;\n result=(double) (MagickPI*slope*(QuantumScale*pixel-center));\n result=(double) (QuantumRange*(range/MagickPI*atan((double)\n result)+bias));\n break;\n }\n case UndefinedFunction:\n break;\n }\n return(ClampToQuantum(result));\n}", "project": "ImageMagick", "hash": 144868375147363456336191166820888674353, "size": 97, "commit_id": "4717744e4bb27de8ea978e51c6d5bcddf62ffe49", "message": "https://github.com/ImageMagick/ImageMagick/issues/3332", "target": 1, "dataset": "other", "idx": 206873} {"func": "static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,\n const size_t number_parameters,const double *parameters,\n ExceptionInfo *exception)\n{\n double\n result;\n\n ssize_t\n i;\n\n (void) exception;\n result=0.0;\n switch (function)\n {\n case PolynomialFunction:\n {\n /*\n Polynomial: polynomial constants, highest to lowest order (e.g. c0*x^3+\n c1*x^2+c2*x+c3).\n */\n result=0.0;\n for (i=0; i < (ssize_t) number_parameters; i++)\n result=result*QuantumScale*pixel+parameters[i];\n result*=QuantumRange;\n break;\n }\n case SinusoidFunction:\n {\n double\n amplitude,\n bias,\n frequency,\n phase;\n\n /*\n Sinusoid: frequency, phase, amplitude, bias.\n */\n frequency=(number_parameters >= 1) ? parameters[0] : 1.0;\n phase=(number_parameters >= 2) ? parameters[1] : 0.0;\n amplitude=(number_parameters >= 3) ? parameters[2] : 0.5;\n bias=(number_parameters >= 4) ? parameters[3] : 0.5;\n result=(double) (QuantumRange*(amplitude*sin((double) (2.0*\n MagickPI*(frequency*QuantumScale*pixel+phase/360.0)))+bias));\n break;\n }\n case ArcsinFunction:\n {\n double\n bias,\n center,\n range,\n width;\n\n /*\n Arcsin (peged at range limits for invalid results): width, center,\n range, and bias.\n */\n width=(number_parameters >= 1) ? parameters[0] : 1.0;\n center=(number_parameters >= 2) ? parameters[1] : 0.5;\n range=(number_parameters >= 3) ? parameters[2] : 1.0;\n bias=(number_parameters >= 4) ? parameters[3] : 0.5;\n result=2.0*PerceptibleReciprocal(width)*(QuantumScale*pixel-center);\n if (result <= -1.0)\n result=bias-range/2.0;\n else\n if (result >= 1.0)\n result=bias+range/2.0;\n else\n result=(double) (range/MagickPI*asin((double) result)+bias);\n result*=QuantumRange;\n break;\n }\n case ArctanFunction:\n {\n double\n center,\n bias,\n range,\n slope;\n\n /*\n Arctan: slope, center, range, and bias.\n */\n slope=(number_parameters >= 1) ? parameters[0] : 1.0;\n center=(number_parameters >= 2) ? parameters[1] : 0.5;\n range=(number_parameters >= 3) ? parameters[2] : 1.0;\n bias=(number_parameters >= 4) ? parameters[3] : 0.5;\n result=(double) (MagickPI*slope*(QuantumScale*pixel-center));\n result=(double) (QuantumRange*(range/MagickPI*atan((double)\n result)+bias));\n break;\n }\n case UndefinedFunction:\n break;\n }\n return(ClampToQuantum(result));\n}", "project": "ImageMagick", "hash": 67328351938312049905670604818711921794, "size": 97, "commit_id": "4717744e4bb27de8ea978e51c6d5bcddf62ffe49", "message": "https://github.com/ImageMagick/ImageMagick/issues/3332", "target": 0, "dataset": "other", "idx": 388298} {"func": "UINT cliprdr_read_format_list(wStream* s, CLIPRDR_FORMAT_LIST* formatList, BOOL useLongFormatNames)\n{\n\tUINT32 index;\n\tsize_t position;\n\tBOOL asciiNames;\n\tint formatNameLength;\n\tchar* szFormatName;\n\tWCHAR* wszFormatName;\n\tUINT32 dataLen = formatList->dataLen;\n\tCLIPRDR_FORMAT* formats = NULL;\n\tUINT error = CHANNEL_RC_OK;\n\n\tasciiNames = (formatList->msgFlags & CB_ASCII_NAMES) ? TRUE : FALSE;\n\n\tindex = 0;\n\tformatList->numFormats = 0;\n\tposition = Stream_GetPosition(s);\n\n\tif (!formatList->dataLen)\n\t{\n\t\t/* empty format list */\n\t\tformatList->formats = NULL;\n\t\tformatList->numFormats = 0;\n\t}\n\telse if (!useLongFormatNames)\n\t{\n\t\tformatList->numFormats = (dataLen / 36);\n\n\t\tif ((formatList->numFormats * 36) != dataLen)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Invalid short format list length: %\" PRIu32 \"\", dataLen);\n\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t}\n\n\t\tif (formatList->numFormats)\n\t\t\tformats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT));\n\n\t\tif (!formats)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\t\tformatList->formats = formats;\n\n\t\twhile (dataLen)\n\t\t{\n\t\t\tStream_Read_UINT32(s, formats[index].formatId); /* formatId (4 bytes) */\n\t\t\tdataLen -= 4;\n\n\t\t\tformats[index].formatName = NULL;\n\n\t\t\t/* According to MS-RDPECLIP 2.2.3.1.1.1 formatName is \"a 32-byte block containing\n\t\t\t * the *null-terminated* name assigned to the Clipboard Format: (32 ASCII 8 characters\n\t\t\t * or 16 Unicode characters)\"\n\t\t\t * However, both Windows RDSH and mstsc violate this specs as seen in the following\n\t\t\t * example of a transferred short format name string: [R.i.c.h. .T.e.x.t. .F.o.r.m.a.t.]\n\t\t\t * These are 16 unicode charaters - *without* terminating null !\n\t\t\t */\n\n\t\t\tif (asciiNames)\n\t\t\t{\n\t\t\t\tszFormatName = (char*)Stream_Pointer(s);\n\n\t\t\t\tif (szFormatName[0])\n\t\t\t\t{\n\t\t\t\t\t/* ensure null termination */\n\t\t\t\t\tformats[index].formatName = (char*)malloc(32 + 1);\n\t\t\t\t\tif (!formats[index].formatName)\n\t\t\t\t\t{\n\t\t\t\t\t\tWLog_ERR(TAG, \"malloc failed!\");\n\t\t\t\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\t\t\t\tgoto error_out;\n\t\t\t\t\t}\n\t\t\t\t\tCopyMemory(formats[index].formatName, szFormatName, 32);\n\t\t\t\t\tformats[index].formatName[32] = '\\0';\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\twszFormatName = (WCHAR*)Stream_Pointer(s);\n\n\t\t\t\tif (wszFormatName[0])\n\t\t\t\t{\n\t\t\t\t\t/* ConvertFromUnicode always returns a null-terminated\n\t\t\t\t\t * string on success, even if the source string isn't.\n\t\t\t\t\t */\n\t\t\t\t\tif (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, 16,\n\t\t\t\t\t &(formats[index].formatName), 0, NULL, NULL) < 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tWLog_ERR(TAG, \"failed to convert short clipboard format name\");\n\t\t\t\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\t\t\t\tgoto error_out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tStream_Seek(s, 32);\n\t\t\tdataLen -= 32;\n\t\t\tindex++;\n\t\t}\n\t}\n\telse\n\t{\n\t\twhile (dataLen)\n\t\t{\n\t\t\tStream_Seek(s, 4); /* formatId (4 bytes) */\n\t\t\tdataLen -= 4;\n\n\t\t\twszFormatName = (WCHAR*)Stream_Pointer(s);\n\n\t\t\tif (!wszFormatName[0])\n\t\t\t\tformatNameLength = 0;\n\t\t\telse\n\t\t\t\tformatNameLength = _wcslen(wszFormatName);\n\n\t\t\tStream_Seek(s, (formatNameLength + 1) * 2);\n\t\t\tdataLen -= ((formatNameLength + 1) * 2);\n\n\t\t\tformatList->numFormats++;\n\t\t}\n\n\t\tdataLen = formatList->dataLen;\n\t\tStream_SetPosition(s, position);\n\n\t\tif (formatList->numFormats)\n\t\t\tformats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT));\n\n\t\tif (!formats)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\t\tformatList->formats = formats;\n\n\t\twhile (dataLen)\n\t\t{\n\t\t\tStream_Read_UINT32(s, formats[index].formatId); /* formatId (4 bytes) */\n\t\t\tdataLen -= 4;\n\n\t\t\tformats[index].formatName = NULL;\n\n\t\t\twszFormatName = (WCHAR*)Stream_Pointer(s);\n\n\t\t\tif (!wszFormatName[0])\n\t\t\t\tformatNameLength = 0;\n\t\t\telse\n\t\t\t\tformatNameLength = _wcslen(wszFormatName);\n\n\t\t\tif (formatNameLength)\n\t\t\t{\n\t\t\t\tif (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, -1, &(formats[index].formatName),\n\t\t\t\t 0, NULL, NULL) < 1)\n\t\t\t\t{\n\t\t\t\t\tWLog_ERR(TAG, \"failed to convert long clipboard format name\");\n\t\t\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\t\t\tgoto error_out;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tStream_Seek(s, (formatNameLength + 1) * 2);\n\t\t\tdataLen -= ((formatNameLength + 1) * 2);\n\n\t\t\tindex++;\n\t\t}\n\t}\n\n\treturn error;\n\nerror_out:\n\tcliprdr_free_format_list(formatList);\n\treturn error;\n}", "project": "FreeRDP", "hash": 291591512452233208574467037688769410743, "size": 174, "commit_id": "b73143cf7ee5fe4cdabcbf56908aa15d8a883821", "message": "Fixed oob read in cliprdr_read_format_list", "target": 1, "dataset": "other", "idx": 206874} {"func": "UINT cliprdr_read_format_list(wStream* s, CLIPRDR_FORMAT_LIST* formatList, BOOL useLongFormatNames)\n{\n\tUINT32 index;\n\tsize_t position;\n\tBOOL asciiNames;\n\tint formatNameLength;\n\tchar* szFormatName;\n\tWCHAR* wszFormatName;\n\twStream sub1, sub2;\n\tCLIPRDR_FORMAT* formats = NULL;\n\tUINT error = CHANNEL_RC_OK;\n\n\tasciiNames = (formatList->msgFlags & CB_ASCII_NAMES) ? TRUE : FALSE;\n\n\tindex = 0;\n\t/* empty format list */\n\tformatList->formats = NULL;\n\tformatList->numFormats = 0;\n\n\tStream_StaticInit(&sub1, Stream_Pointer(s), formatList->dataLen);\n\tif (!Stream_SafeSeek(s, formatList->dataLen))\n\t\treturn ERROR_INVALID_DATA;\n\n\tif (!formatList->dataLen)\n\t{\n\t}\n\telse if (!useLongFormatNames)\n\t{\n\t\tconst size_t cap = Stream_Capacity(&sub1);\n\t\tformatList->numFormats = (cap / 36);\n\n\t\tif ((formatList->numFormats * 36) != cap)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Invalid short format list length: %\" PRIuz \"\", cap);\n\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t}\n\n\t\tif (formatList->numFormats)\n\t\t\tformats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT));\n\n\t\tif (!formats)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\t\tformatList->formats = formats;\n\n\t\twhile (Stream_GetRemainingLength(&sub1) >= 4)\n\t\t{\n\t\t\tStream_Read_UINT32(&sub1, formats[index].formatId); /* formatId (4 bytes) */\n\n\t\t\tformats[index].formatName = NULL;\n\n\t\t\t/* According to MS-RDPECLIP 2.2.3.1.1.1 formatName is \"a 32-byte block containing\n\t\t\t * the *null-terminated* name assigned to the Clipboard Format: (32 ASCII 8 characters\n\t\t\t * or 16 Unicode characters)\"\n\t\t\t * However, both Windows RDSH and mstsc violate this specs as seen in the following\n\t\t\t * example of a transferred short format name string: [R.i.c.h. .T.e.x.t. .F.o.r.m.a.t.]\n\t\t\t * These are 16 unicode charaters - *without* terminating null !\n\t\t\t */\n\n\t\t\tszFormatName = (char*)Stream_Pointer(&sub1);\n\t\t\twszFormatName = (WCHAR*)Stream_Pointer(&sub1);\n\t\t\tif (!Stream_SafeSeek(&sub1, 32))\n\t\t\t\tgoto error_out;\n\t\t\tif (asciiNames)\n\t\t\t{\n\t\t\t\tif (szFormatName[0])\n\t\t\t\t{\n\t\t\t\t\t/* ensure null termination */\n\t\t\t\t\tformats[index].formatName = (char*)malloc(32 + 1);\n\t\t\t\t\tif (!formats[index].formatName)\n\t\t\t\t\t{\n\t\t\t\t\t\tWLog_ERR(TAG, \"malloc failed!\");\n\t\t\t\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\t\t\t\tgoto error_out;\n\t\t\t\t\t}\n\t\t\t\t\tCopyMemory(formats[index].formatName, szFormatName, 32);\n\t\t\t\t\tformats[index].formatName[32] = '\\0';\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (wszFormatName[0])\n\t\t\t\t{\n\t\t\t\t\t/* ConvertFromUnicode always returns a null-terminated\n\t\t\t\t\t * string on success, even if the source string isn't.\n\t\t\t\t\t */\n\t\t\t\t\tif (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, 16,\n\t\t\t\t\t &(formats[index].formatName), 0, NULL, NULL) < 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tWLog_ERR(TAG, \"failed to convert short clipboard format name\");\n\t\t\t\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\t\t\t\tgoto error_out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tindex++;\n\t\t}\n\t}\n\telse\n\t{\n\t\tsub2 = sub1;\n\t\twhile (Stream_GetRemainingLength(&sub1) > 0)\n\t\t{\n\t\t\tsize_t rest;\n\t\t\tif (!Stream_SafeSeek(&sub1, 4)) /* formatId (4 bytes) */\n\t\t\t\tgoto error_out;\n\n\t\t\twszFormatName = (WCHAR*)Stream_Pointer(&sub1);\n\t\t\trest = Stream_GetRemainingLength(&sub1);\n\t\t\tformatNameLength = _wcsnlen(wszFormatName, rest / sizeof(WCHAR));\n\n\t\t\tif (!Stream_SafeSeek(&sub1, (formatNameLength + 1) * sizeof(WCHAR)))\n\t\t\t\tgoto error_out;\n\t\t\tformatList->numFormats++;\n\t\t}\n\n\t\tif (formatList->numFormats)\n\t\t\tformats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT));\n\n\t\tif (!formats)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\t\tformatList->formats = formats;\n\n\t\twhile (Stream_GetRemainingLength(&sub2) >= 4)\n\t\t{\n\t\t\tsize_t rest;\n\t\t\tStream_Read_UINT32(&sub2, formats[index].formatId); /* formatId (4 bytes) */\n\n\t\t\tformats[index].formatName = NULL;\n\n\t\t\twszFormatName = (WCHAR*)Stream_Pointer(&sub2);\n\t\t\trest = Stream_GetRemainingLength(&sub2);\n\t\t\tformatNameLength = _wcsnlen(wszFormatName, rest / sizeof(WCHAR));\n\t\t\tif (!Stream_SafeSeek(&sub2, (formatNameLength + 1) * sizeof(WCHAR)))\n\t\t\t\tgoto error_out;\n\n\t\t\tif (formatNameLength)\n\t\t\t{\n\t\t\t\tif (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, formatNameLength,\n\t\t\t\t &(formats[index].formatName), 0, NULL, NULL) < 1)\n\t\t\t\t{\n\t\t\t\t\tWLog_ERR(TAG, \"failed to convert long clipboard format name\");\n\t\t\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\t\t\tgoto error_out;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tindex++;\n\t\t}\n\t}\n\n\treturn error;\n\nerror_out:\n\tcliprdr_free_format_list(formatList);\n\treturn error;\n}", "project": "FreeRDP", "hash": 237858437120074239124496021317037679825, "size": 165, "commit_id": "b73143cf7ee5fe4cdabcbf56908aa15d8a883821", "message": "Fixed oob read in cliprdr_read_format_list", "target": 0, "dataset": "other", "idx": 388319} {"func": "static int identity_count(void *v, const char *key, const char *val)\n{\n int *count = v;\n *count += strlen(key) * 3 + strlen(val) * 3 + 1;\n return 1;\n}", "project": "httpd", "hash": 50330208498269000547705518476088709988, "size": 6, "commit_id": "7e09dd714fc62c08c5b0319ed7b9702594faf49b", "message": "mod_session: account for the '&' in identity_concat().\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1887052 13f79535-47bb-0310-9956-ffa450edef68", "target": 1, "dataset": "other", "idx": 206917} {"func": "static int identity_count(void *v, const char *key, const char *val)\n{\n int *count = v;\n *count += strlen(key) * 3 + strlen(val) * 3 + 2;\n return 1;\n}", "project": "httpd", "hash": 243767006619414530688134707731592870569, "size": 6, "commit_id": "7e09dd714fc62c08c5b0319ed7b9702594faf49b", "message": "mod_session: account for the '&' in identity_concat().\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1887052 13f79535-47bb-0310-9956-ffa450edef68", "target": 0, "dataset": "other", "idx": 389228} {"func": "static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image *image, *image2=NULL,\n *rotated_image;\n register Quantum *q;\n\n unsigned int status;\n MATHeader MATLAB_HDR;\n size_t size;\n size_t CellType;\n QuantumInfo *quantum_info;\n ImageInfo *clone_info;\n int i;\n ssize_t ldblk;\n unsigned char *BImgBuff = NULL;\n double MinVal, MaxVal;\n unsigned z, z2;\n unsigned Frames;\n int logging;\n int sample_size;\n MagickOffsetType filepos=0x80;\n BlobInfo *blob;\n size_t one;\n\n unsigned int (*ReadBlobXXXLong)(Image *image);\n unsigned short (*ReadBlobXXXShort)(Image *image);\n void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);\n void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);\n\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n logging = LogMagickEvent(CoderEvent,GetMagickModule(),\"enter\");\n\n /*\n Open image file.\n */\n image = AcquireImage(image_info,exception);\n\n status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read MATLAB image.\n */\n quantum_info=(QuantumInfo *) NULL;\n clone_info=(ImageInfo *) NULL;\n if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (strncmp(MATLAB_HDR.identific,\"MATLAB\",6) != 0)\n {\n image2=ReadMATImageV4(image_info,image,exception);\n if (image2 == NULL)\n goto MATLAB_KO;\n image=image2;\n goto END_OF_READING;\n }\n MATLAB_HDR.Version = ReadBlobLSBShort(image);\n if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Endian %c%c\",\n MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);\n if (!strncmp(MATLAB_HDR.EndianIndicator, \"IM\", 2))\n {\n ReadBlobXXXLong = ReadBlobLSBLong;\n ReadBlobXXXShort = ReadBlobLSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesLSB;\n ReadBlobFloatsXXX = ReadBlobFloatsLSB;\n image->endian = LSBEndian;\n }\n else if (!strncmp(MATLAB_HDR.EndianIndicator, \"MI\", 2))\n {\n ReadBlobXXXLong = ReadBlobMSBLong;\n ReadBlobXXXShort = ReadBlobMSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesMSB;\n ReadBlobFloatsXXX = ReadBlobFloatsMSB;\n image->endian = MSBEndian;\n }\n else\n goto MATLAB_KO; /* unsupported endian */\n\n if (strncmp(MATLAB_HDR.identific, \"MATLAB\", 6))\n {\nMATLAB_KO:\n clone_info=DestroyImageInfo(clone_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n\n filepos = TellBlob(image);\n while(!EOFBlob(image)) /* object parser loop */\n {\n Frames = 1;\n (void) SeekBlob(image,filepos,SEEK_SET);\n /* printf(\"pos=%X\\n\",TellBlob(image)); */\n\n MATLAB_HDR.DataType = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))\n goto MATLAB_KO;\n filepos += MATLAB_HDR.ObjectSize + 4 + 4;\n\n clone_info=CloneImageInfo(image_info);\n image2 = image;\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if(MATLAB_HDR.DataType == miCOMPRESSED)\n {\n image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);\n if(image2==NULL) continue;\n MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */\n }\n#endif\n\n if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */\n\n MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);\n MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);\n\n MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);\n MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;\n MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;\n\n MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);\n if(image!=image2)\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);\n MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);\n\n\n switch(MATLAB_HDR.DimFlag)\n {\n case 8: z2=z=1; break; /* 2D matrix*/\n case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/\n (void) ReadBlobXXXLong(image2);\n if(z!=3) ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n break;\n case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */\n if(z!=3 && z!=1)\n ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n Frames = ReadBlobXXXLong(image2);\n if (Frames == 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n default: ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n }\n\n MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);\n MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);\n\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.StructureClass %d\",MATLAB_HDR.StructureClass);\n if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&\n MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */\n MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */\n MATLAB_HDR.StructureClass != mxINT8_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */\n MATLAB_HDR.StructureClass != mxINT16_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */\n MATLAB_HDR.StructureClass != mxINT32_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */\n MATLAB_HDR.StructureClass != mxINT64_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */\n ThrowReaderException(CoderError,\"UnsupportedCellTypeInTheMatrix\");\n\n switch (MATLAB_HDR.NameFlag)\n {\n case 0:\n size = ReadBlobXXXLong(image2); /* Object name string size */\n size = 4 * (ssize_t) ((size + 3 + 1) / 4);\n (void) SeekBlob(image2, size, SEEK_CUR);\n break;\n case 1:\n case 2:\n case 3:\n case 4:\n (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */\n break;\n default:\n goto MATLAB_KO;\n }\n\n CellType = ReadBlobXXXLong(image2); /* Additional object type */\n if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.CellType: %.20g\",(double) CellType);\n\n (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */\n\n NEXT_FRAME:\n switch (CellType)\n {\n case miINT8:\n case miUINT8:\n sample_size = 8;\n if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)\n image->depth = 1;\n else\n image->depth = 8; /* Byte type cell */\n ldblk = (ssize_t) MATLAB_HDR.SizeX;\n break;\n case miINT16:\n case miUINT16:\n sample_size = 16;\n image->depth = 16; /* Word type cell */\n ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);\n break;\n case miINT32:\n case miUINT32:\n sample_size = 32;\n image->depth = 32; /* Dword type cell */\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miINT64:\n case miUINT64:\n sample_size = 64;\n image->depth = 64; /* Qword type cell */\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n case miSINGLE:\n sample_size = 32;\n image->depth = 32; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex float type cell */\n }\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miDOUBLE:\n sample_size = 64;\n image->depth = 64; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\nDisableMSCWarning(4127)\n if (sizeof(double) != 8)\nRestoreMSCWarning\n ThrowReaderException(CoderError, \"IncompatibleSizeOfDouble\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex double type cell */\n }\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n default:\n ThrowReaderException(CoderError, \"UnsupportedCellTypeInTheMatrix\");\n }\n (void) sample_size;\n image->columns = MATLAB_HDR.SizeX;\n image->rows = MATLAB_HDR.SizeY;\n one=1;\n image->colors = one << image->depth;\n if (image->columns == 0 || image->rows == 0)\n goto MATLAB_KO;\n if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)\n goto MATLAB_KO;\n /* Image is gray when no complex flag is set and 2D Matrix */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n {\n image->type=GrayscaleType;\n SetImageColorspace(image,GRAYColorspace,exception);\n }\n\n\n /*\n If ping is true, then only set image size and colors without\n reading any image data.\n */\n if (image_info->ping)\n {\n size_t temp = image->columns;\n image->columns = image->rows;\n image->rows = temp;\n goto done_reading; /* !!!!!! BAD !!!! */\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n quantum_info=AcquireQuantumInfo(clone_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n /* ----- Load raster data ----- */\n BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */\n if (BImgBuff == NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));\n\n MinVal = 0;\n MaxVal = 0;\n if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);\n }\n\n /* Main loop for reading all scanlines */\n if(z==1) z=0; /* read grey scanlines */\n /* else read color scanlines */\n do\n {\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT set image pixels returns unexpected NULL on a row %u.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto done_reading; /* Skip image rotation, when cannot set image pixels */\n }\n if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT cannot read scanrow %u from a file.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))\n {\n FixLogical((unsigned char *)BImgBuff,ldblk);\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n {\nImportQuantumPixelsFailed:\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to ImportQuantumPixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n break;\n }\n }\n else\n {\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n goto ImportQuantumPixelsFailed;\n\n\n if (z<=1 && /* fix only during a last pass z==0 || z==1 */\n (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))\n FixSignedValues(image,q,MATLAB_HDR.SizeX);\n }\n\n if (!SyncAuthenticPixels(image,exception))\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to sync image pixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n }\n } while(z-- >= 2);\nExitLoop:\n\n\n /* Read complex part of numbers here */\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* Find Min and Max Values for complex parts of floats */\n CellType = ReadBlobXXXLong(image2); /* Additional object type */\n i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/\n\n if (CellType==miDOUBLE || CellType==miSINGLE)\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);\n }\n\n if (CellType==miDOUBLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);\n InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,\n exception);\n }\n\n if (CellType==miSINGLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);\n InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,\n exception);\n }\n }\n\n /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n image->type=GrayscaleType;\n if (image->depth == 1)\n image->type=BilevelType;\n\n if(image2==image)\n image2 = NULL; /* Remove shadow copy to an image before rotation. */\n\n /* Rotate image. */\n rotated_image = RotateImage(image, 90.0, exception);\n if (rotated_image != (Image *) NULL)\n {\n /* Remove page offsets added by RotateImage */\n rotated_image->page.x=0;\n rotated_image->page.y=0;\n\n blob = rotated_image->blob;\n rotated_image->blob = image->blob;\n rotated_image->colors = image->colors;\n image->blob = blob;\n AppendImageToList(&image,rotated_image);\n DeleteImageFromList(&image);\n }\n\ndone_reading:\n\n if(image2!=NULL)\n if(image2!=image)\n {\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }\n\n /* Allocate next image structure. */\n AcquireNextImage(image_info,image,exception);\n if (image->next == (Image *) NULL) break;\n image=SyncNextImageInList(image);\n image->columns=image->rows=0;\n image->colors=0;\n\n /* row scan buffer is no longer needed */\n RelinquishMagickMemory(BImgBuff);\n BImgBuff = NULL;\n\n if(--Frames>0)\n {\n z = z2;\n if(image2==NULL) image2 = image;\n goto NEXT_FRAME;\n }\n if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */\n {\n/* CloseBlob(image2); */\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }\n }\n\n RelinquishMagickMemory(BImgBuff);\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\nEND_OF_READING:\n if (clone_info)\n clone_info=DestroyImageInfo(clone_info);\n CloseBlob(image);\n\n\n {\n Image *p;\n ssize_t scene=0;\n\n /*\n Rewind list, removing any empty images while rewinding.\n */\n p=image;\n image=NULL;\n while (p != (Image *) NULL)\n {\n Image *tmp=p;\n if ((p->rows == 0) || (p->columns == 0)) {\n p=p->previous;\n DeleteImageFromList(&tmp);\n } else {\n image=p;\n p=p->previous;\n }\n }\n\n /*\n Fix scene numbers\n */\n for (p=image; p != (Image *) NULL; p=p->next)\n p->scene=scene++;\n }\n\n if(clone_info != NULL) /* cleanup garbage file from compression */\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n DestroyImageInfo(clone_info);\n clone_info = NULL;\n }\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\"return\");\n if(image==NULL)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n return (image);\n}", "project": "ImageMagick", "hash": 213822569694002162486182145935420282110, "size": 512, "commit_id": "a6802e21d824e786d1e2a8440cf749a6e1a8d95f", "message": "https://github.com/ImageMagick/ImageMagick/issues/587", "target": 1, "dataset": "other", "idx": 206930} {"func": "static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image *image, *image2=NULL,\n *rotated_image;\n register Quantum *q;\n\n unsigned int status;\n MATHeader MATLAB_HDR;\n size_t size;\n size_t CellType;\n QuantumInfo *quantum_info;\n ImageInfo *clone_info;\n int i;\n ssize_t ldblk;\n unsigned char *BImgBuff = NULL;\n double MinVal, MaxVal;\n unsigned z, z2;\n unsigned Frames;\n int logging;\n int sample_size;\n MagickOffsetType filepos=0x80;\n BlobInfo *blob;\n size_t one;\n\n unsigned int (*ReadBlobXXXLong)(Image *image);\n unsigned short (*ReadBlobXXXShort)(Image *image);\n void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);\n void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);\n\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n logging = LogMagickEvent(CoderEvent,GetMagickModule(),\"enter\");\n\n /*\n Open image file.\n */\n image = AcquireImage(image_info,exception);\n\n status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read MATLAB image.\n */\n quantum_info=(QuantumInfo *) NULL;\n clone_info=(ImageInfo *) NULL;\n if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (strncmp(MATLAB_HDR.identific,\"MATLAB\",6) != 0)\n {\n image2=ReadMATImageV4(image_info,image,exception);\n if (image2 == NULL)\n goto MATLAB_KO;\n image=image2;\n goto END_OF_READING;\n }\n MATLAB_HDR.Version = ReadBlobLSBShort(image);\n if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n\n if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Endian %c%c\",\n MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);\n if (!strncmp(MATLAB_HDR.EndianIndicator, \"IM\", 2))\n {\n ReadBlobXXXLong = ReadBlobLSBLong;\n ReadBlobXXXShort = ReadBlobLSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesLSB;\n ReadBlobFloatsXXX = ReadBlobFloatsLSB;\n image->endian = LSBEndian;\n }\n else if (!strncmp(MATLAB_HDR.EndianIndicator, \"MI\", 2))\n {\n ReadBlobXXXLong = ReadBlobMSBLong;\n ReadBlobXXXShort = ReadBlobMSBShort;\n ReadBlobDoublesXXX = ReadBlobDoublesMSB;\n ReadBlobFloatsXXX = ReadBlobFloatsMSB;\n image->endian = MSBEndian;\n }\n else\n goto MATLAB_KO; /* unsupported endian */\n\n if (strncmp(MATLAB_HDR.identific, \"MATLAB\", 6))\n {\nMATLAB_KO:\n clone_info=DestroyImageInfo(clone_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n\n filepos = TellBlob(image);\n while(!EOFBlob(image)) /* object parser loop */\n {\n Frames = 1;\n (void) SeekBlob(image,filepos,SEEK_SET);\n /* printf(\"pos=%X\\n\",TellBlob(image)); */\n\n MATLAB_HDR.DataType = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);\n if(EOFBlob(image)) break;\n if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))\n goto MATLAB_KO;\n filepos += MATLAB_HDR.ObjectSize + 4 + 4;\n\n clone_info=CloneImageInfo(image_info);\n image2 = image;\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if(MATLAB_HDR.DataType == miCOMPRESSED)\n {\n image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);\n if(image2==NULL) continue;\n MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */\n }\n#endif\n\n if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */\n\n MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);\n MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);\n\n MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);\n MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;\n MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;\n\n MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);\n if(image!=image2)\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */\n MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);\n MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);\n MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);\n\n\n switch(MATLAB_HDR.DimFlag)\n {\n case 8: z2=z=1; break; /* 2D matrix*/\n case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/\n (void) ReadBlobXXXLong(image2);\n if(z!=3) ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n break;\n case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */\n if(z!=3 && z!=1)\n ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n Frames = ReadBlobXXXLong(image2);\n if (Frames == 0)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n default: ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n }\n\n MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);\n MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);\n\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.StructureClass %d\",MATLAB_HDR.StructureClass);\n if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&\n MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */\n MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */\n MATLAB_HDR.StructureClass != mxINT8_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */\n MATLAB_HDR.StructureClass != mxINT16_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */\n MATLAB_HDR.StructureClass != mxINT32_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */\n MATLAB_HDR.StructureClass != mxINT64_CLASS &&\n MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */\n ThrowReaderException(CoderError,\"UnsupportedCellTypeInTheMatrix\");\n\n switch (MATLAB_HDR.NameFlag)\n {\n case 0:\n size = ReadBlobXXXLong(image2); /* Object name string size */\n size = 4 * (ssize_t) ((size + 3 + 1) / 4);\n (void) SeekBlob(image2, size, SEEK_CUR);\n break;\n case 1:\n case 2:\n case 3:\n case 4:\n (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */\n break;\n default:\n goto MATLAB_KO;\n }\n\n CellType = ReadBlobXXXLong(image2); /* Additional object type */\n if (logging)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"MATLAB_HDR.CellType: %.20g\",(double) CellType);\n\n (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */\n\n NEXT_FRAME:\n switch (CellType)\n {\n case miINT8:\n case miUINT8:\n sample_size = 8;\n if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)\n image->depth = 1;\n else\n image->depth = 8; /* Byte type cell */\n ldblk = (ssize_t) MATLAB_HDR.SizeX;\n break;\n case miINT16:\n case miUINT16:\n sample_size = 16;\n image->depth = 16; /* Word type cell */\n ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);\n break;\n case miINT32:\n case miUINT32:\n sample_size = 32;\n image->depth = 32; /* Dword type cell */\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miINT64:\n case miUINT64:\n sample_size = 64;\n image->depth = 64; /* Qword type cell */\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n case miSINGLE:\n sample_size = 32;\n image->depth = 32; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex float type cell */\n }\n ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);\n break;\n case miDOUBLE:\n sample_size = 64;\n image->depth = 64; /* double type cell */\n (void) SetImageOption(clone_info,\"quantum:format\",\"floating-point\");\nDisableMSCWarning(4127)\n if (sizeof(double) != 8)\nRestoreMSCWarning\n ThrowReaderException(CoderError, \"IncompatibleSizeOfDouble\");\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* complex double type cell */\n }\n ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);\n break;\n default:\n ThrowReaderException(CoderError, \"UnsupportedCellTypeInTheMatrix\");\n }\n (void) sample_size;\n image->columns = MATLAB_HDR.SizeX;\n image->rows = MATLAB_HDR.SizeY;\n one=1;\n image->colors = one << image->depth;\n if (image->columns == 0 || image->rows == 0)\n goto MATLAB_KO;\n if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)\n goto MATLAB_KO;\n /* Image is gray when no complex flag is set and 2D Matrix */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n {\n image->type=GrayscaleType;\n SetImageColorspace(image,GRAYColorspace,exception);\n }\n\n\n /*\n If ping is true, then only set image size and colors without\n reading any image data.\n */\n if (image_info->ping)\n {\n size_t temp = image->columns;\n image->columns = image->rows;\n image->rows = temp;\n goto done_reading; /* !!!!!! BAD !!!! */\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n quantum_info=AcquireQuantumInfo(clone_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n /* ----- Load raster data ----- */\n BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */\n if (BImgBuff == NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));\n\n MinVal = 0;\n MaxVal = 0;\n if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);\n }\n\n /* Main loop for reading all scanlines */\n if(z==1) z=0; /* read grey scanlines */\n /* else read color scanlines */\n do\n {\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT set image pixels returns unexpected NULL on a row %u.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto done_reading; /* Skip image rotation, when cannot set image pixels */\n }\n if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT cannot read scanrow %u from a file.\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))\n {\n FixLogical((unsigned char *)BImgBuff,ldblk);\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n {\nImportQuantumPixelsFailed:\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to ImportQuantumPixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n break;\n }\n }\n else\n {\n if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)\n goto ImportQuantumPixelsFailed;\n\n\n if (z<=1 && /* fix only during a last pass z==0 || z==1 */\n (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))\n FixSignedValues(image,q,MATLAB_HDR.SizeX);\n }\n\n if (!SyncAuthenticPixels(image,exception))\n {\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\n \" MAT failed to sync image pixels for a row %u\", (unsigned)(MATLAB_HDR.SizeY-i-1));\n goto ExitLoop;\n }\n }\n } while(z-- >= 2);\nExitLoop:\n\n\n /* Read complex part of numbers here */\n if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)\n { /* Find Min and Max Values for complex parts of floats */\n CellType = ReadBlobXXXLong(image2); /* Additional object type */\n i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/\n\n if (CellType==miDOUBLE || CellType==miSINGLE)\n {\n CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);\n }\n\n if (CellType==miDOUBLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);\n InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,\n exception);\n }\n\n if (CellType==miSINGLE)\n for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)\n {\n ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);\n InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,\n exception);\n }\n }\n\n /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */\n if ((MATLAB_HDR.DimFlag == 8) &&\n ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))\n image->type=GrayscaleType;\n if (image->depth == 1)\n image->type=BilevelType;\n\n if(image2==image)\n image2 = NULL; /* Remove shadow copy to an image before rotation. */\n\n /* Rotate image. */\n rotated_image = RotateImage(image, 90.0, exception);\n if (rotated_image != (Image *) NULL)\n {\n /* Remove page offsets added by RotateImage */\n rotated_image->page.x=0;\n rotated_image->page.y=0;\n\n blob = rotated_image->blob;\n rotated_image->blob = image->blob;\n rotated_image->colors = image->colors;\n image->blob = blob;\n AppendImageToList(&image,rotated_image);\n DeleteImageFromList(&image);\n }\n\ndone_reading:\n\n if(image2!=NULL)\n if(image2!=image)\n {\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }\n\n /* Allocate next image structure. */\n AcquireNextImage(image_info,image,exception);\n if (image->next == (Image *) NULL) break;\n image=SyncNextImageInList(image);\n image->columns=image->rows=0;\n image->colors=0;\n\n /* row scan buffer is no longer needed */\n RelinquishMagickMemory(BImgBuff);\n BImgBuff = NULL;\n\n if(--Frames>0)\n {\n z = z2;\n if(image2==NULL) image2 = image;\n goto NEXT_FRAME;\n }\n if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */\n {\n/* CloseBlob(image2); */\n DeleteImageFromList(&image2);\n if(clone_info)\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n }\n }\n }\n\n RelinquishMagickMemory(BImgBuff);\n if (quantum_info != (QuantumInfo *) NULL)\n quantum_info=DestroyQuantumInfo(quantum_info);\nEND_OF_READING:\n if (clone_info)\n clone_info=DestroyImageInfo(clone_info);\n CloseBlob(image);\n\n\n {\n Image *p;\n ssize_t scene=0;\n\n /*\n Rewind list, removing any empty images while rewinding.\n */\n p=image;\n image=NULL;\n while (p != (Image *) NULL)\n {\n Image *tmp=p;\n if ((p->rows == 0) || (p->columns == 0)) {\n p=p->previous;\n DeleteImageFromList(&tmp);\n } else {\n image=p;\n p=p->previous;\n }\n }\n\n /*\n Fix scene numbers\n */\n for (p=image; p != (Image *) NULL; p=p->next)\n p->scene=scene++;\n }\n\n if(clone_info != NULL) /* cleanup garbage file from compression */\n {\n if(clone_info->file)\n {\n fclose(clone_info->file);\n clone_info->file = NULL;\n (void) remove_utf8(clone_info->filename);\n }\n DestroyImageInfo(clone_info);\n clone_info = NULL;\n }\n if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),\"return\");\n if ((image != image2) && (image2 != (Image *) NULL))\n image2=DestroyImage(image2);\n if(image==NULL)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n return (image);\n}", "project": "ImageMagick", "hash": 17837560180019284785462531344102032169, "size": 514, "commit_id": "a6802e21d824e786d1e2a8440cf749a6e1a8d95f", "message": "https://github.com/ImageMagick/ImageMagick/issues/587", "target": 0, "dataset": "other", "idx": 389327} {"func": "static void gprinter_free(struct usb_function *f)\n{\n\tstruct printer_dev *dev = func_to_printer(f);\n\tstruct f_printer_opts *opts;\n\n\topts = container_of(f->fi, struct f_printer_opts, func_inst);\n\tkfree(dev);\n\tmutex_lock(&opts->lock);\n\t--opts->refcnt;\n\tmutex_unlock(&opts->lock);\n}", "project": "linux", "hash": 139503561102920286146443985238426195363, "size": 11, "commit_id": "e8d5f92b8d30bb4ade76494490c3c065e12411b1", "message": "usb: gadget: function: printer: fix use-after-free in __lock_acquire\n\nFix this by increase object reference count.\n\nBUG: KASAN: use-after-free in __lock_acquire+0x3fd4/0x4180\nkernel/locking/lockdep.c:3831\nRead of size 8 at addr ffff8880683b0018 by task syz-executor.0/3377\n\nCPU: 1 PID: 3377 Comm: syz-executor.0 Not tainted 5.6.11 #1\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\nCall Trace:\n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0xce/0x128 lib/dump_stack.c:118\n print_address_description.constprop.4+0x21/0x3c0 mm/kasan/report.c:374\n __kasan_report+0x131/0x1b0 mm/kasan/report.c:506\n kasan_report+0x12/0x20 mm/kasan/common.c:641\n __asan_report_load8_noabort+0x14/0x20 mm/kasan/generic_report.c:135\n __lock_acquire+0x3fd4/0x4180 kernel/locking/lockdep.c:3831\n lock_acquire+0x127/0x350 kernel/locking/lockdep.c:4488\n __raw_spin_lock_irqsave include/linux/spinlock_api_smp.h:110 [inline]\n _raw_spin_lock_irqsave+0x35/0x50 kernel/locking/spinlock.c:159\n printer_ioctl+0x4a/0x110 drivers/usb/gadget/function/f_printer.c:723\n vfs_ioctl fs/ioctl.c:47 [inline]\n ksys_ioctl+0xfb/0x130 fs/ioctl.c:763\n __do_sys_ioctl fs/ioctl.c:772 [inline]\n __se_sys_ioctl fs/ioctl.c:770 [inline]\n __x64_sys_ioctl+0x73/0xb0 fs/ioctl.c:770\n do_syscall_64+0x9e/0x510 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x4531a9\nCode: ed 60 fc ff c3 66 2e 0f 1f 84 00 00 00 00 00 66 90 48 89 f8 48\n89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d\n01 f0 ff ff 0f 83 bb 60 fc ff c3 66 2e 0f 1f 84 00 00 00 00\nRSP: 002b:00007fd14ad72c78 EFLAGS: 00000246 ORIG_RAX: 0000000000000010\nRAX: ffffffffffffffda RBX: 000000000073bfa8 RCX: 00000000004531a9\nRDX: fffffffffffffff9 RSI: 000000000000009e RDI: 0000000000000003\nRBP: 0000000000000003 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00000000004bbd61\nR13: 00000000004d0a98 R14: 00007fd14ad736d4 R15: 00000000ffffffff\n\nAllocated by task 2393:\n save_stack+0x21/0x90 mm/kasan/common.c:72\n set_track mm/kasan/common.c:80 [inline]\n __kasan_kmalloc.constprop.3+0xa7/0xd0 mm/kasan/common.c:515\n kasan_kmalloc+0x9/0x10 mm/kasan/common.c:529\n kmem_cache_alloc_trace+0xfa/0x2d0 mm/slub.c:2813\n kmalloc include/linux/slab.h:555 [inline]\n kzalloc include/linux/slab.h:669 [inline]\n gprinter_alloc+0xa1/0x870 drivers/usb/gadget/function/f_printer.c:1416\n usb_get_function+0x58/0xc0 drivers/usb/gadget/functions.c:61\n config_usb_cfg_link+0x1ed/0x3e0 drivers/usb/gadget/configfs.c:444\n configfs_symlink+0x527/0x11d0 fs/configfs/symlink.c:202\n vfs_symlink+0x33d/0x5b0 fs/namei.c:4201\n do_symlinkat+0x11b/0x1d0 fs/namei.c:4228\n __do_sys_symlinkat fs/namei.c:4242 [inline]\n __se_sys_symlinkat fs/namei.c:4239 [inline]\n __x64_sys_symlinkat+0x73/0xb0 fs/namei.c:4239\n do_syscall_64+0x9e/0x510 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nFreed by task 3368:\n save_stack+0x21/0x90 mm/kasan/common.c:72\n set_track mm/kasan/common.c:80 [inline]\n kasan_set_free_info mm/kasan/common.c:337 [inline]\n __kasan_slab_free+0x135/0x190 mm/kasan/common.c:476\n kasan_slab_free+0xe/0x10 mm/kasan/common.c:485\n slab_free_hook mm/slub.c:1444 [inline]\n slab_free_freelist_hook mm/slub.c:1477 [inline]\n slab_free mm/slub.c:3034 [inline]\n kfree+0xf7/0x410 mm/slub.c:3995\n gprinter_free+0x49/0xd0 drivers/usb/gadget/function/f_printer.c:1353\n usb_put_function+0x38/0x50 drivers/usb/gadget/functions.c:87\n config_usb_cfg_unlink+0x2db/0x3b0 drivers/usb/gadget/configfs.c:485\n configfs_unlink+0x3b9/0x7f0 fs/configfs/symlink.c:250\n vfs_unlink+0x287/0x570 fs/namei.c:4073\n do_unlinkat+0x4f9/0x620 fs/namei.c:4137\n __do_sys_unlink fs/namei.c:4184 [inline]\n __se_sys_unlink fs/namei.c:4182 [inline]\n __x64_sys_unlink+0x42/0x50 fs/namei.c:4182\n do_syscall_64+0x9e/0x510 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nThe buggy address belongs to the object at ffff8880683b0000\n which belongs to the cache kmalloc-1k of size 1024\nThe buggy address is located 24 bytes inside of\n 1024-byte region [ffff8880683b0000, ffff8880683b0400)\nThe buggy address belongs to the page:\npage:ffffea0001a0ec00 refcount:1 mapcount:0 mapping:ffff88806c00e300\nindex:0xffff8880683b1800 compound_mapcount: 0\nflags: 0x100000000010200(slab|head)\nraw: 0100000000010200 0000000000000000 0000000600000001 ffff88806c00e300\nraw: ffff8880683b1800 000000008010000a 00000001ffffffff 0000000000000000\npage dumped because: kasan: bad access detected\n\nReported-by: Kyungtae Kim \nSigned-off-by: Zqiang \nSigned-off-by: Felipe Balbi ", "target": 1, "dataset": "other", "idx": 206932} {"func": "static void gprinter_free(struct usb_function *f)\n{\n\tstruct printer_dev *dev = func_to_printer(f);\n\tstruct f_printer_opts *opts;\n\n\topts = container_of(f->fi, struct f_printer_opts, func_inst);\n\n\tkref_put(&dev->kref, printer_dev_free);\n\tmutex_lock(&opts->lock);\n\t--opts->refcnt;\n\tmutex_unlock(&opts->lock);\n}", "project": "linux", "hash": 27438058775959452498290599893423336582, "size": 12, "commit_id": "e8d5f92b8d30bb4ade76494490c3c065e12411b1", "message": "usb: gadget: function: printer: fix use-after-free in __lock_acquire\n\nFix this by increase object reference count.\n\nBUG: KASAN: use-after-free in __lock_acquire+0x3fd4/0x4180\nkernel/locking/lockdep.c:3831\nRead of size 8 at addr ffff8880683b0018 by task syz-executor.0/3377\n\nCPU: 1 PID: 3377 Comm: syz-executor.0 Not tainted 5.6.11 #1\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\nCall Trace:\n __dump_stack lib/dump_stack.c:77 [inline]\n dump_stack+0xce/0x128 lib/dump_stack.c:118\n print_address_description.constprop.4+0x21/0x3c0 mm/kasan/report.c:374\n __kasan_report+0x131/0x1b0 mm/kasan/report.c:506\n kasan_report+0x12/0x20 mm/kasan/common.c:641\n __asan_report_load8_noabort+0x14/0x20 mm/kasan/generic_report.c:135\n __lock_acquire+0x3fd4/0x4180 kernel/locking/lockdep.c:3831\n lock_acquire+0x127/0x350 kernel/locking/lockdep.c:4488\n __raw_spin_lock_irqsave include/linux/spinlock_api_smp.h:110 [inline]\n _raw_spin_lock_irqsave+0x35/0x50 kernel/locking/spinlock.c:159\n printer_ioctl+0x4a/0x110 drivers/usb/gadget/function/f_printer.c:723\n vfs_ioctl fs/ioctl.c:47 [inline]\n ksys_ioctl+0xfb/0x130 fs/ioctl.c:763\n __do_sys_ioctl fs/ioctl.c:772 [inline]\n __se_sys_ioctl fs/ioctl.c:770 [inline]\n __x64_sys_ioctl+0x73/0xb0 fs/ioctl.c:770\n do_syscall_64+0x9e/0x510 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\nRIP: 0033:0x4531a9\nCode: ed 60 fc ff c3 66 2e 0f 1f 84 00 00 00 00 00 66 90 48 89 f8 48\n89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d\n01 f0 ff ff 0f 83 bb 60 fc ff c3 66 2e 0f 1f 84 00 00 00 00\nRSP: 002b:00007fd14ad72c78 EFLAGS: 00000246 ORIG_RAX: 0000000000000010\nRAX: ffffffffffffffda RBX: 000000000073bfa8 RCX: 00000000004531a9\nRDX: fffffffffffffff9 RSI: 000000000000009e RDI: 0000000000000003\nRBP: 0000000000000003 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 00000000004bbd61\nR13: 00000000004d0a98 R14: 00007fd14ad736d4 R15: 00000000ffffffff\n\nAllocated by task 2393:\n save_stack+0x21/0x90 mm/kasan/common.c:72\n set_track mm/kasan/common.c:80 [inline]\n __kasan_kmalloc.constprop.3+0xa7/0xd0 mm/kasan/common.c:515\n kasan_kmalloc+0x9/0x10 mm/kasan/common.c:529\n kmem_cache_alloc_trace+0xfa/0x2d0 mm/slub.c:2813\n kmalloc include/linux/slab.h:555 [inline]\n kzalloc include/linux/slab.h:669 [inline]\n gprinter_alloc+0xa1/0x870 drivers/usb/gadget/function/f_printer.c:1416\n usb_get_function+0x58/0xc0 drivers/usb/gadget/functions.c:61\n config_usb_cfg_link+0x1ed/0x3e0 drivers/usb/gadget/configfs.c:444\n configfs_symlink+0x527/0x11d0 fs/configfs/symlink.c:202\n vfs_symlink+0x33d/0x5b0 fs/namei.c:4201\n do_symlinkat+0x11b/0x1d0 fs/namei.c:4228\n __do_sys_symlinkat fs/namei.c:4242 [inline]\n __se_sys_symlinkat fs/namei.c:4239 [inline]\n __x64_sys_symlinkat+0x73/0xb0 fs/namei.c:4239\n do_syscall_64+0x9e/0x510 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nFreed by task 3368:\n save_stack+0x21/0x90 mm/kasan/common.c:72\n set_track mm/kasan/common.c:80 [inline]\n kasan_set_free_info mm/kasan/common.c:337 [inline]\n __kasan_slab_free+0x135/0x190 mm/kasan/common.c:476\n kasan_slab_free+0xe/0x10 mm/kasan/common.c:485\n slab_free_hook mm/slub.c:1444 [inline]\n slab_free_freelist_hook mm/slub.c:1477 [inline]\n slab_free mm/slub.c:3034 [inline]\n kfree+0xf7/0x410 mm/slub.c:3995\n gprinter_free+0x49/0xd0 drivers/usb/gadget/function/f_printer.c:1353\n usb_put_function+0x38/0x50 drivers/usb/gadget/functions.c:87\n config_usb_cfg_unlink+0x2db/0x3b0 drivers/usb/gadget/configfs.c:485\n configfs_unlink+0x3b9/0x7f0 fs/configfs/symlink.c:250\n vfs_unlink+0x287/0x570 fs/namei.c:4073\n do_unlinkat+0x4f9/0x620 fs/namei.c:4137\n __do_sys_unlink fs/namei.c:4184 [inline]\n __se_sys_unlink fs/namei.c:4182 [inline]\n __x64_sys_unlink+0x42/0x50 fs/namei.c:4182\n do_syscall_64+0x9e/0x510 arch/x86/entry/common.c:294\n entry_SYSCALL_64_after_hwframe+0x49/0xbe\n\nThe buggy address belongs to the object at ffff8880683b0000\n which belongs to the cache kmalloc-1k of size 1024\nThe buggy address is located 24 bytes inside of\n 1024-byte region [ffff8880683b0000, ffff8880683b0400)\nThe buggy address belongs to the page:\npage:ffffea0001a0ec00 refcount:1 mapcount:0 mapping:ffff88806c00e300\nindex:0xffff8880683b1800 compound_mapcount: 0\nflags: 0x100000000010200(slab|head)\nraw: 0100000000010200 0000000000000000 0000000600000001 ffff88806c00e300\nraw: ffff8880683b1800 000000008010000a 00000001ffffffff 0000000000000000\npage dumped because: kasan: bad access detected\n\nReported-by: Kyungtae Kim \nSigned-off-by: Zqiang \nSigned-off-by: Felipe Balbi ", "target": 0, "dataset": "other", "idx": 389362} {"func": "tiff12_print_page(gx_device_printer * pdev, gp_file * file)\n{\n gx_device_tiff *const tfdev = (gx_device_tiff *)pdev;\n int code;\n\n /* open the TIFF device */\n if (gdev_prn_file_is_new(pdev)) {\n tfdev->tif = tiff_from_filep(pdev, pdev->dname, file, tfdev->BigEndian, tfdev->UseBigTIFF);\n if (!tfdev->tif)\n return_error(gs_error_invalidfileaccess);\n }\n\n code = gdev_tiff_begin_page(tfdev, file);\n if (code < 0)\n return code;\n\n TIFFSetField(tfdev->tif, TIFFTAG_BITSPERSAMPLE, 4);\n tiff_set_rgb_fields(tfdev);\n\n TIFFCheckpointDirectory(tfdev->tif);\n\n /* Write the page data. */\n {\n int y;\n int size = gdev_prn_raster(pdev);\n byte *data = gs_alloc_bytes(pdev->memory, size, \"tiff12_print_page\");\n\n if (data == 0)\n return_error(gs_error_VMerror);\n\n memset(data, 0, size);\n\n for (y = 0; y < pdev->height; ++y) {\n const byte *src;\n byte *dest;\n int x;\n\n code = gdev_prn_copy_scan_lines(pdev, y, data, size);\n if (code < 0)\n break;\n\n for (src = data, dest = data, x = 0; x < size;\n src += 6, dest += 3, x += 6\n ) {\n dest[0] = (src[0] & 0xf0) | (src[1] >> 4);\n dest[1] = (src[2] & 0xf0) | (src[3] >> 4);\n dest[2] = (src[4] & 0xf0) | (src[5] >> 4);\n }\n TIFFWriteScanline(tfdev->tif, data, y, 0);\n }\n gs_free_object(pdev->memory, data, \"tiff12_print_page\");\n\n TIFFWriteDirectory(tfdev->tif);\n }\n\n return code;\n}", "project": "ghostpdl", "hash": 112158423848618498504949276444897095461, "size": 57, "commit_id": "714e8995cd582d418276915cbbec3c70711fb19e", "message": "Bug 701807: avoid buffer overflow in tiff12_print_page().\n\nFixes:\n ./sanbin/gs -r650 -sOutputFile=tmp -sDEVICE=tiff12nc ../bug-701807.pdf", "target": 1, "dataset": "other", "idx": 206948} {"func": "tiff12_print_page(gx_device_printer * pdev, gp_file * file)\n{\n gx_device_tiff *const tfdev = (gx_device_tiff *)pdev;\n int code;\n\n /* open the TIFF device */\n if (gdev_prn_file_is_new(pdev)) {\n tfdev->tif = tiff_from_filep(pdev, pdev->dname, file, tfdev->BigEndian, tfdev->UseBigTIFF);\n if (!tfdev->tif)\n return_error(gs_error_invalidfileaccess);\n }\n\n code = gdev_tiff_begin_page(tfdev, file);\n if (code < 0)\n return code;\n\n TIFFSetField(tfdev->tif, TIFFTAG_BITSPERSAMPLE, 4);\n tiff_set_rgb_fields(tfdev);\n\n TIFFCheckpointDirectory(tfdev->tif);\n\n /* Write the page data. */\n {\n int y;\n int size = gdev_prn_raster(pdev);\n\n /* We allocate an extra 5 bytes to avoid buffer overflow when accessing\n src[5] below, if size if not multiple of 6. This fixes bug-701807. */\n int size_alloc = size + 5;\n byte *data = gs_alloc_bytes(pdev->memory, size_alloc, \"tiff12_print_page\");\n\n if (data == 0)\n return_error(gs_error_VMerror);\n\n memset(data, 0, size_alloc);\n\n for (y = 0; y < pdev->height; ++y) {\n const byte *src;\n byte *dest;\n int x;\n\n code = gdev_prn_copy_scan_lines(pdev, y, data, size);\n if (code < 0)\n break;\n\n for (src = data, dest = data, x = 0; x < size;\n src += 6, dest += 3, x += 6\n ) {\n dest[0] = (src[0] & 0xf0) | (src[1] >> 4);\n dest[1] = (src[2] & 0xf0) | (src[3] >> 4);\n dest[2] = (src[4] & 0xf0) | (src[5] >> 4);\n }\n TIFFWriteScanline(tfdev->tif, data, y, 0);\n }\n gs_free_object(pdev->memory, data, \"tiff12_print_page\");\n\n TIFFWriteDirectory(tfdev->tif);\n }\n\n return code;\n}", "project": "ghostpdl", "hash": 199567541113132283956086938291295983290, "size": 61, "commit_id": "714e8995cd582d418276915cbbec3c70711fb19e", "message": "Bug 701807: avoid buffer overflow in tiff12_print_page().\n\nFixes:\n ./sanbin/gs -r650 -sOutputFile=tmp -sDEVICE=tiff12nc ../bug-701807.pdf", "target": 0, "dataset": "other", "idx": 389796} {"func": "static int xar_hash_check(int hash, const void * result, const void * expected)\n{\n int len;\n\n if (!result || !expected)\n return 1;\n switch (hash) {\n case XAR_CKSUM_SHA1:\n len = SHA1_HASH_SIZE;\n break;\n case XAR_CKSUM_MD5:\n len = CLI_HASH_MD5;\n break;\n case XAR_CKSUM_OTHER:\n case XAR_CKSUM_NONE:\n default:\n return 1;\n }\n return memcmp(result, expected, len);\n}", "project": "clamav-devel", "hash": 16464750489424958099095161220741826057, "size": 20, "commit_id": "d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6", "message": "bb11588 - fix out of bounds read.", "target": 1, "dataset": "other", "idx": 206998} {"func": "static int xar_hash_check(int hash, const void * result, const void * expected)\n{\n int len;\n\n if (!result || !expected)\n return 1;\n switch (hash) {\n case XAR_CKSUM_SHA1:\n len = CLI_HASHLEN_SHA1;\n break;\n case XAR_CKSUM_MD5:\n len = CLI_HASHLEN_MD5;\n break;\n case XAR_CKSUM_OTHER:\n case XAR_CKSUM_NONE:\n default:\n return 1;\n }\n return memcmp(result, expected, len);\n}", "project": "clamav-devel", "hash": 298399301874156136344056006861919253944, "size": 20, "commit_id": "d96a6b8bcc7439fa7e3876207aa0a8e79c8451b6", "message": "bb11588 - fix out of bounds read.", "target": 0, "dataset": "other", "idx": 390690} {"func": "void CLASS kodak_65000_load_raw()\n{\n short buf[256];\n int row, col, len, pred[2], ret, i;\n\n for (row=0; row < height; row++)\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n for (col=0; col < width; col+=256) {\n pred[0] = pred[1] = 0;\n len = MIN (256, width-col);\n ret = kodak_65000_decode (buf, len);\n for (i=0; i < len; i++)\n\tif ((RAW(row,col+i) =\tcurve[ret ? buf[i] :\n\t\t(pred[i & 1] += buf[i])]) >> 12) derror();\n }\n }\n}", "project": "LibRaw", "hash": 313345098145828817127235037429126165072, "size": 20, "commit_id": "d13e8f6d1e987b7491182040a188c16a395f1d21", "message": "CVE-2017-1438 credits; fix for Kodak 65000 out of bounds access", "target": 1, "dataset": "other", "idx": 207059} {"func": "void CLASS kodak_65000_load_raw()\n{\n short buf[256];\n int row, col, len, pred[2], ret, i;\n\n for (row=0; row < height; row++)\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n for (col=0; col < width; col+=256) {\n pred[0] = pred[1] = 0;\n len = MIN (256, width-col);\n ret = kodak_65000_decode (buf, len);\n for (i=0; i < len; i++)\n {\n\tint idx = ret ? buf[i] : (pred[i & 1] += buf[i]);\n\tif(idx >=0 && idx <= 0xffff)\n\t {\n\t if ((RAW(row,col+i) = curve[idx]) >> 12) derror();\n }\n\t else\n\t derror();\n }\n }\n }\n}", "project": "LibRaw", "hash": 281742020088408334913030368393690018605, "size": 27, "commit_id": "d13e8f6d1e987b7491182040a188c16a395f1d21", "message": "CVE-2017-1438 credits; fix for Kodak 65000 out of bounds access", "target": 0, "dataset": "other", "idx": 391457} {"func": "static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){\n int i;\n WhereConst *pConst;\n if( pExpr->op!=TK_COLUMN ) return WRC_Continue;\n if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue;\n pConst = pWalker->u.pConst;\n for(i=0; inConst; i++){\n Expr *pColumn = pConst->apExpr[i*2];\n if( pColumn==pExpr ) continue;\n if( pColumn->iTable!=pExpr->iTable ) continue;\n if( pColumn->iColumn!=pExpr->iColumn ) continue;\n /* A match is found. Add the EP_FixedCol property */\n pConst->nChng++;\n ExprClearProperty(pExpr, EP_Leaf);\n ExprSetProperty(pExpr, EP_FixedCol);\n assert( pExpr->pLeft==0 );\n pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);\n break;\n }\n return WRC_Prune;\n}", "project": "sqlite", "hash": 236002876375750538692909015588787193480, "size": 21, "commit_id": "39df24a3f02495e5ef6bb5ea8ce029a2c1e377e6", "message": "Do not allow the constant-propagation optimization to apple to ON/USING clause\nterms as it does not help and it might cause downstream problems.\n\nFossilOrigin-Name: 1bc783da63d58b05c690468b569cb2787846357b63c1100d11777666c5787bf4", "target": 1, "dataset": "other", "idx": 207148} {"func": "static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){\n int i;\n WhereConst *pConst;\n if( pExpr->op!=TK_COLUMN ) return WRC_Continue;\n if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ) return WRC_Continue;\n pConst = pWalker->u.pConst;\n for(i=0; inConst; i++){\n Expr *pColumn = pConst->apExpr[i*2];\n if( pColumn==pExpr ) continue;\n if( pColumn->iTable!=pExpr->iTable ) continue;\n if( pColumn->iColumn!=pExpr->iColumn ) continue;\n /* A match is found. Add the EP_FixedCol property */\n pConst->nChng++;\n ExprClearProperty(pExpr, EP_Leaf);\n ExprSetProperty(pExpr, EP_FixedCol);\n assert( pExpr->pLeft==0 );\n pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);\n break;\n }\n return WRC_Prune;\n}", "project": "sqlite", "hash": 138100391746403533081790549455832608266, "size": 21, "commit_id": "39df24a3f02495e5ef6bb5ea8ce029a2c1e377e6", "message": "Do not allow the constant-propagation optimization to apple to ON/USING clause\nterms as it does not help and it might cause downstream problems.\n\nFossilOrigin-Name: 1bc783da63d58b05c690468b569cb2787846357b63c1100d11777666c5787bf4", "target": 0, "dataset": "other", "idx": 393392} {"func": "prepare_repo_download_targets(LrHandle *handle,\n LrYumRepo *repo,\n LrYumRepoMd *repomd,\n LrMetadataTarget *mdtarget,\n GSList **targets,\n GSList **cbdata_list,\n GError **err)\n{\n char *destdir; /* Destination dir */\n\n destdir = handle->destdir;\n assert(destdir);\n assert(strlen(destdir));\n assert(!err || *err == NULL);\n\n if(handle->cachedir) {\n lr_yum_switch_to_zchunk(handle, repomd);\n repo->use_zchunk = TRUE;\n } else {\n g_debug(\"%s: Cache directory not set, disabling zchunk\", __func__);\n repo->use_zchunk = FALSE;\n }\n\n for (GSList *elem = repomd->records; elem; elem = g_slist_next(elem)) {\n int fd;\n char *path;\n LrDownloadTarget *target;\n LrYumRepoMdRecord *record = elem->data;\n CbData *cbdata = NULL;\n void *user_cbdata = NULL;\n LrEndCb endcb = NULL;\n\n if (mdtarget != NULL) {\n user_cbdata = mdtarget->cbdata;\n endcb = mdtarget->endcb;\n }\n\n assert(record);\n\n if (!lr_yum_repomd_record_enabled(handle, record->type, repomd->records))\n continue;\n\n char *location_href = record->location_href;\n gboolean is_zchunk = FALSE;\n #ifdef WITH_ZCHUNK\n if (handle->cachedir && record->header_checksum)\n is_zchunk = TRUE;\n #endif /* WITH_ZCHUNK */\n\n GSList *checksums = NULL;\n if (is_zchunk) {\n #ifdef WITH_ZCHUNK\n if(!prepare_repo_download_zck_target(handle, record, &path, &fd,\n &checksums, targets, err))\n return FALSE;\n #endif /* WITH_ZCHUNK */\n } else {\n if(!prepare_repo_download_std_target(handle, record, &path, &fd,\n &checksums, targets, err))\n return FALSE;\n }\n\n if (handle->user_cb || handle->hmfcb) {\n cbdata = cbdata_new(handle->user_data,\n user_cbdata,\n handle->user_cb,\n handle->hmfcb,\n record->type);\n *cbdata_list = g_slist_append(*cbdata_list, cbdata);\n }\n\n target = lr_downloadtarget_new(handle,\n location_href,\n record->location_base,\n fd,\n NULL,\n checksums,\n 0,\n 0,\n NULL,\n cbdata,\n endcb,\n NULL,\n NULL,\n 0,\n 0,\n NULL,\n FALSE,\n is_zchunk);\n\n if(is_zchunk) {\n #ifdef WITH_ZCHUNK\n target->expectedsize = record->size_header;\n target->zck_header_size = record->size_header;\n #endif /* WITH_ZCHUNK */\n }\n\n if (mdtarget != NULL)\n mdtarget->repomd_records_to_download++;\n *targets = g_slist_append(*targets, target);\n\n /* Because path may already exists in repo (while update) */\n lr_yum_repo_update(repo, record->type, path);\n lr_free(path);\n }\n\n return TRUE;\n}", "project": "librepo", "hash": 130004621016105399242097539963842119282, "size": 108, "commit_id": "7daea2a2429a54dad68b1de9b37a5f65c5cf2600", "message": "Validate path read from repomd.xml (RhBug:1868639)\n\n= changelog =\nmsg: Validate path read from repomd.xml\ntype: security\nresolves: https://bugzilla.redhat.com/show_bug.cgi?id=1868639", "target": 1, "dataset": "other", "idx": 207158} {"func": "prepare_repo_download_targets(LrHandle *handle,\n LrYumRepo *repo,\n LrYumRepoMd *repomd,\n LrMetadataTarget *mdtarget,\n GSList **targets,\n GSList **cbdata_list,\n GError **err)\n{\n char *destdir; /* Destination dir */\n\n destdir = handle->destdir;\n assert(destdir);\n assert(strlen(destdir));\n assert(!err || *err == NULL);\n\n if(handle->cachedir) {\n lr_yum_switch_to_zchunk(handle, repomd);\n repo->use_zchunk = TRUE;\n } else {\n g_debug(\"%s: Cache directory not set, disabling zchunk\", __func__);\n repo->use_zchunk = FALSE;\n }\n\n for (GSList *elem = repomd->records; elem; elem = g_slist_next(elem)) {\n int fd;\n char *path;\n LrDownloadTarget *target;\n LrYumRepoMdRecord *record = elem->data;\n CbData *cbdata = NULL;\n void *user_cbdata = NULL;\n LrEndCb endcb = NULL;\n\n if (mdtarget != NULL) {\n user_cbdata = mdtarget->cbdata;\n endcb = mdtarget->endcb;\n }\n\n assert(record);\n\n if (!lr_yum_repomd_record_enabled(handle, record->type, repomd->records))\n continue;\n\n char *location_href = record->location_href;\n\n char *dest_dir = realpath(handle->destdir, NULL);\n path = lr_pathconcat(handle->destdir, record->location_href, NULL);\n char *requested_dir = realpath(dirname(path), NULL);\n lr_free(path);\n if (!g_str_has_prefix(requested_dir, dest_dir)) {\n g_debug(\"%s: Invalid path: %s\", __func__, location_href);\n g_set_error(err, LR_YUM_ERROR, LRE_IO, \"Invalid path: %s\", location_href);\n g_slist_free_full(*targets, (GDestroyNotify) lr_downloadtarget_free);\n free(requested_dir);\n free(dest_dir);\n return FALSE;\n }\n free(requested_dir);\n free(dest_dir);\n\n gboolean is_zchunk = FALSE;\n #ifdef WITH_ZCHUNK\n if (handle->cachedir && record->header_checksum)\n is_zchunk = TRUE;\n #endif /* WITH_ZCHUNK */\n\n GSList *checksums = NULL;\n if (is_zchunk) {\n #ifdef WITH_ZCHUNK\n if(!prepare_repo_download_zck_target(handle, record, &path, &fd,\n &checksums, targets, err))\n return FALSE;\n #endif /* WITH_ZCHUNK */\n } else {\n if(!prepare_repo_download_std_target(handle, record, &path, &fd,\n &checksums, targets, err))\n return FALSE;\n }\n\n if (handle->user_cb || handle->hmfcb) {\n cbdata = cbdata_new(handle->user_data,\n user_cbdata,\n handle->user_cb,\n handle->hmfcb,\n record->type);\n *cbdata_list = g_slist_append(*cbdata_list, cbdata);\n }\n\n target = lr_downloadtarget_new(handle,\n location_href,\n record->location_base,\n fd,\n NULL,\n checksums,\n 0,\n 0,\n NULL,\n cbdata,\n endcb,\n NULL,\n NULL,\n 0,\n 0,\n NULL,\n FALSE,\n is_zchunk);\n\n if(is_zchunk) {\n #ifdef WITH_ZCHUNK\n target->expectedsize = record->size_header;\n target->zck_header_size = record->size_header;\n #endif /* WITH_ZCHUNK */\n }\n\n if (mdtarget != NULL)\n mdtarget->repomd_records_to_download++;\n *targets = g_slist_append(*targets, target);\n\n /* Because path may already exists in repo (while update) */\n lr_yum_repo_update(repo, record->type, path);\n lr_free(path);\n }\n\n return TRUE;\n}", "project": "librepo", "hash": 107802422713710840025599174526096987290, "size": 124, "commit_id": "7daea2a2429a54dad68b1de9b37a5f65c5cf2600", "message": "Validate path read from repomd.xml (RhBug:1868639)\n\n= changelog =\nmsg: Validate path read from repomd.xml\ntype: security\nresolves: https://bugzilla.redhat.com/show_bug.cgi?id=1868639", "target": 0, "dataset": "other", "idx": 393607} {"func": "static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)\n{\n\tjpc_siz_t *siz = &ms->parms.siz;\n\tint compno;\n\tint tileno;\n\tjpc_dec_tile_t *tile;\n\tjpc_dec_tcomp_t *tcomp;\n\tint htileno;\n\tint vtileno;\n\tjpc_dec_cmpt_t *cmpt;\n\tsize_t size;\n\tsize_t num_samples;\n\tsize_t num_samples_delta;\n\n\tsize_t tile_samples;\n\tif (!jas_safe_size_mul(siz->tilewidth, siz->tileheight, &tile_samples) ||\n\t (dec->max_samples > 0 && tile_samples > dec->max_samples)) {\n\t\tjas_eprintf(\"tile too large\\n\");\n\t\treturn -1;\n\t}\n\n\tdec->xstart = siz->xoff;\n\tdec->ystart = siz->yoff;\n\tdec->xend = siz->width;\n\tdec->yend = siz->height;\n\tdec->tilewidth = siz->tilewidth;\n\tdec->tileheight = siz->tileheight;\n\tdec->tilexoff = siz->tilexoff;\n\tdec->tileyoff = siz->tileyoff;\n\tdec->numcomps = siz->numcomps;\n\n\tif (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {\n\t\treturn -1;\n\t}\n\n\tif (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {\n\t\treturn -1;\n\t}\n\n\tnum_samples = 0;\n\tfor (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,\n\t ++cmpt) {\n\t\tcmpt->prec = siz->comps[compno].prec;\n\t\tcmpt->sgnd = siz->comps[compno].sgnd;\n\t\tcmpt->hstep = siz->comps[compno].hsamp;\n\t\tcmpt->vstep = siz->comps[compno].vsamp;\n\t\tcmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -\n\t\t JPC_CEILDIV(dec->xstart, cmpt->hstep);\n\t\tcmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -\n\t\t JPC_CEILDIV(dec->ystart, cmpt->vstep);\n\t\tcmpt->hsubstep = 0;\n\t\tcmpt->vsubstep = 0;\n\n\t\tif (!jas_safe_size_mul(cmpt->width, cmpt->height, &num_samples_delta)) {\n\t\t\tjas_eprintf(\"image too large\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tif (!jas_safe_size_add(num_samples, num_samples_delta, &num_samples)) {\n\t\t\tjas_eprintf(\"image too large\\n\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (dec->max_samples > 0 && num_samples > dec->max_samples) {\n\t\tjas_eprintf(\"maximum number of samples exceeded (%zu > %zu)\\n\",\n\t\t num_samples, dec->max_samples);\n\t\treturn -1;\n\t}\n\n\tdec->image = 0;\n\n\tdec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);\n\tdec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);\n\tassert(dec->numhtiles >= 0);\n\tassert(dec->numvtiles >= 0);\n\tif (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size) ||\n\t size > INT_MAX) {\n\t\treturn -1;\n\t}\n\tif (dec->max_samples > 0 && size > dec->max_samples / 16 / 16) {\n\t\t/* avoid Denial of Service by a malicious input file\n\t\t with millions of tiny tiles; if max_samples is\n\t\t configured, then assume the tiles are at least\n\t\t 16x16, and don't allow more than this number of\n\t\t tiles */\n\t\treturn -1;\n\t}\n\tif (dec->max_samples > 0 && size > dec->max_samples / dec->numcomps / 16) {\n\t\t/* another DoS check: since each tile allocates an\n\t\t array of components, this check attempts to catch\n\t\t excessive tile*component numbers */\n\t\treturn -1;\n\t}\n\tdec->numtiles = size;\n\tJAS_DBGLOG(10, (\"numtiles = %d; numhtiles = %d; numvtiles = %d;\\n\",\n\t dec->numtiles, dec->numhtiles, dec->numvtiles));\n\tif (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {\n\t\treturn -1;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\t/* initialize all tiles with JPC_TILE_DONE so\n\t\t jpc_dec_destroy() knows which ones need a\n\t\t jpc_dec_tilefini() call; they are not actually\n\t\t \"done\", of course */\n\t\ttile->state = JPC_TILE_DONE;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\thtileno = tileno % dec->numhtiles;\n\t\tvtileno = tileno / dec->numhtiles;\n\t\ttile->realmode = 0;\n\t\ttile->state = JPC_TILE_INIT;\n\t\ttile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,\n\t\t dec->xstart);\n\t\ttile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,\n\t\t dec->ystart);\n\t\ttile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *\n\t\t dec->tilewidth, dec->xend);\n\t\ttile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *\n\t\t dec->tileheight, dec->yend);\n\t\ttile->numparts = 0;\n\t\ttile->partno = 0;\n\t\ttile->pkthdrstream = 0;\n\t\ttile->pkthdrstreampos = 0;\n\t\ttile->pptstab = 0;\n\t\ttile->cp = 0;\n\t\ttile->pi = 0;\n\t\tif (!(tile->tcomps = jas_alloc2(dec->numcomps,\n\t\t sizeof(jpc_dec_tcomp_t)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tfor (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;\n\t\t compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {\n\t\t\ttcomp->rlvls = 0;\n\t\t\ttcomp->numrlvls = 0;\n\t\t\ttcomp->data = 0;\n\t\t\ttcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);\n\t\t\ttcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);\n\t\t\ttcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);\n\t\t\ttcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);\n\t\t\ttcomp->tsfb = 0;\n\t\t}\n\t}\n\n\tdec->pkthdrstreams = 0;\n\n\t/* We should expect to encounter other main header marker segments\n\t or an SOT marker segment next. */\n\tdec->state = JPC_MH;\n\n\treturn 0;\n}", "project": "jasper", "hash": 20009022757512388200600144044584043479, "size": 155, "commit_id": "1b1c591306817e46e1e6a3300f714992b32f972b", "message": "jpc_dec: fix another integer overflow in SIZ\n\nValidate the width and height values first, before doing anything\nelse. This prevents integer overflows in the `numhtiles` /\n`numvtiles` calculation below, triggering assertion failures.\n\nFixes CVE-2017-13750\n\nCloses https://github.com/mdadams/jasper/issues/165\nCloses https://github.com/mdadams/jasper/issues/174", "target": 1, "dataset": "other", "idx": 207163} {"func": "static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)\n{\n\tjpc_siz_t *siz = &ms->parms.siz;\n\tint compno;\n\tint tileno;\n\tjpc_dec_tile_t *tile;\n\tjpc_dec_tcomp_t *tcomp;\n\tint htileno;\n\tint vtileno;\n\tjpc_dec_cmpt_t *cmpt;\n\tsize_t size;\n\tsize_t num_samples;\n\tsize_t num_samples_delta;\n\n\tsize_t total_samples;\n\tif (!jas_safe_size_mul(siz->width, siz->height, &total_samples) ||\n\t (dec->max_samples > 0 && total_samples > dec->max_samples)) {\n\t\tjas_eprintf(\"image too large\\n\");\n\t\treturn -1;\n\t}\n\n\tsize_t tile_samples;\n\tif (!jas_safe_size_mul(siz->tilewidth, siz->tileheight, &tile_samples) ||\n\t (dec->max_samples > 0 && tile_samples > dec->max_samples)) {\n\t\tjas_eprintf(\"tile too large\\n\");\n\t\treturn -1;\n\t}\n\n\tdec->xstart = siz->xoff;\n\tdec->ystart = siz->yoff;\n\tdec->xend = siz->width;\n\tdec->yend = siz->height;\n\tdec->tilewidth = siz->tilewidth;\n\tdec->tileheight = siz->tileheight;\n\tdec->tilexoff = siz->tilexoff;\n\tdec->tileyoff = siz->tileyoff;\n\tdec->numcomps = siz->numcomps;\n\n\tif (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {\n\t\treturn -1;\n\t}\n\n\tif (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {\n\t\treturn -1;\n\t}\n\n\tnum_samples = 0;\n\tfor (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,\n\t ++cmpt) {\n\t\tcmpt->prec = siz->comps[compno].prec;\n\t\tcmpt->sgnd = siz->comps[compno].sgnd;\n\t\tcmpt->hstep = siz->comps[compno].hsamp;\n\t\tcmpt->vstep = siz->comps[compno].vsamp;\n\t\tcmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -\n\t\t JPC_CEILDIV(dec->xstart, cmpt->hstep);\n\t\tcmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -\n\t\t JPC_CEILDIV(dec->ystart, cmpt->vstep);\n\t\tcmpt->hsubstep = 0;\n\t\tcmpt->vsubstep = 0;\n\n\t\tif (!jas_safe_size_mul(cmpt->width, cmpt->height, &num_samples_delta)) {\n\t\t\tjas_eprintf(\"image too large\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tif (!jas_safe_size_add(num_samples, num_samples_delta, &num_samples)) {\n\t\t\tjas_eprintf(\"image too large\\n\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (dec->max_samples > 0 && num_samples > dec->max_samples) {\n\t\tjas_eprintf(\"maximum number of samples exceeded (%zu > %zu)\\n\",\n\t\t num_samples, dec->max_samples);\n\t\treturn -1;\n\t}\n\n\tdec->image = 0;\n\n\tdec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);\n\tdec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);\n\tassert(dec->numhtiles >= 0);\n\tassert(dec->numvtiles >= 0);\n\tif (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size) ||\n\t size > INT_MAX) {\n\t\treturn -1;\n\t}\n\tif (dec->max_samples > 0 && size > dec->max_samples / 16 / 16) {\n\t\t/* avoid Denial of Service by a malicious input file\n\t\t with millions of tiny tiles; if max_samples is\n\t\t configured, then assume the tiles are at least\n\t\t 16x16, and don't allow more than this number of\n\t\t tiles */\n\t\treturn -1;\n\t}\n\tif (dec->max_samples > 0 && size > dec->max_samples / dec->numcomps / 16) {\n\t\t/* another DoS check: since each tile allocates an\n\t\t array of components, this check attempts to catch\n\t\t excessive tile*component numbers */\n\t\treturn -1;\n\t}\n\tdec->numtiles = size;\n\tJAS_DBGLOG(10, (\"numtiles = %d; numhtiles = %d; numvtiles = %d;\\n\",\n\t dec->numtiles, dec->numhtiles, dec->numvtiles));\n\tif (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {\n\t\treturn -1;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\t/* initialize all tiles with JPC_TILE_DONE so\n\t\t jpc_dec_destroy() knows which ones need a\n\t\t jpc_dec_tilefini() call; they are not actually\n\t\t \"done\", of course */\n\t\ttile->state = JPC_TILE_DONE;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\thtileno = tileno % dec->numhtiles;\n\t\tvtileno = tileno / dec->numhtiles;\n\t\ttile->realmode = 0;\n\t\ttile->state = JPC_TILE_INIT;\n\t\ttile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,\n\t\t dec->xstart);\n\t\ttile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,\n\t\t dec->ystart);\n\t\ttile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *\n\t\t dec->tilewidth, dec->xend);\n\t\ttile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *\n\t\t dec->tileheight, dec->yend);\n\t\ttile->numparts = 0;\n\t\ttile->partno = 0;\n\t\ttile->pkthdrstream = 0;\n\t\ttile->pkthdrstreampos = 0;\n\t\ttile->pptstab = 0;\n\t\ttile->cp = 0;\n\t\ttile->pi = 0;\n\t\tif (!(tile->tcomps = jas_alloc2(dec->numcomps,\n\t\t sizeof(jpc_dec_tcomp_t)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tfor (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;\n\t\t compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {\n\t\t\ttcomp->rlvls = 0;\n\t\t\ttcomp->numrlvls = 0;\n\t\t\ttcomp->data = 0;\n\t\t\ttcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);\n\t\t\ttcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);\n\t\t\ttcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);\n\t\t\ttcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);\n\t\t\ttcomp->tsfb = 0;\n\t\t}\n\t}\n\n\tdec->pkthdrstreams = 0;\n\n\t/* We should expect to encounter other main header marker segments\n\t or an SOT marker segment next. */\n\tdec->state = JPC_MH;\n\n\treturn 0;\n}", "project": "jasper", "hash": 131934528969260506628731666992318104628, "size": 162, "commit_id": "1b1c591306817e46e1e6a3300f714992b32f972b", "message": "jpc_dec: fix another integer overflow in SIZ\n\nValidate the width and height values first, before doing anything\nelse. This prevents integer overflows in the `numhtiles` /\n`numvtiles` calculation below, triggering assertion failures.\n\nFixes CVE-2017-13750\n\nCloses https://github.com/mdadams/jasper/issues/165\nCloses https://github.com/mdadams/jasper/issues/174", "target": 0, "dataset": "other", "idx": 393685} {"func": "void LibRaw::parseSonySRF(unsigned len)\n{\n\n if ((len > 0xfffff) || (len == 0))\n return;\n\n INT64 save = ftell(ifp);\n INT64 offset =\n 0x0310c0 - save; /* for non-DNG this value normally is 0x8ddc */\n if (len < offset || offset < 0)\n return;\n INT64 decrypt_len = offset >> 2; /* master key offset value is the next\n un-encrypted metadata field after SRF0 */\n\n unsigned i, nWB;\n unsigned MasterKey, SRF2Key, RawDataKey;\n INT64 srf_offset, tag_offset, tag_data, tag_dataoffset;\n int tag_dataunitlen;\n uchar *srf_buf;\n short entries;\n unsigned tag_id, tag_type, tag_datalen;\n\n srf_buf = (uchar *)malloc(len);\n fread(srf_buf, len, 1, ifp);\n\n offset += srf_buf[offset] << 2;\n\n#define CHECKBUFFER_SGET4(offset) \\\n do \\\n { \\\n if ((((offset) + 4) > len) || ((offset) < 0)) \\\n goto restore_after_parseSonySRF; \\\n } while (0)\n\n#define CHECKBUFFER_SGET2(offset) \\\n do \\\n { \\\n if ( ((offset + 2) > len) || ((offset) < 0)) \\\n goto restore_after_parseSonySRF; \\\n } while (0)\n\n CHECKBUFFER_SGET4(offset);\n\n /* master key is stored in big endian */\n MasterKey = ((unsigned)srf_buf[offset] << 24) |\n ((unsigned)srf_buf[offset + 1] << 16) |\n ((unsigned)srf_buf[offset + 2] << 8) |\n (unsigned)srf_buf[offset + 3];\n\n /* skip SRF0 */\n srf_offset = 0;\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n CHECKBUFFER_SGET4(offset);\n CHECKBUFFER_SGET4(offset + 12 * entries);\n srf_offset = sget4(srf_buf + offset + 12 * entries) -\n save; /* SRF0 ends with SRF1 abs. position */\n\n /* get SRF1, it has fixed 40 bytes length and contains keys to decode metadata\n * and raw data */\n if (srf_offset < 0 || decrypt_len < srf_offset / 4)\n goto restore_after_parseSonySRF;\n sony_decrypt((unsigned *)(srf_buf + srf_offset), decrypt_len - srf_offset / 4,\n 1, MasterKey);\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n tag_offset = offset;\n\n while (entries--) {\n if (tiff_sget (save, srf_buf, len,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if (tag_id == 0x0000) {\n SRF2Key = sget4(srf_buf + tag_dataoffset);\n } else if (tag_id == 0x0001) {\n RawDataKey = sget4(srf_buf + tag_dataoffset);\n }\n } else goto restore_after_parseSonySRF;\n }\n offset = tag_offset;\n\n /* get SRF2 */\n CHECKBUFFER_SGET4(offset);\n srf_offset =\n sget4(srf_buf + offset) - save; /* SRFn ends with SRFn+1 position */\n if (srf_offset < 0 || decrypt_len < srf_offset / 4)\n goto restore_after_parseSonySRF;\n sony_decrypt((unsigned *)(srf_buf + srf_offset), decrypt_len - srf_offset / 4,\n 1, SRF2Key);\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n tag_offset = offset;\n\n while (entries--) {\n if (tiff_sget (save, srf_buf, len,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if ((tag_id >= 0x00c0) && (tag_id <= 0x00ce)) {\n i = (tag_id - 0x00c0) % 3;\n nWB = (tag_id - 0x00c0) / 3;\n icWBC[Sony_SRF_wb_list[nWB]][i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n icWBC[Sony_SRF_wb_list[nWB]][3] =\n icWBC[Sony_SRF_wb_list[nWB]][i];\n }\n } else if ((tag_id >= 0x00d0) && (tag_id <= 0x00d2)) {\n i = (tag_id - 0x00d0) % 3;\n cam_mul[i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n cam_mul[3] = cam_mul[i];\n }\n } else switch (tag_id) {\n /*\n 0x0002 SRF6Offset\n 0x0003 SRFDataOffset (?)\n 0x0004 RawDataOffset\n 0x0005 RawDataLength\n */\n case 0x0043:\n ilm.MaxAp4MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0044:\n ilm.MaxAp4MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0045:\n ilm.MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0046:\n ilm.MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n }\n } else goto restore_after_parseSonySRF;\n }\n offset = tag_offset;\n\nrestore_after_parseSonySRF:\n free(srf_buf);\n fseek(ifp, save, SEEK_SET);\n#undef CHECKBUFFER_SGET4\n#undef CHECKBUFFER_SGET2\n}", "project": "LibRaw", "hash": 133935611544622211790149768901407187953, "size": 150, "commit_id": "c243f4539233053466c1309bde606815351bee81", "message": "additional checks in parseSonySRF\n\nparseSonySR2: buffer size check", "target": 1, "dataset": "other", "idx": 207218} {"func": "void LibRaw::parseSonySRF(unsigned len)\n{\n\n if ((len > 0xfffff) || (len == 0))\n return;\n\n INT64 save = ftell(ifp);\n INT64 offset =\n 0x0310c0 - save; /* for non-DNG this value normally is 0x8ddc */\n if (len < offset || offset < 0)\n return;\n INT64 decrypt_len = offset >> 2; /* master key offset value is the next\n un-encrypted metadata field after SRF0 */\n\n unsigned i, nWB;\n unsigned MasterKey, SRF2Key, RawDataKey;\n INT64 srf_offset, tag_offset, tag_data, tag_dataoffset;\n int tag_dataunitlen;\n uchar *srf_buf;\n ushort entries;\n unsigned tag_id, tag_type, tag_datalen;\n\n srf_buf = (uchar *)malloc(len+64);\n fread(srf_buf, len, 1, ifp);\n\n offset += srf_buf[offset] << 2;\n\n#define CHECKBUFFER_SGET4(offset) \\\n do \\\n { \\\n if ((((offset) + 4) > len) || ((offset) < 0)) \\\n goto restore_after_parseSonySRF; \\\n } while (0)\n\n#define CHECKBUFFER_SGET2(offset) \\\n do \\\n { \\\n if ( ((offset + 2) > len) || ((offset) < 0)) \\\n goto restore_after_parseSonySRF; \\\n } while (0)\n\n CHECKBUFFER_SGET4(offset);\n\n /* master key is stored in big endian */\n MasterKey = ((unsigned)srf_buf[offset] << 24) |\n ((unsigned)srf_buf[offset + 1] << 16) |\n ((unsigned)srf_buf[offset + 2] << 8) |\n (unsigned)srf_buf[offset + 3];\n\n /* skip SRF0 */\n srf_offset = 0;\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n CHECKBUFFER_SGET4(offset);\n CHECKBUFFER_SGET4(offset + 12 * entries);\n srf_offset = sget4(srf_buf + offset + 12 * entries) -\n save; /* SRF0 ends with SRF1 abs. position */\n\n /* get SRF1, it has fixed 40 bytes length and contains keys to decode metadata\n * and raw data */\n if (srf_offset < 0 || decrypt_len < srf_offset / 4)\n goto restore_after_parseSonySRF;\n sony_decrypt((unsigned *)(srf_buf + srf_offset), decrypt_len - srf_offset / 4,\n 1, MasterKey);\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n tag_offset = offset;\n\n while (entries--) {\n if (tiff_sget (save, srf_buf, len,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if (tag_id == 0x0000) {\n\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n\t\t SRF2Key = sget4(srf_buf + tag_dataoffset);\n } else if (tag_id == 0x0001) {\n\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n\t\t RawDataKey = sget4(srf_buf + tag_dataoffset);\n }\n } else goto restore_after_parseSonySRF;\n }\n offset = tag_offset;\n\n /* get SRF2 */\n CHECKBUFFER_SGET4(offset);\n srf_offset =\n sget4(srf_buf + offset) - save; /* SRFn ends with SRFn+1 position */\n if (srf_offset < 0 || decrypt_len < srf_offset / 4)\n goto restore_after_parseSonySRF;\n sony_decrypt((unsigned *)(srf_buf + srf_offset), decrypt_len - srf_offset / 4,\n 1, SRF2Key);\n CHECKBUFFER_SGET2(srf_offset);\n entries = sget2(srf_buf + srf_offset);\n if (entries > 1000)\n goto restore_after_parseSonySRF;\n offset = srf_offset + 2;\n tag_offset = offset;\n\n while (entries--) {\n\t if (tiff_sget(save, srf_buf, len,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if ((tag_id >= 0x00c0) && (tag_id <= 0x00ce)) {\n i = (tag_id - 0x00c0) % 3;\n nWB = (tag_id - 0x00c0) / 3;\n\t\tCHECKBUFFER_SGET4(tag_dataoffset);\n\t\ticWBC[Sony_SRF_wb_list[nWB]][i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n icWBC[Sony_SRF_wb_list[nWB]][3] =\n icWBC[Sony_SRF_wb_list[nWB]][i];\n }\n } else if ((tag_id >= 0x00d0) && (tag_id <= 0x00d2)) {\n i = (tag_id - 0x00d0) % 3;\n\t\tCHECKBUFFER_SGET4(tag_dataoffset);\n\t\tcam_mul[i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n cam_mul[3] = cam_mul[i];\n }\n } else switch (tag_id) {\n /*\n 0x0002 SRF6Offset\n 0x0003 SRFDataOffset (?)\n 0x0004 RawDataOffset\n 0x0005 RawDataLength\n */\n case 0x0043:\n\t\t CHECKBUFFER_SGET4(tag_dataoffset); // need to add extra space\n\t\t ilm.MaxAp4MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0044:\n\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n\t\t ilm.MaxAp4MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0045:\n\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n\t\t ilm.MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0046:\n\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n\t\t ilm.MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n }\n } else goto restore_after_parseSonySRF;\n }\n offset = tag_offset;\n\nrestore_after_parseSonySRF:\n free(srf_buf);\n fseek(ifp, save, SEEK_SET);\n#undef CHECKBUFFER_SGET4\n#undef CHECKBUFFER_SGET2\n}", "project": "LibRaw", "hash": 211422748523486439603542502209147525104, "size": 158, "commit_id": "c243f4539233053466c1309bde606815351bee81", "message": "additional checks in parseSonySRF\n\nparseSonySR2: buffer size check", "target": 0, "dataset": "other", "idx": 394100} {"func": "ctnetlink_parse_tuple_filter(const struct nlattr * const cda[],\n\t\t\t struct nf_conntrack_tuple *tuple, u32 type,\n\t\t\t u_int8_t l3num, struct nf_conntrack_zone *zone,\n\t\t\t u_int32_t flags)\n{\n\tstruct nlattr *tb[CTA_TUPLE_MAX+1];\n\tint err;\n\n\tmemset(tuple, 0, sizeof(*tuple));\n\n\terr = nla_parse_nested_deprecated(tb, CTA_TUPLE_MAX, cda[type],\n\t\t\t\t\t tuple_nla_policy, NULL);\n\tif (err < 0)\n\t\treturn err;\n\n\n\ttuple->src.l3num = l3num;\n\n\tif (flags & CTA_FILTER_FLAG(CTA_IP_DST) ||\n\t flags & CTA_FILTER_FLAG(CTA_IP_SRC)) {\n\t\tif (!tb[CTA_TUPLE_IP])\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_ip(tb[CTA_TUPLE_IP], tuple, flags);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tif (flags & CTA_FILTER_FLAG(CTA_PROTO_NUM)) {\n\t\tif (!tb[CTA_TUPLE_PROTO])\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_proto(tb[CTA_TUPLE_PROTO], tuple, flags);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t} else if (flags & CTA_FILTER_FLAG(ALL_CTA_PROTO)) {\n\t\t/* Can't manage proto flags without a protonum */\n\t\treturn -EINVAL;\n\t}\n\n\tif ((flags & CTA_FILTER_FLAG(CTA_TUPLE_ZONE)) && tb[CTA_TUPLE_ZONE]) {\n\t\tif (!zone)\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_zone(tb[CTA_TUPLE_ZONE],\n\t\t\t\t\t\t type, zone);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\t/* orig and expect tuples get DIR_ORIGINAL */\n\tif (type == CTA_TUPLE_REPLY)\n\t\ttuple->dst.dir = IP_CT_DIR_REPLY;\n\telse\n\t\ttuple->dst.dir = IP_CT_DIR_ORIGINAL;\n\n\treturn 0;\n}", "project": "linux", "hash": 305449011109180351247584082573465785790, "size": 58, "commit_id": "1cc5ef91d2ff94d2bf2de3b3585423e8a1051cb6", "message": "netfilter: ctnetlink: add a range check for l3/l4 protonum\n\nThe indexes to the nf_nat_l[34]protos arrays come from userspace. So\ncheck the tuple's family, e.g. l3num, when creating the conntrack in\norder to prevent an OOB memory access during setup. Here is an example\nkernel panic on 4.14.180 when userspace passes in an index greater than\nNFPROTO_NUMPROTO.\n\nInternal error: Oops - BUG: 0 [#1] PREEMPT SMP\nModules linked in:...\nProcess poc (pid: 5614, stack limit = 0x00000000a3933121)\nCPU: 4 PID: 5614 Comm: poc Tainted: G S W O 4.14.180-g051355490483\nHardware name: Qualcomm Technologies, Inc. SM8150 V2 PM8150 Google Inc. MSM\ntask: 000000002a3dfffe task.stack: 00000000a3933121\npc : __cfi_check_fail+0x1c/0x24\nlr : __cfi_check_fail+0x1c/0x24\n...\nCall trace:\n__cfi_check_fail+0x1c/0x24\nname_to_dev_t+0x0/0x468\nnfnetlink_parse_nat_setup+0x234/0x258\nctnetlink_parse_nat_setup+0x4c/0x228\nctnetlink_new_conntrack+0x590/0xc40\nnfnetlink_rcv_msg+0x31c/0x4d4\nnetlink_rcv_skb+0x100/0x184\nnfnetlink_rcv+0xf4/0x180\nnetlink_unicast+0x360/0x770\nnetlink_sendmsg+0x5a0/0x6a4\n___sys_sendmsg+0x314/0x46c\nSyS_sendmsg+0xb4/0x108\nel0_svc_naked+0x34/0x38\n\nThis crash is not happening since 5.4+, however, ctnetlink still\nallows for creating entries with unsupported layer 3 protocol number.\n\nFixes: c1d10adb4a521 (\"[NETFILTER]: Add ctnetlink port for nf_conntrack\")\nSigned-off-by: Will McVicker \n[pablo@netfilter.org: rebased original patch on top of nf.git]\nSigned-off-by: Pablo Neira Ayuso ", "target": 1, "dataset": "other", "idx": 207223} {"func": "ctnetlink_parse_tuple_filter(const struct nlattr * const cda[],\n\t\t\t struct nf_conntrack_tuple *tuple, u32 type,\n\t\t\t u_int8_t l3num, struct nf_conntrack_zone *zone,\n\t\t\t u_int32_t flags)\n{\n\tstruct nlattr *tb[CTA_TUPLE_MAX+1];\n\tint err;\n\n\tmemset(tuple, 0, sizeof(*tuple));\n\n\terr = nla_parse_nested_deprecated(tb, CTA_TUPLE_MAX, cda[type],\n\t\t\t\t\t tuple_nla_policy, NULL);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (l3num != NFPROTO_IPV4 && l3num != NFPROTO_IPV6)\n\t\treturn -EOPNOTSUPP;\n\ttuple->src.l3num = l3num;\n\n\tif (flags & CTA_FILTER_FLAG(CTA_IP_DST) ||\n\t flags & CTA_FILTER_FLAG(CTA_IP_SRC)) {\n\t\tif (!tb[CTA_TUPLE_IP])\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_ip(tb[CTA_TUPLE_IP], tuple, flags);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\tif (flags & CTA_FILTER_FLAG(CTA_PROTO_NUM)) {\n\t\tif (!tb[CTA_TUPLE_PROTO])\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_proto(tb[CTA_TUPLE_PROTO], tuple, flags);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t} else if (flags & CTA_FILTER_FLAG(ALL_CTA_PROTO)) {\n\t\t/* Can't manage proto flags without a protonum */\n\t\treturn -EINVAL;\n\t}\n\n\tif ((flags & CTA_FILTER_FLAG(CTA_TUPLE_ZONE)) && tb[CTA_TUPLE_ZONE]) {\n\t\tif (!zone)\n\t\t\treturn -EINVAL;\n\n\t\terr = ctnetlink_parse_tuple_zone(tb[CTA_TUPLE_ZONE],\n\t\t\t\t\t\t type, zone);\n\t\tif (err < 0)\n\t\t\treturn err;\n\t}\n\n\t/* orig and expect tuples get DIR_ORIGINAL */\n\tif (type == CTA_TUPLE_REPLY)\n\t\ttuple->dst.dir = IP_CT_DIR_REPLY;\n\telse\n\t\ttuple->dst.dir = IP_CT_DIR_ORIGINAL;\n\n\treturn 0;\n}", "project": "linux", "hash": 16152469972975795768075689172273398454, "size": 59, "commit_id": "1cc5ef91d2ff94d2bf2de3b3585423e8a1051cb6", "message": "netfilter: ctnetlink: add a range check for l3/l4 protonum\n\nThe indexes to the nf_nat_l[34]protos arrays come from userspace. So\ncheck the tuple's family, e.g. l3num, when creating the conntrack in\norder to prevent an OOB memory access during setup. Here is an example\nkernel panic on 4.14.180 when userspace passes in an index greater than\nNFPROTO_NUMPROTO.\n\nInternal error: Oops - BUG: 0 [#1] PREEMPT SMP\nModules linked in:...\nProcess poc (pid: 5614, stack limit = 0x00000000a3933121)\nCPU: 4 PID: 5614 Comm: poc Tainted: G S W O 4.14.180-g051355490483\nHardware name: Qualcomm Technologies, Inc. SM8150 V2 PM8150 Google Inc. MSM\ntask: 000000002a3dfffe task.stack: 00000000a3933121\npc : __cfi_check_fail+0x1c/0x24\nlr : __cfi_check_fail+0x1c/0x24\n...\nCall trace:\n__cfi_check_fail+0x1c/0x24\nname_to_dev_t+0x0/0x468\nnfnetlink_parse_nat_setup+0x234/0x258\nctnetlink_parse_nat_setup+0x4c/0x228\nctnetlink_new_conntrack+0x590/0xc40\nnfnetlink_rcv_msg+0x31c/0x4d4\nnetlink_rcv_skb+0x100/0x184\nnfnetlink_rcv+0xf4/0x180\nnetlink_unicast+0x360/0x770\nnetlink_sendmsg+0x5a0/0x6a4\n___sys_sendmsg+0x314/0x46c\nSyS_sendmsg+0xb4/0x108\nel0_svc_naked+0x34/0x38\n\nThis crash is not happening since 5.4+, however, ctnetlink still\nallows for creating entries with unsupported layer 3 protocol number.\n\nFixes: c1d10adb4a521 (\"[NETFILTER]: Add ctnetlink port for nf_conntrack\")\nSigned-off-by: Will McVicker \n[pablo@netfilter.org: rebased original patch on top of nf.git]\nSigned-off-by: Pablo Neira Ayuso ", "target": 0, "dataset": "other", "idx": 394260} {"func": "LJ_NOINLINE void lj_err_run(lua_State *L)\n{\n ptrdiff_t ef = finderrfunc(L);\n if (ef) {\n TValue *errfunc = restorestack(L, ef);\n TValue *top = L->top;\n lj_trace_abort(G(L));\n if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) {\n setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR));\n lj_err_throw(L, LUA_ERRERR);\n }\n L->status = LUA_ERRERR;\n copyTV(L, top, top-1);\n copyTV(L, top-1, errfunc);\n L->top = top+1;\n lj_vm_call(L, top, 1+1); /* Stack: |errfunc|msg| -> |msg| */\n }\n lj_err_throw(L, LUA_ERRRUN);\n}", "project": "LuaJIT", "hash": 295611232396518332386836316299494710511, "size": 19, "commit_id": "e296f56b825c688c3530a981dc6b495d972f3d01", "message": "Call error function on rethrow after trace exit.", "target": 1, "dataset": "other", "idx": 207262} {"func": "LJ_NOINLINE void LJ_FASTCALL lj_err_run(lua_State *L)\n{\n ptrdiff_t ef = finderrfunc(L);\n if (ef) {\n TValue *errfunc = restorestack(L, ef);\n TValue *top = L->top;\n lj_trace_abort(G(L));\n if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) {\n setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR));\n lj_err_throw(L, LUA_ERRERR);\n }\n L->status = LUA_ERRERR;\n copyTV(L, top, top-1);\n copyTV(L, top-1, errfunc);\n L->top = top+1;\n lj_vm_call(L, top, 1+1); /* Stack: |errfunc|msg| -> |msg| */\n }\n lj_err_throw(L, LUA_ERRRUN);\n}", "project": "LuaJIT", "hash": 38911403279138630648125077204690901074, "size": 19, "commit_id": "e296f56b825c688c3530a981dc6b495d972f3d01", "message": "Call error function on rethrow after trace exit.", "target": 0, "dataset": "other", "idx": 394651} {"func": "void LibRaw::parse_exif(int base)\n{\n unsigned entries, tag, type, len, save, c;\n double expo, ape;\n\n unsigned kodak = !strncmp(make, \"EASTMAN\", 7) && tiff_nifds < 3;\n\n entries = get2();\n if (!strncmp(make, \"Hasselblad\", 10) && (tiff_nifds > 3) && (entries > 512))\n return;\n INT64 fsize = ifp->size();\n while (entries--)\n {\n tiff_get(base, &tag, &type, &len, &save);\n\n INT64 savepos = ftell(ifp);\n if (len > 8 && savepos + len > fsize * 2)\n {\n fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!\n continue;\n }\n if (callbacks.exif_cb)\n {\n callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp,\n base);\n fseek(ifp, savepos, SEEK_SET);\n }\n\n switch (tag)\n {\n\tcase 0xA005: // Interoperability IFD\n\t\tfseek(ifp, get4() + base, SEEK_SET);\n\t\tparse_exif_interop(base);\n\t\tbreak;\n\tcase 0xA001: // ExifIFD.ColorSpace\n\t\tc = get2();\n\t\tif (c == 1 && imgdata.color.ExifColorSpace == LIBRAW_COLORSPACE_Unknown)\n\t\t\timgdata.color.ExifColorSpace = LIBRAW_COLORSPACE_sRGB;\n\t\telse if (c == 2)\n\t\t\timgdata.color.ExifColorSpace = LIBRAW_COLORSPACE_AdobeRGB;\n\t\tbreak;\n case 0x9400:\n imCommon.exifAmbientTemperature = getreal(type);\n if ((imCommon.CameraTemperature > -273.15f) &&\n ((OlyID == OlyID_TG_5) ||\n (OlyID == OlyID_TG_6))\n )\n imCommon.CameraTemperature += imCommon.exifAmbientTemperature;\n break;\n case 0x9401:\n imCommon.exifHumidity = getreal(type);\n break;\n case 0x9402:\n imCommon.exifPressure = getreal(type);\n break;\n case 0x9403:\n imCommon.exifWaterDepth = getreal(type);\n break;\n case 0x9404:\n imCommon.exifAcceleration = getreal(type);\n break;\n case 0x9405:\n imCommon.exifCameraElevationAngle = getreal(type);\n break;\n\n case 0xa405: // FocalLengthIn35mmFormat\n imgdata.lens.FocalLengthIn35mmFormat = get2();\n break;\n case 0xa431: // BodySerialNumber\n stmread(imgdata.shootinginfo.BodySerial, len, ifp);\n break;\n case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard\n imgdata.lens.MinFocal = getreal(type);\n imgdata.lens.MaxFocal = getreal(type);\n imgdata.lens.MaxAp4MinFocal = getreal(type);\n imgdata.lens.MaxAp4MaxFocal = getreal(type);\n break;\n case 0xa435: // LensSerialNumber\n stmread(imgdata.lens.LensSerial, len, ifp);\n if (!strncmp(imgdata.lens.LensSerial, \"----\", 4))\n imgdata.lens.LensSerial[0] = '\\0';\n break;\n case 0xa420: /* 42016, ImageUniqueID */\n stmread(imgdata.color.ImageUniqueID, len, ifp);\n break;\n case 0xc65d: /* 50781, RawDataUniqueID */\n imgdata.color.RawDataUniqueID[16] = 0;\n fread(imgdata.color.RawDataUniqueID, 1, 16, ifp);\n break;\n case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard\n imgdata.lens.dng.MinFocal = getreal(type);\n imgdata.lens.dng.MaxFocal = getreal(type);\n imgdata.lens.dng.MaxAp4MinFocal = getreal(type);\n imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);\n break;\n case 0xc68b: /* 50827, OriginalRawFileName */\n stmread(imgdata.color.OriginalRawFileName, len, ifp);\n break;\n case 0xa433: // LensMake\n stmread(imgdata.lens.LensMake, len, ifp);\n break;\n case 0xa434: // LensModel\n stmread(imgdata.lens.Lens, len, ifp);\n if (!strncmp(imgdata.lens.Lens, \"----\", 4))\n imgdata.lens.Lens[0] = '\\0';\n break;\n case 0x9205:\n imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f));\n break;\n case 0x829a: // 33434\n tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type);\n break;\n case 0x829d: // 33437, FNumber\n aperture = getreal(type);\n break;\n case 0x8827: // 34855\n iso_speed = get2();\n break;\n case 0x8831: // 34865\n if (iso_speed == 0xffff && !strncasecmp(make, \"FUJI\", 4))\n iso_speed = getreal(type);\n break;\n case 0x8832: // 34866\n if (iso_speed == 0xffff &&\n (!strncasecmp(make, \"SONY\", 4) || !strncasecmp(make, \"CANON\", 5)))\n iso_speed = getreal(type);\n break;\n case 0x9003: // 36867\n case 0x9004: // 36868\n get_timestamp(0);\n break;\n case 0x9201: // 37377\n if ((expo = -getreal(type)) < 128 && shutter == 0.)\n tiff_ifd[tiff_nifds - 1].t_shutter = shutter =\n libraw_powf64l(2.0, expo);\n break;\n case 0x9202: // 37378 ApertureValue\n if ((fabs(ape = getreal(type)) < 256.0) && (!aperture))\n aperture = libraw_powf64l(2.0, ape / 2);\n break;\n case 0x9209: // 37385\n flash_used = getreal(type);\n break;\n case 0x920a: // 37386\n focal_len = getreal(type);\n break;\n case 0x927c: // 37500\n if (((make[0] == '\\0') && !strncmp(model, \"ov5647\", 6)) ||\n (!strncmp(make, \"RaspberryPi\", 11) &&\n (!strncmp(model, \"RP_OV5647\", 9) ||\n !strncmp(model, \"RP_imx219\", 9))))\n {\n char mn_text[512];\n char *pos;\n char ccms[512];\n ushort l;\n float num;\n\n fgets(mn_text, MIN(len, 511), ifp);\n mn_text[511] = 0;\n\n pos = strstr(mn_text, \"gain_r=\");\n if (pos)\n cam_mul[0] = atof(pos + 7);\n pos = strstr(mn_text, \"gain_b=\");\n if (pos)\n cam_mul[2] = atof(pos + 7);\n if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f))\n cam_mul[1] = cam_mul[3] = 1.0f;\n else\n cam_mul[0] = cam_mul[2] = 0.0f;\n\n pos = strstr(mn_text, \"ccm=\");\n if (pos)\n {\n pos += 4;\n char *pos2 = strstr(pos, \" \");\n if (pos2)\n {\n l = pos2 - pos;\n memcpy(ccms, pos, l);\n ccms[l] = '\\0';\n#ifdef LIBRAW_WIN32_CALLS\n // Win32 strtok is already thread-safe\n pos = strtok(ccms, \",\");\n#else\n char *last = 0;\n pos = strtok_r(ccms, \",\", &last);\n#endif\n if (pos)\n {\n for (l = 0; l < 4; l++)\n {\n num = 0.0;\n for (c = 0; c < 3; c++)\n {\n imgdata.color.ccm[l][c] = (float)atoi(pos);\n num += imgdata.color.ccm[l][c];\n#ifdef LIBRAW_WIN32_CALLS\n pos = strtok(NULL, \",\");\n#else\n pos = strtok_r(NULL, \",\", &last);\n#endif\n if (!pos)\n goto end; // broken\n }\n if (num > 0.01)\n FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n }\n }\n }\n }\n end:;\n }\n else if (!strncmp(make, \"SONY\", 4) &&\n (!strncmp(model, \"DSC-V3\", 6) || !strncmp(model, \"DSC-F828\", 8)))\n {\n parseSonySRF(len);\n break;\n }\n else if ((len == 1) && !strncmp(make, \"NIKON\", 5))\n {\n c = get4();\n if (c)\n fseek(ifp, c, SEEK_SET);\n is_NikonTransfer = 1;\n }\n parse_makernote(base, 0);\n break;\n case 0xa002: // 40962\n if (kodak)\n raw_width = get4();\n break;\n case 0xa003: // 40963\n if (kodak)\n raw_height = get4();\n break;\n case 0xa302: // 41730\n if (get4() == 0x20002)\n for (exif_cfa = c = 0; c < 8; c += 2)\n exif_cfa |= fgetc(ifp) * 0x01010101U << c;\n }\n fseek(ifp, save, SEEK_SET);\n }\n}", "project": "LibRaw", "hash": 182171441535201305274163229980614035603, "size": 245, "commit_id": "55f0a0c08974b8b79ebfa7762b555a1704b25fb2", "message": "possible buffer underrun in exif parser", "target": 1, "dataset": "other", "idx": 207309} {"func": "void LibRaw::parse_exif(int base)\n{\n unsigned entries, tag, type, len, save, c;\n double expo, ape;\n\n unsigned kodak = !strncmp(make, \"EASTMAN\", 7) && tiff_nifds < 3;\n\n entries = get2();\n if (!strncmp(make, \"Hasselblad\", 10) && (tiff_nifds > 3) && (entries > 512))\n return;\n INT64 fsize = ifp->size();\n while (entries--)\n {\n tiff_get(base, &tag, &type, &len, &save);\n\n INT64 savepos = ftell(ifp);\n if (len > 8 && savepos + len > fsize * 2)\n {\n fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!\n continue;\n }\n if (callbacks.exif_cb)\n {\n callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp,\n base);\n fseek(ifp, savepos, SEEK_SET);\n }\n\n switch (tag)\n {\n\tcase 0xA005: // Interoperability IFD\n\t\tfseek(ifp, get4() + base, SEEK_SET);\n\t\tparse_exif_interop(base);\n\t\tbreak;\n\tcase 0xA001: // ExifIFD.ColorSpace\n\t\tc = get2();\n\t\tif (c == 1 && imgdata.color.ExifColorSpace == LIBRAW_COLORSPACE_Unknown)\n\t\t\timgdata.color.ExifColorSpace = LIBRAW_COLORSPACE_sRGB;\n\t\telse if (c == 2)\n\t\t\timgdata.color.ExifColorSpace = LIBRAW_COLORSPACE_AdobeRGB;\n\t\tbreak;\n case 0x9400:\n imCommon.exifAmbientTemperature = getreal(type);\n if ((imCommon.CameraTemperature > -273.15f) &&\n ((OlyID == OlyID_TG_5) ||\n (OlyID == OlyID_TG_6))\n )\n imCommon.CameraTemperature += imCommon.exifAmbientTemperature;\n break;\n case 0x9401:\n imCommon.exifHumidity = getreal(type);\n break;\n case 0x9402:\n imCommon.exifPressure = getreal(type);\n break;\n case 0x9403:\n imCommon.exifWaterDepth = getreal(type);\n break;\n case 0x9404:\n imCommon.exifAcceleration = getreal(type);\n break;\n case 0x9405:\n imCommon.exifCameraElevationAngle = getreal(type);\n break;\n\n case 0xa405: // FocalLengthIn35mmFormat\n imgdata.lens.FocalLengthIn35mmFormat = get2();\n break;\n case 0xa431: // BodySerialNumber\n stmread(imgdata.shootinginfo.BodySerial, len, ifp);\n break;\n case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard\n imgdata.lens.MinFocal = getreal(type);\n imgdata.lens.MaxFocal = getreal(type);\n imgdata.lens.MaxAp4MinFocal = getreal(type);\n imgdata.lens.MaxAp4MaxFocal = getreal(type);\n break;\n case 0xa435: // LensSerialNumber\n stmread(imgdata.lens.LensSerial, len, ifp);\n if (!strncmp(imgdata.lens.LensSerial, \"----\", 4))\n imgdata.lens.LensSerial[0] = '\\0';\n break;\n case 0xa420: /* 42016, ImageUniqueID */\n stmread(imgdata.color.ImageUniqueID, len, ifp);\n break;\n case 0xc65d: /* 50781, RawDataUniqueID */\n imgdata.color.RawDataUniqueID[16] = 0;\n fread(imgdata.color.RawDataUniqueID, 1, 16, ifp);\n break;\n case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard\n imgdata.lens.dng.MinFocal = getreal(type);\n imgdata.lens.dng.MaxFocal = getreal(type);\n imgdata.lens.dng.MaxAp4MinFocal = getreal(type);\n imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);\n break;\n case 0xc68b: /* 50827, OriginalRawFileName */\n stmread(imgdata.color.OriginalRawFileName, len, ifp);\n break;\n case 0xa433: // LensMake\n stmread(imgdata.lens.LensMake, len, ifp);\n break;\n case 0xa434: // LensModel\n stmread(imgdata.lens.Lens, len, ifp);\n if (!strncmp(imgdata.lens.Lens, \"----\", 4))\n imgdata.lens.Lens[0] = '\\0';\n break;\n case 0x9205:\n imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f));\n break;\n case 0x829a: // 33434\n shutter = getreal(type);\n if (tiff_nifds > 0 && tiff_nifds <= LIBRAW_IFD_MAXCOUNT)\n tiff_ifd[tiff_nifds - 1].t_shutter = shutter;\n break;\n case 0x829d: // 33437, FNumber\n aperture = getreal(type);\n break;\n case 0x8827: // 34855\n iso_speed = get2();\n break;\n case 0x8831: // 34865\n if (iso_speed == 0xffff && !strncasecmp(make, \"FUJI\", 4))\n iso_speed = getreal(type);\n break;\n case 0x8832: // 34866\n if (iso_speed == 0xffff &&\n (!strncasecmp(make, \"SONY\", 4) || !strncasecmp(make, \"CANON\", 5)))\n iso_speed = getreal(type);\n break;\n case 0x9003: // 36867\n case 0x9004: // 36868\n get_timestamp(0);\n break;\n case 0x9201: // 37377\n if ((expo = -getreal(type)) < 128 && shutter == 0.)\n {\n shutter = libraw_powf64l(2.0, expo);\n if (tiff_nifds > 0 && tiff_nifds <= LIBRAW_IFD_MAXCOUNT)\n tiff_ifd[tiff_nifds - 1].t_shutter = shutter;\n }\n break;\n case 0x9202: // 37378 ApertureValue\n if ((fabs(ape = getreal(type)) < 256.0) && (!aperture))\n aperture = libraw_powf64l(2.0, ape / 2);\n break;\n case 0x9209: // 37385\n flash_used = getreal(type);\n break;\n case 0x920a: // 37386\n focal_len = getreal(type);\n break;\n case 0x927c: // 37500\n if (((make[0] == '\\0') && !strncmp(model, \"ov5647\", 6)) ||\n (!strncmp(make, \"RaspberryPi\", 11) &&\n (!strncmp(model, \"RP_OV5647\", 9) ||\n !strncmp(model, \"RP_imx219\", 9))))\n {\n char mn_text[512];\n char *pos;\n char ccms[512];\n ushort l;\n float num;\n\n fgets(mn_text, MIN(len, 511), ifp);\n mn_text[511] = 0;\n\n pos = strstr(mn_text, \"gain_r=\");\n if (pos)\n cam_mul[0] = atof(pos + 7);\n pos = strstr(mn_text, \"gain_b=\");\n if (pos)\n cam_mul[2] = atof(pos + 7);\n if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f))\n cam_mul[1] = cam_mul[3] = 1.0f;\n else\n cam_mul[0] = cam_mul[2] = 0.0f;\n\n pos = strstr(mn_text, \"ccm=\");\n if (pos)\n {\n pos += 4;\n char *pos2 = strstr(pos, \" \");\n if (pos2)\n {\n l = pos2 - pos;\n memcpy(ccms, pos, l);\n ccms[l] = '\\0';\n#ifdef LIBRAW_WIN32_CALLS\n // Win32 strtok is already thread-safe\n pos = strtok(ccms, \",\");\n#else\n char *last = 0;\n pos = strtok_r(ccms, \",\", &last);\n#endif\n if (pos)\n {\n for (l = 0; l < 4; l++)\n {\n num = 0.0;\n for (c = 0; c < 3; c++)\n {\n imgdata.color.ccm[l][c] = (float)atoi(pos);\n num += imgdata.color.ccm[l][c];\n#ifdef LIBRAW_WIN32_CALLS\n pos = strtok(NULL, \",\");\n#else\n pos = strtok_r(NULL, \",\", &last);\n#endif\n if (!pos)\n goto end; // broken\n }\n if (num > 0.01)\n FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n }\n }\n }\n }\n end:;\n }\n else if (!strncmp(make, \"SONY\", 4) &&\n (!strncmp(model, \"DSC-V3\", 6) || !strncmp(model, \"DSC-F828\", 8)))\n {\n parseSonySRF(len);\n break;\n }\n else if ((len == 1) && !strncmp(make, \"NIKON\", 5))\n {\n c = get4();\n if (c)\n fseek(ifp, c, SEEK_SET);\n is_NikonTransfer = 1;\n }\n parse_makernote(base, 0);\n break;\n case 0xa002: // 40962\n if (kodak)\n raw_width = get4();\n break;\n case 0xa003: // 40963\n if (kodak)\n raw_height = get4();\n break;\n case 0xa302: // 41730\n if (get4() == 0x20002)\n for (exif_cfa = c = 0; c < 8; c += 2)\n exif_cfa |= fgetc(ifp) * 0x01010101U << c;\n }\n fseek(ifp, save, SEEK_SET);\n }\n}", "project": "LibRaw", "hash": 124973419188282141476335511350835218609, "size": 250, "commit_id": "55f0a0c08974b8b79ebfa7762b555a1704b25fb2", "message": "possible buffer underrun in exif parser", "target": 0, "dataset": "other", "idx": 395532} {"func": "static Image *ReadDPSImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n const char\n *client_name;\n\n Display\n *display;\n\n float\n pixels_per_point;\n\n Image\n *image;\n\n int\n sans,\n status;\n\n Pixmap\n pixmap;\n\n register IndexPacket\n *indexes;\n\n register ssize_t\n i;\n\n register PixelPacket\n *q;\n\n register size_t\n pixel;\n\n Screen\n *screen;\n\n ssize_t\n x,\n y;\n\n XColor\n *colors;\n\n XImage\n *dps_image;\n\n XRectangle\n page,\n bits_per_pixel;\n\n XResourceInfo\n resource_info;\n\n XrmDatabase\n resource_database;\n\n XStandardColormap\n *map_info;\n\n XVisualInfo\n *visual_info;\n\n /*\n Open X server connection.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n display=XOpenDisplay(image_info->server_name);\n if (display == (Display *) NULL)\n return((Image *) NULL);\n /*\n Set our forgiving exception handler.\n */\n (void) XSetErrorHandler(XError);\n /*\n Open image file.\n */\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n return((Image *) NULL);\n /*\n Get user defaults from X resource database.\n */\n client_name=GetClientName();\n resource_database=XGetResourceDatabase(display,client_name);\n XGetResourceInfo(image_info,resource_database,client_name,&resource_info);\n /*\n Allocate standard colormap.\n */\n map_info=XAllocStandardColormap();\n visual_info=(XVisualInfo *) NULL;\n if (map_info == (XStandardColormap *) NULL)\n ThrowReaderException(ResourceLimitError,\"UnableToCreateStandardColormap\")\n else\n {\n /*\n Initialize visual info.\n */\n (void) CloneString(&resource_info.visual_type,\"default\");\n visual_info=XBestVisualInfo(display,map_info,&resource_info);\n map_info->colormap=(Colormap) NULL;\n }\n if ((map_info == (XStandardColormap *) NULL) ||\n (visual_info == (XVisualInfo *) NULL))\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Create a pixmap the appropriate size for the image.\n */\n screen=ScreenOfDisplay(display,visual_info->screen);\n pixels_per_point=XDPSPixelsPerPoint(screen);\n if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))\n pixels_per_point=MagickMin(image->x_resolution,image->y_resolution)/\n DefaultResolution;\n status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen,\n GetBlobFileHandle(image),visual_info->depth,pixels_per_point,&pixmap,\n &bits_per_pixel,&page);\n if ((status == dps_status_failure) || (status == dps_status_no_extension))\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Rasterize the file into the pixmap.\n */\n status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap,\n GetBlobFileHandle(image),(int) bits_per_pixel.height,visual_info->depth,\n &page,-page.x,-page.y,pixels_per_point,MagickTrue,MagickFalse,MagickTrue,\n &sans);\n if (status != dps_status_success)\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Initialize DPS X image.\n */\n dps_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width,\n bits_per_pixel.height,AllPlanes,ZPixmap);\n (void) XFreePixmap(display,pixmap);\n if (dps_image == (XImage *) NULL)\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Get the colormap colors.\n */\n colors=(XColor *) AcquireQuantumMemory(visual_info->colormap_size,\n sizeof(*colors));\n if (colors == (XColor *) NULL)\n {\n image=DestroyImage(image);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n if ((visual_info->klass != DirectColor) && (visual_info->klass != TrueColor))\n for (i=0; i < visual_info->colormap_size; i++)\n {\n colors[i].pixel=(size_t) i;\n colors[i].pad=0;\n }\n else\n {\n size_t\n blue,\n blue_bit,\n green,\n green_bit,\n red,\n red_bit;\n\n /*\n DirectColor or TrueColor visual.\n */\n red=0;\n green=0;\n blue=0;\n red_bit=visual_info->red_mask & (~(visual_info->red_mask)+1);\n green_bit=visual_info->green_mask & (~(visual_info->green_mask)+1);\n blue_bit=visual_info->blue_mask & (~(visual_info->blue_mask)+1);\n for (i=0; i < visual_info->colormap_size; i++)\n {\n colors[i].pixel=red | green | blue;\n colors[i].pad=0;\n red+=red_bit;\n if (red > visual_info->red_mask)\n red=0;\n green+=green_bit;\n if (green > visual_info->green_mask)\n green=0;\n blue+=blue_bit;\n if (blue > visual_info->blue_mask)\n blue=0;\n }\n }\n (void) XQueryColors(display,XDefaultColormap(display,visual_info->screen),\n colors,visual_info->colormap_size);\n /*\n Convert X image to MIFF format.\n */\n if ((visual_info->klass != TrueColor) && (visual_info->klass != DirectColor))\n image->storage_class=PseudoClass;\n image->columns=(size_t) dps_image->width;\n image->rows=(size_t) dps_image->height;\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n switch (image->storage_class)\n {\n case DirectClass:\n default:\n {\n register size_t\n color,\n index;\n\n size_t\n blue_mask,\n blue_shift,\n green_mask,\n green_shift,\n red_mask,\n red_shift;\n\n /*\n Determine shift and mask for red, green, and blue.\n */\n red_mask=visual_info->red_mask;\n red_shift=0;\n while ((red_mask != 0) && ((red_mask & 0x01) == 0))\n {\n red_mask>>=1;\n red_shift++;\n }\n green_mask=visual_info->green_mask;\n green_shift=0;\n while ((green_mask != 0) && ((green_mask & 0x01) == 0))\n {\n green_mask>>=1;\n green_shift++;\n }\n blue_mask=visual_info->blue_mask;\n blue_shift=0;\n while ((blue_mask != 0) && ((blue_mask & 0x01) == 0))\n {\n blue_mask>>=1;\n blue_shift++;\n }\n /*\n Convert X image to DirectClass packets.\n */\n if ((visual_info->colormap_size > 0) &&\n (visual_info->klass == DirectColor))\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=XGetPixel(dps_image,x,y);\n index=(pixel >> red_shift) & red_mask;\n SetPixelRed(q,ScaleShortToQuantum(colors[index].red));\n index=(pixel >> green_shift) & green_mask;\n SetPixelGreen(q,ScaleShortToQuantum(colors[index].green));\n index=(pixel >> blue_shift) & blue_mask;\n SetPixelBlue(q,ScaleShortToQuantum(colors[index].blue));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)\n break;\n }\n else\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=XGetPixel(dps_image,x,y);\n color=(pixel >> red_shift) & red_mask;\n color=(color*65535L)/red_mask;\n SetPixelRed(q,ScaleShortToQuantum((unsigned short) color));\n color=(pixel >> green_shift) & green_mask;\n color=(color*65535L)/green_mask;\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short)\n color));\n color=(pixel >> blue_shift) & blue_mask;\n color=(color*65535L)/blue_mask;\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short)\n color));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)\n break;\n }\n break;\n }\n case PseudoClass:\n {\n /*\n Create colormap.\n */\n if (AcquireImageColormap(image,(size_t) visual_info->colormap_size) == MagickFalse)\n {\n image=DestroyImage(image);\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[colors[i].pixel].red=ScaleShortToQuantum(colors[i].red);\n image->colormap[colors[i].pixel].green=\n ScaleShortToQuantum(colors[i].green);\n image->colormap[colors[i].pixel].blue=\n ScaleShortToQuantum(colors[i].blue);\n }\n /*\n Convert X image to PseudoClass packets.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n SetPixelIndex(indexes+x,(unsigned short)\n XGetPixel(dps_image,x,y));\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)\n break;\n }\n break;\n }\n }\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n if (image->storage_class == PseudoClass)\n (void) SyncImage(image);\n /*\n Rasterize matte image.\n */\n status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen,\n GetBlobFileHandle(image),1,pixels_per_point,&pixmap,&bits_per_pixel,&page);\n if ((status != dps_status_failure) && (status != dps_status_no_extension))\n {\n status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap,\n GetBlobFileHandle(image),(int) bits_per_pixel.height,1,&page,-page.x,\n -page.y,pixels_per_point,MagickTrue,MagickTrue,MagickTrue,&sans);\n if (status == dps_status_success)\n {\n XImage\n *matte_image;\n\n /*\n Initialize image matte.\n */\n matte_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width,\n bits_per_pixel.height,AllPlanes,ZPixmap);\n (void) XFreePixmap(display,pixmap);\n if (matte_image != (XImage *) NULL)\n {\n image->storage_class=DirectClass;\n image->matte=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelOpacity(q,OpaqueOpacity);\n if (XGetPixel(matte_image,x,y) == 0)\n SetPixelOpacity(q,TransparentOpacity);\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n XDestroyImage(matte_image);\n }\n }\n }\n /*\n Relinquish resources.\n */\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}", "project": "ImageMagick6", "hash": 290877276966701211376434314093754867321, "size": 436, "commit_id": "ebe38274941908892c32b7244fa4e0fe7497e528", "message": "...", "target": 1, "dataset": "other", "idx": 207312} {"func": "static Image *ReadDPSImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n const char\n *client_name;\n\n Display\n *display;\n\n float\n pixels_per_point;\n\n Image\n *image;\n\n int\n sans,\n status;\n\n Pixmap\n pixmap;\n\n register IndexPacket\n *indexes;\n\n register ssize_t\n i;\n\n register PixelPacket\n *q;\n\n register size_t\n pixel;\n\n Screen\n *screen;\n\n ssize_t\n x,\n y;\n\n XColor\n *colors;\n\n XImage\n *dps_image;\n\n XRectangle\n page,\n bits_per_pixel;\n\n XResourceInfo\n resource_info;\n\n XrmDatabase\n resource_database;\n\n XStandardColormap\n *map_info;\n\n XVisualInfo\n *visual_info;\n\n /*\n Open X server connection.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n display=XOpenDisplay(image_info->server_name);\n if (display == (Display *) NULL)\n return((Image *) NULL);\n /*\n Set our forgiving exception handler.\n */\n (void) XSetErrorHandler(XError);\n /*\n Open image file.\n */\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Get user defaults from X resource database.\n */\n client_name=GetClientName();\n resource_database=XGetResourceDatabase(display,client_name);\n XGetResourceInfo(image_info,resource_database,client_name,&resource_info);\n /*\n Allocate standard colormap.\n */\n map_info=XAllocStandardColormap();\n visual_info=(XVisualInfo *) NULL;\n if (map_info == (XStandardColormap *) NULL)\n ThrowReaderException(ResourceLimitError,\"UnableToCreateStandardColormap\")\n else\n {\n /*\n Initialize visual info.\n */\n (void) CloneString(&resource_info.visual_type,\"default\");\n visual_info=XBestVisualInfo(display,map_info,&resource_info);\n map_info->colormap=(Colormap) NULL;\n }\n if ((map_info == (XStandardColormap *) NULL) ||\n (visual_info == (XVisualInfo *) NULL))\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Create a pixmap the appropriate size for the image.\n */\n screen=ScreenOfDisplay(display,visual_info->screen);\n pixels_per_point=XDPSPixelsPerPoint(screen);\n if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))\n pixels_per_point=MagickMin(image->x_resolution,image->y_resolution)/\n DefaultResolution;\n status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen,\n GetBlobFileHandle(image),visual_info->depth,pixels_per_point,&pixmap,\n &bits_per_pixel,&page);\n if ((status == dps_status_failure) || (status == dps_status_no_extension))\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Rasterize the file into the pixmap.\n */\n status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap,\n GetBlobFileHandle(image),(int) bits_per_pixel.height,visual_info->depth,\n &page,-page.x,-page.y,pixels_per_point,MagickTrue,MagickFalse,MagickTrue,\n &sans);\n if (status != dps_status_success)\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Initialize DPS X image.\n */\n dps_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width,\n bits_per_pixel.height,AllPlanes,ZPixmap);\n (void) XFreePixmap(display,pixmap);\n if (dps_image == (XImage *) NULL)\n {\n image=DestroyImage(image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n /*\n Get the colormap colors.\n */\n colors=(XColor *) AcquireQuantumMemory(visual_info->colormap_size,\n sizeof(*colors));\n if (colors == (XColor *) NULL)\n {\n image=DestroyImage(image);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n if ((visual_info->klass != DirectColor) && (visual_info->klass != TrueColor))\n for (i=0; i < visual_info->colormap_size; i++)\n {\n colors[i].pixel=(size_t) i;\n colors[i].pad=0;\n }\n else\n {\n size_t\n blue,\n blue_bit,\n green,\n green_bit,\n red,\n red_bit;\n\n /*\n DirectColor or TrueColor visual.\n */\n red=0;\n green=0;\n blue=0;\n red_bit=visual_info->red_mask & (~(visual_info->red_mask)+1);\n green_bit=visual_info->green_mask & (~(visual_info->green_mask)+1);\n blue_bit=visual_info->blue_mask & (~(visual_info->blue_mask)+1);\n for (i=0; i < visual_info->colormap_size; i++)\n {\n colors[i].pixel=red | green | blue;\n colors[i].pad=0;\n red+=red_bit;\n if (red > visual_info->red_mask)\n red=0;\n green+=green_bit;\n if (green > visual_info->green_mask)\n green=0;\n blue+=blue_bit;\n if (blue > visual_info->blue_mask)\n blue=0;\n }\n }\n (void) XQueryColors(display,XDefaultColormap(display,visual_info->screen),\n colors,visual_info->colormap_size);\n /*\n Convert X image to MIFF format.\n */\n if ((visual_info->klass != TrueColor) && (visual_info->klass != DirectColor))\n image->storage_class=PseudoClass;\n image->columns=(size_t) dps_image->width;\n image->rows=(size_t) dps_image->height;\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n switch (image->storage_class)\n {\n case DirectClass:\n default:\n {\n register size_t\n color,\n index;\n\n size_t\n blue_mask,\n blue_shift,\n green_mask,\n green_shift,\n red_mask,\n red_shift;\n\n /*\n Determine shift and mask for red, green, and blue.\n */\n red_mask=visual_info->red_mask;\n red_shift=0;\n while ((red_mask != 0) && ((red_mask & 0x01) == 0))\n {\n red_mask>>=1;\n red_shift++;\n }\n green_mask=visual_info->green_mask;\n green_shift=0;\n while ((green_mask != 0) && ((green_mask & 0x01) == 0))\n {\n green_mask>>=1;\n green_shift++;\n }\n blue_mask=visual_info->blue_mask;\n blue_shift=0;\n while ((blue_mask != 0) && ((blue_mask & 0x01) == 0))\n {\n blue_mask>>=1;\n blue_shift++;\n }\n /*\n Convert X image to DirectClass packets.\n */\n if ((visual_info->colormap_size > 0) &&\n (visual_info->klass == DirectColor))\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=XGetPixel(dps_image,x,y);\n index=(pixel >> red_shift) & red_mask;\n SetPixelRed(q,ScaleShortToQuantum(colors[index].red));\n index=(pixel >> green_shift) & green_mask;\n SetPixelGreen(q,ScaleShortToQuantum(colors[index].green));\n index=(pixel >> blue_shift) & blue_mask;\n SetPixelBlue(q,ScaleShortToQuantum(colors[index].blue));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)\n break;\n }\n else\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n pixel=XGetPixel(dps_image,x,y);\n color=(pixel >> red_shift) & red_mask;\n color=(color*65535L)/red_mask;\n SetPixelRed(q,ScaleShortToQuantum((unsigned short) color));\n color=(pixel >> green_shift) & green_mask;\n color=(color*65535L)/green_mask;\n SetPixelGreen(q,ScaleShortToQuantum((unsigned short)\n color));\n color=(pixel >> blue_shift) & blue_mask;\n color=(color*65535L)/blue_mask;\n SetPixelBlue(q,ScaleShortToQuantum((unsigned short)\n color));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)\n break;\n }\n break;\n }\n case PseudoClass:\n {\n /*\n Create colormap.\n */\n if (AcquireImageColormap(image,(size_t) visual_info->colormap_size) == MagickFalse)\n {\n image=DestroyImage(image);\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n return((Image *) NULL);\n }\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n image->colormap[colors[i].pixel].red=ScaleShortToQuantum(colors[i].red);\n image->colormap[colors[i].pixel].green=\n ScaleShortToQuantum(colors[i].green);\n image->colormap[colors[i].pixel].blue=\n ScaleShortToQuantum(colors[i].blue);\n }\n /*\n Convert X image to PseudoClass packets.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n SetPixelIndex(indexes+x,(unsigned short)\n XGetPixel(dps_image,x,y));\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse)\n break;\n }\n break;\n }\n }\n colors=(XColor *) RelinquishMagickMemory(colors);\n XDestroyImage(dps_image);\n if (image->storage_class == PseudoClass)\n (void) SyncImage(image);\n /*\n Rasterize matte image.\n */\n status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen,\n GetBlobFileHandle(image),1,pixels_per_point,&pixmap,&bits_per_pixel,&page);\n if ((status != dps_status_failure) && (status != dps_status_no_extension))\n {\n status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap,\n GetBlobFileHandle(image),(int) bits_per_pixel.height,1,&page,-page.x,\n -page.y,pixels_per_point,MagickTrue,MagickTrue,MagickTrue,&sans);\n if (status == dps_status_success)\n {\n XImage\n *matte_image;\n\n /*\n Initialize image matte.\n */\n matte_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width,\n bits_per_pixel.height,AllPlanes,ZPixmap);\n (void) XFreePixmap(display,pixmap);\n if (matte_image != (XImage *) NULL)\n {\n image->storage_class=DirectClass;\n image->matte=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelOpacity(q,OpaqueOpacity);\n if (XGetPixel(matte_image,x,y) == 0)\n SetPixelOpacity(q,TransparentOpacity);\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n XDestroyImage(matte_image);\n }\n }\n }\n /*\n Relinquish resources.\n */\n XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL,\n (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}", "project": "ImageMagick6", "hash": 82893322187814403256007653034729823397, "size": 439, "commit_id": "ebe38274941908892c32b7244fa4e0fe7497e528", "message": "...", "target": 0, "dataset": "other", "idx": 395543} {"func": "ipmi_get_session_info(struct ipmi_intf * intf,\n\t\t\t\t\t Ipmi_Session_Request_Type session_request_type,\n\t\t\t\t\t uint32_t id_or_handle)\n{\n\tint i, retval = 0;\n\n\tstruct ipmi_rs * rsp;\n\tstruct ipmi_rq req;\n\tuint8_t rqdata[5]; // max length of the variable length request\n\tstruct get_session_info_rsp session_info;\n\n\tmemset(&req, 0, sizeof(req));\n\tmemset(&session_info, 0, sizeof(session_info));\n\treq.msg.netfn = IPMI_NETFN_APP; // 0x06\n\treq.msg.cmd = IPMI_GET_SESSION_INFO; // 0x3D\n\treq.msg.data = rqdata;\n\n\tswitch (session_request_type)\n\t{\n\t\t\n\tcase IPMI_SESSION_REQUEST_CURRENT:\n\tcase IPMI_SESSION_REQUEST_BY_ID:\t\n\tcase IPMI_SESSION_REQUEST_BY_HANDLE:\n\t\tswitch (session_request_type)\n\t\t{\n\t\tcase IPMI_SESSION_REQUEST_CURRENT:\n\t\t\trqdata[0] = 0x00;\n\t\t\treq.msg.data_len = 1;\n\t\t\tbreak;\n\t\tcase IPMI_SESSION_REQUEST_BY_ID:\t\n\t\t\trqdata[0] = 0xFF;\n\t\t\trqdata[1] = id_or_handle & 0x000000FF;\n\t\t\trqdata[2] = (id_or_handle >> 8) & 0x000000FF;\n\t\t\trqdata[3] = (id_or_handle >> 16) & 0x000000FF;\n\t\t\trqdata[4] = (id_or_handle >> 24) & 0x000000FF;\n\t\t\treq.msg.data_len = 5;\n\t\t\tbreak;\n\t\tcase IPMI_SESSION_REQUEST_BY_HANDLE:\n\t\t\trqdata[0] = 0xFE;\n\t\t\trqdata[1] = (uint8_t)id_or_handle;\n\t\t\treq.msg.data_len = 2;\n\t\t\tbreak;\n\t\tcase IPMI_SESSION_REQUEST_ALL:\n\t\t\tbreak;\n\t\t}\n\n\t\trsp = intf->sendrecv(intf, &req);\n\t\tif (!rsp)\n\t\t{\n\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed\");\n\t\t\tretval = -1;\n\t\t}\n\t\telse if (rsp->ccode)\n\t\t{\n\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed: %s\",\n\t\t\t\tval2str(rsp->ccode, completion_code_vals));\n\t\t\tretval = -1;\n\t\t}\n\n\t\tif (retval < 0)\n\t\t{\n\t\t\tif ((session_request_type == IPMI_SESSION_REQUEST_CURRENT) &&\n\t\t\t (strncmp(intf->name, \"lan\", 3) != 0))\n\t\t\t\tlprintf(LOG_ERR, \"It is likely that the channel in use \"\n\t\t\t\t\t\"does not support sessions\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmemcpy(&session_info, rsp->data, rsp->data_len);\n\t\t\tprint_session_info(&session_info, rsp->data_len);\n\t\t}\n\t\tbreak;\n\t\t\n\tcase IPMI_SESSION_REQUEST_ALL:\n\t\treq.msg.data_len = 1;\n\t\ti = 1;\n\t\tdo\n\t\t{\n\t\t\trqdata[0] = i++;\n\t\t\trsp = intf->sendrecv(intf, &req);\n\t\t\t\n\t\t\tif (!rsp)\n\t\t\t{\n\t\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed\");\n\t\t\t\tretval = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (rsp->ccode && rsp->ccode != 0xCC && rsp->ccode != 0xCB)\n\t\t\t{\n\t\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed: %s\",\n\t\t\t\t\tval2str(rsp->ccode, completion_code_vals));\n\t\t\t\tretval = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (rsp->data_len < 3)\n\t\t\t{\n\t\t\t\tretval = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tmemcpy(&session_info, rsp->data, rsp->data_len);\n\t\t\tprint_session_info(&session_info, rsp->data_len);\n\t\t\t\n\t\t} while (i <= session_info.session_slot_count);\n\t\tbreak;\n\t}\n\n\treturn retval;\n}", "project": "ipmitool", "hash": 224137137758231083307007282464002439869, "size": 109, "commit_id": "41d7026946fafbd4d1ec0bcaca3ea30a6e8eed22", "message": "session: Fix buffer overflow in ipmi_get_session_info\n\nPartial fix for CVE-2020-5208, see\nhttps://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp\n\nThe `ipmi_get_session_info` function does not properly check the\nresponse `data_len`, which is used as a copy size, allowing stack buffer\noverflow.", "target": 1, "dataset": "other", "idx": 207463} {"func": "ipmi_get_session_info(struct ipmi_intf * intf,\n\t\t\t\t\t Ipmi_Session_Request_Type session_request_type,\n\t\t\t\t\t uint32_t id_or_handle)\n{\n\tint i, retval = 0;\n\n\tstruct ipmi_rs * rsp;\n\tstruct ipmi_rq req;\n\tuint8_t rqdata[5]; // max length of the variable length request\n\tstruct get_session_info_rsp session_info;\n\n\tmemset(&req, 0, sizeof(req));\n\tmemset(&session_info, 0, sizeof(session_info));\n\treq.msg.netfn = IPMI_NETFN_APP; // 0x06\n\treq.msg.cmd = IPMI_GET_SESSION_INFO; // 0x3D\n\treq.msg.data = rqdata;\n\n\tswitch (session_request_type)\n\t{\n\t\t\n\tcase IPMI_SESSION_REQUEST_CURRENT:\n\tcase IPMI_SESSION_REQUEST_BY_ID:\t\n\tcase IPMI_SESSION_REQUEST_BY_HANDLE:\n\t\tswitch (session_request_type)\n\t\t{\n\t\tcase IPMI_SESSION_REQUEST_CURRENT:\n\t\t\trqdata[0] = 0x00;\n\t\t\treq.msg.data_len = 1;\n\t\t\tbreak;\n\t\tcase IPMI_SESSION_REQUEST_BY_ID:\t\n\t\t\trqdata[0] = 0xFF;\n\t\t\trqdata[1] = id_or_handle & 0x000000FF;\n\t\t\trqdata[2] = (id_or_handle >> 8) & 0x000000FF;\n\t\t\trqdata[3] = (id_or_handle >> 16) & 0x000000FF;\n\t\t\trqdata[4] = (id_or_handle >> 24) & 0x000000FF;\n\t\t\treq.msg.data_len = 5;\n\t\t\tbreak;\n\t\tcase IPMI_SESSION_REQUEST_BY_HANDLE:\n\t\t\trqdata[0] = 0xFE;\n\t\t\trqdata[1] = (uint8_t)id_or_handle;\n\t\t\treq.msg.data_len = 2;\n\t\t\tbreak;\n\t\tcase IPMI_SESSION_REQUEST_ALL:\n\t\t\tbreak;\n\t\t}\n\n\t\trsp = intf->sendrecv(intf, &req);\n\t\tif (!rsp)\n\t\t{\n\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed\");\n\t\t\tretval = -1;\n\t\t}\n\t\telse if (rsp->ccode)\n\t\t{\n\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed: %s\",\n\t\t\t\tval2str(rsp->ccode, completion_code_vals));\n\t\t\tretval = -1;\n\t\t}\n\n\t\tif (retval < 0)\n\t\t{\n\t\t\tif ((session_request_type == IPMI_SESSION_REQUEST_CURRENT) &&\n\t\t\t (strncmp(intf->name, \"lan\", 3) != 0))\n\t\t\t\tlprintf(LOG_ERR, \"It is likely that the channel in use \"\n\t\t\t\t\t\"does not support sessions\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmemcpy(&session_info, rsp->data,\n\t\t\t __min(rsp->data_len, sizeof(session_info)));\n\t\t\tprint_session_info(&session_info,\n\t\t\t __min(rsp->data_len, sizeof(session_info)));\n\t\t}\n\t\tbreak;\n\t\t\n\tcase IPMI_SESSION_REQUEST_ALL:\n\t\treq.msg.data_len = 1;\n\t\ti = 1;\n\t\tdo\n\t\t{\n\t\t\trqdata[0] = i++;\n\t\t\trsp = intf->sendrecv(intf, &req);\n\t\t\t\n\t\t\tif (!rsp)\n\t\t\t{\n\t\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed\");\n\t\t\t\tretval = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (rsp->ccode && rsp->ccode != 0xCC && rsp->ccode != 0xCB)\n\t\t\t{\n\t\t\t\tlprintf(LOG_ERR, \"Get Session Info command failed: %s\",\n\t\t\t\t\tval2str(rsp->ccode, completion_code_vals));\n\t\t\t\tretval = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (rsp->data_len < 3)\n\t\t\t{\n\t\t\t\tretval = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tmemcpy(&session_info, rsp->data,\n\t\t\t __min(rsp->data_len, sizeof(session_info)));\n\t\t\tprint_session_info(&session_info,\n\t\t\t __min(rsp->data_len, sizeof(session_info)));\n\t\t\t\n\t\t} while (i <= session_info.session_slot_count);\n\t\tbreak;\n\t}\n\n\treturn retval;\n}", "project": "ipmitool", "hash": 242323179109677020584476187087776996309, "size": 113, "commit_id": "41d7026946fafbd4d1ec0bcaca3ea30a6e8eed22", "message": "session: Fix buffer overflow in ipmi_get_session_info\n\nPartial fix for CVE-2020-5208, see\nhttps://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp\n\nThe `ipmi_get_session_info` function does not properly check the\nresponse `data_len`, which is used as a copy size, allowing stack buffer\noverflow.", "target": 0, "dataset": "other", "idx": 398021} {"func": "static void sctp_destroy_sock(struct sock *sk)\n{\n\tstruct sctp_sock *sp;\n\n\tpr_debug(\"%s: sk:%p\\n\", __func__, sk);\n\n\t/* Release our hold on the endpoint. */\n\tsp = sctp_sk(sk);\n\t/* This could happen during socket init, thus we bail out\n\t * early, since the rest of the below is not setup either.\n\t */\n\tif (sp->ep == NULL)\n\t\treturn;\n\n\tif (sp->do_auto_asconf) {\n\t\tsp->do_auto_asconf = 0;\n\t\tlist_del(&sp->auto_asconf_list);\n\t}\n\tsctp_endpoint_free(sp->ep);\n\tlocal_bh_disable();\n\tsk_sockets_allocated_dec(sk);\n\tsock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);\n\tlocal_bh_enable();\n}", "project": "linux", "hash": 16718687577270921329602634345512729479, "size": 24, "commit_id": "b166a20b07382b8bc1dcee2a448715c9c2c81b5b", "message": "net/sctp: fix race condition in sctp_destroy_sock\n\nIf sctp_destroy_sock is called without sock_net(sk)->sctp.addr_wq_lock\nheld and sp->do_auto_asconf is true, then an element is removed\nfrom the auto_asconf_splist without any proper locking.\n\nThis can happen in the following functions:\n1. In sctp_accept, if sctp_sock_migrate fails.\n2. In inet_create or inet6_create, if there is a bpf program\n attached to BPF_CGROUP_INET_SOCK_CREATE which denies\n creation of the sctp socket.\n\nThe bug is fixed by acquiring addr_wq_lock in sctp_destroy_sock\ninstead of sctp_close.\n\nThis addresses CVE-2021-23133.\n\nReported-by: Or Cohen \nReviewed-by: Xin Long \nFixes: 610236587600 (\"bpf: Add new cgroup attach type to enable sock modifications\")\nSigned-off-by: Or Cohen \nAcked-by: Marcelo Ricardo Leitner \nSigned-off-by: David S. Miller ", "target": 1, "dataset": "other", "idx": 207478} {"func": "static void sctp_destroy_sock(struct sock *sk)\n{\n\tstruct sctp_sock *sp;\n\n\tpr_debug(\"%s: sk:%p\\n\", __func__, sk);\n\n\t/* Release our hold on the endpoint. */\n\tsp = sctp_sk(sk);\n\t/* This could happen during socket init, thus we bail out\n\t * early, since the rest of the below is not setup either.\n\t */\n\tif (sp->ep == NULL)\n\t\treturn;\n\n\tif (sp->do_auto_asconf) {\n\t\tsp->do_auto_asconf = 0;\n\t\tspin_lock_bh(&sock_net(sk)->sctp.addr_wq_lock);\n\t\tlist_del(&sp->auto_asconf_list);\n\t\tspin_unlock_bh(&sock_net(sk)->sctp.addr_wq_lock);\n\t}\n\tsctp_endpoint_free(sp->ep);\n\tlocal_bh_disable();\n\tsk_sockets_allocated_dec(sk);\n\tsock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);\n\tlocal_bh_enable();\n}", "project": "linux", "hash": 169454299650799904813060257343861693714, "size": 26, "commit_id": "b166a20b07382b8bc1dcee2a448715c9c2c81b5b", "message": "net/sctp: fix race condition in sctp_destroy_sock\n\nIf sctp_destroy_sock is called without sock_net(sk)->sctp.addr_wq_lock\nheld and sp->do_auto_asconf is true, then an element is removed\nfrom the auto_asconf_splist without any proper locking.\n\nThis can happen in the following functions:\n1. In sctp_accept, if sctp_sock_migrate fails.\n2. In inet_create or inet6_create, if there is a bpf program\n attached to BPF_CGROUP_INET_SOCK_CREATE which denies\n creation of the sctp socket.\n\nThe bug is fixed by acquiring addr_wq_lock in sctp_destroy_sock\ninstead of sctp_close.\n\nThis addresses CVE-2021-23133.\n\nReported-by: Or Cohen \nReviewed-by: Xin Long \nFixes: 610236587600 (\"bpf: Add new cgroup attach type to enable sock modifications\")\nSigned-off-by: Or Cohen \nAcked-by: Marcelo Ricardo Leitner \nSigned-off-by: David S. Miller ", "target": 0, "dataset": "other", "idx": 398128} {"func": "static void mcba_usb_disconnect(struct usb_interface *intf)\n{\n\tstruct mcba_priv *priv = usb_get_intfdata(intf);\n\n\tusb_set_intfdata(intf, NULL);\n\n\tnetdev_info(priv->netdev, \"device disconnected\\n\");\n\n\tunregister_candev(priv->netdev);\n\tfree_candev(priv->netdev);\n\n\tmcba_urb_unlink(priv);\n}", "project": "linux", "hash": 331613299342883456089163439463915430023, "size": 13, "commit_id": "4d6636498c41891d0482a914dd570343a838ad79", "message": "can: mcba_usb: fix use-after-free on disconnect\n\nThe driver was accessing its driver data after having freed it.\n\nFixes: 51f3baad7de9 (\"can: mcba_usb: Add support for Microchip CAN BUS Analyzer\")\nCc: stable # 4.12\nCc: Remigiusz Ko\u0142\u0142\u0105taj \nReported-by: syzbot+e29b17e5042bbc56fae9@syzkaller.appspotmail.com\nSigned-off-by: Johan Hovold \nSigned-off-by: Marc Kleine-Budde ", "target": 1, "dataset": "other", "idx": 207488} {"func": "static void mcba_usb_disconnect(struct usb_interface *intf)\n{\n\tstruct mcba_priv *priv = usb_get_intfdata(intf);\n\n\tusb_set_intfdata(intf, NULL);\n\n\tnetdev_info(priv->netdev, \"device disconnected\\n\");\n\n\tunregister_candev(priv->netdev);\n\tmcba_urb_unlink(priv);\n\tfree_candev(priv->netdev);\n}", "project": "linux", "hash": 111040647052107229552079151990945826263, "size": 12, "commit_id": "4d6636498c41891d0482a914dd570343a838ad79", "message": "can: mcba_usb: fix use-after-free on disconnect\n\nThe driver was accessing its driver data after having freed it.\n\nFixes: 51f3baad7de9 (\"can: mcba_usb: Add support for Microchip CAN BUS Analyzer\")\nCc: stable # 4.12\nCc: Remigiusz Ko\u0142\u0142\u0105taj \nReported-by: syzbot+e29b17e5042bbc56fae9@syzkaller.appspotmail.com\nSigned-off-by: Johan Hovold \nSigned-off-by: Marc Kleine-Budde ", "target": 0, "dataset": "other", "idx": 398308} {"func": "BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n{\n\tUINT32 os_major;\n\tUINT32 os_minor;\n\tUINT32 cbScope, cbCompanyName, cbProductId, cbLicenseInfo;\n\twStream* licenseStream = NULL;\n\tBOOL ret = FALSE;\n\tBYTE computedMac[16];\n\tLICENSE_BLOB* calBlob;\n\n\tDEBUG_LICENSE(\"Receiving Server New/Upgrade License Packet\");\n\n\tcalBlob = license_new_binary_blob(BB_DATA_BLOB);\n\tif (!calBlob)\n\t\treturn FALSE;\n\n\t/* EncryptedLicenseInfo */\n\tif (!license_read_encrypted_blob(license, s, calBlob))\n\t\tgoto out_free_blob;\n\n\t/* compute MAC and check it */\n\tif (Stream_GetRemainingLength(s) < 16)\n\t\tgoto out_free_blob;\n\n\tif (!security_mac_data(license->MacSaltKey, calBlob->data, calBlob->length, computedMac))\n\t\tgoto out_free_blob;\n\n\tif (memcmp(computedMac, Stream_Pointer(s), sizeof(computedMac)) != 0)\n\t{\n\t\tWLog_ERR(TAG, \"new or upgrade license MAC mismatch\");\n\t\tgoto out_free_blob;\n\t}\n\n\tif (!Stream_SafeSeek(s, 16))\n\t\tgoto out_free_blob;\n\n\tlicenseStream = Stream_New(calBlob->data, calBlob->length);\n\tif (!licenseStream)\n\t\tgoto out_free_blob;\n\n\tStream_Read_UINT16(licenseStream, os_minor);\n\tStream_Read_UINT16(licenseStream, os_major);\n\n\t/* Scope */\n\tStream_Read_UINT32(licenseStream, cbScope);\n\tif (Stream_GetRemainingLength(licenseStream) < cbScope)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Scope:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbScope);\n#endif\n\tStream_Seek(licenseStream, cbScope);\n\n\t/* CompanyName */\n\tStream_Read_UINT32(licenseStream, cbCompanyName);\n\tif (Stream_GetRemainingLength(licenseStream) < cbCompanyName)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Company name:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbCompanyName);\n#endif\n\tStream_Seek(licenseStream, cbCompanyName);\n\n\t/* productId */\n\tStream_Read_UINT32(licenseStream, cbProductId);\n\tif (Stream_GetRemainingLength(licenseStream) < cbProductId)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Product id:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbProductId);\n#endif\n\tStream_Seek(licenseStream, cbProductId);\n\n\t/* licenseInfo */\n\tStream_Read_UINT32(licenseStream, cbLicenseInfo);\n\tif (Stream_GetRemainingLength(licenseStream) < cbLicenseInfo)\n\t\tgoto out_free_stream;\n\n\tlicense->state = LICENSE_STATE_COMPLETED;\n\n\tret = TRUE;\n\tif (!license->rdp->settings->OldLicenseBehaviour)\n\t\tret = saveCal(license->rdp->settings, Stream_Pointer(licenseStream), cbLicenseInfo,\n\t\t license->rdp->settings->ClientHostname);\n\nout_free_stream:\n\tStream_Free(licenseStream, FALSE);\nout_free_blob:\n\tlicense_free_binary_blob(calBlob);\n\treturn ret;\n}", "project": "FreeRDP", "hash": 315612488608223251182245385146208820876, "size": 91, "commit_id": "6ade7b4cbfd71c54b3d724e8f2d6ac76a58e879a", "message": "Fixed OOB Read in license_read_new_or_upgrade_license_packet\n\nCVE-2020-11099 thanks to @antonio-morales for finding this.", "target": 1, "dataset": "other", "idx": 207567} {"func": "BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n{\n\tUINT32 os_major;\n\tUINT32 os_minor;\n\tUINT32 cbScope, cbCompanyName, cbProductId, cbLicenseInfo;\n\twStream* licenseStream = NULL;\n\tBOOL ret = FALSE;\n\tBYTE computedMac[16];\n\tLICENSE_BLOB* calBlob;\n\n\tDEBUG_LICENSE(\"Receiving Server New/Upgrade License Packet\");\n\n\tcalBlob = license_new_binary_blob(BB_DATA_BLOB);\n\tif (!calBlob)\n\t\treturn FALSE;\n\n\t/* EncryptedLicenseInfo */\n\tif (!license_read_encrypted_blob(license, s, calBlob))\n\t\tgoto out_free_blob;\n\n\t/* compute MAC and check it */\n\tif (Stream_GetRemainingLength(s) < 16)\n\t\tgoto out_free_blob;\n\n\tif (!security_mac_data(license->MacSaltKey, calBlob->data, calBlob->length, computedMac))\n\t\tgoto out_free_blob;\n\n\tif (memcmp(computedMac, Stream_Pointer(s), sizeof(computedMac)) != 0)\n\t{\n\t\tWLog_ERR(TAG, \"new or upgrade license MAC mismatch\");\n\t\tgoto out_free_blob;\n\t}\n\n\tif (!Stream_SafeSeek(s, 16))\n\t\tgoto out_free_blob;\n\n\tlicenseStream = Stream_New(calBlob->data, calBlob->length);\n\tif (!licenseStream)\n\t\tgoto out_free_blob;\n\n\tif (Stream_GetRemainingLength(licenseStream) < 8)\n\t\tgoto out_free_stream;\n\n\tStream_Read_UINT16(licenseStream, os_minor);\n\tStream_Read_UINT16(licenseStream, os_major);\n\n\t/* Scope */\n\tStream_Read_UINT32(licenseStream, cbScope);\n\tif (Stream_GetRemainingLength(licenseStream) < cbScope)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Scope:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbScope);\n#endif\n\tStream_Seek(licenseStream, cbScope);\n\n\t/* CompanyName */\n\tif (Stream_GetRemainingLength(licenseStream) < 4)\n\t\tgoto out_free_stream;\n\tStream_Read_UINT32(licenseStream, cbCompanyName);\n\tif (Stream_GetRemainingLength(licenseStream) < cbCompanyName)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Company name:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbCompanyName);\n#endif\n\tStream_Seek(licenseStream, cbCompanyName);\n\n\t/* productId */\n\tif (Stream_GetRemainingLength(licenseStream) < 4)\n\t\tgoto out_free_stream;\n\tStream_Read_UINT32(licenseStream, cbProductId);\n\tif (Stream_GetRemainingLength(licenseStream) < cbProductId)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Product id:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbProductId);\n#endif\n\tStream_Seek(licenseStream, cbProductId);\n\n\t/* licenseInfo */\n\tif (Stream_GetRemainingLength(licenseStream) < 4)\n\t\tgoto out_free_stream;\n\tStream_Read_UINT32(licenseStream, cbLicenseInfo);\n\tif (Stream_GetRemainingLength(licenseStream) < cbLicenseInfo)\n\t\tgoto out_free_stream;\n\n\tlicense->state = LICENSE_STATE_COMPLETED;\n\n\tret = TRUE;\n\tif (!license->rdp->settings->OldLicenseBehaviour)\n\t\tret = saveCal(license->rdp->settings, Stream_Pointer(licenseStream), cbLicenseInfo,\n\t\t license->rdp->settings->ClientHostname);\n\nout_free_stream:\n\tStream_Free(licenseStream, FALSE);\nout_free_blob:\n\tlicense_free_binary_blob(calBlob);\n\treturn ret;\n}", "project": "FreeRDP", "hash": 119587276096900182263474845173512880982, "size": 100, "commit_id": "6ade7b4cbfd71c54b3d724e8f2d6ac76a58e879a", "message": "Fixed OOB Read in license_read_new_or_upgrade_license_packet\n\nCVE-2020-11099 thanks to @antonio-morales for finding this.", "target": 0, "dataset": "other", "idx": 399253} {"func": "int mutt_seqset_iterator_next(struct SeqsetIterator *iter, unsigned int *next)\n{\n if (!iter || !next)\n return -1;\n\n if (iter->in_range)\n {\n if ((iter->down && (iter->range_cur == (iter->range_end - 1))) ||\n (!iter->down && (iter->range_cur == (iter->range_end + 1))))\n {\n iter->in_range = 0;\n }\n }\n\n if (!iter->in_range)\n {\n iter->substr_cur = iter->substr_end;\n if (iter->substr_cur == iter->eostr)\n return 1;\n\n while (!*(iter->substr_cur))\n iter->substr_cur++;\n iter->substr_end = strchr(iter->substr_cur, ',');\n if (!iter->substr_end)\n iter->substr_end = iter->eostr;\n else\n *(iter->substr_end) = '\\0';\n\n char *range_sep = strchr(iter->substr_cur, ':');\n if (range_sep)\n *range_sep++ = '\\0';\n\n if (mutt_str_atoui(iter->substr_cur, &iter->range_cur) != 0)\n return -1;\n if (range_sep)\n {\n if (mutt_str_atoui(range_sep, &iter->range_end) != 0)\n return -1;\n }\n else\n iter->range_end = iter->range_cur;\n\n iter->down = (iter->range_end < iter->range_cur);\n iter->in_range = 1;\n }\n\n *next = iter->range_cur;\n if (iter->down)\n iter->range_cur--;\n else\n iter->range_cur++;\n\n return 0;\n}", "project": "neomutt", "hash": 255563423373473490710136560651315420142, "size": 54, "commit_id": "fa1db5785e5cfd9d3cd27b7571b9fe268d2ec2dc", "message": "Fix seqset iterator when it ends in a comma\n\nIf the seqset ended with a comma, the substr_end marker would be just\nbefore the trailing nul. In the next call, the loop to skip the\nmarker would iterate right past the end of string too.\n\nThe fix is simple: place the substr_end marker and skip past it\nimmediately.", "target": 1, "dataset": "other", "idx": 207568} {"func": "int mutt_seqset_iterator_next(struct SeqsetIterator *iter, unsigned int *next)\n{\n if (!iter || !next)\n return -1;\n\n if (iter->in_range)\n {\n if ((iter->down && (iter->range_cur == (iter->range_end - 1))) ||\n (!iter->down && (iter->range_cur == (iter->range_end + 1))))\n {\n iter->in_range = 0;\n }\n }\n\n if (!iter->in_range)\n {\n iter->substr_cur = iter->substr_end;\n if (iter->substr_cur == iter->eostr)\n return 1;\n\n iter->substr_end = strchr(iter->substr_cur, ',');\n if (!iter->substr_end)\n iter->substr_end = iter->eostr;\n else\n *(iter->substr_end++) = '\\0';\n\n char *range_sep = strchr(iter->substr_cur, ':');\n if (range_sep)\n *range_sep++ = '\\0';\n\n if (mutt_str_atoui(iter->substr_cur, &iter->range_cur) != 0)\n return -1;\n if (range_sep)\n {\n if (mutt_str_atoui(range_sep, &iter->range_end) != 0)\n return -1;\n }\n else\n iter->range_end = iter->range_cur;\n\n iter->down = (iter->range_end < iter->range_cur);\n iter->in_range = 1;\n }\n\n *next = iter->range_cur;\n if (iter->down)\n iter->range_cur--;\n else\n iter->range_cur++;\n\n return 0;\n}", "project": "neomutt", "hash": 234210525400853698338379777365300845795, "size": 52, "commit_id": "fa1db5785e5cfd9d3cd27b7571b9fe268d2ec2dc", "message": "Fix seqset iterator when it ends in a comma\n\nIf the seqset ended with a comma, the substr_end marker would be just\nbefore the trailing nul. In the next call, the loop to skip the\nmarker would iterate right past the end of string too.\n\nThe fix is simple: place the substr_end marker and skip past it\nimmediately.", "target": 0, "dataset": "other", "idx": 399279} {"func": "virtio_dev_rx_batch_packed(struct virtio_net *dev,\n\t\t\t struct vhost_virtqueue *vq,\n\t\t\t struct rte_mbuf **pkts)\n{\n\tbool wrap_counter = vq->avail_wrap_counter;\n\tstruct vring_packed_desc *descs = vq->desc_packed;\n\tuint16_t avail_idx = vq->last_avail_idx;\n\tuint64_t desc_addrs[PACKED_BATCH_SIZE];\n\tstruct virtio_net_hdr_mrg_rxbuf *hdrs[PACKED_BATCH_SIZE];\n\tuint32_t buf_offset = dev->vhost_hlen;\n\tuint64_t lens[PACKED_BATCH_SIZE];\n\tuint16_t ids[PACKED_BATCH_SIZE];\n\tuint16_t i;\n\n\tif (unlikely(avail_idx & PACKED_BATCH_MASK))\n\t\treturn -1;\n\n\tif (unlikely((avail_idx + PACKED_BATCH_SIZE) > vq->size))\n\t\treturn -1;\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(pkts[i]->next != NULL))\n\t\t\treturn -1;\n\t\tif (unlikely(!desc_is_avail(&descs[avail_idx + i],\n\t\t\t\t\t wrap_counter)))\n\t\t\treturn -1;\n\t}\n\n\trte_smp_rmb();\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tlens[i] = descs[avail_idx + i].len;\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(pkts[i]->pkt_len > (lens[i] - buf_offset)))\n\t\t\treturn -1;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tdesc_addrs[i] = vhost_iova_to_vva(dev, vq,\n\t\t\t\t\t\t descs[avail_idx + i].addr,\n\t\t\t\t\t\t &lens[i],\n\t\t\t\t\t\t VHOST_ACCESS_RW);\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(lens[i] != descs[avail_idx + i].len))\n\t\t\treturn -1;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\trte_prefetch0((void *)(uintptr_t)desc_addrs[i]);\n\t\thdrs[i] = (struct virtio_net_hdr_mrg_rxbuf *)\n\t\t\t\t\t(uintptr_t)desc_addrs[i];\n\t\tlens[i] = pkts[i]->pkt_len + dev->vhost_hlen;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tvirtio_enqueue_offload(pkts[i], &hdrs[i]->hdr);\n\n\tvq_inc_last_avail_packed(vq, PACKED_BATCH_SIZE);\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\trte_memcpy((void *)(uintptr_t)(desc_addrs[i] + buf_offset),\n\t\t\t rte_pktmbuf_mtod_offset(pkts[i], void *, 0),\n\t\t\t pkts[i]->pkt_len);\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tvhost_log_cache_write_iova(dev, vq, descs[avail_idx + i].addr,\n\t\t\t\t\t lens[i]);\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tids[i] = descs[avail_idx + i].id;\n\n\tvhost_flush_enqueue_batch_packed(dev, vq, lens, ids);\n\n\treturn 0;\n}", "project": "dpdk", "hash": 141015319348152109183918601798829151336, "size": 78, "commit_id": "97ecc1c85c95c13bc66a87435758e93406c35c48", "message": "vhost: fix translated address not checked\n\nMalicious guest can construct desc with invalid address and zero buffer\nlength. That will request vhost to check both translated address and\ntranslated data length. This patch will add missed address check.\n\nCVE-2020-10725\nFixes: 75ed51697820 (\"vhost: add packed ring batch dequeue\")\nFixes: ef861692c398 (\"vhost: add packed ring batch enqueue\")\nCc: stable@dpdk.org\n\nSigned-off-by: Marvin Liu \nReviewed-by: Maxime Coquelin ", "target": 1, "dataset": "other", "idx": 207646} {"func": "virtio_dev_rx_batch_packed(struct virtio_net *dev,\n\t\t\t struct vhost_virtqueue *vq,\n\t\t\t struct rte_mbuf **pkts)\n{\n\tbool wrap_counter = vq->avail_wrap_counter;\n\tstruct vring_packed_desc *descs = vq->desc_packed;\n\tuint16_t avail_idx = vq->last_avail_idx;\n\tuint64_t desc_addrs[PACKED_BATCH_SIZE];\n\tstruct virtio_net_hdr_mrg_rxbuf *hdrs[PACKED_BATCH_SIZE];\n\tuint32_t buf_offset = dev->vhost_hlen;\n\tuint64_t lens[PACKED_BATCH_SIZE];\n\tuint16_t ids[PACKED_BATCH_SIZE];\n\tuint16_t i;\n\n\tif (unlikely(avail_idx & PACKED_BATCH_MASK))\n\t\treturn -1;\n\n\tif (unlikely((avail_idx + PACKED_BATCH_SIZE) > vq->size))\n\t\treturn -1;\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(pkts[i]->next != NULL))\n\t\t\treturn -1;\n\t\tif (unlikely(!desc_is_avail(&descs[avail_idx + i],\n\t\t\t\t\t wrap_counter)))\n\t\t\treturn -1;\n\t}\n\n\trte_smp_rmb();\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tlens[i] = descs[avail_idx + i].len;\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(pkts[i]->pkt_len > (lens[i] - buf_offset)))\n\t\t\treturn -1;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tdesc_addrs[i] = vhost_iova_to_vva(dev, vq,\n\t\t\t\t\t\t descs[avail_idx + i].addr,\n\t\t\t\t\t\t &lens[i],\n\t\t\t\t\t\t VHOST_ACCESS_RW);\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\tif (unlikely(!desc_addrs[i]))\n\t\t\treturn -1;\n\t\tif (unlikely(lens[i] != descs[avail_idx + i].len))\n\t\t\treturn -1;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\trte_prefetch0((void *)(uintptr_t)desc_addrs[i]);\n\t\thdrs[i] = (struct virtio_net_hdr_mrg_rxbuf *)\n\t\t\t\t\t(uintptr_t)desc_addrs[i];\n\t\tlens[i] = pkts[i]->pkt_len + dev->vhost_hlen;\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tvirtio_enqueue_offload(pkts[i], &hdrs[i]->hdr);\n\n\tvq_inc_last_avail_packed(vq, PACKED_BATCH_SIZE);\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) {\n\t\trte_memcpy((void *)(uintptr_t)(desc_addrs[i] + buf_offset),\n\t\t\t rte_pktmbuf_mtod_offset(pkts[i], void *, 0),\n\t\t\t pkts[i]->pkt_len);\n\t}\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tvhost_log_cache_write_iova(dev, vq, descs[avail_idx + i].addr,\n\t\t\t\t\t lens[i]);\n\n\tvhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE)\n\t\tids[i] = descs[avail_idx + i].id;\n\n\tvhost_flush_enqueue_batch_packed(dev, vq, lens, ids);\n\n\treturn 0;\n}", "project": "dpdk", "hash": 198754053444601304377848158125427004349, "size": 80, "commit_id": "97ecc1c85c95c13bc66a87435758e93406c35c48", "message": "vhost: fix translated address not checked\n\nMalicious guest can construct desc with invalid address and zero buffer\nlength. That will request vhost to check both translated address and\ntranslated data length. This patch will add missed address check.\n\nCVE-2020-10725\nFixes: 75ed51697820 (\"vhost: add packed ring batch dequeue\")\nFixes: ef861692c398 (\"vhost: add packed ring batch enqueue\")\nCc: stable@dpdk.org\n\nSigned-off-by: Marvin Liu \nReviewed-by: Maxime Coquelin ", "target": 0, "dataset": "other", "idx": 399931} {"func": "parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,\n u_int *secondsp, int *confirmp, char **sk_providerp)\n{\n\tu_char ctype;\n\tint r;\n\tu_int seconds, maxsign = 0;\n\tchar *ext_name = NULL;\n\tstruct sshbuf *b = NULL;\n\n\twhile (sshbuf_len(m)) {\n\t\tif ((r = sshbuf_get_u8(m, &ctype)) != 0) {\n\t\t\terror_fr(r, \"parse constraint type\");\n\t\t\tgoto err;\n\t\t}\n\t\tswitch (ctype) {\n\t\tcase SSH_AGENT_CONSTRAIN_LIFETIME:\n\t\t\tif (*deathp != 0) {\n\t\t\t\terror_f(\"lifetime already set\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tif ((r = sshbuf_get_u32(m, &seconds)) != 0) {\n\t\t\t\terror_fr(r, \"parse lifetime constraint\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\t*deathp = monotime() + seconds;\n\t\t\t*secondsp = seconds;\n\t\t\tbreak;\n\t\tcase SSH_AGENT_CONSTRAIN_CONFIRM:\n\t\t\tif (*confirmp != 0) {\n\t\t\t\terror_f(\"confirm already set\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\t*confirmp = 1;\n\t\t\tbreak;\n\t\tcase SSH_AGENT_CONSTRAIN_MAXSIGN:\n\t\t\tif (k == NULL) {\n\t\t\t\terror_f(\"maxsign not valid here\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tif (maxsign != 0) {\n\t\t\t\terror_f(\"maxsign already set\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tif ((r = sshbuf_get_u32(m, &maxsign)) != 0) {\n\t\t\t\terror_fr(r, \"parse maxsign constraint\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tif ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {\n\t\t\t\terror_fr(r, \"enable maxsign\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SSH_AGENT_CONSTRAIN_EXTENSION:\n\t\t\tif ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {\n\t\t\t\terror_fr(r, \"parse constraint extension\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tdebug_f(\"constraint ext %s\", ext_name);\n\t\t\tif (strcmp(ext_name, \"sk-provider@openssh.com\") == 0) {\n\t\t\t\tif (sk_providerp == NULL) {\n\t\t\t\t\terror_f(\"%s not valid here\", ext_name);\n\t\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t\tif (*sk_providerp != NULL) {\n\t\t\t\t\terror_f(\"%s already set\", ext_name);\n\t\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t\tif ((r = sshbuf_get_cstring(m,\n\t\t\t\t sk_providerp, NULL)) != 0) {\n\t\t\t\t\terror_fr(r, \"parse %s\", ext_name);\n\t\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terror_f(\"unsupported constraint \\\"%s\\\"\",\n\t\t\t\t ext_name);\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tfree(ext_name);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terror_f(\"Unknown constraint %d\", ctype);\n err:\n\t\t\tfree(ext_name);\n\t\t\tsshbuf_free(b);\n\t\t\treturn -1;\n\t\t}\n\t}\n\t/* success */\n\treturn 0;\n}", "project": "openssh-portable", "hash": 68211468467426422101137350916636802558, "size": 90, "commit_id": "e04fd6dde16de1cdc5a4d9946397ff60d96568db", "message": "upstream: factor SSH_AGENT_CONSTRAIN_EXTENSION parsing into its own\n\nfunction and remove an unused variable; ok dtucker@\n\nOpenBSD-Commit-ID: e1a938657fbf7ef0ba5e73b30365734a0cc96559", "target": 1, "dataset": "other", "idx": 207709} {"func": "parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,\n u_int *secondsp, int *confirmp, char **sk_providerp)\n{\n\tu_char ctype;\n\tint r;\n\tu_int seconds, maxsign = 0;\n\n\twhile (sshbuf_len(m)) {\n\t\tif ((r = sshbuf_get_u8(m, &ctype)) != 0) {\n\t\t\terror_fr(r, \"parse constraint type\");\n\t\t\tgoto out;\n\t\t}\n\t\tswitch (ctype) {\n\t\tcase SSH_AGENT_CONSTRAIN_LIFETIME:\n\t\t\tif (*deathp != 0) {\n\t\t\t\terror_f(\"lifetime already set\");\n\t\t\t\tr = SSH_ERR_INVALID_FORMAT;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tif ((r = sshbuf_get_u32(m, &seconds)) != 0) {\n\t\t\t\terror_fr(r, \"parse lifetime constraint\");\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\t*deathp = monotime() + seconds;\n\t\t\t*secondsp = seconds;\n\t\t\tbreak;\n\t\tcase SSH_AGENT_CONSTRAIN_CONFIRM:\n\t\t\tif (*confirmp != 0) {\n\t\t\t\terror_f(\"confirm already set\");\n\t\t\t\tr = SSH_ERR_INVALID_FORMAT;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\t*confirmp = 1;\n\t\t\tbreak;\n\t\tcase SSH_AGENT_CONSTRAIN_MAXSIGN:\n\t\t\tif (k == NULL) {\n\t\t\t\terror_f(\"maxsign not valid here\");\n\t\t\t\tr = SSH_ERR_INVALID_FORMAT;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tif (maxsign != 0) {\n\t\t\t\terror_f(\"maxsign already set\");\n\t\t\t\tr = SSH_ERR_INVALID_FORMAT;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tif ((r = sshbuf_get_u32(m, &maxsign)) != 0) {\n\t\t\t\terror_fr(r, \"parse maxsign constraint\");\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tif ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {\n\t\t\t\terror_fr(r, \"enable maxsign\");\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SSH_AGENT_CONSTRAIN_EXTENSION:\n\t\t\tif ((r = parse_key_constraint_extension(m,\n\t\t\t sk_providerp)) != 0)\n\t\t\t\tgoto out; /* error already logged */\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terror_f(\"Unknown constraint %d\", ctype);\n\t\t\tr = SSH_ERR_FEATURE_UNSUPPORTED;\n\t\t\tgoto out;\n\t\t}\n\t}\n\t/* success */\n\tr = 0;\n out:\n\treturn r;\n}", "project": "openssh-portable", "hash": 302547089865800792591833484855608026826, "size": 70, "commit_id": "e04fd6dde16de1cdc5a4d9946397ff60d96568db", "message": "upstream: factor SSH_AGENT_CONSTRAIN_EXTENSION parsing into its own\n\nfunction and remove an unused variable; ok dtucker@\n\nOpenBSD-Commit-ID: e1a938657fbf7ef0ba5e73b30365734a0cc96559", "target": 0, "dataset": "other", "idx": 400219} {"func": "z_jbig2decode(i_ctx_t * i_ctx_p)\n{\n os_ptr op = osp;\n ref *sop = NULL;\n s_jbig2_global_data_t *gref;\n stream_jbig2decode_state state;\n\n /* Extract the global context reference, if any, from the parameter\n dictionary and embed it in our stream state. The original object\n ref is under the JBIG2Globals key.\n We expect the postscript code to resolve this and call\n z_jbig2makeglobalctx() below to create an astruct wrapping the\n global decoder data and store it under the .jbig2globalctx key\n */\n s_jbig2decode_set_global_data((stream_state*)&state, NULL);\n if (r_has_type(op, t_dictionary)) {\n check_dict_read(*op);\n if ( dict_find_string(op, \".jbig2globalctx\", &sop) > 0) {\n gref = r_ptr(sop, s_jbig2_global_data_t);\n s_jbig2decode_set_global_data((stream_state*)&state, gref);\n }\n }\n\n /* we pass npop=0, since we've no arguments left to consume */\n return filter_read(i_ctx_p, 0, &s_jbig2decode_template,\n (stream_state *) & state, (sop ? r_space(sop) : 0));\n}", "project": "ghostpdl", "hash": 196694238274389223071484648318752658727, "size": 27, "commit_id": "ef252e7dc214bcbd9a2539216aab9202848602bb", "message": "Bug #700168 - add a type check\n\nBug #700168 \"Type confusion in JBIG2Decode\"\n\nThe code was assuming that .jbig2globalctx was a structure allocated\nby the graphics library, without checking.\n\nAdd a check to see that it is a structure and that its the correct\ntype of structure.", "target": 1, "dataset": "other", "idx": 207760} {"func": "z_jbig2decode(i_ctx_t * i_ctx_p)\n{\n os_ptr op = osp;\n ref *sop = NULL;\n s_jbig2_global_data_t *gref;\n stream_jbig2decode_state state;\n\n /* Extract the global context reference, if any, from the parameter\n dictionary and embed it in our stream state. The original object\n ref is under the JBIG2Globals key.\n We expect the postscript code to resolve this and call\n z_jbig2makeglobalctx() below to create an astruct wrapping the\n global decoder data and store it under the .jbig2globalctx key\n */\n s_jbig2decode_set_global_data((stream_state*)&state, NULL);\n if (r_has_type(op, t_dictionary)) {\n check_dict_read(*op);\n if ( dict_find_string(op, \".jbig2globalctx\", &sop) > 0) {\n if (!r_is_struct(sop) || !r_has_stype(sop, imemory, st_jbig2_global_data_t))\n return_error(gs_error_typecheck);\n gref = r_ptr(sop, s_jbig2_global_data_t);\n s_jbig2decode_set_global_data((stream_state*)&state, gref);\n }\n }\n\n /* we pass npop=0, since we've no arguments left to consume */\n return filter_read(i_ctx_p, 0, &s_jbig2decode_template,\n (stream_state *) & state, (sop ? r_space(sop) : 0));\n}", "project": "ghostpdl", "hash": 88125760258340032082692592349055443353, "size": 29, "commit_id": "ef252e7dc214bcbd9a2539216aab9202848602bb", "message": "Bug #700168 - add a type check\n\nBug #700168 \"Type confusion in JBIG2Decode\"\n\nThe code was assuming that .jbig2globalctx was a structure allocated\nby the graphics library, without checking.\n\nAdd a check to see that it is a structure and that its the correct\ntype of structure.", "target": 0, "dataset": "other", "idx": 400829} {"func": "ReadFromRFBServer(rfbClient* client, char *out, unsigned int n)\n{\n#undef DEBUG_READ_EXACT\n#ifdef DEBUG_READ_EXACT\n\tchar* oout=out;\n\tunsigned int nn=n;\n\trfbClientLog(\"ReadFromRFBServer %d bytes\\n\",n);\n#endif\n\n /* Handle attempts to write to NULL out buffer that might occur\n when an outside malloc() fails. For instance, memcpy() to NULL\n results in undefined behaviour and probably memory corruption.*/\n if(!out)\n return FALSE;\n\n if (client->serverPort==-1) {\n /* vncrec playing */\n rfbVNCRec* rec = client->vncRec;\n struct timeval tv;\n\n if (rec->readTimestamp) {\n rec->readTimestamp = FALSE;\n if (!fread(&tv,sizeof(struct timeval),1,rec->file))\n return FALSE;\n\n tv.tv_sec = rfbClientSwap32IfLE (tv.tv_sec);\n tv.tv_usec = rfbClientSwap32IfLE (tv.tv_usec);\n\n if (rec->tv.tv_sec!=0 && !rec->doNotSleep) {\n struct timeval diff;\n diff.tv_sec = tv.tv_sec - rec->tv.tv_sec;\n diff.tv_usec = tv.tv_usec - rec->tv.tv_usec;\n if(diff.tv_usec<0) {\n\t diff.tv_sec--;\n\t diff.tv_usec+=1000000;\n }\n#ifndef WIN32\n sleep (diff.tv_sec);\n usleep (diff.tv_usec);\n#else\n\tSleep (diff.tv_sec * 1000 + diff.tv_usec/1000);\n#endif\n }\n\n rec->tv=tv;\n }\n \n return (fread(out,1,n,rec->file) != n ? FALSE : TRUE);\n }\n \n if (n <= client->buffered) {\n memcpy(out, client->bufoutptr, n);\n client->bufoutptr += n;\n client->buffered -= n;\n#ifdef DEBUG_READ_EXACT\n goto hexdump;\n#endif\n return TRUE;\n }\n\n memcpy(out, client->bufoutptr, client->buffered);\n\n out += client->buffered;\n n -= client->buffered;\n\n client->bufoutptr = client->buf;\n client->buffered = 0;\n\n if (n <= RFB_BUF_SIZE) {\n\n while (client->buffered < n) {\n int i;\n if (client->tlsSession)\n i = ReadFromTLS(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n else\n#ifdef LIBVNCSERVER_HAVE_SASL\n if (client->saslconn)\n i = ReadFromSASL(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n else {\n#endif /* LIBVNCSERVER_HAVE_SASL */\n i = read(client->sock, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n#ifdef WIN32\n\tif (i < 0) errno=WSAGetLastError();\n#endif\n#ifdef LIBVNCSERVER_HAVE_SASL\n }\n#endif\n \n if (i <= 0) {\n\tif (i < 0) {\n\t if (errno == EWOULDBLOCK || errno == EAGAIN) {\n\t /* TODO:\n\t ProcessXtEvents();\n\t */\n\t WaitForMessage(client, 100000);\n\t i = 0;\n\t } else {\n\t rfbClientErr(\"read (%d: %s)\\n\",errno,strerror(errno));\n\t return FALSE;\n\t }\n\t} else {\n\t if (errorMessageOnReadFailure) {\n\t rfbClientLog(\"VNC server closed connection\\n\");\n\t }\n\t return FALSE;\n\t}\n }\n client->buffered += i;\n }\n\n memcpy(out, client->bufoutptr, n);\n client->bufoutptr += n;\n client->buffered -= n;\n\n } else {\n\n while (n > 0) {\n int i;\n if (client->tlsSession)\n i = ReadFromTLS(client, out, n);\n else\n#ifdef LIBVNCSERVER_HAVE_SASL\n if (client->saslconn)\n i = ReadFromSASL(client, out, n);\n else\n#endif\n i = read(client->sock, out, n);\n\n if (i <= 0) {\n\tif (i < 0) {\n#ifdef WIN32\n\t errno=WSAGetLastError();\n#endif\n\t if (errno == EWOULDBLOCK || errno == EAGAIN) {\n\t /* TODO:\n\t ProcessXtEvents();\n\t */\n\t WaitForMessage(client, 100000);\n\t i = 0;\n\t } else {\n\t rfbClientErr(\"read (%s)\\n\",strerror(errno));\n\t return FALSE;\n\t }\n\t} else {\n\t if (errorMessageOnReadFailure) {\n\t rfbClientLog(\"VNC server closed connection\\n\");\n\t }\n\t return FALSE;\n\t}\n }\n out += i;\n n -= i;\n }\n }\n\n#ifdef DEBUG_READ_EXACT\nhexdump:\n { unsigned int ii;\n for(ii=0;iiserverPort==-1) {\n /* vncrec playing */\n rfbVNCRec* rec = client->vncRec;\n struct timeval tv;\n\n if (rec->readTimestamp) {\n rec->readTimestamp = FALSE;\n if (!fread(&tv,sizeof(struct timeval),1,rec->file))\n return FALSE;\n\n tv.tv_sec = rfbClientSwap32IfLE (tv.tv_sec);\n tv.tv_usec = rfbClientSwap32IfLE (tv.tv_usec);\n\n if (rec->tv.tv_sec!=0 && !rec->doNotSleep) {\n struct timeval diff;\n diff.tv_sec = tv.tv_sec - rec->tv.tv_sec;\n diff.tv_usec = tv.tv_usec - rec->tv.tv_usec;\n if(diff.tv_usec<0) {\n\t diff.tv_sec--;\n\t diff.tv_usec+=1000000;\n }\n#ifndef WIN32\n sleep (diff.tv_sec);\n usleep (diff.tv_usec);\n#else\n\tSleep (diff.tv_sec * 1000 + diff.tv_usec/1000);\n#endif\n }\n\n rec->tv=tv;\n }\n \n return (fread(out,1,n,rec->file) != n ? FALSE : TRUE);\n }\n \n if (n <= client->buffered) {\n memcpy(out, client->bufoutptr, n);\n client->bufoutptr += n;\n client->buffered -= n;\n#ifdef DEBUG_READ_EXACT\n goto hexdump;\n#endif\n return TRUE;\n }\n\n memcpy(out, client->bufoutptr, client->buffered);\n\n out += client->buffered;\n n -= client->buffered;\n\n client->bufoutptr = client->buf;\n client->buffered = 0;\n\n if (n <= RFB_BUF_SIZE) {\n\n while (client->buffered < n) {\n int i;\n if (client->tlsSession)\n i = ReadFromTLS(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n else\n#ifdef LIBVNCSERVER_HAVE_SASL\n if (client->saslconn)\n i = ReadFromSASL(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n else {\n#endif /* LIBVNCSERVER_HAVE_SASL */\n i = read(client->sock, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);\n#ifdef WIN32\n\tif (i < 0) errno=WSAGetLastError();\n#endif\n#ifdef LIBVNCSERVER_HAVE_SASL\n }\n#endif\n \n if (i <= 0) {\n\tif (i < 0) {\n\t if (errno == EWOULDBLOCK || errno == EAGAIN) {\n\t if (client->readTimeout > 0 &&\n\t\t++retries > (client->readTimeout * 1000 * 1000 / USECS_WAIT_PER_RETRY))\n\t {\n\t rfbClientLog(\"Connection timed out\\n\");\n\t return FALSE;\n\t }\n\t /* TODO:\n\t ProcessXtEvents();\n\t */\n\t WaitForMessage(client, USECS_WAIT_PER_RETRY);\n\t i = 0;\n\t } else {\n\t rfbClientErr(\"read (%d: %s)\\n\",errno,strerror(errno));\n\t return FALSE;\n\t }\n\t} else {\n\t if (errorMessageOnReadFailure) {\n\t rfbClientLog(\"VNC server closed connection\\n\");\n\t }\n\t return FALSE;\n\t}\n }\n client->buffered += i;\n }\n\n memcpy(out, client->bufoutptr, n);\n client->bufoutptr += n;\n client->buffered -= n;\n\n } else {\n\n while (n > 0) {\n int i;\n if (client->tlsSession)\n i = ReadFromTLS(client, out, n);\n else\n#ifdef LIBVNCSERVER_HAVE_SASL\n if (client->saslconn)\n i = ReadFromSASL(client, out, n);\n else\n#endif\n i = read(client->sock, out, n);\n\n if (i <= 0) {\n\tif (i < 0) {\n#ifdef WIN32\n\t errno=WSAGetLastError();\n#endif\n\t if (errno == EWOULDBLOCK || errno == EAGAIN) {\n\t if (client->readTimeout > 0 &&\n\t\t++retries > (client->readTimeout * 1000 * 1000 / USECS_WAIT_PER_RETRY))\n\t {\n\t\trfbClientLog(\"Connection timed out\\n\");\n\t\treturn FALSE;\n\t }\n\t /* TODO:\n\t ProcessXtEvents();\n\t */\n\t WaitForMessage(client, USECS_WAIT_PER_RETRY);\n\t i = 0;\n\t } else {\n\t rfbClientErr(\"read (%s)\\n\",strerror(errno));\n\t return FALSE;\n\t }\n\t} else {\n\t if (errorMessageOnReadFailure) {\n\t rfbClientLog(\"VNC server closed connection\\n\");\n\t }\n\t return FALSE;\n\t}\n }\n out += i;\n n -= i;\n }\n }\n\n#ifdef DEBUG_READ_EXACT\nhexdump:\n { unsigned int ii;\n for(ii=0;ii= rowDelta)\n\t\t\t{\n\t\t\t\tfFirstLine = FALSE;\n\t\t\t\tfInsertFgPel = FALSE;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t Extract the compression order code ID from the compression\n\t\t order header.\n\t\t*/\n\t\tcode = ExtractCodeId(*pbSrc);\n\n\t\t/* Handle Background Run Orders. */\n\t\tif (code == REGULAR_BG_RUN || code == MEGA_MEGA_BG_RUN)\n\t\t{\n\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\tpbSrc = pbSrc + advance;\n\n\t\t\tif (fFirstLine)\n\t\t\t{\n\t\t\t\tif (fInsertFgPel)\n\t\t\t\t{\n\t\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, fgPel);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\trunLength = runLength - 1;\n\t\t\t\t}\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, BLACK_PIXEL);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (fInsertFgPel)\n\t\t\t\t{\n\t\t\t\t\tDESTREADPIXEL(temp, pbDest - rowDelta);\n\n\t\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp ^ fgPel);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\trunLength--;\n\t\t\t\t}\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTREADPIXEL(temp, pbDest - rowDelta);\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t/* A follow-on background run order will need a foreground pel inserted. */\n\t\t\tfInsertFgPel = TRUE;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* For any of the other run-types a follow-on background run\n\t\t order does not need a foreground pel inserted. */\n\t\tfInsertFgPel = FALSE;\n\n\t\tswitch (code)\n\t\t{\n\t\t\t/* Handle Foreground Run Orders. */\n\t\t\tcase REGULAR_FG_RUN:\n\t\t\tcase MEGA_MEGA_FG_RUN:\n\t\t\tcase LITE_SET_FG_FG_RUN:\n\t\t\tcase MEGA_MEGA_SET_FG_RUN:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\n\t\t\t\tif (code == LITE_SET_FG_FG_RUN || code == MEGA_MEGA_SET_FG_RUN)\n\t\t\t\t{\n\t\t\t\t\tSRCREADPIXEL(fgPel, pbSrc);\n\t\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\t}\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\t\tDESTWRITEPIXEL(pbDest, fgPel);\n\t\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\t\tDESTREADPIXEL(temp, pbDest - rowDelta);\n\t\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp ^ fgPel);\n\t\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Dithered Run Orders. */\n\t\t\tcase LITE_DITHERED_RUN:\n\t\t\tcase MEGA_MEGA_DITHERED_RUN:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\t\t\t\tSRCREADPIXEL(pixelA, pbSrc);\n\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\tSRCREADPIXEL(pixelB, pbSrc);\n\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength * 2))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, pixelA);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, pixelB);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Color Run Orders. */\n\t\t\tcase REGULAR_COLOR_RUN:\n\t\t\tcase MEGA_MEGA_COLOR_RUN:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\t\t\t\tSRCREADPIXEL(pixelA, pbSrc);\n\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, pixelA);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Foreground/Background Image Orders. */\n\t\t\tcase REGULAR_FGBG_IMAGE:\n\t\t\tcase MEGA_MEGA_FGBG_IMAGE:\n\t\t\tcase LITE_SET_FG_FGBG_IMAGE:\n\t\t\tcase MEGA_MEGA_SET_FGBG_IMAGE:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\n\t\t\t\tif (code == LITE_SET_FG_FGBG_IMAGE || code == MEGA_MEGA_SET_FGBG_IMAGE)\n\t\t\t\t{\n\t\t\t\t\tSRCREADPIXEL(fgPel, pbSrc);\n\t\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\t}\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\twhile (runLength > 8)\n\t\t\t\t\t{\n\t\t\t\t\t\tbitmask = *pbSrc;\n\t\t\t\t\t\tpbSrc = pbSrc + 1;\n\t\t\t\t\t\tpbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, 8);\n\n\t\t\t\t\t\tif (!pbDest)\n\t\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\t\trunLength = runLength - 8;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\twhile (runLength > 8)\n\t\t\t\t\t{\n\t\t\t\t\t\tbitmask = *pbSrc;\n\t\t\t\t\t\tpbSrc = pbSrc + 1;\n\t\t\t\t\t\tpbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, 8);\n\n\t\t\t\t\t\tif (!pbDest)\n\t\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\t\trunLength = runLength - 8;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (runLength > 0)\n\t\t\t\t{\n\t\t\t\t\tbitmask = *pbSrc;\n\t\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\t\tif (fFirstLine)\n\t\t\t\t\t{\n\t\t\t\t\t\tpbDest =\n\t\t\t\t\t\t WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, runLength);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tpbDest =\n\t\t\t\t\t\t WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, runLength);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!pbDest)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Color Image Orders. */\n\t\t\tcase REGULAR_COLOR_IMAGE:\n\t\t\tcase MEGA_MEGA_COLOR_IMAGE:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tSRCREADPIXEL(temp, pbSrc);\n\t\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Special Order 1. */\n\t\t\tcase SPECIAL_FGBG_1:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg1, fgPel, 8);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg1, fgPel, 8);\n\t\t\t\t}\n\n\t\t\t\tif (!pbDest)\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Special Order 2. */\n\t\t\tcase SPECIAL_FGBG_2:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg2, fgPel, 8);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg2, fgPel, 8);\n\t\t\t\t}\n\n\t\t\t\tif (!pbDest)\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle White Order. */\n\t\t\tcase SPECIAL_WHITE:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tDESTWRITEPIXEL(pbDest, WHITE_PIXEL);\n\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Black Order. */\n\t\t\tcase SPECIAL_BLACK:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tDESTWRITEPIXEL(pbDest, BLACK_PIXEL);\n\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\treturn TRUE;\n}", "project": "FreeRDP", "hash": 9826210098596619583118666328681710851, "size": 329, "commit_id": "0a98c450c58ec150e44781c89aa6f8e7e0f571f5", "message": "Fixed out of bound read in RLEDECOMPRESS\n\nCVE-2020-4033 thanks to @antonio-morales for finding this.", "target": 1, "dataset": "other", "idx": 207836} {"func": "static INLINE BOOL RLEDECOMPRESS(const BYTE* pbSrcBuffer, UINT32 cbSrcBuffer, BYTE* pbDestBuffer,\n UINT32 rowDelta, UINT32 width, UINT32 height)\n{\n\tconst BYTE* pbSrc = pbSrcBuffer;\n\tconst BYTE* pbEnd;\n\tconst BYTE* pbDestEnd;\n\tBYTE* pbDest = pbDestBuffer;\n\tPIXEL temp;\n\tPIXEL fgPel = WHITE_PIXEL;\n\tBOOL fInsertFgPel = FALSE;\n\tBOOL fFirstLine = TRUE;\n\tBYTE bitmask;\n\tPIXEL pixelA, pixelB;\n\tUINT32 runLength;\n\tUINT32 code;\n\tUINT32 advance;\n\tRLEEXTRA\n\n\tif ((rowDelta == 0) || (rowDelta < width))\n\t\treturn FALSE;\n\n\tif (!pbSrcBuffer || !pbDestBuffer)\n\t\treturn FALSE;\n\n\tpbEnd = pbSrcBuffer + cbSrcBuffer;\n\tpbDestEnd = pbDestBuffer + rowDelta * height;\n\n\twhile (pbSrc < pbEnd)\n\t{\n\t\t/* Watch out for the end of the first scanline. */\n\t\tif (fFirstLine)\n\t\t{\n\t\t\tif ((UINT32)(pbDest - pbDestBuffer) >= rowDelta)\n\t\t\t{\n\t\t\t\tfFirstLine = FALSE;\n\t\t\t\tfInsertFgPel = FALSE;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t Extract the compression order code ID from the compression\n\t\t order header.\n\t\t*/\n\t\tcode = ExtractCodeId(*pbSrc);\n\n\t\t/* Handle Background Run Orders. */\n\t\tif (code == REGULAR_BG_RUN || code == MEGA_MEGA_BG_RUN)\n\t\t{\n\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\tpbSrc = pbSrc + advance;\n\n\t\t\tif (fFirstLine)\n\t\t\t{\n\t\t\t\tif (fInsertFgPel)\n\t\t\t\t{\n\t\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, fgPel);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\trunLength = runLength - 1;\n\t\t\t\t}\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, BLACK_PIXEL);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (fInsertFgPel)\n\t\t\t\t{\n\t\t\t\t\tDESTREADPIXEL(temp, pbDest - rowDelta);\n\n\t\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp ^ fgPel);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\trunLength--;\n\t\t\t\t}\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTREADPIXEL(temp, pbDest - rowDelta);\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t/* A follow-on background run order will need a foreground pel inserted. */\n\t\t\tfInsertFgPel = TRUE;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* For any of the other run-types a follow-on background run\n\t\t order does not need a foreground pel inserted. */\n\t\tfInsertFgPel = FALSE;\n\n\t\tswitch (code)\n\t\t{\n\t\t\t/* Handle Foreground Run Orders. */\n\t\t\tcase REGULAR_FG_RUN:\n\t\t\tcase MEGA_MEGA_FG_RUN:\n\t\t\tcase LITE_SET_FG_FG_RUN:\n\t\t\tcase MEGA_MEGA_SET_FG_RUN:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\n\t\t\t\tif (code == LITE_SET_FG_FG_RUN || code == MEGA_MEGA_SET_FG_RUN)\n\t\t\t\t{\n\t\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\tSRCREADPIXEL(fgPel, pbSrc);\n\t\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\t}\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\t\tDESTWRITEPIXEL(pbDest, fgPel);\n\t\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\t\tDESTREADPIXEL(temp, pbDest - rowDelta);\n\t\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp ^ fgPel);\n\t\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Dithered Run Orders. */\n\t\t\tcase LITE_DITHERED_RUN:\n\t\t\tcase MEGA_MEGA_DITHERED_RUN:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\treturn FALSE;\n\t\t\t\tSRCREADPIXEL(pixelA, pbSrc);\n\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\treturn FALSE;\n\t\t\t\tSRCREADPIXEL(pixelB, pbSrc);\n\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength * 2))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, pixelA);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, pixelB);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Color Run Orders. */\n\t\t\tcase REGULAR_COLOR_RUN:\n\t\t\tcase MEGA_MEGA_COLOR_RUN:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\treturn FALSE;\n\t\t\t\tSRCREADPIXEL(pixelA, pbSrc);\n\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, pixelA);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Foreground/Background Image Orders. */\n\t\t\tcase REGULAR_FGBG_IMAGE:\n\t\t\tcase MEGA_MEGA_FGBG_IMAGE:\n\t\t\tcase LITE_SET_FG_FGBG_IMAGE:\n\t\t\tcase MEGA_MEGA_SET_FGBG_IMAGE:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\n\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\treturn FALSE;\n\t\t\t\tif (code == LITE_SET_FG_FGBG_IMAGE || code == MEGA_MEGA_SET_FGBG_IMAGE)\n\t\t\t\t{\n\t\t\t\t\tSRCREADPIXEL(fgPel, pbSrc);\n\t\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\t}\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\twhile (runLength > 8)\n\t\t\t\t\t{\n\t\t\t\t\t\tbitmask = *pbSrc;\n\t\t\t\t\t\tpbSrc = pbSrc + 1;\n\t\t\t\t\t\tpbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, 8);\n\n\t\t\t\t\t\tif (!pbDest)\n\t\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\t\trunLength = runLength - 8;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\twhile (runLength > 8)\n\t\t\t\t\t{\n\t\t\t\t\t\tbitmask = *pbSrc;\n\t\t\t\t\t\tpbSrc = pbSrc + 1;\n\t\t\t\t\t\tpbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, 8);\n\n\t\t\t\t\t\tif (!pbDest)\n\t\t\t\t\t\t\treturn FALSE;\n\n\t\t\t\t\t\trunLength = runLength - 8;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (runLength > 0)\n\t\t\t\t{\n\t\t\t\t\tbitmask = *pbSrc;\n\t\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\t\tif (fFirstLine)\n\t\t\t\t\t{\n\t\t\t\t\t\tpbDest =\n\t\t\t\t\t\t WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, runLength);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tpbDest =\n\t\t\t\t\t\t WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, runLength);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!pbDest)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Color Image Orders. */\n\t\t\tcase REGULAR_COLOR_IMAGE:\n\t\t\tcase MEGA_MEGA_COLOR_IMAGE:\n\t\t\t\trunLength = ExtractRunLength(code, pbSrc, &advance);\n\t\t\t\tpbSrc = pbSrc + advance;\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tUNROLL(runLength, {\n\t\t\t\t\tif (pbSrc >= pbEnd)\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t\tSRCREADPIXEL(temp, pbSrc);\n\t\t\t\t\tSRCNEXTPIXEL(pbSrc);\n\t\t\t\t\tDESTWRITEPIXEL(pbDest, temp);\n\t\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Special Order 1. */\n\t\t\tcase SPECIAL_FGBG_1:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg1, fgPel, 8);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg1, fgPel, 8);\n\t\t\t\t}\n\n\t\t\t\tif (!pbDest)\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Special Order 2. */\n\t\t\tcase SPECIAL_FGBG_2:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (fFirstLine)\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg2, fgPel, 8);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpbDest =\n\t\t\t\t\t WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg2, fgPel, 8);\n\t\t\t\t}\n\n\t\t\t\tif (!pbDest)\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tbreak;\n\n\t\t\t/* Handle White Order. */\n\t\t\tcase SPECIAL_WHITE:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tDESTWRITEPIXEL(pbDest, WHITE_PIXEL);\n\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\tbreak;\n\n\t\t\t/* Handle Black Order. */\n\t\t\tcase SPECIAL_BLACK:\n\t\t\t\tpbSrc = pbSrc + 1;\n\n\t\t\t\tif (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))\n\t\t\t\t\treturn FALSE;\n\n\t\t\t\tDESTWRITEPIXEL(pbDest, BLACK_PIXEL);\n\t\t\t\tDESTNEXTPIXEL(pbDest);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\treturn TRUE;\n}", "project": "FreeRDP", "hash": 37817883328068271668101554775017217633, "size": 341, "commit_id": "0a98c450c58ec150e44781c89aa6f8e7e0f571f5", "message": "Fixed out of bound read in RLEDECOMPRESS\n\nCVE-2020-4033 thanks to @antonio-morales for finding this.", "target": 0, "dataset": "other", "idx": 402135} {"func": "static int vcf_parse_format(kstring_t *s, const bcf_hdr_t *h, bcf1_t *v, char *p, char *q)\n{\n if ( !bcf_hdr_nsamples(h) ) return 0;\n\n static int extreme_val_warned = 0;\n char *r, *t;\n int j, l, m, g, overflow = 0;\n khint_t k;\n ks_tokaux_t aux1;\n vdict_t *d = (vdict_t*)h->dict[BCF_DT_ID];\n kstring_t *mem = (kstring_t*)&h->mem;\n fmt_aux_t fmt[MAX_N_FMT];\n mem->l = 0;\n\n char *end = s->s + s->l;\n if ( q>=end )\n {\n hts_log_error(\"FORMAT column with no sample columns starting at %s:%\"PRIhts_pos\"\", bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_NCOLS;\n return -1;\n }\n\n v->n_fmt = 0;\n if ( p[0]=='.' && p[1]==0 ) // FORMAT field is empty \".\"\n {\n v->n_sample = bcf_hdr_nsamples(h);\n return 0;\n }\n\n // get format information from the dictionary\n for (j = 0, t = kstrtok(p, \":\", &aux1); t; t = kstrtok(0, 0, &aux1), ++j) {\n if (j >= MAX_N_FMT) {\n v->errcode |= BCF_ERR_LIMITS;\n hts_log_error(\"FORMAT column at %s:%\"PRIhts_pos\" lists more identifiers than htslib can handle\",\n bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n\n *(char*)aux1.p = 0;\n k = kh_get(vdict, d, t);\n if (k == kh_end(d) || kh_val(d, k).info[BCF_HL_FMT] == 15) {\n if ( t[0]=='.' && t[1]==0 )\n {\n hts_log_error(\"Invalid FORMAT tag name '.' at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n hts_log_warning(\"FORMAT '%s' at %s:%\"PRIhts_pos\" is not defined in the header, assuming Type=String\", t, bcf_seqname_safe(h,v), v->pos+1);\n kstring_t tmp = {0,0,0};\n int l;\n ksprintf(&tmp, \"##FORMAT=\", t);\n bcf_hrec_t *hrec = bcf_hdr_parse_line(h,tmp.s,&l);\n free(tmp.s);\n int res = hrec ? bcf_hdr_add_hrec((bcf_hdr_t*)h, hrec) : -1;\n if (res < 0) bcf_hrec_destroy(hrec);\n if (res > 0) res = bcf_hdr_sync((bcf_hdr_t*)h);\n\n k = kh_get(vdict, d, t);\n v->errcode = BCF_ERR_TAG_UNDEF;\n if (res || k == kh_end(d)) {\n hts_log_error(\"Could not add dummy header for FORMAT '%s' at %s:%\"PRIhts_pos, t, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n }\n fmt[j].max_l = fmt[j].max_m = fmt[j].max_g = 0;\n fmt[j].key = kh_val(d, k).id;\n fmt[j].is_gt = !strcmp(t, \"GT\");\n fmt[j].y = h->id[0][fmt[j].key].val->info[BCF_HL_FMT];\n v->n_fmt++;\n }\n // compute max\n int n_sample_ori = -1;\n r = q + 1; // r: position in the format string\n l = 0, m = g = 1, v->n_sample = 0; // m: max vector size, l: max field len, g: max number of alleles\n while ( rkeep_samples )\n {\n n_sample_ori++;\n if ( !bit_array_test(h->keep_samples,n_sample_ori) )\n {\n while ( *r!='\\t' && ris_gt) g++;\n break;\n\n case '\\t':\n *r = 0; // fall through\n\n case '\\0':\n case ':':\n if (f->max_m < m) f->max_m = m;\n if (f->max_l < l) f->max_l = l;\n if (f->is_gt && f->max_g < g) f->max_g = g;\n l = 0, m = g = 1;\n if ( *r==':' ) {\n j++; f++;\n if ( j>=v->n_fmt ) {\n hts_log_error(\"Incorrect number of FORMAT fields at %s:%\"PRIhts_pos\"\",\n h->id[BCF_DT_CTG][v->rid].key, v->pos+1);\n v->errcode |= BCF_ERR_NCOLS;\n return -1;\n }\n } else goto end_for;\n break;\n }\n if ( r>=end ) break;\n r++; l++;\n }\n end_for:\n v->n_sample++;\n if ( v->n_sample == bcf_hdr_nsamples(h) ) break;\n r++;\n }\n\n // allocate memory for arrays\n for (j = 0; j < v->n_fmt; ++j) {\n fmt_aux_t *f = &fmt[j];\n if ( !f->max_m ) f->max_m = 1; // omitted trailing format field\n if ((f->y>>4&0xf) == BCF_HT_STR) {\n f->size = f->is_gt? f->max_g << 2 : f->max_l;\n } else if ((f->y>>4&0xf) == BCF_HT_REAL || (f->y>>4&0xf) == BCF_HT_INT) {\n f->size = f->max_m << 2;\n } else\n {\n hts_log_error(\"The format type %d at %s:%\"PRIhts_pos\" is currently not supported\", f->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n if (align_mem(mem) < 0) {\n hts_log_error(\"Memory allocation failure at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n f->offset = mem->l;\n\n // Limit the total memory to ~2Gb per VCF row. This should mean\n // malformed VCF data is less likely to take excessive memory and/or\n // time.\n if (v->n_sample * (uint64_t)f->size > INT_MAX) {\n hts_log_error(\"Excessive memory required by FORMAT fields at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n if (ks_resize(mem, mem->l + v->n_sample * (size_t)f->size) < 0) {\n hts_log_error(\"Memory allocation failure at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n mem->l += v->n_sample * f->size;\n }\n for (j = 0; j < v->n_fmt; ++j)\n fmt[j].buf = (uint8_t*)mem->s + fmt[j].offset;\n // fill the sample fields; at beginning of the loop, t points to the first char of a format\n n_sample_ori = -1;\n t = q + 1; m = 0; // m: sample id\n while ( tkeep_samples )\n {\n n_sample_ori++;\n if ( !bit_array_test(h->keep_samples,n_sample_ori) )\n {\n while ( *t && tbuf) {\n hts_log_error(\"Memory allocation failure for FORMAT field type %d at %s:%\"PRIhts_pos,\n z->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n if ((z->y>>4&0xf) == BCF_HT_STR) {\n if (z->is_gt) { // genotypes\n int32_t is_phased = 0;\n uint32_t *x = (uint32_t*)(z->buf + z->size * (size_t)m);\n uint32_t unreadable = 0;\n uint32_t max = 0;\n overflow = 0;\n for (l = 0;; ++t) {\n if (*t == '.') {\n ++t, x[l++] = is_phased;\n } else {\n char *tt = t;\n uint32_t val = hts_str2uint(t, &t, sizeof(val) * CHAR_MAX - 2, &overflow);\n unreadable |= tt == t;\n if (max < val) max = val;\n x[l++] = (val + 1) << 1 | is_phased;\n }\n is_phased = (*t == '|');\n if (*t != '|' && *t != '/') break;\n }\n // Possibly check max against v->n_allele instead?\n if (overflow || max > (INT32_MAX >> 1) - 1) {\n hts_log_error(\"Couldn't read GT data: value too large at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n if (unreadable) {\n hts_log_error(\"Couldn't read GT data: value not a number or '.' at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n if ( !l ) x[l++] = 0; // An empty field, insert missing value\n for (; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else {\n char *x = (char*)z->buf + z->size * (size_t)m;\n for (r = t, l = 0; *t != ':' && *t; ++t) x[l++] = *t;\n for (; l < z->size; ++l) x[l] = 0;\n }\n } else if ((z->y>>4&0xf) == BCF_HT_INT) {\n int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m);\n for (l = 0;; ++t) {\n if (*t == '.') {\n x[l++] = bcf_int32_missing, ++t; // ++t to skip \".\"\n } else {\n overflow = 0;\n char *te;\n long int tmp_val = hts_str2int(t, &te, sizeof(tmp_val)*CHAR_BIT, &overflow);\n if ( te==t || overflow || tmp_valBCF_MAX_BT_INT32 )\n {\n if ( !extreme_val_warned )\n {\n hts_log_warning(\"Extreme FORMAT/%s value encountered and set to missing at %s:%\"PRIhts_pos, h->id[BCF_DT_ID][fmt[j-1].key].key, bcf_seqname_safe(h,v), v->pos+1);\n extreme_val_warned = 1;\n }\n tmp_val = bcf_int32_missing;\n }\n x[l++] = tmp_val;\n t = te;\n }\n if (*t != ',') break;\n }\n if ( !l ) x[l++] = bcf_int32_missing;\n for (; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else if ((z->y>>4&0xf) == BCF_HT_REAL) {\n float *x = (float*)(z->buf + z->size * (size_t)m);\n for (l = 0;; ++t) {\n if (*t == '.' && !isdigit_c(t[1])) {\n bcf_float_set_missing(x[l++]), ++t; // ++t to skip \".\"\n } else {\n overflow = 0;\n char *te;\n float tmp_val = hts_str2dbl(t, &te, &overflow);\n if ( (te==t || overflow) && !extreme_val_warned )\n {\n hts_log_warning(\"Extreme FORMAT/%s value encountered at %s:%\"PRIhts_pos, h->id[BCF_DT_ID][fmt[j-1].key].key, bcf_seqname(h,v), v->pos+1);\n extreme_val_warned = 1;\n }\n x[l++] = tmp_val;\n t = te;\n }\n if (*t != ',') break;\n }\n if ( !l ) bcf_float_set_missing(x[l++]); // An empty field, insert missing value\n for (; l < z->size>>2; ++l) bcf_float_set_vector_end(x[l]);\n } else {\n hts_log_error(\"Unknown FORMAT field type %d at %s:%\"PRIhts_pos, z->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n\n if (*t == '\\0') {\n break;\n }\n else if (*t == ':') {\n t++;\n }\n else {\n char buffer[8];\n hts_log_error(\"Invalid character %s in '%s' FORMAT field at %s:%\"PRIhts_pos\"\",\n hts_strprint(buffer, sizeof buffer, '\\'', t, 1),\n h->id[BCF_DT_ID][z->key].key, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_CHAR;\n return -1;\n }\n }\n\n for (; j < v->n_fmt; ++j) { // fill end-of-vector values\n fmt_aux_t *z = &fmt[j];\n if ((z->y>>4&0xf) == BCF_HT_STR) {\n if (z->is_gt) {\n int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m);\n if (z->size) x[0] = bcf_int32_missing;\n for (l = 1; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else {\n char *x = (char*)z->buf + z->size * (size_t)m;\n if ( z->size ) x[0] = '.';\n for (l = 1; l < z->size; ++l) x[l] = 0;\n }\n } else if ((z->y>>4&0xf) == BCF_HT_INT) {\n int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m);\n x[0] = bcf_int32_missing;\n for (l = 1; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else if ((z->y>>4&0xf) == BCF_HT_REAL) {\n float *x = (float*)(z->buf + z->size * (size_t)m);\n bcf_float_set_missing(x[0]);\n for (l = 1; l < z->size>>2; ++l) bcf_float_set_vector_end(x[l]);\n }\n }\n\n m++; t++;\n }\n\n // write individual genotype information\n kstring_t *str = &v->indiv;\n int i;\n if (v->n_sample > 0) {\n for (i = 0; i < v->n_fmt; ++i) {\n fmt_aux_t *z = &fmt[i];\n bcf_enc_int1(str, z->key);\n if ((z->y>>4&0xf) == BCF_HT_STR && !z->is_gt) {\n bcf_enc_size(str, z->size, BCF_BT_CHAR);\n kputsn((char*)z->buf, z->size * (size_t)v->n_sample, str);\n } else if ((z->y>>4&0xf) == BCF_HT_INT || z->is_gt) {\n bcf_enc_vint(str, (z->size>>2) * v->n_sample, (int32_t*)z->buf, z->size>>2);\n } else {\n bcf_enc_size(str, z->size>>2, BCF_BT_FLOAT);\n if (serialize_float_array(str, (z->size>>2) * (size_t)v->n_sample,\n (float *) z->buf) != 0) {\n v->errcode |= BCF_ERR_LIMITS;\n hts_log_error(\"Out of memory at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n }\n }\n }\n\n if ( v->n_sample!=bcf_hdr_nsamples(h) )\n {\n hts_log_error(\"Number of columns at %s:%\"PRIhts_pos\" does not match the number of samples (%d vs %d)\",\n bcf_seqname_safe(h,v), v->pos+1, v->n_sample, bcf_hdr_nsamples(h));\n v->errcode |= BCF_ERR_NCOLS;\n return -1;\n }\n if ( v->indiv.l > 0xffffffff )\n {\n hts_log_error(\"The FORMAT at %s:%\"PRIhts_pos\" is too long\", bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n\n // Error recovery: return -1 if this is a critical error or 0 if we want to ignore the FORMAT and proceed\n v->n_fmt = 0;\n return -1;\n }\n\n return 0;\n}", "project": "htslib", "hash": 315712016709704795623581796512547762288, "size": 371, "commit_id": "dcd4b7304941a8832fba2d0fc4c1e716e7a4e72c", "message": "Fix check for VCF record size\n\nThe check for excessive record size in vcf_parse_format() only\nlooked at individual fields. It was therefore possible to\nexceed the limit and overflow fmt_aux_t::offset by having\nmultiple fields with a combined size that went over INT_MAX.\nFix by including the amount of memory used so far in the check.\n\nCredit to OSS-Fuzz\nFixes oss-fuzz 24097", "target": 1, "dataset": "other", "idx": 207837} {"func": "static int vcf_parse_format(kstring_t *s, const bcf_hdr_t *h, bcf1_t *v, char *p, char *q)\n{\n if ( !bcf_hdr_nsamples(h) ) return 0;\n\n static int extreme_val_warned = 0;\n char *r, *t;\n int j, l, m, g, overflow = 0;\n khint_t k;\n ks_tokaux_t aux1;\n vdict_t *d = (vdict_t*)h->dict[BCF_DT_ID];\n kstring_t *mem = (kstring_t*)&h->mem;\n fmt_aux_t fmt[MAX_N_FMT];\n mem->l = 0;\n\n char *end = s->s + s->l;\n if ( q>=end )\n {\n hts_log_error(\"FORMAT column with no sample columns starting at %s:%\"PRIhts_pos\"\", bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_NCOLS;\n return -1;\n }\n\n v->n_fmt = 0;\n if ( p[0]=='.' && p[1]==0 ) // FORMAT field is empty \".\"\n {\n v->n_sample = bcf_hdr_nsamples(h);\n return 0;\n }\n\n // get format information from the dictionary\n for (j = 0, t = kstrtok(p, \":\", &aux1); t; t = kstrtok(0, 0, &aux1), ++j) {\n if (j >= MAX_N_FMT) {\n v->errcode |= BCF_ERR_LIMITS;\n hts_log_error(\"FORMAT column at %s:%\"PRIhts_pos\" lists more identifiers than htslib can handle\",\n bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n\n *(char*)aux1.p = 0;\n k = kh_get(vdict, d, t);\n if (k == kh_end(d) || kh_val(d, k).info[BCF_HL_FMT] == 15) {\n if ( t[0]=='.' && t[1]==0 )\n {\n hts_log_error(\"Invalid FORMAT tag name '.' at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n hts_log_warning(\"FORMAT '%s' at %s:%\"PRIhts_pos\" is not defined in the header, assuming Type=String\", t, bcf_seqname_safe(h,v), v->pos+1);\n kstring_t tmp = {0,0,0};\n int l;\n ksprintf(&tmp, \"##FORMAT=\", t);\n bcf_hrec_t *hrec = bcf_hdr_parse_line(h,tmp.s,&l);\n free(tmp.s);\n int res = hrec ? bcf_hdr_add_hrec((bcf_hdr_t*)h, hrec) : -1;\n if (res < 0) bcf_hrec_destroy(hrec);\n if (res > 0) res = bcf_hdr_sync((bcf_hdr_t*)h);\n\n k = kh_get(vdict, d, t);\n v->errcode = BCF_ERR_TAG_UNDEF;\n if (res || k == kh_end(d)) {\n hts_log_error(\"Could not add dummy header for FORMAT '%s' at %s:%\"PRIhts_pos, t, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n }\n fmt[j].max_l = fmt[j].max_m = fmt[j].max_g = 0;\n fmt[j].key = kh_val(d, k).id;\n fmt[j].is_gt = !strcmp(t, \"GT\");\n fmt[j].y = h->id[0][fmt[j].key].val->info[BCF_HL_FMT];\n v->n_fmt++;\n }\n // compute max\n int n_sample_ori = -1;\n r = q + 1; // r: position in the format string\n l = 0, m = g = 1, v->n_sample = 0; // m: max vector size, l: max field len, g: max number of alleles\n while ( rkeep_samples )\n {\n n_sample_ori++;\n if ( !bit_array_test(h->keep_samples,n_sample_ori) )\n {\n while ( *r!='\\t' && ris_gt) g++;\n break;\n\n case '\\t':\n *r = 0; // fall through\n\n case '\\0':\n case ':':\n if (f->max_m < m) f->max_m = m;\n if (f->max_l < l) f->max_l = l;\n if (f->is_gt && f->max_g < g) f->max_g = g;\n l = 0, m = g = 1;\n if ( *r==':' ) {\n j++; f++;\n if ( j>=v->n_fmt ) {\n hts_log_error(\"Incorrect number of FORMAT fields at %s:%\"PRIhts_pos\"\",\n h->id[BCF_DT_CTG][v->rid].key, v->pos+1);\n v->errcode |= BCF_ERR_NCOLS;\n return -1;\n }\n } else goto end_for;\n break;\n }\n if ( r>=end ) break;\n r++; l++;\n }\n end_for:\n v->n_sample++;\n if ( v->n_sample == bcf_hdr_nsamples(h) ) break;\n r++;\n }\n\n // allocate memory for arrays\n for (j = 0; j < v->n_fmt; ++j) {\n fmt_aux_t *f = &fmt[j];\n if ( !f->max_m ) f->max_m = 1; // omitted trailing format field\n if ((f->y>>4&0xf) == BCF_HT_STR) {\n f->size = f->is_gt? f->max_g << 2 : f->max_l;\n } else if ((f->y>>4&0xf) == BCF_HT_REAL || (f->y>>4&0xf) == BCF_HT_INT) {\n f->size = f->max_m << 2;\n } else\n {\n hts_log_error(\"The format type %d at %s:%\"PRIhts_pos\" is currently not supported\", f->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n if (align_mem(mem) < 0) {\n hts_log_error(\"Memory allocation failure at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n\n // Limit the total memory to ~2Gb per VCF row. This should mean\n // malformed VCF data is less likely to take excessive memory and/or\n // time.\n if ((uint64_t) mem->l + v->n_sample * (uint64_t)f->size > INT_MAX) {\n hts_log_error(\"Excessive memory required by FORMAT fields at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n\n f->offset = mem->l;\n if (ks_resize(mem, mem->l + v->n_sample * (size_t)f->size) < 0) {\n hts_log_error(\"Memory allocation failure at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n mem->l += v->n_sample * f->size;\n }\n for (j = 0; j < v->n_fmt; ++j)\n fmt[j].buf = (uint8_t*)mem->s + fmt[j].offset;\n // fill the sample fields; at beginning of the loop, t points to the first char of a format\n n_sample_ori = -1;\n t = q + 1; m = 0; // m: sample id\n while ( tkeep_samples )\n {\n n_sample_ori++;\n if ( !bit_array_test(h->keep_samples,n_sample_ori) )\n {\n while ( *t && tbuf) {\n hts_log_error(\"Memory allocation failure for FORMAT field type %d at %s:%\"PRIhts_pos,\n z->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n return -1;\n }\n if ((z->y>>4&0xf) == BCF_HT_STR) {\n if (z->is_gt) { // genotypes\n int32_t is_phased = 0;\n uint32_t *x = (uint32_t*)(z->buf + z->size * (size_t)m);\n uint32_t unreadable = 0;\n uint32_t max = 0;\n overflow = 0;\n for (l = 0;; ++t) {\n if (*t == '.') {\n ++t, x[l++] = is_phased;\n } else {\n char *tt = t;\n uint32_t val = hts_str2uint(t, &t, sizeof(val) * CHAR_MAX - 2, &overflow);\n unreadable |= tt == t;\n if (max < val) max = val;\n x[l++] = (val + 1) << 1 | is_phased;\n }\n is_phased = (*t == '|');\n if (*t != '|' && *t != '/') break;\n }\n // Possibly check max against v->n_allele instead?\n if (overflow || max > (INT32_MAX >> 1) - 1) {\n hts_log_error(\"Couldn't read GT data: value too large at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n if (unreadable) {\n hts_log_error(\"Couldn't read GT data: value not a number or '.' at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n if ( !l ) x[l++] = 0; // An empty field, insert missing value\n for (; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else {\n char *x = (char*)z->buf + z->size * (size_t)m;\n for (r = t, l = 0; *t != ':' && *t; ++t) x[l++] = *t;\n for (; l < z->size; ++l) x[l] = 0;\n }\n } else if ((z->y>>4&0xf) == BCF_HT_INT) {\n int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m);\n for (l = 0;; ++t) {\n if (*t == '.') {\n x[l++] = bcf_int32_missing, ++t; // ++t to skip \".\"\n } else {\n overflow = 0;\n char *te;\n long int tmp_val = hts_str2int(t, &te, sizeof(tmp_val)*CHAR_BIT, &overflow);\n if ( te==t || overflow || tmp_valBCF_MAX_BT_INT32 )\n {\n if ( !extreme_val_warned )\n {\n hts_log_warning(\"Extreme FORMAT/%s value encountered and set to missing at %s:%\"PRIhts_pos, h->id[BCF_DT_ID][fmt[j-1].key].key, bcf_seqname_safe(h,v), v->pos+1);\n extreme_val_warned = 1;\n }\n tmp_val = bcf_int32_missing;\n }\n x[l++] = tmp_val;\n t = te;\n }\n if (*t != ',') break;\n }\n if ( !l ) x[l++] = bcf_int32_missing;\n for (; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else if ((z->y>>4&0xf) == BCF_HT_REAL) {\n float *x = (float*)(z->buf + z->size * (size_t)m);\n for (l = 0;; ++t) {\n if (*t == '.' && !isdigit_c(t[1])) {\n bcf_float_set_missing(x[l++]), ++t; // ++t to skip \".\"\n } else {\n overflow = 0;\n char *te;\n float tmp_val = hts_str2dbl(t, &te, &overflow);\n if ( (te==t || overflow) && !extreme_val_warned )\n {\n hts_log_warning(\"Extreme FORMAT/%s value encountered at %s:%\"PRIhts_pos, h->id[BCF_DT_ID][fmt[j-1].key].key, bcf_seqname(h,v), v->pos+1);\n extreme_val_warned = 1;\n }\n x[l++] = tmp_val;\n t = te;\n }\n if (*t != ',') break;\n }\n if ( !l ) bcf_float_set_missing(x[l++]); // An empty field, insert missing value\n for (; l < z->size>>2; ++l) bcf_float_set_vector_end(x[l]);\n } else {\n hts_log_error(\"Unknown FORMAT field type %d at %s:%\"PRIhts_pos, z->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_TAG_INVALID;\n return -1;\n }\n\n if (*t == '\\0') {\n break;\n }\n else if (*t == ':') {\n t++;\n }\n else {\n char buffer[8];\n hts_log_error(\"Invalid character %s in '%s' FORMAT field at %s:%\"PRIhts_pos\"\",\n hts_strprint(buffer, sizeof buffer, '\\'', t, 1),\n h->id[BCF_DT_ID][z->key].key, bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_CHAR;\n return -1;\n }\n }\n\n for (; j < v->n_fmt; ++j) { // fill end-of-vector values\n fmt_aux_t *z = &fmt[j];\n if ((z->y>>4&0xf) == BCF_HT_STR) {\n if (z->is_gt) {\n int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m);\n if (z->size) x[0] = bcf_int32_missing;\n for (l = 1; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else {\n char *x = (char*)z->buf + z->size * (size_t)m;\n if ( z->size ) x[0] = '.';\n for (l = 1; l < z->size; ++l) x[l] = 0;\n }\n } else if ((z->y>>4&0xf) == BCF_HT_INT) {\n int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m);\n x[0] = bcf_int32_missing;\n for (l = 1; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;\n } else if ((z->y>>4&0xf) == BCF_HT_REAL) {\n float *x = (float*)(z->buf + z->size * (size_t)m);\n bcf_float_set_missing(x[0]);\n for (l = 1; l < z->size>>2; ++l) bcf_float_set_vector_end(x[l]);\n }\n }\n\n m++; t++;\n }\n\n // write individual genotype information\n kstring_t *str = &v->indiv;\n int i;\n if (v->n_sample > 0) {\n for (i = 0; i < v->n_fmt; ++i) {\n fmt_aux_t *z = &fmt[i];\n bcf_enc_int1(str, z->key);\n if ((z->y>>4&0xf) == BCF_HT_STR && !z->is_gt) {\n bcf_enc_size(str, z->size, BCF_BT_CHAR);\n kputsn((char*)z->buf, z->size * (size_t)v->n_sample, str);\n } else if ((z->y>>4&0xf) == BCF_HT_INT || z->is_gt) {\n bcf_enc_vint(str, (z->size>>2) * v->n_sample, (int32_t*)z->buf, z->size>>2);\n } else {\n bcf_enc_size(str, z->size>>2, BCF_BT_FLOAT);\n if (serialize_float_array(str, (z->size>>2) * (size_t)v->n_sample,\n (float *) z->buf) != 0) {\n v->errcode |= BCF_ERR_LIMITS;\n hts_log_error(\"Out of memory at %s:%\"PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1);\n return -1;\n }\n }\n }\n }\n\n if ( v->n_sample!=bcf_hdr_nsamples(h) )\n {\n hts_log_error(\"Number of columns at %s:%\"PRIhts_pos\" does not match the number of samples (%d vs %d)\",\n bcf_seqname_safe(h,v), v->pos+1, v->n_sample, bcf_hdr_nsamples(h));\n v->errcode |= BCF_ERR_NCOLS;\n return -1;\n }\n if ( v->indiv.l > 0xffffffff )\n {\n hts_log_error(\"The FORMAT at %s:%\"PRIhts_pos\" is too long\", bcf_seqname_safe(h,v), v->pos+1);\n v->errcode |= BCF_ERR_LIMITS;\n\n // Error recovery: return -1 if this is a critical error or 0 if we want to ignore the FORMAT and proceed\n v->n_fmt = 0;\n return -1;\n }\n\n return 0;\n}", "project": "htslib", "hash": 92847516526430128297643351147009305704, "size": 372, "commit_id": "dcd4b7304941a8832fba2d0fc4c1e716e7a4e72c", "message": "Fix check for VCF record size\n\nThe check for excessive record size in vcf_parse_format() only\nlooked at individual fields. It was therefore possible to\nexceed the limit and overflow fmt_aux_t::offset by having\nmultiple fields with a combined size that went over INT_MAX.\nFix by including the amount of memory used so far in the check.\n\nCredit to OSS-Fuzz\nFixes oss-fuzz 24097", "target": 0, "dataset": "other", "idx": 402146} {"func": "int hci_req_sync(struct hci_dev *hdev, int (*req)(struct hci_request *req,\n\t\t\t\t\t\t unsigned long opt),\n\t\t unsigned long opt, u32 timeout, u8 *hci_status)\n{\n\tint ret;\n\n\tif (!test_bit(HCI_UP, &hdev->flags))\n\t\treturn -ENETDOWN;\n\n\t/* Serialize all requests */\n\thci_req_sync_lock(hdev);\n\tret = __hci_req_sync(hdev, req, opt, timeout, hci_status);\n\thci_req_sync_unlock(hdev);\n\n\treturn ret;\n}", "project": "linux", "hash": 119058947373563095041334918661267933841, "size": 16, "commit_id": "e2cb6b891ad2b8caa9131e3be70f45243df82a80", "message": "bluetooth: eliminate the potential race condition when removing the HCI controller\n\nThere is a possible race condition vulnerability between issuing a HCI\ncommand and removing the cont. Specifically, functions hci_req_sync()\nand hci_dev_do_close() can race each other like below:\n\nthread-A in hci_req_sync() | thread-B in hci_dev_do_close()\n | hci_req_sync_lock(hdev);\ntest_bit(HCI_UP, &hdev->flags); |\n... | test_and_clear_bit(HCI_UP, &hdev->flags)\nhci_req_sync_lock(hdev); |\n |\nIn this commit we alter the sequence in function hci_req_sync(). Hence,\nthe thread-A cannot issue th.\n\nSigned-off-by: Lin Ma \nCc: Marcel Holtmann \nFixes: 7c6a329e4447 (\"[Bluetooth] Fix regression from using default link policy\")\nSigned-off-by: Greg Kroah-Hartman ", "target": 1, "dataset": "other", "idx": 207859} {"func": "int hci_req_sync(struct hci_dev *hdev, int (*req)(struct hci_request *req,\n\t\t\t\t\t\t unsigned long opt),\n\t\t unsigned long opt, u32 timeout, u8 *hci_status)\n{\n\tint ret;\n\n\t/* Serialize all requests */\n\thci_req_sync_lock(hdev);\n\t/* check the state after obtaing the lock to protect the HCI_UP\n\t * against any races from hci_dev_do_close when the controller\n\t * gets removed.\n\t */\n\tif (test_bit(HCI_UP, &hdev->flags))\n\t\tret = __hci_req_sync(hdev, req, opt, timeout, hci_status);\n\telse\n\t\tret = -ENETDOWN;\n\thci_req_sync_unlock(hdev);\n\n\treturn ret;\n}", "project": "linux", "hash": 18084705760266005754007910834066501149, "size": 20, "commit_id": "e2cb6b891ad2b8caa9131e3be70f45243df82a80", "message": "bluetooth: eliminate the potential race condition when removing the HCI controller\n\nThere is a possible race condition vulnerability between issuing a HCI\ncommand and removing the cont. Specifically, functions hci_req_sync()\nand hci_dev_do_close() can race each other like below:\n\nthread-A in hci_req_sync() | thread-B in hci_dev_do_close()\n | hci_req_sync_lock(hdev);\ntest_bit(HCI_UP, &hdev->flags); |\n... | test_and_clear_bit(HCI_UP, &hdev->flags)\nhci_req_sync_lock(hdev); |\n |\nIn this commit we alter the sequence in function hci_req_sync(). Hence,\nthe thread-A cannot issue th.\n\nSigned-off-by: Lin Ma \nCc: Marcel Holtmann \nFixes: 7c6a329e4447 (\"[Bluetooth] Fix regression from using default link policy\")\nSigned-off-by: Greg Kroah-Hartman ", "target": 0, "dataset": "other", "idx": 402494} {"func": "static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp)\n{\n\tchar* path = NULL;\n\tint status;\n\tUINT32 PathLength;\n\tStream_Seek(irp->input, 28);\n\t/* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */\n\t/* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */\n\tStream_Read_UINT32(irp->input, PathLength);\n\tstatus = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)Stream_Pointer(irp->input), PathLength / 2,\n\t &path, 0, NULL, NULL);\n\n\tif (status < 1)\n\t\tif (!(path = (char*)calloc(1, 1)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\tparallel->id = irp->devman->id_sequence++;\n\tparallel->file = open(parallel->path, O_RDWR);\n\n\tif (parallel->file < 0)\n\t{\n\t\tirp->IoStatus = STATUS_ACCESS_DENIED;\n\t\tparallel->id = 0;\n\t}\n\telse\n\t{\n\t\t/* all read and write operations should be non-blocking */\n\t\tif (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1)\n\t\t{\n\t\t}\n\t}\n\n\tStream_Write_UINT32(irp->output, parallel->id);\n\tStream_Write_UINT8(irp->output, 0);\n\tfree(path);\n\treturn irp->Complete(irp);\n}", "project": "FreeRDP", "hash": 91654068438972054959889615095747233707, "size": 40, "commit_id": "795842f4096501fcefc1a7f535ccc8132feb31d7", "message": "Fixed oob read in parallel_process_irp_create", "target": 1, "dataset": "other", "idx": 207960} {"func": "static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp)\n{\n\tchar* path = NULL;\n\tint status;\n\tWCHAR* ptr;\n\tUINT32 PathLength;\n\tif (!Stream_SafeSeek(irp->input, 28))\n\t\treturn ERROR_INVALID_DATA;\n\t/* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */\n\t/* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */\n\tif (Stream_GetRemainingLength(irp->input) < 4)\n\t\treturn ERROR_INVALID_DATA;\n\tStream_Read_UINT32(irp->input, PathLength);\n\tptr = (WCHAR*)Stream_Pointer(irp->input);\n\tif (!Stream_SafeSeek(irp->input, PathLength))\n\t\treturn ERROR_INVALID_DATA;\n\tstatus = ConvertFromUnicode(CP_UTF8, 0, ptr, PathLength / 2, &path, 0, NULL, NULL);\n\n\tif (status < 1)\n\t\tif (!(path = (char*)calloc(1, 1)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\tparallel->id = irp->devman->id_sequence++;\n\tparallel->file = open(parallel->path, O_RDWR);\n\n\tif (parallel->file < 0)\n\t{\n\t\tirp->IoStatus = STATUS_ACCESS_DENIED;\n\t\tparallel->id = 0;\n\t}\n\telse\n\t{\n\t\t/* all read and write operations should be non-blocking */\n\t\tif (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1)\n\t\t{\n\t\t}\n\t}\n\n\tStream_Write_UINT32(irp->output, parallel->id);\n\tStream_Write_UINT8(irp->output, 0);\n\tfree(path);\n\treturn irp->Complete(irp);\n}", "project": "FreeRDP", "hash": 213401734041482676778583216895571372326, "size": 46, "commit_id": "795842f4096501fcefc1a7f535ccc8132feb31d7", "message": "Fixed oob read in parallel_process_irp_create", "target": 0, "dataset": "other", "idx": 403469} {"func": "struct torture_suite *torture_smb2_notify_init(TALLOC_CTX *ctx)\n{\n\tstruct torture_suite *suite = torture_suite_create(ctx, \"notify\");\n\n\ttorture_suite_add_1smb2_test(suite, \"valid-req\", test_valid_request);\n\ttorture_suite_add_1smb2_test(suite, \"tcon\", torture_smb2_notify_tcon);\n\ttorture_suite_add_2smb2_test(suite, \"dir\", torture_smb2_notify_dir);\n\ttorture_suite_add_2smb2_test(suite, \"mask\", torture_smb2_notify_mask);\n\ttorture_suite_add_1smb2_test(suite, \"tdis\", torture_smb2_notify_tree_disconnect);\n\ttorture_suite_add_1smb2_test(suite, \"tdis1\", torture_smb2_notify_tree_disconnect_1);\n\ttorture_suite_add_2smb2_test(suite, \"mask-change\", torture_smb2_notify_mask_change);\n\ttorture_suite_add_1smb2_test(suite, \"close\", torture_smb2_notify_close);\n\ttorture_suite_add_1smb2_test(suite, \"logoff\", torture_smb2_notify_ulogoff);\n\ttorture_suite_add_1smb2_test(suite, \"session-reconnect\", torture_smb2_notify_session_reconnect);\n\ttorture_suite_add_2smb2_test(suite, \"invalid-reauth\", torture_smb2_notify_invalid_reauth);\n\ttorture_suite_add_1smb2_test(suite, \"tree\", torture_smb2_notify_tree);\n\ttorture_suite_add_2smb2_test(suite, \"basedir\", torture_smb2_notify_basedir);\n\ttorture_suite_add_2smb2_test(suite, \"double\", torture_smb2_notify_double);\n\ttorture_suite_add_1smb2_test(suite, \"file\", torture_smb2_notify_file);\n\ttorture_suite_add_1smb2_test(suite, \"tcp\", torture_smb2_notify_tcp_disconnect);\n\ttorture_suite_add_2smb2_test(suite, \"rec\", torture_smb2_notify_recursive);\n\ttorture_suite_add_1smb2_test(suite, \"overflow\", torture_smb2_notify_overflow);\n\ttorture_suite_add_1smb2_test(suite, \"rmdir1\",\n\t\t\t\t torture_smb2_notify_rmdir1);\n\ttorture_suite_add_1smb2_test(suite, \"rmdir2\",\n\t\t\t\t torture_smb2_notify_rmdir2);\n\ttorture_suite_add_2smb2_test(suite, \"rmdir3\",\n\t\t\t\t torture_smb2_notify_rmdir3);\n\ttorture_suite_add_2smb2_test(suite, \"rmdir4\",\n\t\t\t\t torture_smb2_notify_rmdir4);\n\n\tsuite->description = talloc_strdup(suite, \"SMB2-NOTIFY tests\");\n\n\treturn suite;\n}", "project": "samba", "hash": 270007973625551949002175375598998346622, "size": 35, "commit_id": "f100bd2f2e4f047942002a992c99104227a17f81", "message": "s4: torture: Add smb2.notify.handle-permissions test.\n\nAdd knownfail entry.\n\nCVE-2020-14318\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=14434\n\nSigned-off-by: Jeremy Allison ", "target": 1, "dataset": "other", "idx": 207975} {"func": "struct torture_suite *torture_smb2_notify_init(TALLOC_CTX *ctx)\n{\n\tstruct torture_suite *suite = torture_suite_create(ctx, \"notify\");\n\n\ttorture_suite_add_1smb2_test(suite, \"valid-req\", test_valid_request);\n\ttorture_suite_add_1smb2_test(suite, \"tcon\", torture_smb2_notify_tcon);\n\ttorture_suite_add_2smb2_test(suite, \"dir\", torture_smb2_notify_dir);\n\ttorture_suite_add_2smb2_test(suite, \"mask\", torture_smb2_notify_mask);\n\ttorture_suite_add_1smb2_test(suite, \"tdis\", torture_smb2_notify_tree_disconnect);\n\ttorture_suite_add_1smb2_test(suite, \"tdis1\", torture_smb2_notify_tree_disconnect_1);\n\ttorture_suite_add_2smb2_test(suite, \"mask-change\", torture_smb2_notify_mask_change);\n\ttorture_suite_add_1smb2_test(suite, \"close\", torture_smb2_notify_close);\n\ttorture_suite_add_1smb2_test(suite, \"logoff\", torture_smb2_notify_ulogoff);\n\ttorture_suite_add_1smb2_test(suite, \"session-reconnect\", torture_smb2_notify_session_reconnect);\n\ttorture_suite_add_2smb2_test(suite, \"invalid-reauth\", torture_smb2_notify_invalid_reauth);\n\ttorture_suite_add_1smb2_test(suite, \"tree\", torture_smb2_notify_tree);\n\ttorture_suite_add_2smb2_test(suite, \"basedir\", torture_smb2_notify_basedir);\n\ttorture_suite_add_2smb2_test(suite, \"double\", torture_smb2_notify_double);\n\ttorture_suite_add_1smb2_test(suite, \"file\", torture_smb2_notify_file);\n\ttorture_suite_add_1smb2_test(suite, \"tcp\", torture_smb2_notify_tcp_disconnect);\n\ttorture_suite_add_2smb2_test(suite, \"rec\", torture_smb2_notify_recursive);\n\ttorture_suite_add_1smb2_test(suite, \"overflow\", torture_smb2_notify_overflow);\n\ttorture_suite_add_1smb2_test(suite, \"rmdir1\",\n\t\t\t\t torture_smb2_notify_rmdir1);\n\ttorture_suite_add_1smb2_test(suite, \"rmdir2\",\n\t\t\t\t torture_smb2_notify_rmdir2);\n\ttorture_suite_add_2smb2_test(suite, \"rmdir3\",\n\t\t\t\t torture_smb2_notify_rmdir3);\n\ttorture_suite_add_2smb2_test(suite, \"rmdir4\",\n\t\t\t\t torture_smb2_notify_rmdir4);\n\ttorture_suite_add_1smb2_test(suite,\n\t\t\t\t \"handle-permissions\",\n\t\t\t\t torture_smb2_notify_handle_permissions);\n\n\tsuite->description = talloc_strdup(suite, \"SMB2-NOTIFY tests\");\n\n\treturn suite;\n}", "project": "samba", "hash": 19139210488759600268757183606179666736, "size": 38, "commit_id": "f100bd2f2e4f047942002a992c99104227a17f81", "message": "s4: torture: Add smb2.notify.handle-permissions test.\n\nAdd knownfail entry.\n\nCVE-2020-14318\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=14434\n\nSigned-off-by: Jeremy Allison ", "target": 0, "dataset": "other", "idx": 403809} {"func": "exif_data_load_data_thumbnail (ExifData *data, const unsigned char *d,\n\t\t\t unsigned int ds, ExifLong o, ExifLong s)\n{\n\t/* Sanity checks */\n\tif (o >= ds) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\", \"Bogus thumbnail offset (%u).\", o);\n\t\treturn;\n\t}\n\tif (s > ds - o) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\", \"Bogus thumbnail size (%u), max would be %u.\", s, ds-o);\n\t\treturn;\n\t}\n\tif (data->data) \n\t\texif_mem_free (data->priv->mem, data->data);\n\tif (!(data->data = exif_data_alloc (data, s))) {\n\t\tEXIF_LOG_NO_MEMORY (data->priv->log, \"ExifData\", s);\n\t\tdata->size = 0;\n\t\treturn;\n\t}\n\tdata->size = s;\n\tmemcpy (data->data, d + o, s);\n}", "project": "libexif", "hash": 204041437380593833360882392912459353328, "size": 22, "commit_id": "ce03ad7ef4e8aeefce79192bf5b6f69fae396f0c", "message": "fixed another unsigned integer overflow\n\nfirst fixed by google in android fork,\nhttps://android.googlesource.com/platform/external/libexif/+/1e187b62682ffab5003c702657d6d725b4278f16%5E%21/#F0\n\n(use a more generic overflow check method, also check second overflow instance.)\n\nhttps://security-tracker.debian.org/tracker/CVE-2020-0198", "target": 1, "dataset": "other", "idx": 207982} {"func": "exif_data_load_data_thumbnail (ExifData *data, const unsigned char *d,\n\t\t\t unsigned int ds, ExifLong o, ExifLong s)\n{\n\t/* Sanity checks */\n\tif (o >= ds) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\", \"Bogus thumbnail offset (%u).\", o);\n\t\treturn;\n\t}\n\tif (CHECKOVERFLOW(o,ds,s)) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\", \"Bogus thumbnail size (%u), max would be %u.\", s, ds-o);\n\t\treturn;\n\t}\n\tif (data->data) \n\t\texif_mem_free (data->priv->mem, data->data);\n\tif (!(data->data = exif_data_alloc (data, s))) {\n\t\tEXIF_LOG_NO_MEMORY (data->priv->log, \"ExifData\", s);\n\t\tdata->size = 0;\n\t\treturn;\n\t}\n\tdata->size = s;\n\tmemcpy (data->data, d + o, s);\n}", "project": "libexif", "hash": 93334110242984400786615733042597988830, "size": 22, "commit_id": "ce03ad7ef4e8aeefce79192bf5b6f69fae396f0c", "message": "fixed another unsigned integer overflow\n\nfirst fixed by google in android fork,\nhttps://android.googlesource.com/platform/external/libexif/+/1e187b62682ffab5003c702657d6d725b4278f16%5E%21/#F0\n\n(use a more generic overflow check method, also check second overflow instance.)\n\nhttps://security-tracker.debian.org/tracker/CVE-2020-0198", "target": 0, "dataset": "other", "idx": 404043} {"func": "static int hva_to_pfn_remapped(struct vm_area_struct *vma,\n\t\t\t unsigned long addr, bool *async,\n\t\t\t bool write_fault, bool *writable,\n\t\t\t kvm_pfn_t *p_pfn)\n{\n\tkvm_pfn_t pfn;\n\tpte_t *ptep;\n\tspinlock_t *ptl;\n\tint r;\n\n\tr = follow_pte(vma->vm_mm, addr, &ptep, &ptl);\n\tif (r) {\n\t\t/*\n\t\t * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does\n\t\t * not call the fault handler, so do it here.\n\t\t */\n\t\tbool unlocked = false;\n\t\tr = fixup_user_fault(current->mm, addr,\n\t\t\t\t (write_fault ? FAULT_FLAG_WRITE : 0),\n\t\t\t\t &unlocked);\n\t\tif (unlocked)\n\t\t\treturn -EAGAIN;\n\t\tif (r)\n\t\t\treturn r;\n\n\t\tr = follow_pte(vma->vm_mm, addr, &ptep, &ptl);\n\t\tif (r)\n\t\t\treturn r;\n\t}\n\n\tif (write_fault && !pte_write(*ptep)) {\n\t\tpfn = KVM_PFN_ERR_RO_FAULT;\n\t\tgoto out;\n\t}\n\n\tif (writable)\n\t\t*writable = pte_write(*ptep);\n\tpfn = pte_pfn(*ptep);\n\n\t/*\n\t * Get a reference here because callers of *hva_to_pfn* and\n\t * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the\n\t * returned pfn. This is only needed if the VMA has VM_MIXEDMAP\n\t * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will\n\t * simply do nothing for reserved pfns.\n\t *\n\t * Whoever called remap_pfn_range is also going to call e.g.\n\t * unmap_mapping_range before the underlying pages are freed,\n\t * causing a call to our MMU notifier.\n\t */ \n\tkvm_get_pfn(pfn);\n\nout:\n\tpte_unmap_unlock(ptep, ptl);\n\t*p_pfn = pfn;\n\treturn 0;\n}", "project": "linux", "hash": 260764785426289038088174052083851102831, "size": 57, "commit_id": "f8be156be163a052a067306417cd0ff679068c97", "message": "KVM: do not allow mapping valid but non-reference-counted pages\n\nIt's possible to create a region which maps valid but non-refcounted\npages (e.g., tail pages of non-compound higher order allocations). These\nhost pages can then be returned by gfn_to_page, gfn_to_pfn, etc., family\nof APIs, which take a reference to the page, which takes it from 0 to 1.\nWhen the reference is dropped, this will free the page incorrectly.\n\nFix this by only taking a reference on valid pages if it was non-zero,\nwhich indicates it is participating in normal refcounting (and can be\nreleased with put_page).\n\nThis addresses CVE-2021-22543.\n\nSigned-off-by: Nicholas Piggin \nTested-by: Paolo Bonzini \nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini ", "target": 1, "dataset": "other", "idx": 207984} {"func": "static int hva_to_pfn_remapped(struct vm_area_struct *vma,\n\t\t\t unsigned long addr, bool *async,\n\t\t\t bool write_fault, bool *writable,\n\t\t\t kvm_pfn_t *p_pfn)\n{\n\tkvm_pfn_t pfn;\n\tpte_t *ptep;\n\tspinlock_t *ptl;\n\tint r;\n\n\tr = follow_pte(vma->vm_mm, addr, &ptep, &ptl);\n\tif (r) {\n\t\t/*\n\t\t * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does\n\t\t * not call the fault handler, so do it here.\n\t\t */\n\t\tbool unlocked = false;\n\t\tr = fixup_user_fault(current->mm, addr,\n\t\t\t\t (write_fault ? FAULT_FLAG_WRITE : 0),\n\t\t\t\t &unlocked);\n\t\tif (unlocked)\n\t\t\treturn -EAGAIN;\n\t\tif (r)\n\t\t\treturn r;\n\n\t\tr = follow_pte(vma->vm_mm, addr, &ptep, &ptl);\n\t\tif (r)\n\t\t\treturn r;\n\t}\n\n\tif (write_fault && !pte_write(*ptep)) {\n\t\tpfn = KVM_PFN_ERR_RO_FAULT;\n\t\tgoto out;\n\t}\n\n\tif (writable)\n\t\t*writable = pte_write(*ptep);\n\tpfn = pte_pfn(*ptep);\n\n\t/*\n\t * Get a reference here because callers of *hva_to_pfn* and\n\t * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the\n\t * returned pfn. This is only needed if the VMA has VM_MIXEDMAP\n\t * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will\n\t * simply do nothing for reserved pfns.\n\t *\n\t * Whoever called remap_pfn_range is also going to call e.g.\n\t * unmap_mapping_range before the underlying pages are freed,\n\t * causing a call to our MMU notifier.\n\t *\n\t * Certain IO or PFNMAP mappings can be backed with valid\n\t * struct pages, but be allocated without refcounting e.g.,\n\t * tail pages of non-compound higher order allocations, which\n\t * would then underflow the refcount when the caller does the\n\t * required put_page. Don't allow those pages here.\n\t */ \n\tif (!kvm_try_get_pfn(pfn))\n\t\tr = -EFAULT;\n\nout:\n\tpte_unmap_unlock(ptep, ptl);\n\t*p_pfn = pfn;\n\n\treturn r;\n}", "project": "linux", "hash": 119627960290880640791677244710201346582, "size": 65, "commit_id": "f8be156be163a052a067306417cd0ff679068c97", "message": "KVM: do not allow mapping valid but non-reference-counted pages\n\nIt's possible to create a region which maps valid but non-refcounted\npages (e.g., tail pages of non-compound higher order allocations). These\nhost pages can then be returned by gfn_to_page, gfn_to_pfn, etc., family\nof APIs, which take a reference to the page, which takes it from 0 to 1.\nWhen the reference is dropped, this will free the page incorrectly.\n\nFix this by only taking a reference on valid pages if it was non-zero,\nwhich indicates it is participating in normal refcounting (and can be\nreleased with put_page).\n\nThis addresses CVE-2021-22543.\n\nSigned-off-by: Nicholas Piggin \nTested-by: Paolo Bonzini \nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini ", "target": 0, "dataset": "other", "idx": 404071} {"func": "file_rlookup(const char *filename)\t/* I - Filename */\n{\n int\t\ti;\t\t\t/* Looping var */\n cache_t\t*wc;\t\t\t/* Current cache file */\n\n\n for (i = web_files, wc = web_cache; i > 0; i --, wc ++)\n if (!strcmp(wc->name, filename))\n return (wc->url);\n\n return (filename);\n}", "project": "htmldoc", "hash": 37144065587419517647394917709524696999, "size": 12, "commit_id": "369b2ea1fd0d0537ba707f20a2f047b6afd2fbdc", "message": "Fix JPEG error handling (Issue #415)", "target": 1, "dataset": "other", "idx": 207988} {"func": "file_rlookup(const char *filename)\t/* I - Filename */\n{\n int\t\ti;\t\t\t/* Looping var */\n cache_t\t*wc;\t\t\t/* Current cache file */\n\n\n for (i = web_files, wc = web_cache; i > 0; i --, wc ++)\n {\n if (!strcmp(wc->name, filename))\n {\n if (!strncmp(wc->url, \"data:\", 5))\n return (\"data URL\");\n else\n return (wc->url);\n }\n }\n\n return (filename);\n}", "project": "htmldoc", "hash": 5027088153078274175236805576153910500, "size": 19, "commit_id": "369b2ea1fd0d0537ba707f20a2f047b6afd2fbdc", "message": "Fix JPEG error handling (Issue #415)", "target": 0, "dataset": "other", "idx": 404189} {"func": "static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n filename[MagickPathExtent];\n\n const char\n *option;\n\n FILE\n *file;\n\n Image\n *image,\n *next;\n\n int\n status,\n unique_file;\n\n ssize_t\n n;\n\n SVGInfo\n *svg_info;\n\n unsigned char\n message[MagickPathExtent];\n\n xmlSAXHandler\n sax_modules;\n\n xmlSAXHandlerPtr\n sax_handler;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if ((fabs(image->resolution.x) < MagickEpsilon) ||\n (fabs(image->resolution.y) < MagickEpsilon))\n {\n GeometryInfo\n geometry_info;\n\n int\n flags;\n\n flags=ParseGeometry(SVGDensityGeometry,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n }\n if (LocaleCompare(image_info->magick,\"MSVG\") != 0)\n {\n Image\n *svg_image;\n\n svg_image=RenderSVGImage(image_info,image,exception);\n if (svg_image != (Image *) NULL)\n {\n image=DestroyImageList(image);\n return(svg_image);\n }\n {\n#if defined(MAGICKCORE_RSVG_DELEGATE)\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n cairo_surface_t\n *cairo_surface;\n\n cairo_t\n *cairo_image;\n\n MagickBooleanType\n apply_density;\n\n MemoryInfo\n *pixel_info;\n\n register unsigned char\n *p;\n\n RsvgDimensionData\n dimension_info;\n\n unsigned char\n *pixels;\n\n#else\n GdkPixbuf\n *pixel_buffer;\n\n register const guchar\n *p;\n#endif\n\n GError\n *error;\n\n PixelInfo\n fill_color;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n RsvgHandle\n *svg_handle;\n\n ssize_t\n y;\n\n unsigned char\n *buffer;\n\n buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent,\n sizeof(*buffer));\n if (buffer == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n#if LIBRSVG_CHECK_VERSION(2,40,3)\n option=GetImageOption(image_info,\"svg:xml-parse-huge\");\n if ((option != (char *) NULL) && (IsStringTrue(option) != MagickFalse))\n svg_handle=rsvg_handle_new_with_flags(RSVG_HANDLE_FLAG_UNLIMITED);\n else\n#endif\n svg_handle=rsvg_handle_new();\n if (svg_handle == (RsvgHandle *) NULL)\n {\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n rsvg_handle_set_base_uri(svg_handle,image_info->filename);\n if ((fabs(image->resolution.x) > MagickEpsilon) &&\n (fabs(image->resolution.y) > MagickEpsilon))\n rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x,\n image->resolution.y);\n while ((n=ReadBlob(image,MagickMaxBufferExtent-1,buffer)) != 0)\n {\n buffer[n]='\\0';\n error=(GError *) NULL;\n (void) rsvg_handle_write(svg_handle,buffer,n,&error);\n if (error != (GError *) NULL)\n g_error_free(error);\n }\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n error=(GError *) NULL;\n rsvg_handle_close(svg_handle,&error);\n if (error != (GError *) NULL)\n g_error_free(error);\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n apply_density=MagickTrue;\n rsvg_handle_get_dimensions(svg_handle,&dimension_info);\n if ((image->resolution.x > 0.0) && (image->resolution.y > 0.0))\n {\n RsvgDimensionData\n dpi_dimension_info;\n\n /*\n We should not apply the density when the internal 'factor' is 'i'.\n This can be checked by using the trick below.\n */\n rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x*256,\n image->resolution.y*256);\n rsvg_handle_get_dimensions(svg_handle,&dpi_dimension_info);\n if ((dpi_dimension_info.width != dimension_info.width) ||\n (dpi_dimension_info.height != dimension_info.height))\n apply_density=MagickFalse;\n rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x,\n image->resolution.y);\n }\n if (image_info->size != (char *) NULL)\n {\n (void) GetGeometry(image_info->size,(ssize_t *) NULL,\n (ssize_t *) NULL,&image->columns,&image->rows);\n if ((image->columns != 0) || (image->rows != 0))\n {\n image->resolution.x=DefaultSVGDensity*image->columns/\n dimension_info.width;\n image->resolution.y=DefaultSVGDensity*image->rows/\n dimension_info.height;\n if (fabs(image->resolution.x) < MagickEpsilon)\n image->resolution.x=image->resolution.y;\n else\n if (fabs(image->resolution.y) < MagickEpsilon)\n image->resolution.y=image->resolution.x;\n else\n image->resolution.x=image->resolution.y=MagickMin(\n image->resolution.x,image->resolution.y);\n apply_density=MagickTrue;\n }\n }\n if (apply_density != MagickFalse)\n {\n image->columns=image->resolution.x*dimension_info.width/\n DefaultSVGDensity;\n image->rows=image->resolution.y*dimension_info.height/\n DefaultSVGDensity;\n }\n else\n {\n image->columns=dimension_info.width;\n image->rows=dimension_info.height;\n }\n pixel_info=(MemoryInfo *) NULL;\n#else\n pixel_buffer=rsvg_handle_get_pixbuf(svg_handle);\n rsvg_handle_free(svg_handle);\n image->columns=gdk_pixbuf_get_width(pixel_buffer);\n image->rows=gdk_pixbuf_get_height(pixel_buffer);\n#endif\n image->alpha_trait=BlendPixelTrait;\n if (image_info->ping == MagickFalse)\n {\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n size_t\n stride;\n#endif\n\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n {\n#if !defined(MAGICKCORE_CAIRO_DELEGATE)\n g_object_unref(G_OBJECT(pixel_buffer));\n#endif\n g_object_unref(svg_handle);\n ThrowReaderException(MissingDelegateError,\n \"NoDecodeDelegateForThisImageFormat\");\n }\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n stride=4*image->columns;\n#if defined(MAGICKCORE_PANGOCAIRO_DELEGATE)\n stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32,\n (int) image->columns);\n#endif\n pixel_info=AcquireVirtualMemory(stride,image->rows*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n g_object_unref(svg_handle);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n#endif\n (void) SetImageBackgroundColor(image,exception);\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n cairo_surface=cairo_image_surface_create_for_data(pixels,\n CAIRO_FORMAT_ARGB32,(int) image->columns,(int) image->rows,(int)\n stride);\n if ((cairo_surface == (cairo_surface_t *) NULL) ||\n (cairo_surface_status(cairo_surface) != CAIRO_STATUS_SUCCESS))\n {\n if (cairo_surface != (cairo_surface_t *) NULL)\n cairo_surface_destroy(cairo_surface);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n g_object_unref(svg_handle);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n cairo_image=cairo_create(cairo_surface);\n cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR);\n cairo_paint(cairo_image);\n cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER);\n if (apply_density != MagickFalse)\n cairo_scale(cairo_image,image->resolution.x/DefaultSVGDensity,\n image->resolution.y/DefaultSVGDensity);\n rsvg_handle_render_cairo(svg_handle,cairo_image);\n cairo_destroy(cairo_image);\n cairo_surface_destroy(cairo_surface);\n g_object_unref(svg_handle);\n p=pixels;\n#else\n p=gdk_pixbuf_get_pixels(pixel_buffer);\n#endif\n GetPixelInfo(image,&fill_color);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n fill_color.blue=ScaleCharToQuantum(*p++);\n fill_color.green=ScaleCharToQuantum(*p++);\n fill_color.red=ScaleCharToQuantum(*p++);\n#else\n fill_color.red=ScaleCharToQuantum(*p++);\n fill_color.green=ScaleCharToQuantum(*p++);\n fill_color.blue=ScaleCharToQuantum(*p++);\n#endif\n fill_color.alpha=ScaleCharToQuantum(*p++);\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n {\n double\n gamma;\n\n gamma=QuantumScale*fill_color.alpha;\n gamma=PerceptibleReciprocal(gamma);\n fill_color.blue*=gamma;\n fill_color.green*=gamma;\n fill_color.red*=gamma;\n }\n#endif\n CompositePixelOver(image,&fill_color,fill_color.alpha,q,(double)\n GetPixelAlpha(image,q),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n if (pixel_info != (MemoryInfo *) NULL)\n pixel_info=RelinquishVirtualMemory(pixel_info);\n#else\n g_object_unref(G_OBJECT(pixel_buffer));\n#endif\n (void) CloseBlob(image);\n for (next=GetFirstImageInList(image); next != (Image *) NULL; )\n {\n (void) CopyMagickString(next->filename,image->filename,MaxTextExtent);\n (void) CopyMagickString(next->magick,image->magick,MaxTextExtent);\n next=GetNextImageInList(next);\n }\n return(GetFirstImageInList(image));\n#endif\n }\n }\n /*\n Open draw file.\n */\n file=(FILE *) NULL;\n unique_file=AcquireUniqueFileResource(filename);\n if (unique_file != -1)\n file=fdopen(unique_file,\"w\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n {\n (void) CopyMagickString(image->filename,filename,MagickPathExtent);\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Parse SVG file.\n */\n svg_info=AcquireSVGInfo();\n if (svg_info == (SVGInfo *) NULL)\n {\n (void) fclose(file);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n svg_info->file=file;\n svg_info->exception=exception;\n svg_info->image=image;\n svg_info->image_info=image_info;\n svg_info->bounds.width=image->columns;\n svg_info->bounds.height=image->rows;\n svg_info->svgDepth=0;\n if (image_info->size != (char *) NULL)\n (void) CloneString(&svg_info->size,image_info->size);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"begin SAX\");\n xmlInitParser();\n (void) xmlSubstituteEntitiesDefault(1);\n (void) memset(&sax_modules,0,sizeof(sax_modules));\n sax_modules.internalSubset=SVGInternalSubset;\n sax_modules.isStandalone=SVGIsStandalone;\n sax_modules.hasInternalSubset=SVGHasInternalSubset;\n sax_modules.hasExternalSubset=SVGHasExternalSubset;\n sax_modules.resolveEntity=SVGResolveEntity;\n sax_modules.getEntity=SVGGetEntity;\n sax_modules.entityDecl=SVGEntityDeclaration;\n sax_modules.notationDecl=SVGNotationDeclaration;\n sax_modules.attributeDecl=SVGAttributeDeclaration;\n sax_modules.elementDecl=SVGElementDeclaration;\n sax_modules.unparsedEntityDecl=SVGUnparsedEntityDeclaration;\n sax_modules.setDocumentLocator=SVGSetDocumentLocator;\n sax_modules.startDocument=SVGStartDocument;\n sax_modules.endDocument=SVGEndDocument;\n sax_modules.startElement=SVGStartElement;\n sax_modules.endElement=SVGEndElement;\n sax_modules.reference=SVGReference;\n sax_modules.characters=SVGCharacters;\n sax_modules.ignorableWhitespace=SVGIgnorableWhitespace;\n sax_modules.processingInstruction=SVGProcessingInstructions;\n sax_modules.comment=SVGComment;\n sax_modules.warning=SVGWarning;\n sax_modules.error=SVGError;\n sax_modules.fatalError=SVGError;\n sax_modules.getParameterEntity=SVGGetParameterEntity;\n sax_modules.cdataBlock=SVGCDataBlock;\n sax_modules.externalSubset=SVGExternalSubset;\n sax_handler=(&sax_modules);\n n=ReadBlob(image,MagickPathExtent-1,message);\n message[n]='\\0';\n if (n > 0)\n {\n svg_info->parser=xmlCreatePushParserCtxt(sax_handler,svg_info,(char *)\n message,n,image->filename);\n option=GetImageOption(image_info,\"svg:xml-parse-huge\");\n if ((option != (char *) NULL) && (IsStringTrue(option) != MagickFalse))\n (void) xmlCtxtUseOptions(svg_info->parser,XML_PARSE_HUGE);\n while ((n=ReadBlob(image,MagickPathExtent-1,message)) != 0)\n {\n message[n]='\\0';\n status=xmlParseChunk(svg_info->parser,(char *) message,(int) n,0);\n if (status != 0)\n break;\n }\n }\n (void) xmlParseChunk(svg_info->parser,(char *) message,0,1);\n SVGEndDocument(svg_info);\n if (svg_info->parser->myDoc != (xmlDocPtr) NULL)\n xmlFreeDoc(svg_info->parser->myDoc);\n xmlFreeParserCtxt(svg_info->parser);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"end SAX\");\n (void) fclose(file);\n (void) CloseBlob(image);\n image->columns=svg_info->width;\n image->rows=svg_info->height;\n if (exception->severity >= ErrorException)\n {\n svg_info=DestroySVGInfo(svg_info);\n (void) RelinquishUniqueFileResource(filename);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n if (image_info->ping == MagickFalse)\n {\n ImageInfo\n *read_info;\n\n /*\n Draw image.\n */\n image=DestroyImage(image);\n image=(Image *) NULL;\n read_info=CloneImageInfo(image_info);\n SetImageInfoBlob(read_info,(void *) NULL,0);\n (void) FormatLocaleString(read_info->filename,MagickPathExtent,\"mvg:%s\",\n filename);\n image=ReadImage(read_info,exception);\n read_info=DestroyImageInfo(read_info);\n if (image != (Image *) NULL)\n (void) CopyMagickString(image->filename,image_info->filename,\n MagickPathExtent);\n }\n /*\n Relinquish resources.\n */\n if (image != (Image *) NULL)\n {\n if (svg_info->title != (char *) NULL)\n (void) SetImageProperty(image,\"svg:title\",svg_info->title,exception);\n if (svg_info->comment != (char *) NULL)\n (void) SetImageProperty(image,\"svg:comment\",svg_info->comment,\n exception);\n }\n for (next=GetFirstImageInList(image); next != (Image *) NULL; )\n {\n (void) CopyMagickString(next->filename,image->filename,MaxTextExtent);\n (void) CopyMagickString(next->magick,image->magick,MaxTextExtent);\n next=GetNextImageInList(next);\n }\n svg_info=DestroySVGInfo(svg_info);\n (void) RelinquishUniqueFileResource(filename);\n return(GetFirstImageInList(image));\n}", "project": "ImageMagick", "hash": 25217158321971555438423291073333068574, "size": 492, "commit_id": "43dfb1894761c4929d5d5c98dc80ba4e59a0d114", "message": "Handle null pointer return from call to xmlCreatePushParserCtxt (#2624).", "target": 1, "dataset": "other", "idx": 208034} {"func": "static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n filename[MagickPathExtent];\n\n const char\n *option;\n\n FILE\n *file;\n\n Image\n *image,\n *next;\n\n int\n status,\n unique_file;\n\n ssize_t\n n;\n\n SVGInfo\n *svg_info;\n\n unsigned char\n message[MagickPathExtent];\n\n xmlSAXHandler\n sax_modules;\n\n xmlSAXHandlerPtr\n sax_handler;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception->signature == MagickCoreSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if ((fabs(image->resolution.x) < MagickEpsilon) ||\n (fabs(image->resolution.y) < MagickEpsilon))\n {\n GeometryInfo\n geometry_info;\n\n int\n flags;\n\n flags=ParseGeometry(SVGDensityGeometry,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n }\n if (LocaleCompare(image_info->magick,\"MSVG\") != 0)\n {\n Image\n *svg_image;\n\n svg_image=RenderSVGImage(image_info,image,exception);\n if (svg_image != (Image *) NULL)\n {\n image=DestroyImageList(image);\n return(svg_image);\n }\n {\n#if defined(MAGICKCORE_RSVG_DELEGATE)\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n cairo_surface_t\n *cairo_surface;\n\n cairo_t\n *cairo_image;\n\n MagickBooleanType\n apply_density;\n\n MemoryInfo\n *pixel_info;\n\n register unsigned char\n *p;\n\n RsvgDimensionData\n dimension_info;\n\n unsigned char\n *pixels;\n\n#else\n GdkPixbuf\n *pixel_buffer;\n\n register const guchar\n *p;\n#endif\n\n GError\n *error;\n\n PixelInfo\n fill_color;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n RsvgHandle\n *svg_handle;\n\n ssize_t\n y;\n\n unsigned char\n *buffer;\n\n buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent,\n sizeof(*buffer));\n if (buffer == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n#if LIBRSVG_CHECK_VERSION(2,40,3)\n option=GetImageOption(image_info,\"svg:xml-parse-huge\");\n if ((option != (char *) NULL) && (IsStringTrue(option) != MagickFalse))\n svg_handle=rsvg_handle_new_with_flags(RSVG_HANDLE_FLAG_UNLIMITED);\n else\n#endif\n svg_handle=rsvg_handle_new();\n if (svg_handle == (RsvgHandle *) NULL)\n {\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n rsvg_handle_set_base_uri(svg_handle,image_info->filename);\n if ((fabs(image->resolution.x) > MagickEpsilon) &&\n (fabs(image->resolution.y) > MagickEpsilon))\n rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x,\n image->resolution.y);\n while ((n=ReadBlob(image,MagickMaxBufferExtent-1,buffer)) != 0)\n {\n buffer[n]='\\0';\n error=(GError *) NULL;\n (void) rsvg_handle_write(svg_handle,buffer,n,&error);\n if (error != (GError *) NULL)\n g_error_free(error);\n }\n buffer=(unsigned char *) RelinquishMagickMemory(buffer);\n error=(GError *) NULL;\n rsvg_handle_close(svg_handle,&error);\n if (error != (GError *) NULL)\n g_error_free(error);\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n apply_density=MagickTrue;\n rsvg_handle_get_dimensions(svg_handle,&dimension_info);\n if ((image->resolution.x > 0.0) && (image->resolution.y > 0.0))\n {\n RsvgDimensionData\n dpi_dimension_info;\n\n /*\n We should not apply the density when the internal 'factor' is 'i'.\n This can be checked by using the trick below.\n */\n rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x*256,\n image->resolution.y*256);\n rsvg_handle_get_dimensions(svg_handle,&dpi_dimension_info);\n if ((dpi_dimension_info.width != dimension_info.width) ||\n (dpi_dimension_info.height != dimension_info.height))\n apply_density=MagickFalse;\n rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x,\n image->resolution.y);\n }\n if (image_info->size != (char *) NULL)\n {\n (void) GetGeometry(image_info->size,(ssize_t *) NULL,\n (ssize_t *) NULL,&image->columns,&image->rows);\n if ((image->columns != 0) || (image->rows != 0))\n {\n image->resolution.x=DefaultSVGDensity*image->columns/\n dimension_info.width;\n image->resolution.y=DefaultSVGDensity*image->rows/\n dimension_info.height;\n if (fabs(image->resolution.x) < MagickEpsilon)\n image->resolution.x=image->resolution.y;\n else\n if (fabs(image->resolution.y) < MagickEpsilon)\n image->resolution.y=image->resolution.x;\n else\n image->resolution.x=image->resolution.y=MagickMin(\n image->resolution.x,image->resolution.y);\n apply_density=MagickTrue;\n }\n }\n if (apply_density != MagickFalse)\n {\n image->columns=image->resolution.x*dimension_info.width/\n DefaultSVGDensity;\n image->rows=image->resolution.y*dimension_info.height/\n DefaultSVGDensity;\n }\n else\n {\n image->columns=dimension_info.width;\n image->rows=dimension_info.height;\n }\n pixel_info=(MemoryInfo *) NULL;\n#else\n pixel_buffer=rsvg_handle_get_pixbuf(svg_handle);\n rsvg_handle_free(svg_handle);\n image->columns=gdk_pixbuf_get_width(pixel_buffer);\n image->rows=gdk_pixbuf_get_height(pixel_buffer);\n#endif\n image->alpha_trait=BlendPixelTrait;\n if (image_info->ping == MagickFalse)\n {\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n size_t\n stride;\n#endif\n\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n {\n#if !defined(MAGICKCORE_CAIRO_DELEGATE)\n g_object_unref(G_OBJECT(pixel_buffer));\n#endif\n g_object_unref(svg_handle);\n ThrowReaderException(MissingDelegateError,\n \"NoDecodeDelegateForThisImageFormat\");\n }\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n stride=4*image->columns;\n#if defined(MAGICKCORE_PANGOCAIRO_DELEGATE)\n stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32,\n (int) image->columns);\n#endif\n pixel_info=AcquireVirtualMemory(stride,image->rows*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n g_object_unref(svg_handle);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n#endif\n (void) SetImageBackgroundColor(image,exception);\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n cairo_surface=cairo_image_surface_create_for_data(pixels,\n CAIRO_FORMAT_ARGB32,(int) image->columns,(int) image->rows,(int)\n stride);\n if ((cairo_surface == (cairo_surface_t *) NULL) ||\n (cairo_surface_status(cairo_surface) != CAIRO_STATUS_SUCCESS))\n {\n if (cairo_surface != (cairo_surface_t *) NULL)\n cairo_surface_destroy(cairo_surface);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n g_object_unref(svg_handle);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n cairo_image=cairo_create(cairo_surface);\n cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR);\n cairo_paint(cairo_image);\n cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER);\n if (apply_density != MagickFalse)\n cairo_scale(cairo_image,image->resolution.x/DefaultSVGDensity,\n image->resolution.y/DefaultSVGDensity);\n rsvg_handle_render_cairo(svg_handle,cairo_image);\n cairo_destroy(cairo_image);\n cairo_surface_destroy(cairo_surface);\n g_object_unref(svg_handle);\n p=pixels;\n#else\n p=gdk_pixbuf_get_pixels(pixel_buffer);\n#endif\n GetPixelInfo(image,&fill_color);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n fill_color.blue=ScaleCharToQuantum(*p++);\n fill_color.green=ScaleCharToQuantum(*p++);\n fill_color.red=ScaleCharToQuantum(*p++);\n#else\n fill_color.red=ScaleCharToQuantum(*p++);\n fill_color.green=ScaleCharToQuantum(*p++);\n fill_color.blue=ScaleCharToQuantum(*p++);\n#endif\n fill_color.alpha=ScaleCharToQuantum(*p++);\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n {\n double\n gamma;\n\n gamma=QuantumScale*fill_color.alpha;\n gamma=PerceptibleReciprocal(gamma);\n fill_color.blue*=gamma;\n fill_color.green*=gamma;\n fill_color.red*=gamma;\n }\n#endif\n CompositePixelOver(image,&fill_color,fill_color.alpha,q,(double)\n GetPixelAlpha(image,q),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n#if defined(MAGICKCORE_CAIRO_DELEGATE)\n if (pixel_info != (MemoryInfo *) NULL)\n pixel_info=RelinquishVirtualMemory(pixel_info);\n#else\n g_object_unref(G_OBJECT(pixel_buffer));\n#endif\n (void) CloseBlob(image);\n for (next=GetFirstImageInList(image); next != (Image *) NULL; )\n {\n (void) CopyMagickString(next->filename,image->filename,MaxTextExtent);\n (void) CopyMagickString(next->magick,image->magick,MaxTextExtent);\n next=GetNextImageInList(next);\n }\n return(GetFirstImageInList(image));\n#endif\n }\n }\n /*\n Open draw file.\n */\n file=(FILE *) NULL;\n unique_file=AcquireUniqueFileResource(filename);\n if (unique_file != -1)\n file=fdopen(unique_file,\"w\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n {\n (void) CopyMagickString(image->filename,filename,MagickPathExtent);\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Parse SVG file.\n */\n svg_info=AcquireSVGInfo();\n if (svg_info == (SVGInfo *) NULL)\n {\n (void) fclose(file);\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n svg_info->file=file;\n svg_info->exception=exception;\n svg_info->image=image;\n svg_info->image_info=image_info;\n svg_info->bounds.width=image->columns;\n svg_info->bounds.height=image->rows;\n svg_info->svgDepth=0;\n if (image_info->size != (char *) NULL)\n (void) CloneString(&svg_info->size,image_info->size);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"begin SAX\");\n xmlInitParser();\n (void) xmlSubstituteEntitiesDefault(1);\n (void) memset(&sax_modules,0,sizeof(sax_modules));\n sax_modules.internalSubset=SVGInternalSubset;\n sax_modules.isStandalone=SVGIsStandalone;\n sax_modules.hasInternalSubset=SVGHasInternalSubset;\n sax_modules.hasExternalSubset=SVGHasExternalSubset;\n sax_modules.resolveEntity=SVGResolveEntity;\n sax_modules.getEntity=SVGGetEntity;\n sax_modules.entityDecl=SVGEntityDeclaration;\n sax_modules.notationDecl=SVGNotationDeclaration;\n sax_modules.attributeDecl=SVGAttributeDeclaration;\n sax_modules.elementDecl=SVGElementDeclaration;\n sax_modules.unparsedEntityDecl=SVGUnparsedEntityDeclaration;\n sax_modules.setDocumentLocator=SVGSetDocumentLocator;\n sax_modules.startDocument=SVGStartDocument;\n sax_modules.endDocument=SVGEndDocument;\n sax_modules.startElement=SVGStartElement;\n sax_modules.endElement=SVGEndElement;\n sax_modules.reference=SVGReference;\n sax_modules.characters=SVGCharacters;\n sax_modules.ignorableWhitespace=SVGIgnorableWhitespace;\n sax_modules.processingInstruction=SVGProcessingInstructions;\n sax_modules.comment=SVGComment;\n sax_modules.warning=SVGWarning;\n sax_modules.error=SVGError;\n sax_modules.fatalError=SVGError;\n sax_modules.getParameterEntity=SVGGetParameterEntity;\n sax_modules.cdataBlock=SVGCDataBlock;\n sax_modules.externalSubset=SVGExternalSubset;\n sax_handler=(&sax_modules);\n n=ReadBlob(image,MagickPathExtent-1,message);\n message[n]='\\0';\n if (n > 0)\n {\n svg_info->parser=xmlCreatePushParserCtxt(sax_handler,svg_info,(char *)\n message,n,image->filename);\n if (svg_info->parser != (xmlParserCtxtPtr) NULL)\n {\n option=GetImageOption(image_info,\"svg:xml-parse-huge\");\n if ((option != (char *) NULL) && (IsStringTrue(option) != MagickFalse))\n (void) xmlCtxtUseOptions(svg_info->parser,XML_PARSE_HUGE);\n while ((n=ReadBlob(image,MagickPathExtent-1,message)) != 0)\n {\n message[n]='\\0';\n status=xmlParseChunk(svg_info->parser,(char *) message,(int) n,0);\n if (status != 0)\n break;\n }\n }\n }\n if (svg_info->parser == (xmlParserCtxtPtr) NULL)\n {\n svg_info=DestroySVGInfo(svg_info);\n (void) RelinquishUniqueFileResource(filename);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n (void) xmlParseChunk(svg_info->parser,(char *) message,0,1);\n SVGEndDocument(svg_info);\n if (svg_info->parser->myDoc != (xmlDocPtr) NULL)\n xmlFreeDoc(svg_info->parser->myDoc);\n xmlFreeParserCtxt(svg_info->parser);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"end SAX\");\n (void) fclose(file);\n (void) CloseBlob(image);\n image->columns=svg_info->width;\n image->rows=svg_info->height;\n if (exception->severity >= ErrorException)\n {\n svg_info=DestroySVGInfo(svg_info);\n (void) RelinquishUniqueFileResource(filename);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n if (image_info->ping == MagickFalse)\n {\n ImageInfo\n *read_info;\n\n /*\n Draw image.\n */\n image=DestroyImage(image);\n image=(Image *) NULL;\n read_info=CloneImageInfo(image_info);\n SetImageInfoBlob(read_info,(void *) NULL,0);\n (void) FormatLocaleString(read_info->filename,MagickPathExtent,\"mvg:%s\",\n filename);\n image=ReadImage(read_info,exception);\n read_info=DestroyImageInfo(read_info);\n if (image != (Image *) NULL)\n (void) CopyMagickString(image->filename,image_info->filename,\n MagickPathExtent);\n }\n /*\n Relinquish resources.\n */\n if (image != (Image *) NULL)\n {\n if (svg_info->title != (char *) NULL)\n (void) SetImageProperty(image,\"svg:title\",svg_info->title,exception);\n if (svg_info->comment != (char *) NULL)\n (void) SetImageProperty(image,\"svg:comment\",svg_info->comment,\n exception);\n }\n for (next=GetFirstImageInList(image); next != (Image *) NULL; )\n {\n (void) CopyMagickString(next->filename,image->filename,MaxTextExtent);\n (void) CopyMagickString(next->magick,image->magick,MaxTextExtent);\n next=GetNextImageInList(next);\n }\n svg_info=DestroySVGInfo(svg_info);\n (void) RelinquishUniqueFileResource(filename);\n return(GetFirstImageInList(image));\n}", "project": "ImageMagick", "hash": 69475010542433184360573770927608777665, "size": 502, "commit_id": "43dfb1894761c4929d5d5c98dc80ba4e59a0d114", "message": "Handle null pointer return from call to xmlCreatePushParserCtxt (#2624).", "target": 0, "dataset": "other", "idx": 404419} {"func": "CryptRsaDecrypt(\n\t\tTPM2B *dOut, // OUT: the decrypted data\n\t\tTPM2B *cIn, // IN: the data to decrypt\n\t\tOBJECT *key, // IN: the key to use for decryption\n\t\tTPMT_RSA_DECRYPT *scheme, // IN: the padding scheme\n\t\tconst TPM2B *label // IN: in case it is needed for the scheme\n\t\t)\n{\n TPM_RC retVal;\n EVP_PKEY *pkey = NULL;\n EVP_PKEY_CTX *ctx = NULL;\n const EVP_MD *md = NULL;\n const char *digestname;\n size_t outlen;\n unsigned char *tmp = NULL;\n\n // Make sure that the necessary parameters are provided\n pAssert(cIn != NULL && dOut != NULL && key != NULL);\n // Size is checked to make sure that the encrypted value is the right size\n if(cIn->size != key->publicArea.unique.rsa.t.size)\n ERROR_RETURN(TPM_RC_SIZE);\n TEST(scheme->scheme);\n\n retVal = InitOpenSSLRSAPrivateKey(key, &pkey);\n if (retVal != TPM_RC_SUCCESS)\n return retVal;\n\n ctx = EVP_PKEY_CTX_new(pkey, NULL);\n if (ctx == NULL ||\n EVP_PKEY_decrypt_init(ctx) <= 0)\n ERROR_RETURN(TPM_RC_FAILURE);\n\n switch(scheme->scheme)\n\t{\n\t case ALG_NULL_VALUE: // 'raw' encryption\n if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_NO_PADDING) <= 0)\n ERROR_RETURN(TPM_RC_FAILURE);\n break;\n\t case ALG_RSAES_VALUE:\n if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0)\n ERROR_RETURN(TPM_RC_FAILURE);\n break;\n\t case ALG_OAEP_VALUE:\n digestname = GetDigestNameByHashAlg(scheme->details.oaep.hashAlg);\n if (digestname == NULL)\n ERROR_RETURN(TPM_RC_VALUE);\n\n md = EVP_get_digestbyname(digestname);\n if (md == NULL ||\n EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0 ||\n EVP_PKEY_CTX_set_rsa_oaep_md(ctx, md) <= 0)\n ERROR_RETURN(TPM_RC_FAILURE);\n\n if (label->size > 0) {\n tmp = malloc(label->size);\n if (tmp == NULL)\n ERROR_RETURN(TPM_RC_FAILURE);\n memcpy(tmp, label->buffer, label->size);\n }\n\n if (EVP_PKEY_CTX_set0_rsa_oaep_label(ctx, tmp, label->size) <= 0)\n ERROR_RETURN(TPM_RC_FAILURE);\n tmp = NULL;\n break;\n\t default:\n ERROR_RETURN(TPM_RC_SCHEME);\n break;\n\t}\n\n outlen = cIn->size;\n if (EVP_PKEY_decrypt(ctx, dOut->buffer, &outlen,\n cIn->buffer, cIn->size) <= 0)\n ERROR_RETURN(TPM_RC_FAILURE);\n\n dOut->size = outlen;\n\n retVal = TPM_RC_SUCCESS;\n\n Exit:\n EVP_PKEY_free(pkey);\n EVP_PKEY_CTX_free(ctx);\n free(tmp);\n\n return retVal;\n}", "project": "libtpms", "hash": 336056029318474660269537136446607856601, "size": 85, "commit_id": "40cfe134c017d3aeaaed05ce71eaf9bfbe556b16", "message": "tpm2: Fix output buffer parameter and size for RSA decryption\n\nFor the RSA decryption we have to use an output buffer of the size of the\n(largest possible) RSA key for the decryption to always work.\n\nThis fixes a stack corruption bug that caused a SIGBUS and termination of\n'swtpm'.\n\nSigned-off-by: Stefan Berger ", "target": 1, "dataset": "other", "idx": 208069} {"func": "CryptRsaDecrypt(\n\t\tTPM2B *dOut, // OUT: the decrypted data\n\t\tTPM2B *cIn, // IN: the data to decrypt\n\t\tOBJECT *key, // IN: the key to use for decryption\n\t\tTPMT_RSA_DECRYPT *scheme, // IN: the padding scheme\n\t\tconst TPM2B *label // IN: in case it is needed for the scheme\n\t\t)\n{\n TPM_RC retVal;\n EVP_PKEY *pkey = NULL;\n EVP_PKEY_CTX *ctx = NULL;\n const EVP_MD *md = NULL;\n const char *digestname;\n size_t outlen;\n unsigned char *tmp = NULL;\n unsigned char buffer[MAX_RSA_KEY_BYTES];\n\n // Make sure that the necessary parameters are provided\n pAssert(cIn != NULL && dOut != NULL && key != NULL);\n // Size is checked to make sure that the encrypted value is the right size\n if(cIn->size != key->publicArea.unique.rsa.t.size)\n ERROR_RETURN(TPM_RC_SIZE);\n TEST(scheme->scheme);\n\n retVal = InitOpenSSLRSAPrivateKey(key, &pkey);\n if (retVal != TPM_RC_SUCCESS)\n return retVal;\n\n ctx = EVP_PKEY_CTX_new(pkey, NULL);\n if (ctx == NULL ||\n EVP_PKEY_decrypt_init(ctx) <= 0)\n ERROR_RETURN(TPM_RC_FAILURE);\n\n switch(scheme->scheme)\n\t{\n\t case ALG_NULL_VALUE: // 'raw' encryption\n if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_NO_PADDING) <= 0)\n ERROR_RETURN(TPM_RC_FAILURE);\n break;\n\t case ALG_RSAES_VALUE:\n if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0)\n ERROR_RETURN(TPM_RC_FAILURE);\n break;\n\t case ALG_OAEP_VALUE:\n digestname = GetDigestNameByHashAlg(scheme->details.oaep.hashAlg);\n if (digestname == NULL)\n ERROR_RETURN(TPM_RC_VALUE);\n\n md = EVP_get_digestbyname(digestname);\n if (md == NULL ||\n EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0 ||\n EVP_PKEY_CTX_set_rsa_oaep_md(ctx, md) <= 0)\n ERROR_RETURN(TPM_RC_FAILURE);\n\n if (label->size > 0) {\n tmp = malloc(label->size);\n if (tmp == NULL)\n ERROR_RETURN(TPM_RC_FAILURE);\n memcpy(tmp, label->buffer, label->size);\n }\n\n if (EVP_PKEY_CTX_set0_rsa_oaep_label(ctx, tmp, label->size) <= 0)\n ERROR_RETURN(TPM_RC_FAILURE);\n tmp = NULL;\n break;\n\t default:\n ERROR_RETURN(TPM_RC_SCHEME);\n break;\n\t}\n\n /* cannot use cOut->buffer */\n outlen = sizeof(buffer);\n if (EVP_PKEY_decrypt(ctx, buffer, &outlen,\n cIn->buffer, cIn->size) <= 0)\n ERROR_RETURN(TPM_RC_FAILURE);\n\n if (outlen > dOut->size)\n ERROR_RETURN(TPM_RC_FAILURE);\n\n memcpy(dOut->buffer, buffer, outlen);\n dOut->size = outlen;\n\n retVal = TPM_RC_SUCCESS;\n\n Exit:\n EVP_PKEY_free(pkey);\n EVP_PKEY_CTX_free(ctx);\n free(tmp);\n\n return retVal;\n}", "project": "libtpms", "hash": 84935986072655399087103363215779446823, "size": 91, "commit_id": "40cfe134c017d3aeaaed05ce71eaf9bfbe556b16", "message": "tpm2: Fix output buffer parameter and size for RSA decryption\n\nFor the RSA decryption we have to use an output buffer of the size of the\n(largest possible) RSA key for the decryption to always work.\n\nThis fixes a stack corruption bug that caused a SIGBUS and termination of\n'swtpm'.\n\nSigned-off-by: Stefan Berger ", "target": 0, "dataset": "other", "idx": 404492} {"func": "convert(\n Imaging imOut, Imaging imIn, const char *mode, ImagingPalette palette, int dither) {\n ImagingSectionCookie cookie;\n ImagingShuffler convert;\n int y;\n\n if (!imIn) {\n return (Imaging)ImagingError_ModeError();\n }\n\n if (!mode) {\n /* Map palette image to full depth */\n if (!imIn->palette) {\n return (Imaging)ImagingError_ModeError();\n }\n mode = imIn->palette->mode;\n } else {\n /* Same mode? */\n if (!strcmp(imIn->mode, mode)) {\n return ImagingCopy2(imOut, imIn);\n }\n }\n\n /* test for special conversions */\n\n if (strcmp(imIn->mode, \"P\") == 0 || strcmp(imIn->mode, \"PA\") == 0) {\n return frompalette(imOut, imIn, mode);\n }\n\n if (strcmp(mode, \"P\") == 0 || strcmp(mode, \"PA\") == 0) {\n return topalette(imOut, imIn, mode, palette, dither);\n }\n\n if (dither && strcmp(mode, \"1\") == 0) {\n return tobilevel(imOut, imIn, dither);\n }\n\n /* standard conversion machinery */\n\n convert = NULL;\n\n for (y = 0; converters[y].from; y++) {\n if (!strcmp(imIn->mode, converters[y].from) &&\n !strcmp(mode, converters[y].to)) {\n convert = converters[y].convert;\n break;\n }\n }\n\n if (!convert) {\n#ifdef notdef\n return (Imaging)ImagingError_ValueError(\"conversion not supported\");\n#else\n static char buf[100];\n sprintf(buf, \"conversion from %.10s to %.10s not supported\", imIn->mode, mode);\n return (Imaging)ImagingError_ValueError(buf);\n#endif\n }\n\n imOut = ImagingNew2Dirty(mode, imOut, imIn);\n if (!imOut) {\n return NULL;\n }\n\n ImagingSectionEnter(&cookie);\n for (y = 0; y < imIn->ysize; y++) {\n (*convert)((UINT8 *)imOut->image[y], (UINT8 *)imIn->image[y], imIn->xsize);\n }\n ImagingSectionLeave(&cookie);\n\n return imOut;\n}", "project": "Pillow", "hash": 106666609759821496258963236330025048119, "size": 72, "commit_id": "518ee3722a99d7f7d890db82a20bd81c1c0327fb", "message": "Use snprintf instead of sprintf", "target": 1, "dataset": "other", "idx": 208176} {"func": "convert(\n Imaging imOut, Imaging imIn, const char *mode, ImagingPalette palette, int dither) {\n ImagingSectionCookie cookie;\n ImagingShuffler convert;\n int y;\n\n if (!imIn) {\n return (Imaging)ImagingError_ModeError();\n }\n\n if (!mode) {\n /* Map palette image to full depth */\n if (!imIn->palette) {\n return (Imaging)ImagingError_ModeError();\n }\n mode = imIn->palette->mode;\n } else {\n /* Same mode? */\n if (!strcmp(imIn->mode, mode)) {\n return ImagingCopy2(imOut, imIn);\n }\n }\n\n /* test for special conversions */\n\n if (strcmp(imIn->mode, \"P\") == 0 || strcmp(imIn->mode, \"PA\") == 0) {\n return frompalette(imOut, imIn, mode);\n }\n\n if (strcmp(mode, \"P\") == 0 || strcmp(mode, \"PA\") == 0) {\n return topalette(imOut, imIn, mode, palette, dither);\n }\n\n if (dither && strcmp(mode, \"1\") == 0) {\n return tobilevel(imOut, imIn, dither);\n }\n\n /* standard conversion machinery */\n\n convert = NULL;\n\n for (y = 0; converters[y].from; y++) {\n if (!strcmp(imIn->mode, converters[y].from) &&\n !strcmp(mode, converters[y].to)) {\n convert = converters[y].convert;\n break;\n }\n }\n\n if (!convert) {\n#ifdef notdef\n return (Imaging)ImagingError_ValueError(\"conversion not supported\");\n#else\n static char buf[100];\n snprintf(buf, 100, \"conversion from %.10s to %.10s not supported\", imIn->mode, mode);\n return (Imaging)ImagingError_ValueError(buf);\n#endif\n }\n\n imOut = ImagingNew2Dirty(mode, imOut, imIn);\n if (!imOut) {\n return NULL;\n }\n\n ImagingSectionEnter(&cookie);\n for (y = 0; y < imIn->ysize; y++) {\n (*convert)((UINT8 *)imOut->image[y], (UINT8 *)imIn->image[y], imIn->xsize);\n }\n ImagingSectionLeave(&cookie);\n\n return imOut;\n}", "project": "Pillow", "hash": 250426672546487471044540466681713327260, "size": 72, "commit_id": "518ee3722a99d7f7d890db82a20bd81c1c0327fb", "message": "Use snprintf instead of sprintf", "target": 0, "dataset": "other", "idx": 406417} {"func": "MagickExport void ScaleResampleFilter(ResampleFilter *resample_filter,\n const double dux,const double duy,const double dvx,const double dvy)\n{\n double A,B,C,F;\n\n assert(resample_filter != (ResampleFilter *) NULL);\n assert(resample_filter->signature == MagickCoreSignature);\n\n resample_filter->limit_reached = MagickFalse;\n\n /* A 'point' filter forces use of interpolation instead of area sampling */\n if ( resample_filter->filter == PointFilter )\n return; /* EWA turned off - nothing to do */\n\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"# -----\\n\" );\n (void) FormatLocaleFile(stderr, \"dux=%lf; dvx=%lf; duy=%lf; dvy=%lf;\\n\",\n dux, dvx, duy, dvy);\n#endif\n\n /* Find Ellipse Coefficents such that\n A*u^2 + B*u*v + C*v^2 = F\n With u,v relative to point around which we are resampling.\n And the given scaling dx,dy vectors in u,v space\n du/dx,dv/dx and du/dy,dv/dy\n */\n#if EWA\n /* Direct conversion of derivatives into elliptical coefficients\n However when magnifying images, the scaling vectors will be small\n resulting in a ellipse that is too small to sample properly.\n As such we need to clamp the major/minor axis to a minumum of 1.0\n to prevent it getting too small.\n */\n#if EWA_CLAMP\n { double major_mag,\n minor_mag,\n major_x,\n major_y,\n minor_x,\n minor_y;\n\n ClampUpAxes(dux,dvx,duy,dvy, &major_mag, &minor_mag,\n &major_x, &major_y, &minor_x, &minor_y);\n major_x *= major_mag; major_y *= major_mag;\n minor_x *= minor_mag; minor_y *= minor_mag;\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"major_x=%lf; major_y=%lf; minor_x=%lf; minor_y=%lf;\\n\",\n major_x, major_y, minor_x, minor_y);\n#endif\n A = major_y*major_y+minor_y*minor_y;\n B = -2.0*(major_x*major_y+minor_x*minor_y);\n C = major_x*major_x+minor_x*minor_x;\n F = major_mag*minor_mag;\n F *= F; /* square it */\n }\n#else /* raw unclamped EWA */\n A = dvx*dvx+dvy*dvy;\n B = -2.0*(dux*dvx+duy*dvy);\n C = dux*dux+duy*duy;\n F = dux*dvy-duy*dvx;\n F *= F; /* square it */\n#endif /* EWA_CLAMP */\n\n#else /* HQ_EWA */\n /*\n This Paul Heckbert's \"Higher Quality EWA\" formula, from page 60 in his\n thesis, which adds a unit circle to the elliptical area so as to do both\n Reconstruction and Prefiltering of the pixels in the resampling. It also\n means it is always likely to have at least 4 pixels within the area of the\n ellipse, for weighted averaging. No scaling will result with F == 4.0 and\n a circle of radius 2.0, and F smaller than this means magnification is\n being used.\n\n NOTE: This method produces a very blury result at near unity scale while\n producing perfect results for strong minitification and magnifications.\n\n However filter support is fixed to 2.0 (no good for Windowed Sinc filters)\n */\n A = dvx*dvx+dvy*dvy+1;\n B = -2.0*(dux*dvx+duy*dvy);\n C = dux*dux+duy*duy+1;\n F = A*C - B*B/4;\n#endif\n\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"A=%lf; B=%lf; C=%lf; F=%lf\\n\", A,B,C,F);\n\n /* Figure out the various information directly about the ellipse.\n This information currently not needed at this time, but may be\n needed later for better limit determination.\n\n It is also good to have as a record for future debugging\n */\n { double alpha, beta, gamma, Major, Minor;\n double Eccentricity, Ellipse_Area, Ellipse_Angle;\n\n alpha = A+C;\n beta = A-C;\n gamma = sqrt(beta*beta + B*B );\n\n if ( alpha - gamma <= MagickEpsilon )\n Major=MagickMaximumValue;\n else\n Major=sqrt(2*F/(alpha - gamma));\n Minor = sqrt(2*F/(alpha + gamma));\n\n (void) FormatLocaleFile(stderr, \"# Major=%lf; Minor=%lf\\n\", Major, Minor );\n\n /* other information about ellipse include... */\n Eccentricity = Major/Minor;\n Ellipse_Area = MagickPI*Major*Minor;\n Ellipse_Angle = atan2(B, A-C);\n\n (void) FormatLocaleFile(stderr, \"# Angle=%lf Area=%lf\\n\",\n (double) RadiansToDegrees(Ellipse_Angle), Ellipse_Area);\n }\n#endif\n\n /* If one or both of the scaling vectors is impossibly large\n (producing a very large raw F value), we may as well not bother\n doing any form of resampling since resampled area is very large.\n In this case some alternative means of pixel sampling, such as\n the average of the whole image is needed to get a reasonable\n result. Calculate only as needed.\n */\n if ( (4*A*C - B*B) > MagickMaximumValue ) {\n resample_filter->limit_reached = MagickTrue;\n return;\n }\n\n /* Scale ellipse to match the filters support\n (that is, multiply F by the square of the support)\n Simplier to just multiply it by the support twice!\n */\n F *= resample_filter->support;\n F *= resample_filter->support;\n\n /* Orthogonal bounds of the ellipse */\n resample_filter->Ulimit = sqrt(C*F/(A*C-0.25*B*B));\n resample_filter->Vlimit = sqrt(A*F/(A*C-0.25*B*B));\n\n /* Horizontally aligned parallelogram fitted to Ellipse */\n resample_filter->Uwidth = sqrt(F/A); /* Half of the parallelogram width */\n resample_filter->slope = -B/(2.0*A); /* Reciprocal slope of the parallelogram */\n\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"Ulimit=%lf; Vlimit=%lf; UWidth=%lf; Slope=%lf;\\n\",\n resample_filter->Ulimit, resample_filter->Vlimit,\n resample_filter->Uwidth, resample_filter->slope );\n#endif\n\n /* Check the absolute area of the parallelogram involved.\n * This limit needs more work, as it is too slow for larger images\n * with tiled views of the horizon.\n */\n if ( (resample_filter->Uwidth * resample_filter->Vlimit)\n > (4.0*resample_filter->image_area)) {\n resample_filter->limit_reached = MagickTrue;\n return;\n }\n\n /* Scale ellipse formula to directly index the Filter Lookup Table */\n { double scale;\n#if FILTER_LUT\n /* scale so that F = WLUT_WIDTH; -- hardcoded */\n scale = (double)WLUT_WIDTH/F;\n#else\n /* scale so that F = resample_filter->F (support^2) */\n scale = resample_filter->F/F;\n#endif\n resample_filter->A = A*scale;\n resample_filter->B = B*scale;\n resample_filter->C = C*scale;\n }\n}", "project": "ImageMagick", "hash": 231019287981565352051359680228225257165, "size": 175, "commit_id": "8d25d94a363b104acd6ff23df7470aeedb806c51", "message": "https://github.com/ImageMagick/ImageMagick/issues/3195", "target": 1, "dataset": "other", "idx": 208186} {"func": "MagickExport void ScaleResampleFilter(ResampleFilter *resample_filter,\n const double dux,const double duy,const double dvx,const double dvy)\n{\n double A,B,C,F;\n\n assert(resample_filter != (ResampleFilter *) NULL);\n assert(resample_filter->signature == MagickCoreSignature);\n\n resample_filter->limit_reached = MagickFalse;\n\n /* A 'point' filter forces use of interpolation instead of area sampling */\n if ( resample_filter->filter == PointFilter )\n return; /* EWA turned off - nothing to do */\n\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"# -----\\n\" );\n (void) FormatLocaleFile(stderr, \"dux=%lf; dvx=%lf; duy=%lf; dvy=%lf;\\n\",\n dux, dvx, duy, dvy);\n#endif\n\n /* Find Ellipse Coefficents such that\n A*u^2 + B*u*v + C*v^2 = F\n With u,v relative to point around which we are resampling.\n And the given scaling dx,dy vectors in u,v space\n du/dx,dv/dx and du/dy,dv/dy\n */\n#if EWA\n /* Direct conversion of derivatives into elliptical coefficients\n However when magnifying images, the scaling vectors will be small\n resulting in a ellipse that is too small to sample properly.\n As such we need to clamp the major/minor axis to a minumum of 1.0\n to prevent it getting too small.\n */\n#if EWA_CLAMP\n { double major_mag,\n minor_mag,\n major_x,\n major_y,\n minor_x,\n minor_y;\n\n ClampUpAxes(dux,dvx,duy,dvy, &major_mag, &minor_mag,\n &major_x, &major_y, &minor_x, &minor_y);\n major_x *= major_mag; major_y *= major_mag;\n minor_x *= minor_mag; minor_y *= minor_mag;\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"major_x=%lf; major_y=%lf; minor_x=%lf; minor_y=%lf;\\n\",\n major_x, major_y, minor_x, minor_y);\n#endif\n A = major_y*major_y+minor_y*minor_y;\n B = -2.0*(major_x*major_y+minor_x*minor_y);\n C = major_x*major_x+minor_x*minor_x;\n F = major_mag*minor_mag;\n F *= F; /* square it */\n }\n#else /* raw unclamped EWA */\n A = dvx*dvx+dvy*dvy;\n B = -2.0*(dux*dvx+duy*dvy);\n C = dux*dux+duy*duy;\n F = dux*dvy-duy*dvx;\n F *= F; /* square it */\n#endif /* EWA_CLAMP */\n\n#else /* HQ_EWA */\n /*\n This Paul Heckbert's \"Higher Quality EWA\" formula, from page 60 in his\n thesis, which adds a unit circle to the elliptical area so as to do both\n Reconstruction and Prefiltering of the pixels in the resampling. It also\n means it is always likely to have at least 4 pixels within the area of the\n ellipse, for weighted averaging. No scaling will result with F == 4.0 and\n a circle of radius 2.0, and F smaller than this means magnification is\n being used.\n\n NOTE: This method produces a very blury result at near unity scale while\n producing perfect results for strong minitification and magnifications.\n\n However filter support is fixed to 2.0 (no good for Windowed Sinc filters)\n */\n A = dvx*dvx+dvy*dvy+1;\n B = -2.0*(dux*dvx+duy*dvy);\n C = dux*dux+duy*duy+1;\n F = A*C - B*B/4;\n#endif\n\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"A=%lf; B=%lf; C=%lf; F=%lf\\n\", A,B,C,F);\n\n /* Figure out the various information directly about the ellipse.\n This information currently not needed at this time, but may be\n needed later for better limit determination.\n\n It is also good to have as a record for future debugging\n */\n { double alpha, beta, gamma, Major, Minor;\n double Eccentricity, Ellipse_Area, Ellipse_Angle;\n\n alpha = A+C;\n beta = A-C;\n gamma = sqrt(beta*beta + B*B );\n\n if ( alpha - gamma <= MagickEpsilon )\n Major=MagickMaximumValue;\n else\n Major=sqrt(2*F/(alpha - gamma));\n Minor = sqrt(2*F/(alpha + gamma));\n\n (void) FormatLocaleFile(stderr, \"# Major=%lf; Minor=%lf\\n\", Major, Minor );\n\n /* other information about ellipse include... */\n Eccentricity = Major/Minor;\n Ellipse_Area = MagickPI*Major*Minor;\n Ellipse_Angle = atan2(B, A-C);\n\n (void) FormatLocaleFile(stderr, \"# Angle=%lf Area=%lf\\n\",\n (double) RadiansToDegrees(Ellipse_Angle), Ellipse_Area);\n }\n#endif\n\n /* If one or both of the scaling vectors is impossibly large\n (producing a very large raw F value), we may as well not bother\n doing any form of resampling since resampled area is very large.\n In this case some alternative means of pixel sampling, such as\n the average of the whole image is needed to get a reasonable\n result. Calculate only as needed.\n */\n if ( (4*A*C - B*B) > MagickMaximumValue ) {\n resample_filter->limit_reached = MagickTrue;\n return;\n }\n\n /* Scale ellipse to match the filters support\n (that is, multiply F by the square of the support)\n Simplier to just multiply it by the support twice!\n */\n F *= resample_filter->support;\n F *= resample_filter->support;\n\n /* Orthogonal bounds of the ellipse */\n resample_filter->Ulimit = sqrt(C*F/(A*C-0.25*B*B));\n resample_filter->Vlimit = sqrt(A*F/(A*C-0.25*B*B));\n\n /* Horizontally aligned parallelogram fitted to Ellipse */\n resample_filter->Uwidth = sqrt(F/A); /* Half of the parallelogram width */\n resample_filter->slope = -B/(2.0*A); /* Reciprocal slope of the parallelogram */\n\n#if DEBUG_ELLIPSE\n (void) FormatLocaleFile(stderr, \"Ulimit=%lf; Vlimit=%lf; UWidth=%lf; Slope=%lf;\\n\",\n resample_filter->Ulimit, resample_filter->Vlimit,\n resample_filter->Uwidth, resample_filter->slope );\n#endif\n\n /* Check the absolute area of the parallelogram involved.\n * This limit needs more work, as it is too slow for larger images\n * with tiled views of the horizon.\n */\n if ( (resample_filter->Uwidth * resample_filter->Vlimit)\n > (4.0*resample_filter->image_area)) {\n resample_filter->limit_reached = MagickTrue;\n return;\n }\n\n /* Scale ellipse formula to directly index the Filter Lookup Table */\n { double scale;\n#if FILTER_LUT\n /* scale so that F = WLUT_WIDTH; -- hardcoded */\n scale=(double) WLUT_WIDTH*PerceptibleReciprocal(F);\n#else\n /* scale so that F = resample_filter->F (support^2) */\n scale=resample_filter->F*PerceptibleReciprocal(F);\n#endif\n resample_filter->A = A*scale;\n resample_filter->B = B*scale;\n resample_filter->C = C*scale;\n }\n}", "project": "ImageMagick", "hash": 159696077506715638875467992554706158674, "size": 175, "commit_id": "8d25d94a363b104acd6ff23df7470aeedb806c51", "message": "https://github.com/ImageMagick/ImageMagick/issues/3195", "target": 0, "dataset": "other", "idx": 406508} {"func": "handle_spawn (PortalFlatpak *object,\n GDBusMethodInvocation *invocation,\n GUnixFDList *fd_list,\n const gchar *arg_cwd_path,\n const gchar *const *arg_argv,\n GVariant *arg_fds,\n GVariant *arg_envs,\n guint arg_flags,\n GVariant *arg_options)\n{\n g_autoptr(GError) error = NULL;\n ChildSetupData child_setup_data = { NULL };\n GPid pid;\n PidData *pid_data;\n InstanceIdReadData *instance_id_read_data = NULL;\n gsize i, j, n_fds, n_envs;\n const gint *fds = NULL;\n gint fds_len = 0;\n g_autofree FdMapEntry *fd_map = NULL;\n gchar **env;\n gint32 max_fd;\n GKeyFile *app_info;\n g_autoptr(GPtrArray) flatpak_argv = g_ptr_array_new_with_free_func (g_free);\n g_autofree char *app_id = NULL;\n g_autofree char *branch = NULL;\n g_autofree char *arch = NULL;\n g_autofree char *app_commit = NULL;\n g_autofree char *runtime_ref = NULL;\n g_auto(GStrv) runtime_parts = NULL;\n g_autofree char *runtime_commit = NULL;\n g_autofree char *instance_path = NULL;\n g_auto(GStrv) extra_args = NULL;\n g_auto(GStrv) shares = NULL;\n g_auto(GStrv) sockets = NULL;\n g_auto(GStrv) devices = NULL;\n g_auto(GStrv) sandbox_expose = NULL;\n g_auto(GStrv) sandbox_expose_ro = NULL;\n g_autoptr(GVariant) sandbox_expose_fd = NULL;\n g_autoptr(GVariant) sandbox_expose_fd_ro = NULL;\n g_autoptr(GOutputStream) instance_id_out_stream = NULL;\n guint sandbox_flags = 0;\n gboolean sandboxed;\n gboolean expose_pids;\n gboolean share_pids;\n gboolean notify_start;\n gboolean devel;\n g_autoptr(GString) env_string = g_string_new (\"\");\n\n child_setup_data.instance_id_fd = -1;\n child_setup_data.env_fd = -1;\n\n if (fd_list != NULL)\n fds = g_unix_fd_list_peek_fds (fd_list, &fds_len);\n\n app_info = g_object_get_data (G_OBJECT (invocation), \"app-info\");\n g_assert (app_info != NULL);\n\n app_id = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_APPLICATION,\n FLATPAK_METADATA_KEY_NAME, NULL);\n g_assert (app_id != NULL);\n\n g_debug (\"spawn() called from app: '%s'\", app_id);\n if (*app_id == 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"org.freedesktop.portal.Flatpak.Spawn only works in a flatpak\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (*arg_cwd_path == 0)\n arg_cwd_path = NULL;\n\n if (arg_argv == NULL || *arg_argv == NULL)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No command given\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if ((arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL) != 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,\n \"Unsupported flags enabled: 0x%x\", arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n runtime_ref = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_APPLICATION,\n FLATPAK_METADATA_KEY_RUNTIME, NULL);\n if (runtime_ref == NULL)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,\n \"No runtime found\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n runtime_parts = g_strsplit (runtime_ref, \"/\", -1);\n\n branch = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_BRANCH, NULL);\n instance_path = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_INSTANCE_PATH, NULL);\n arch = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_ARCH, NULL);\n extra_args = g_key_file_get_string_list (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_EXTRA_ARGS, NULL, NULL);\n app_commit = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_APP_COMMIT, NULL);\n runtime_commit = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_RUNTIME_COMMIT, NULL);\n shares = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SHARED, NULL, NULL);\n sockets = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SOCKETS, NULL, NULL);\n devices = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_DEVICES, NULL, NULL);\n\n devel = g_key_file_get_boolean (app_info, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_DEVEL, NULL);\n\n g_variant_lookup (arg_options, \"sandbox-expose\", \"^as\", &sandbox_expose);\n g_variant_lookup (arg_options, \"sandbox-expose-ro\", \"^as\", &sandbox_expose_ro);\n g_variant_lookup (arg_options, \"sandbox-flags\", \"u\", &sandbox_flags);\n sandbox_expose_fd = g_variant_lookup_value (arg_options, \"sandbox-expose-fd\", G_VARIANT_TYPE (\"ah\"));\n sandbox_expose_fd_ro = g_variant_lookup_value (arg_options, \"sandbox-expose-fd-ro\", G_VARIANT_TYPE (\"ah\"));\n\n if ((sandbox_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL) != 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,\n \"Unsupported sandbox flags enabled: 0x%x\", arg_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (instance_path == NULL &&\n ((sandbox_expose != NULL && sandbox_expose[0] != NULL) ||\n (sandbox_expose_ro != NULL && sandbox_expose_ro[0] != NULL)))\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"Invalid sandbox expose, caller has no instance path\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)\n {\n const char *expose = sandbox_expose[i];\n\n g_debug (\"exposing %s\", expose);\n if (!is_valid_expose (expose, &error))\n {\n g_dbus_method_invocation_return_gerror (invocation, error);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n\n for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)\n {\n const char *expose = sandbox_expose_ro[i];\n g_debug (\"exposing %s\", expose);\n if (!is_valid_expose (expose, &error))\n {\n g_dbus_method_invocation_return_gerror (invocation, error);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n\n g_debug (\"Running spawn command %s\", arg_argv[0]);\n\n n_fds = 0;\n if (fds != NULL)\n n_fds = g_variant_n_children (arg_fds);\n fd_map = g_new0 (FdMapEntry, n_fds);\n\n child_setup_data.fd_map = fd_map;\n child_setup_data.fd_map_len = n_fds;\n\n max_fd = -1;\n for (i = 0; i < n_fds; i++)\n {\n gint32 handle, dest_fd;\n int handle_fd;\n\n g_variant_get_child (arg_fds, i, \"{uh}\", &dest_fd, &handle);\n\n if (handle >= fds_len || handle < 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No file descriptor for handle %d\",\n handle);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n handle_fd = fds[handle];\n\n fd_map[i].to = dest_fd;\n fd_map[i].from = handle_fd;\n fd_map[i].final = fd_map[i].to;\n\n /* If stdin/out/err is a tty we try to set it as the controlling\n tty for the app, this way we can use this to run in a terminal. */\n if ((dest_fd == 0 || dest_fd == 1 || dest_fd == 2) &&\n !child_setup_data.set_tty &&\n isatty (handle_fd))\n {\n child_setup_data.set_tty = TRUE;\n child_setup_data.tty = handle_fd;\n }\n\n max_fd = MAX (max_fd, fd_map[i].to);\n max_fd = MAX (max_fd, fd_map[i].from);\n }\n\n /* We make a second pass over the fds to find if any \"to\" fd index\n overlaps an already in use fd (i.e. one in the \"from\" category\n that are allocated randomly). If a fd overlaps \"to\" fd then its\n a caller issue and not our fault, so we ignore that. */\n for (i = 0; i < n_fds; i++)\n {\n int to_fd = fd_map[i].to;\n gboolean conflict = FALSE;\n\n /* At this point we're fine with using \"from\" values for this\n value (because we handle to==from in the code), or values\n that are before \"i\" in the fd_map (because those will be\n closed at this point when dup:ing). However, we can't\n reuse a fd that is in \"from\" for j > i. */\n for (j = i + 1; j < n_fds; j++)\n {\n int from_fd = fd_map[j].from;\n if (from_fd == to_fd)\n {\n conflict = TRUE;\n break;\n }\n }\n\n if (conflict)\n fd_map[i].to = ++max_fd;\n }\n\n if (arg_flags & FLATPAK_SPAWN_FLAGS_CLEAR_ENV)\n {\n char *empty[] = { NULL };\n env = g_strdupv (empty);\n }\n else\n env = g_get_environ ();\n\n n_envs = g_variant_n_children (arg_envs);\n for (i = 0; i < n_envs; i++)\n {\n const char *var = NULL;\n const char *val = NULL;\n g_variant_get_child (arg_envs, i, \"{&s&s}\", &var, &val);\n\n env = g_environ_setenv (env, var, val, TRUE);\n }\n\n g_ptr_array_add (flatpak_argv, g_strdup (\"flatpak\"));\n g_ptr_array_add (flatpak_argv, g_strdup (\"run\"));\n\n sandboxed = (arg_flags & FLATPAK_SPAWN_FLAGS_SANDBOX) != 0;\n\n if (sandboxed)\n {\n g_ptr_array_add (flatpak_argv, g_strdup (\"--sandbox\"));\n\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_DISPLAY)\n {\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"wayland\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=wayland\"));\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"fallback-x11\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=fallback-x11\"));\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"x11\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=x11\"));\n if (shares != NULL && g_strv_contains ((const char * const *) shares, \"ipc\") &&\n sockets != NULL && (g_strv_contains ((const char * const *) sockets, \"fallback-x11\") ||\n g_strv_contains ((const char * const *) sockets, \"x11\")))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--share=ipc\"));\n }\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_SOUND)\n {\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"pulseaudio\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=pulseaudio\"));\n }\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_GPU)\n {\n if (devices != NULL &&\n (g_strv_contains ((const char * const *) devices, \"dri\") ||\n g_strv_contains ((const char * const *) devices, \"all\")))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--device=dri\"));\n }\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_DBUS)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--session-bus\"));\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_A11Y)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--a11y-bus\"));\n }\n else\n {\n for (i = 0; extra_args != NULL && extra_args[i] != NULL; i++)\n {\n if (g_str_has_prefix (extra_args[i], \"--env=\"))\n {\n const char *var_val = extra_args[i] + strlen (\"--env=\");\n\n if (var_val[0] == '\\0' || var_val[0] == '=')\n {\n g_warning (\"Environment variable in extra-args has empty name\");\n continue;\n }\n\n if (strchr (var_val, '=') == NULL)\n {\n g_warning (\"Environment variable in extra-args has no value\");\n continue;\n }\n\n g_string_append (env_string, var_val);\n g_string_append_c (env_string, '\\0');\n }\n else\n {\n g_ptr_array_add (flatpak_argv, g_strdup (extra_args[i]));\n }\n }\n }\n\n if (env_string->len > 0)\n {\n g_auto(GLnxTmpfile) env_tmpf = { 0, };\n\n if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&env_tmpf, \"environ\",\n env_string->str,\n env_string->len, &error))\n {\n g_dbus_method_invocation_return_gerror (invocation, error);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n child_setup_data.env_fd = glnx_steal_fd (&env_tmpf.fd);\n g_ptr_array_add (flatpak_argv,\n g_strdup_printf (\"--env-fd=%d\",\n child_setup_data.env_fd));\n }\n\n expose_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_EXPOSE_PIDS) != 0;\n share_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_SHARE_PIDS) != 0;\n\n if (expose_pids || share_pids)\n {\n g_autofree char *instance_id = NULL;\n int sender_pid1 = 0;\n\n if (!(supports & FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS))\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_NOT_SUPPORTED,\n \"Expose pids not supported with setuid bwrap\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n instance_id = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_INSTANCE_ID, NULL);\n\n if (instance_id)\n {\n g_autoptr(FlatpakInstance) instance = flatpak_instance_new_for_id (instance_id);\n sender_pid1 = flatpak_instance_get_child_pid (instance);\n }\n\n if (sender_pid1 == 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"Could not find requesting pid\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--parent-pid=%d\", sender_pid1));\n\n if (share_pids)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--parent-share-pids\"));\n else\n g_ptr_array_add (flatpak_argv, g_strdup (\"--parent-expose-pids\"));\n }\n\n notify_start = (arg_flags & FLATPAK_SPAWN_FLAGS_NOTIFY_START) != 0;\n if (notify_start)\n {\n int pipe_fds[2];\n if (pipe (pipe_fds) == -1)\n {\n int errsv = errno;\n g_dbus_method_invocation_return_error (invocation, G_IO_ERROR,\n g_io_error_from_errno (errsv),\n \"Failed to create instance ID pipe: %s\",\n g_strerror (errsv));\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n GInputStream *in_stream = G_INPUT_STREAM (g_unix_input_stream_new (pipe_fds[0], TRUE));\n /* This is saved to ensure the portal's end gets closed after the exec. */\n instance_id_out_stream = G_OUTPUT_STREAM (g_unix_output_stream_new (pipe_fds[1], TRUE));\n\n instance_id_read_data = g_new0 (InstanceIdReadData, 1);\n\n g_input_stream_read_async (in_stream, instance_id_read_data->buffer,\n INSTANCE_ID_BUFFER_SIZE - 1, G_PRIORITY_DEFAULT, NULL,\n instance_id_read_finish, instance_id_read_data);\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--instance-id-fd=%d\", pipe_fds[1]));\n child_setup_data.instance_id_fd = pipe_fds[1];\n }\n\n if (devel)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--devel\"));\n\n /* Inherit launcher network access from launcher, unless\n NO_NETWORK set. */\n if (shares != NULL && g_strv_contains ((const char * const *) shares, \"network\") &&\n !(arg_flags & FLATPAK_SPAWN_FLAGS_NO_NETWORK))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--share=network\"));\n else\n g_ptr_array_add (flatpak_argv, g_strdup (\"--unshare=network\"));\n\n\n if (instance_path)\n {\n for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)\n g_ptr_array_add (flatpak_argv,\n filesystem_sandbox_arg (instance_path, sandbox_expose[i], FALSE));\n for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)\n g_ptr_array_add (flatpak_argv,\n filesystem_sandbox_arg (instance_path, sandbox_expose_ro[i], TRUE));\n }\n\n for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)\n {\n const char *expose = sandbox_expose_ro[i];\n g_debug (\"exposing %s\", expose);\n }\n\n if (sandbox_expose_fd != NULL)\n {\n gsize len = g_variant_n_children (sandbox_expose_fd);\n for (i = 0; i < len; i++)\n {\n gint32 handle;\n g_variant_get_child (sandbox_expose_fd, i, \"h\", &handle);\n if (handle >= 0 && handle < fds_len)\n {\n int handle_fd = fds[handle];\n g_autofree char *path = NULL;\n gboolean writable = FALSE;\n\n path = get_path_for_fd (handle_fd, &writable, &error);\n\n if (path)\n {\n g_ptr_array_add (flatpak_argv, filesystem_arg (path, !writable));\n }\n else\n {\n g_debug (\"unable to get path for sandbox-exposed fd %d, ignoring: %s\",\n handle_fd, error->message);\n g_clear_error (&error);\n }\n }\n else\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No file descriptor for handle %d\",\n handle);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n }\n\n if (sandbox_expose_fd_ro != NULL)\n {\n gsize len = g_variant_n_children (sandbox_expose_fd_ro);\n for (i = 0; i < len; i++)\n {\n gint32 handle;\n g_variant_get_child (sandbox_expose_fd_ro, i, \"h\", &handle);\n if (handle >= 0 && handle < fds_len)\n {\n int handle_fd = fds[handle];\n g_autofree char *path = NULL;\n gboolean writable = FALSE;\n\n path = get_path_for_fd (handle_fd, &writable, &error);\n\n if (path)\n {\n g_ptr_array_add (flatpak_argv, filesystem_arg (path, TRUE));\n }\n else\n {\n g_debug (\"unable to get path for sandbox-exposed fd %d, ignoring: %s\",\n handle_fd, error->message);\n g_clear_error (&error);\n }\n }\n else\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No file descriptor for handle %d\",\n handle);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n }\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--runtime=%s\", runtime_parts[1]));\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--runtime-version=%s\", runtime_parts[3]));\n\n if ((arg_flags & FLATPAK_SPAWN_FLAGS_LATEST_VERSION) == 0)\n {\n if (app_commit)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--commit=%s\", app_commit));\n if (runtime_commit)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--runtime-commit=%s\", runtime_commit));\n }\n\n if (arg_cwd_path != NULL)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--cwd=%s\", arg_cwd_path));\n\n if (arg_argv[0][0] != 0)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--command=%s\", arg_argv[0]));\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"%s/%s/%s\", app_id, arch ? arch : \"\", branch ? branch : \"\"));\n for (i = 1; arg_argv[i] != NULL; i++)\n g_ptr_array_add (flatpak_argv, g_strdup (arg_argv[i]));\n g_ptr_array_add (flatpak_argv, NULL);\n\n if (opt_verbose)\n {\n g_autoptr(GString) cmd = g_string_new (\"\");\n\n for (i = 0; flatpak_argv->pdata[i] != NULL; i++)\n {\n if (i > 0)\n g_string_append (cmd, \" \");\n g_string_append (cmd, flatpak_argv->pdata[i]);\n }\n\n g_debug (\"Starting: %s\\n\", cmd->str);\n }\n\n /* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */\n if (!g_spawn_async_with_pipes (NULL,\n (char **) flatpak_argv->pdata,\n env,\n G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,\n child_setup_func, &child_setup_data,\n &pid,\n NULL,\n NULL,\n NULL,\n &error))\n {\n gint code = G_DBUS_ERROR_FAILED;\n if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_ACCES))\n code = G_DBUS_ERROR_ACCESS_DENIED;\n else if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT))\n code = G_DBUS_ERROR_FILE_NOT_FOUND;\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, code,\n \"Failed to start command: %s\",\n error->message);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (instance_id_read_data)\n instance_id_read_data->pid = pid;\n\n pid_data = g_new0 (PidData, 1);\n pid_data->pid = pid;\n pid_data->client = g_strdup (g_dbus_method_invocation_get_sender (invocation));\n pid_data->watch_bus = (arg_flags & FLATPAK_SPAWN_FLAGS_WATCH_BUS) != 0;\n pid_data->expose_or_share_pids = (expose_pids || share_pids);\n pid_data->child_watch = g_child_watch_add_full (G_PRIORITY_DEFAULT,\n pid,\n child_watch_died,\n pid_data,\n NULL);\n\n g_debug (\"Client Pid is %d\", pid_data->pid);\n\n g_hash_table_replace (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid),\n pid_data);\n\n portal_flatpak_complete_spawn (object, invocation, NULL, pid);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n}", "project": "flatpak", "hash": 337708073948946729047618626634843221247, "size": 608, "commit_id": "cc1401043c075268ecc652eac557ef8076b5eaba", "message": "portal: Do not use caller-supplied variables in environment\n\nIf the caller specifies a variable that can be used to inject arbitrary\ncode into processes, we must not allow it to enter the environment\nblock used to run `flatpak run`, which runs unsandboxed.\n\nThis change requires the previous commit \"context: Add --env-fd option\",\nwhich adds infrastructure used here.\n\nTo be secure, this change also requires the previous commit\n\"run: Convert all environment variables into bwrap arguments\", which\nprotects a non-setuid bwrap(1) from the same attack.\n\nSigned-off-by: Simon McVittie \nPart-of: https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2", "target": 1, "dataset": "other", "idx": 208226} {"func": "handle_spawn (PortalFlatpak *object,\n GDBusMethodInvocation *invocation,\n GUnixFDList *fd_list,\n const gchar *arg_cwd_path,\n const gchar *const *arg_argv,\n GVariant *arg_fds,\n GVariant *arg_envs,\n guint arg_flags,\n GVariant *arg_options)\n{\n g_autoptr(GError) error = NULL;\n ChildSetupData child_setup_data = { NULL };\n GPid pid;\n PidData *pid_data;\n InstanceIdReadData *instance_id_read_data = NULL;\n gsize i, j, n_fds, n_envs;\n const gint *fds = NULL;\n gint fds_len = 0;\n g_autofree FdMapEntry *fd_map = NULL;\n gchar **env;\n gint32 max_fd;\n GKeyFile *app_info;\n g_autoptr(GPtrArray) flatpak_argv = g_ptr_array_new_with_free_func (g_free);\n g_autofree char *app_id = NULL;\n g_autofree char *branch = NULL;\n g_autofree char *arch = NULL;\n g_autofree char *app_commit = NULL;\n g_autofree char *runtime_ref = NULL;\n g_auto(GStrv) runtime_parts = NULL;\n g_autofree char *runtime_commit = NULL;\n g_autofree char *instance_path = NULL;\n g_auto(GStrv) extra_args = NULL;\n g_auto(GStrv) shares = NULL;\n g_auto(GStrv) sockets = NULL;\n g_auto(GStrv) devices = NULL;\n g_auto(GStrv) sandbox_expose = NULL;\n g_auto(GStrv) sandbox_expose_ro = NULL;\n g_autoptr(GVariant) sandbox_expose_fd = NULL;\n g_autoptr(GVariant) sandbox_expose_fd_ro = NULL;\n g_autoptr(GOutputStream) instance_id_out_stream = NULL;\n guint sandbox_flags = 0;\n gboolean sandboxed;\n gboolean expose_pids;\n gboolean share_pids;\n gboolean notify_start;\n gboolean devel;\n g_autoptr(GString) env_string = g_string_new (\"\");\n\n child_setup_data.instance_id_fd = -1;\n child_setup_data.env_fd = -1;\n\n if (fd_list != NULL)\n fds = g_unix_fd_list_peek_fds (fd_list, &fds_len);\n\n app_info = g_object_get_data (G_OBJECT (invocation), \"app-info\");\n g_assert (app_info != NULL);\n\n app_id = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_APPLICATION,\n FLATPAK_METADATA_KEY_NAME, NULL);\n g_assert (app_id != NULL);\n\n g_debug (\"spawn() called from app: '%s'\", app_id);\n if (*app_id == 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"org.freedesktop.portal.Flatpak.Spawn only works in a flatpak\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (*arg_cwd_path == 0)\n arg_cwd_path = NULL;\n\n if (arg_argv == NULL || *arg_argv == NULL)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No command given\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if ((arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL) != 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,\n \"Unsupported flags enabled: 0x%x\", arg_flags & ~FLATPAK_SPAWN_FLAGS_ALL);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n runtime_ref = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_APPLICATION,\n FLATPAK_METADATA_KEY_RUNTIME, NULL);\n if (runtime_ref == NULL)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,\n \"No runtime found\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n runtime_parts = g_strsplit (runtime_ref, \"/\", -1);\n\n branch = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_BRANCH, NULL);\n instance_path = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_INSTANCE_PATH, NULL);\n arch = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_ARCH, NULL);\n extra_args = g_key_file_get_string_list (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_EXTRA_ARGS, NULL, NULL);\n app_commit = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_APP_COMMIT, NULL);\n runtime_commit = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_RUNTIME_COMMIT, NULL);\n shares = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SHARED, NULL, NULL);\n sockets = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_SOCKETS, NULL, NULL);\n devices = g_key_file_get_string_list (app_info, FLATPAK_METADATA_GROUP_CONTEXT,\n FLATPAK_METADATA_KEY_DEVICES, NULL, NULL);\n\n devel = g_key_file_get_boolean (app_info, FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_DEVEL, NULL);\n\n g_variant_lookup (arg_options, \"sandbox-expose\", \"^as\", &sandbox_expose);\n g_variant_lookup (arg_options, \"sandbox-expose-ro\", \"^as\", &sandbox_expose_ro);\n g_variant_lookup (arg_options, \"sandbox-flags\", \"u\", &sandbox_flags);\n sandbox_expose_fd = g_variant_lookup_value (arg_options, \"sandbox-expose-fd\", G_VARIANT_TYPE (\"ah\"));\n sandbox_expose_fd_ro = g_variant_lookup_value (arg_options, \"sandbox-expose-fd-ro\", G_VARIANT_TYPE (\"ah\"));\n\n if ((sandbox_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL) != 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,\n \"Unsupported sandbox flags enabled: 0x%x\", arg_flags & ~FLATPAK_SPAWN_SANDBOX_FLAGS_ALL);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (instance_path == NULL &&\n ((sandbox_expose != NULL && sandbox_expose[0] != NULL) ||\n (sandbox_expose_ro != NULL && sandbox_expose_ro[0] != NULL)))\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"Invalid sandbox expose, caller has no instance path\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)\n {\n const char *expose = sandbox_expose[i];\n\n g_debug (\"exposing %s\", expose);\n if (!is_valid_expose (expose, &error))\n {\n g_dbus_method_invocation_return_gerror (invocation, error);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n\n for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)\n {\n const char *expose = sandbox_expose_ro[i];\n g_debug (\"exposing %s\", expose);\n if (!is_valid_expose (expose, &error))\n {\n g_dbus_method_invocation_return_gerror (invocation, error);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n\n g_debug (\"Running spawn command %s\", arg_argv[0]);\n\n n_fds = 0;\n if (fds != NULL)\n n_fds = g_variant_n_children (arg_fds);\n fd_map = g_new0 (FdMapEntry, n_fds);\n\n child_setup_data.fd_map = fd_map;\n child_setup_data.fd_map_len = n_fds;\n\n max_fd = -1;\n for (i = 0; i < n_fds; i++)\n {\n gint32 handle, dest_fd;\n int handle_fd;\n\n g_variant_get_child (arg_fds, i, \"{uh}\", &dest_fd, &handle);\n\n if (handle >= fds_len || handle < 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No file descriptor for handle %d\",\n handle);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n handle_fd = fds[handle];\n\n fd_map[i].to = dest_fd;\n fd_map[i].from = handle_fd;\n fd_map[i].final = fd_map[i].to;\n\n /* If stdin/out/err is a tty we try to set it as the controlling\n tty for the app, this way we can use this to run in a terminal. */\n if ((dest_fd == 0 || dest_fd == 1 || dest_fd == 2) &&\n !child_setup_data.set_tty &&\n isatty (handle_fd))\n {\n child_setup_data.set_tty = TRUE;\n child_setup_data.tty = handle_fd;\n }\n\n max_fd = MAX (max_fd, fd_map[i].to);\n max_fd = MAX (max_fd, fd_map[i].from);\n }\n\n /* We make a second pass over the fds to find if any \"to\" fd index\n overlaps an already in use fd (i.e. one in the \"from\" category\n that are allocated randomly). If a fd overlaps \"to\" fd then its\n a caller issue and not our fault, so we ignore that. */\n for (i = 0; i < n_fds; i++)\n {\n int to_fd = fd_map[i].to;\n gboolean conflict = FALSE;\n\n /* At this point we're fine with using \"from\" values for this\n value (because we handle to==from in the code), or values\n that are before \"i\" in the fd_map (because those will be\n closed at this point when dup:ing). However, we can't\n reuse a fd that is in \"from\" for j > i. */\n for (j = i + 1; j < n_fds; j++)\n {\n int from_fd = fd_map[j].from;\n if (from_fd == to_fd)\n {\n conflict = TRUE;\n break;\n }\n }\n\n if (conflict)\n fd_map[i].to = ++max_fd;\n }\n\n if (arg_flags & FLATPAK_SPAWN_FLAGS_CLEAR_ENV)\n {\n char *empty[] = { NULL };\n env = g_strdupv (empty);\n }\n else\n env = g_get_environ ();\n\n /* Let the environment variables given by the caller override the ones\n * from extra_args. Don't add them to @env, because they are controlled\n * by our caller, which might be trying to use them to inject code into\n * flatpak(1); add them to the environment block instead.\n *\n * We don't use --env= here, so that if the values are something that\n * should not be exposed to other uids, they can remain confidential. */\n n_envs = g_variant_n_children (arg_envs);\n for (i = 0; i < n_envs; i++)\n {\n const char *var = NULL;\n const char *val = NULL;\n g_variant_get_child (arg_envs, i, \"{&s&s}\", &var, &val);\n\n if (var[0] == '\\0')\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"Environment variable cannot have empty name\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (strchr (var, '=') != NULL)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"Environment variable name cannot contain '='\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n g_string_append (env_string, var);\n g_string_append_c (env_string, '=');\n g_string_append (env_string, val);\n g_string_append_c (env_string, '\\0');\n }\n\n g_ptr_array_add (flatpak_argv, g_strdup (\"flatpak\"));\n g_ptr_array_add (flatpak_argv, g_strdup (\"run\"));\n\n sandboxed = (arg_flags & FLATPAK_SPAWN_FLAGS_SANDBOX) != 0;\n\n if (sandboxed)\n {\n g_ptr_array_add (flatpak_argv, g_strdup (\"--sandbox\"));\n\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_DISPLAY)\n {\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"wayland\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=wayland\"));\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"fallback-x11\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=fallback-x11\"));\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"x11\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=x11\"));\n if (shares != NULL && g_strv_contains ((const char * const *) shares, \"ipc\") &&\n sockets != NULL && (g_strv_contains ((const char * const *) sockets, \"fallback-x11\") ||\n g_strv_contains ((const char * const *) sockets, \"x11\")))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--share=ipc\"));\n }\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_SOUND)\n {\n if (sockets != NULL && g_strv_contains ((const char * const *) sockets, \"pulseaudio\"))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--socket=pulseaudio\"));\n }\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_SHARE_GPU)\n {\n if (devices != NULL &&\n (g_strv_contains ((const char * const *) devices, \"dri\") ||\n g_strv_contains ((const char * const *) devices, \"all\")))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--device=dri\"));\n }\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_DBUS)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--session-bus\"));\n if (sandbox_flags & FLATPAK_SPAWN_SANDBOX_FLAGS_ALLOW_A11Y)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--a11y-bus\"));\n }\n else\n {\n for (i = 0; extra_args != NULL && extra_args[i] != NULL; i++)\n {\n if (g_str_has_prefix (extra_args[i], \"--env=\"))\n {\n const char *var_val = extra_args[i] + strlen (\"--env=\");\n\n if (var_val[0] == '\\0' || var_val[0] == '=')\n {\n g_warning (\"Environment variable in extra-args has empty name\");\n continue;\n }\n\n if (strchr (var_val, '=') == NULL)\n {\n g_warning (\"Environment variable in extra-args has no value\");\n continue;\n }\n\n g_string_append (env_string, var_val);\n g_string_append_c (env_string, '\\0');\n }\n else\n {\n g_ptr_array_add (flatpak_argv, g_strdup (extra_args[i]));\n }\n }\n }\n\n if (env_string->len > 0)\n {\n g_auto(GLnxTmpfile) env_tmpf = { 0, };\n\n if (!flatpak_buffer_to_sealed_memfd_or_tmpfile (&env_tmpf, \"environ\",\n env_string->str,\n env_string->len, &error))\n {\n g_dbus_method_invocation_return_gerror (invocation, error);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n child_setup_data.env_fd = glnx_steal_fd (&env_tmpf.fd);\n g_ptr_array_add (flatpak_argv,\n g_strdup_printf (\"--env-fd=%d\",\n child_setup_data.env_fd));\n }\n\n expose_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_EXPOSE_PIDS) != 0;\n share_pids = (arg_flags & FLATPAK_SPAWN_FLAGS_SHARE_PIDS) != 0;\n\n if (expose_pids || share_pids)\n {\n g_autofree char *instance_id = NULL;\n int sender_pid1 = 0;\n\n if (!(supports & FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS))\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_NOT_SUPPORTED,\n \"Expose pids not supported with setuid bwrap\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n instance_id = g_key_file_get_string (app_info,\n FLATPAK_METADATA_GROUP_INSTANCE,\n FLATPAK_METADATA_KEY_INSTANCE_ID, NULL);\n\n if (instance_id)\n {\n g_autoptr(FlatpakInstance) instance = flatpak_instance_new_for_id (instance_id);\n sender_pid1 = flatpak_instance_get_child_pid (instance);\n }\n\n if (sender_pid1 == 0)\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"Could not find requesting pid\");\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--parent-pid=%d\", sender_pid1));\n\n if (share_pids)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--parent-share-pids\"));\n else\n g_ptr_array_add (flatpak_argv, g_strdup (\"--parent-expose-pids\"));\n }\n\n notify_start = (arg_flags & FLATPAK_SPAWN_FLAGS_NOTIFY_START) != 0;\n if (notify_start)\n {\n int pipe_fds[2];\n if (pipe (pipe_fds) == -1)\n {\n int errsv = errno;\n g_dbus_method_invocation_return_error (invocation, G_IO_ERROR,\n g_io_error_from_errno (errsv),\n \"Failed to create instance ID pipe: %s\",\n g_strerror (errsv));\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n GInputStream *in_stream = G_INPUT_STREAM (g_unix_input_stream_new (pipe_fds[0], TRUE));\n /* This is saved to ensure the portal's end gets closed after the exec. */\n instance_id_out_stream = G_OUTPUT_STREAM (g_unix_output_stream_new (pipe_fds[1], TRUE));\n\n instance_id_read_data = g_new0 (InstanceIdReadData, 1);\n\n g_input_stream_read_async (in_stream, instance_id_read_data->buffer,\n INSTANCE_ID_BUFFER_SIZE - 1, G_PRIORITY_DEFAULT, NULL,\n instance_id_read_finish, instance_id_read_data);\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--instance-id-fd=%d\", pipe_fds[1]));\n child_setup_data.instance_id_fd = pipe_fds[1];\n }\n\n if (devel)\n g_ptr_array_add (flatpak_argv, g_strdup (\"--devel\"));\n\n /* Inherit launcher network access from launcher, unless\n NO_NETWORK set. */\n if (shares != NULL && g_strv_contains ((const char * const *) shares, \"network\") &&\n !(arg_flags & FLATPAK_SPAWN_FLAGS_NO_NETWORK))\n g_ptr_array_add (flatpak_argv, g_strdup (\"--share=network\"));\n else\n g_ptr_array_add (flatpak_argv, g_strdup (\"--unshare=network\"));\n\n\n if (instance_path)\n {\n for (i = 0; sandbox_expose != NULL && sandbox_expose[i] != NULL; i++)\n g_ptr_array_add (flatpak_argv,\n filesystem_sandbox_arg (instance_path, sandbox_expose[i], FALSE));\n for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)\n g_ptr_array_add (flatpak_argv,\n filesystem_sandbox_arg (instance_path, sandbox_expose_ro[i], TRUE));\n }\n\n for (i = 0; sandbox_expose_ro != NULL && sandbox_expose_ro[i] != NULL; i++)\n {\n const char *expose = sandbox_expose_ro[i];\n g_debug (\"exposing %s\", expose);\n }\n\n if (sandbox_expose_fd != NULL)\n {\n gsize len = g_variant_n_children (sandbox_expose_fd);\n for (i = 0; i < len; i++)\n {\n gint32 handle;\n g_variant_get_child (sandbox_expose_fd, i, \"h\", &handle);\n if (handle >= 0 && handle < fds_len)\n {\n int handle_fd = fds[handle];\n g_autofree char *path = NULL;\n gboolean writable = FALSE;\n\n path = get_path_for_fd (handle_fd, &writable, &error);\n\n if (path)\n {\n g_ptr_array_add (flatpak_argv, filesystem_arg (path, !writable));\n }\n else\n {\n g_debug (\"unable to get path for sandbox-exposed fd %d, ignoring: %s\",\n handle_fd, error->message);\n g_clear_error (&error);\n }\n }\n else\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No file descriptor for handle %d\",\n handle);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n }\n\n if (sandbox_expose_fd_ro != NULL)\n {\n gsize len = g_variant_n_children (sandbox_expose_fd_ro);\n for (i = 0; i < len; i++)\n {\n gint32 handle;\n g_variant_get_child (sandbox_expose_fd_ro, i, \"h\", &handle);\n if (handle >= 0 && handle < fds_len)\n {\n int handle_fd = fds[handle];\n g_autofree char *path = NULL;\n gboolean writable = FALSE;\n\n path = get_path_for_fd (handle_fd, &writable, &error);\n\n if (path)\n {\n g_ptr_array_add (flatpak_argv, filesystem_arg (path, TRUE));\n }\n else\n {\n g_debug (\"unable to get path for sandbox-exposed fd %d, ignoring: %s\",\n handle_fd, error->message);\n g_clear_error (&error);\n }\n }\n else\n {\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR,\n G_DBUS_ERROR_INVALID_ARGS,\n \"No file descriptor for handle %d\",\n handle);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n }\n }\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--runtime=%s\", runtime_parts[1]));\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--runtime-version=%s\", runtime_parts[3]));\n\n if ((arg_flags & FLATPAK_SPAWN_FLAGS_LATEST_VERSION) == 0)\n {\n if (app_commit)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--commit=%s\", app_commit));\n if (runtime_commit)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--runtime-commit=%s\", runtime_commit));\n }\n\n if (arg_cwd_path != NULL)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--cwd=%s\", arg_cwd_path));\n\n if (arg_argv[0][0] != 0)\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"--command=%s\", arg_argv[0]));\n\n g_ptr_array_add (flatpak_argv, g_strdup_printf (\"%s/%s/%s\", app_id, arch ? arch : \"\", branch ? branch : \"\"));\n for (i = 1; arg_argv[i] != NULL; i++)\n g_ptr_array_add (flatpak_argv, g_strdup (arg_argv[i]));\n g_ptr_array_add (flatpak_argv, NULL);\n\n if (opt_verbose)\n {\n g_autoptr(GString) cmd = g_string_new (\"\");\n\n for (i = 0; flatpak_argv->pdata[i] != NULL; i++)\n {\n if (i > 0)\n g_string_append (cmd, \" \");\n g_string_append (cmd, flatpak_argv->pdata[i]);\n }\n\n g_debug (\"Starting: %s\\n\", cmd->str);\n }\n\n /* We use LEAVE_DESCRIPTORS_OPEN to work around dead-lock, see flatpak_close_fds_workaround */\n if (!g_spawn_async_with_pipes (NULL,\n (char **) flatpak_argv->pdata,\n env,\n G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,\n child_setup_func, &child_setup_data,\n &pid,\n NULL,\n NULL,\n NULL,\n &error))\n {\n gint code = G_DBUS_ERROR_FAILED;\n if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_ACCES))\n code = G_DBUS_ERROR_ACCESS_DENIED;\n else if (g_error_matches (error, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT))\n code = G_DBUS_ERROR_FILE_NOT_FOUND;\n g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, code,\n \"Failed to start command: %s\",\n error->message);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n }\n\n if (instance_id_read_data)\n instance_id_read_data->pid = pid;\n\n pid_data = g_new0 (PidData, 1);\n pid_data->pid = pid;\n pid_data->client = g_strdup (g_dbus_method_invocation_get_sender (invocation));\n pid_data->watch_bus = (arg_flags & FLATPAK_SPAWN_FLAGS_WATCH_BUS) != 0;\n pid_data->expose_or_share_pids = (expose_pids || share_pids);\n pid_data->child_watch = g_child_watch_add_full (G_PRIORITY_DEFAULT,\n pid,\n child_watch_died,\n pid_data,\n NULL);\n\n g_debug (\"Client Pid is %d\", pid_data->pid);\n\n g_hash_table_replace (client_pid_data_hash, GUINT_TO_POINTER (pid_data->pid),\n pid_data);\n\n portal_flatpak_complete_spawn (object, invocation, NULL, pid);\n return G_DBUS_METHOD_INVOCATION_HANDLED;\n}", "project": "flatpak", "hash": 232713244041032616005904953820748692526, "size": 634, "commit_id": "cc1401043c075268ecc652eac557ef8076b5eaba", "message": "portal: Do not use caller-supplied variables in environment\n\nIf the caller specifies a variable that can be used to inject arbitrary\ncode into processes, we must not allow it to enter the environment\nblock used to run `flatpak run`, which runs unsandboxed.\n\nThis change requires the previous commit \"context: Add --env-fd option\",\nwhich adds infrastructure used here.\n\nTo be secure, this change also requires the previous commit\n\"run: Convert all environment variables into bwrap arguments\", which\nprotects a non-setuid bwrap(1) from the same attack.\n\nSigned-off-by: Simon McVittie \nPart-of: https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2", "target": 0, "dataset": "other", "idx": 406983} {"func": "static void msf2_dma_tx(MSF2EmacState *s)\n{\n NetClientState *nc = qemu_get_queue(s->nic);\n hwaddr desc = s->regs[R_DMA_TX_DESC];\n uint8_t buf[MAX_PKT_SIZE];\n EmacDesc d;\n int size;\n uint8_t pktcnt;\n uint32_t status;\n\n if (!(s->regs[R_CFG1] & R_CFG1_TX_EN_MASK)) {\n return;\n }\n\n while (1) {\n emac_load_desc(s, &d, desc);\n if (d.pktsize & EMPTY_MASK) {\n break;\n }\n size = d.pktsize & PKT_SIZE;\n address_space_read(&s->dma_as, d.pktaddr, MEMTXATTRS_UNSPECIFIED,\n buf, size);\n /*\n * This is very basic way to send packets. Ideally there should be\n * a FIFO and packets should be sent out from FIFO only when\n * R_CFG1 bit 0 is set.\n */\n if (s->regs[R_CFG1] & R_CFG1_LB_EN_MASK) {\n nc->info->receive(nc, buf, size);\n } else {\n qemu_send_packet(nc, buf, size);\n }\n d.pktsize |= EMPTY_MASK;\n emac_store_desc(s, &d, desc);\n /* update sent packets count */\n status = s->regs[R_DMA_TX_STATUS];\n pktcnt = FIELD_EX32(status, DMA_TX_STATUS, PKTCNT);\n pktcnt++;\n s->regs[R_DMA_TX_STATUS] = FIELD_DP32(status, DMA_TX_STATUS,\n PKTCNT, pktcnt);\n s->regs[R_DMA_TX_STATUS] |= R_DMA_TX_STATUS_PKT_SENT_MASK;\n desc = d.next;\n }\n s->regs[R_DMA_TX_STATUS] |= R_DMA_TX_STATUS_UNDERRUN_MASK;\n s->regs[R_DMA_TX_CTL] &= ~R_DMA_TX_CTL_EN_MASK;\n}", "project": "qemu", "hash": 266996506783650672252406401947191343006, "size": 46, "commit_id": "26194a58f4eb83c5bdf4061a1628508084450ba1", "message": "msf2-mac: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Jason Wang ", "target": 1, "dataset": "other", "idx": 208328} {"func": "static void msf2_dma_tx(MSF2EmacState *s)\n{\n NetClientState *nc = qemu_get_queue(s->nic);\n hwaddr desc = s->regs[R_DMA_TX_DESC];\n uint8_t buf[MAX_PKT_SIZE];\n EmacDesc d;\n int size;\n uint8_t pktcnt;\n uint32_t status;\n\n if (!(s->regs[R_CFG1] & R_CFG1_TX_EN_MASK)) {\n return;\n }\n\n while (1) {\n emac_load_desc(s, &d, desc);\n if (d.pktsize & EMPTY_MASK) {\n break;\n }\n size = d.pktsize & PKT_SIZE;\n address_space_read(&s->dma_as, d.pktaddr, MEMTXATTRS_UNSPECIFIED,\n buf, size);\n /*\n * This is very basic way to send packets. Ideally there should be\n * a FIFO and packets should be sent out from FIFO only when\n * R_CFG1 bit 0 is set.\n */\n if (s->regs[R_CFG1] & R_CFG1_LB_EN_MASK) {\n qemu_receive_packet(nc, buf, size);\n } else {\n qemu_send_packet(nc, buf, size);\n }\n d.pktsize |= EMPTY_MASK;\n emac_store_desc(s, &d, desc);\n /* update sent packets count */\n status = s->regs[R_DMA_TX_STATUS];\n pktcnt = FIELD_EX32(status, DMA_TX_STATUS, PKTCNT);\n pktcnt++;\n s->regs[R_DMA_TX_STATUS] = FIELD_DP32(status, DMA_TX_STATUS,\n PKTCNT, pktcnt);\n s->regs[R_DMA_TX_STATUS] |= R_DMA_TX_STATUS_PKT_SENT_MASK;\n desc = d.next;\n }\n s->regs[R_DMA_TX_STATUS] |= R_DMA_TX_STATUS_UNDERRUN_MASK;\n s->regs[R_DMA_TX_CTL] &= ~R_DMA_TX_CTL_EN_MASK;\n}", "project": "qemu", "hash": 673024745665237607007576976494892674, "size": 46, "commit_id": "26194a58f4eb83c5bdf4061a1628508084450ba1", "message": "msf2-mac: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Philippe Mathieu-Daud\u00e9 \nSigned-off-by: Jason Wang ", "target": 0, "dataset": "other", "idx": 408536} {"func": "static int ca8210_probe(struct spi_device *spi_device)\n{\n\tstruct ca8210_priv *priv;\n\tstruct ieee802154_hw *hw;\n\tstruct ca8210_platform_data *pdata;\n\tint ret;\n\n\tdev_info(&spi_device->dev, \"Inserting ca8210\\n\");\n\n\t/* allocate ieee802154_hw and private data */\n\thw = ieee802154_alloc_hw(sizeof(struct ca8210_priv), &ca8210_phy_ops);\n\tif (!hw) {\n\t\tdev_crit(&spi_device->dev, \"ieee802154_alloc_hw failed\\n\");\n\t\tret = -ENOMEM;\n\t\tgoto error;\n\t}\n\n\tpriv = hw->priv;\n\tpriv->hw = hw;\n\tpriv->spi = spi_device;\n\thw->parent = &spi_device->dev;\n\tspin_lock_init(&priv->lock);\n\tpriv->async_tx_pending = false;\n\tpriv->hw_registered = false;\n\tpriv->sync_up = 0;\n\tpriv->sync_down = 0;\n\tpriv->promiscuous = false;\n\tpriv->retries = 0;\n\tinit_completion(&priv->ca8210_is_awake);\n\tinit_completion(&priv->spi_transfer_complete);\n\tinit_completion(&priv->sync_exchange_complete);\n\tspi_set_drvdata(priv->spi, priv);\n\tif (IS_ENABLED(CONFIG_IEEE802154_CA8210_DEBUGFS)) {\n\t\tcascoda_api_upstream = ca8210_test_int_driver_write;\n\t\tca8210_test_interface_init(priv);\n\t} else {\n\t\tcascoda_api_upstream = NULL;\n\t}\n\tca8210_hw_setup(hw);\n\tieee802154_random_extended_addr(&hw->phy->perm_extended_addr);\n\n\tpdata = kmalloc(sizeof(*pdata), GFP_KERNEL);\n\tif (!pdata) {\n\t\tret = -ENOMEM;\n\t\tgoto error;\n\t}\n\n\tret = ca8210_get_platform_data(priv->spi, pdata);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_get_platform_data failed\\n\");\n\t\tgoto error;\n\t}\n\tpriv->spi->dev.platform_data = pdata;\n\n\tret = ca8210_dev_com_init(priv);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_dev_com_init failed\\n\");\n\t\tgoto error;\n\t}\n\tret = ca8210_reset_init(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_reset_init failed\\n\");\n\t\tgoto error;\n\t}\n\n\tret = ca8210_interrupt_init(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_interrupt_init failed\\n\");\n\t\tgoto error;\n\t}\n\n\tmsleep(100);\n\n\tca8210_reset_send(priv->spi, 1);\n\n\tret = tdme_chipinit(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"tdme_chipinit failed\\n\");\n\t\tgoto error;\n\t}\n\n\tif (pdata->extclockenable) {\n\t\tret = ca8210_config_extern_clk(pdata, priv->spi, 1);\n\t\tif (ret) {\n\t\t\tdev_crit(\n\t\t\t\t&spi_device->dev,\n\t\t\t\t\"ca8210_config_extern_clk failed\\n\"\n\t\t\t);\n\t\t\tgoto error;\n\t\t}\n\t\tret = ca8210_register_ext_clock(priv->spi);\n\t\tif (ret) {\n\t\t\tdev_crit(\n\t\t\t\t&spi_device->dev,\n\t\t\t\t\"ca8210_register_ext_clock failed\\n\"\n\t\t\t);\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tret = ieee802154_register_hw(hw);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ieee802154_register_hw failed\\n\");\n\t\tgoto error;\n\t}\n\tpriv->hw_registered = true;\n\n\treturn 0;\nerror:\n\tmsleep(100); /* wait for pending spi transfers to complete */\n\tca8210_remove(spi_device);\n\treturn link_to_linux_err(ret);\n}", "project": "linux", "hash": 140536448521281187745613931545799203059, "size": 113, "commit_id": "6402939ec86eaf226c8b8ae00ed983936b164908", "message": "ieee802154: ca8210: prevent memory leak\n\nIn ca8210_probe the allocated pdata needs to be assigned to\nspi_device->dev.platform_data before calling ca8210_get_platform_data.\nOthrwise when ca8210_get_platform_data fails pdata cannot be released.\n\nSigned-off-by: Navid Emamdoost \nLink: https://lore.kernel.org/r/20190917224713.26371-1-navid.emamdoost@gmail.com\nSigned-off-by: Stefan Schmidt ", "target": 1, "dataset": "other", "idx": 208360} {"func": "static int ca8210_probe(struct spi_device *spi_device)\n{\n\tstruct ca8210_priv *priv;\n\tstruct ieee802154_hw *hw;\n\tstruct ca8210_platform_data *pdata;\n\tint ret;\n\n\tdev_info(&spi_device->dev, \"Inserting ca8210\\n\");\n\n\t/* allocate ieee802154_hw and private data */\n\thw = ieee802154_alloc_hw(sizeof(struct ca8210_priv), &ca8210_phy_ops);\n\tif (!hw) {\n\t\tdev_crit(&spi_device->dev, \"ieee802154_alloc_hw failed\\n\");\n\t\tret = -ENOMEM;\n\t\tgoto error;\n\t}\n\n\tpriv = hw->priv;\n\tpriv->hw = hw;\n\tpriv->spi = spi_device;\n\thw->parent = &spi_device->dev;\n\tspin_lock_init(&priv->lock);\n\tpriv->async_tx_pending = false;\n\tpriv->hw_registered = false;\n\tpriv->sync_up = 0;\n\tpriv->sync_down = 0;\n\tpriv->promiscuous = false;\n\tpriv->retries = 0;\n\tinit_completion(&priv->ca8210_is_awake);\n\tinit_completion(&priv->spi_transfer_complete);\n\tinit_completion(&priv->sync_exchange_complete);\n\tspi_set_drvdata(priv->spi, priv);\n\tif (IS_ENABLED(CONFIG_IEEE802154_CA8210_DEBUGFS)) {\n\t\tcascoda_api_upstream = ca8210_test_int_driver_write;\n\t\tca8210_test_interface_init(priv);\n\t} else {\n\t\tcascoda_api_upstream = NULL;\n\t}\n\tca8210_hw_setup(hw);\n\tieee802154_random_extended_addr(&hw->phy->perm_extended_addr);\n\n\tpdata = kmalloc(sizeof(*pdata), GFP_KERNEL);\n\tif (!pdata) {\n\t\tret = -ENOMEM;\n\t\tgoto error;\n\t}\n\n\tpriv->spi->dev.platform_data = pdata;\n\tret = ca8210_get_platform_data(priv->spi, pdata);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_get_platform_data failed\\n\");\n\t\tgoto error;\n\t}\n\n\tret = ca8210_dev_com_init(priv);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_dev_com_init failed\\n\");\n\t\tgoto error;\n\t}\n\tret = ca8210_reset_init(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_reset_init failed\\n\");\n\t\tgoto error;\n\t}\n\n\tret = ca8210_interrupt_init(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ca8210_interrupt_init failed\\n\");\n\t\tgoto error;\n\t}\n\n\tmsleep(100);\n\n\tca8210_reset_send(priv->spi, 1);\n\n\tret = tdme_chipinit(priv->spi);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"tdme_chipinit failed\\n\");\n\t\tgoto error;\n\t}\n\n\tif (pdata->extclockenable) {\n\t\tret = ca8210_config_extern_clk(pdata, priv->spi, 1);\n\t\tif (ret) {\n\t\t\tdev_crit(\n\t\t\t\t&spi_device->dev,\n\t\t\t\t\"ca8210_config_extern_clk failed\\n\"\n\t\t\t);\n\t\t\tgoto error;\n\t\t}\n\t\tret = ca8210_register_ext_clock(priv->spi);\n\t\tif (ret) {\n\t\t\tdev_crit(\n\t\t\t\t&spi_device->dev,\n\t\t\t\t\"ca8210_register_ext_clock failed\\n\"\n\t\t\t);\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tret = ieee802154_register_hw(hw);\n\tif (ret) {\n\t\tdev_crit(&spi_device->dev, \"ieee802154_register_hw failed\\n\");\n\t\tgoto error;\n\t}\n\tpriv->hw_registered = true;\n\n\treturn 0;\nerror:\n\tmsleep(100); /* wait for pending spi transfers to complete */\n\tca8210_remove(spi_device);\n\treturn link_to_linux_err(ret);\n}", "project": "linux", "hash": 188473089036627924087079919084020542406, "size": 113, "commit_id": "6402939ec86eaf226c8b8ae00ed983936b164908", "message": "ieee802154: ca8210: prevent memory leak\n\nIn ca8210_probe the allocated pdata needs to be assigned to\nspi_device->dev.platform_data before calling ca8210_get_platform_data.\nOthrwise when ca8210_get_platform_data fails pdata cannot be released.\n\nSigned-off-by: Navid Emamdoost \nLink: https://lore.kernel.org/r/20190917224713.26371-1-navid.emamdoost@gmail.com\nSigned-off-by: Stefan Schmidt ", "target": 0, "dataset": "other", "idx": 408790} {"func": " void Jp2Image::encodeJp2Header(const DataBuf& boxBuf,DataBuf& outBuf)\n {\n DataBuf output(boxBuf.size_ + iccProfile_.size_ + 100); // allocate sufficient space\n int outlen = sizeof(Jp2BoxHeader) ; // now many bytes have we written to output?\n int inlen = sizeof(Jp2BoxHeader) ; // how many bytes have we read from boxBuf?\n Jp2BoxHeader* pBox = (Jp2BoxHeader*) boxBuf.pData_;\n int32_t length = getLong((byte*)&pBox->length, bigEndian);\n int32_t count = sizeof (Jp2BoxHeader);\n char* p = (char*) boxBuf.pData_;\n bool bWroteColor = false ;\n\n while ( count < length || !bWroteColor ) {\n Jp2BoxHeader* pSubBox = (Jp2BoxHeader*) (p+count) ;\n\n // copy data. pointer could be into a memory mapped file which we will decode!\n Jp2BoxHeader subBox ; memcpy(&subBox,pSubBox,sizeof(subBox));\n Jp2BoxHeader newBox = subBox;\n\n if ( count < length ) {\n subBox.length = getLong((byte*)&subBox.length, bigEndian);\n subBox.type = getLong((byte*)&subBox.type , bigEndian);\n#ifdef EXIV2_DEBUG_MESSAGES\n std::cout << \"Jp2Image::encodeJp2Header subbox: \"<< toAscii(subBox.type) << \" length = \" << subBox.length << std::endl;\n#endif\n count += subBox.length;\n newBox.type = subBox.type;\n } else {\n subBox.length=0;\n newBox.type = kJp2BoxTypeColorHeader;\n count = length;\n }\n\n int32_t newlen = subBox.length;\n if ( newBox.type == kJp2BoxTypeColorHeader ) {\n bWroteColor = true ;\n if ( ! iccProfileDefined() ) {\n const char* pad = \"\\x01\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x05\\x1cuuid\";\n uint32_t psize = 15;\n newlen = sizeof(newBox) + psize ;\n ul2Data((byte*)&newBox.length,psize ,bigEndian);\n ul2Data((byte*)&newBox.type ,newBox.type,bigEndian);\n ::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox));\n ::memcpy(output.pData_+outlen+sizeof(newBox) ,pad ,psize );\n } else {\n const char* pad = \"\\x02\\x00\\x00\";\n uint32_t psize = 3;\n newlen = sizeof(newBox) + psize + iccProfile_.size_;\n ul2Data((byte*)&newBox.length,newlen,bigEndian);\n ul2Data((byte*)&newBox.type,newBox.type,bigEndian);\n ::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox) );\n ::memcpy(output.pData_+outlen+sizeof(newBox) , pad ,psize );\n ::memcpy(output.pData_+outlen+sizeof(newBox)+psize,iccProfile_.pData_,iccProfile_.size_);\n }\n } else {\n ::memcpy(output.pData_+outlen,boxBuf.pData_+inlen,subBox.length);\n }\n\n outlen += newlen;\n inlen += subBox.length;\n }\n\n // allocate the correct number of bytes, copy the data and update the box header\n outBuf.alloc(outlen);\n ::memcpy(outBuf.pData_,output.pData_,outlen);\n pBox = (Jp2BoxHeader*) outBuf.pData_;\n ul2Data((byte*)&pBox->type,kJp2BoxTypeJp2Header,bigEndian);\n ul2Data((byte*)&pBox->length,outlen,bigEndian);\n } // Jp2Image::encodeJp2Header", "project": "exiv2", "hash": 3024404238179680571348817945424819382, "size": 68, "commit_id": "f9308839198aca5e68a65194f151a1de92398f54", "message": "Better bounds checking in Jp2Image::encodeJp2Header()", "target": 1, "dataset": "other", "idx": 208379} {"func": " void Jp2Image::encodeJp2Header(const DataBuf& boxBuf,DataBuf& outBuf)\n {\n DataBuf output(boxBuf.size_ + iccProfile_.size_ + 100); // allocate sufficient space\n long outlen = sizeof(Jp2BoxHeader) ; // now many bytes have we written to output?\n long inlen = sizeof(Jp2BoxHeader) ; // how many bytes have we read from boxBuf?\n Jp2BoxHeader* pBox = (Jp2BoxHeader*) boxBuf.pData_;\n uint32_t length = getLong((byte*)&pBox->length, bigEndian);\n uint32_t count = sizeof (Jp2BoxHeader);\n char* p = (char*) boxBuf.pData_;\n bool bWroteColor = false ;\n\n while ( count < length || !bWroteColor ) {\n Jp2BoxHeader* pSubBox = (Jp2BoxHeader*) (p+count) ;\n\n // copy data. pointer could be into a memory mapped file which we will decode!\n Jp2BoxHeader subBox ; memcpy(&subBox,pSubBox,sizeof(subBox));\n Jp2BoxHeader newBox = subBox;\n\n if ( count < length ) {\n subBox.length = getLong((byte*)&subBox.length, bigEndian);\n subBox.type = getLong((byte*)&subBox.type , bigEndian);\n#ifdef EXIV2_DEBUG_MESSAGES\n std::cout << \"Jp2Image::encodeJp2Header subbox: \"<< toAscii(subBox.type) << \" length = \" << subBox.length << std::endl;\n#endif\n enforce(subBox.length <= length - count, Exiv2::kerCorruptedMetadata);\n count += subBox.length;\n newBox.type = subBox.type;\n } else {\n subBox.length=0;\n newBox.type = kJp2BoxTypeColorHeader;\n count = length;\n }\n\n uint32_t newlen = subBox.length;\n if ( newBox.type == kJp2BoxTypeColorHeader ) {\n bWroteColor = true ;\n if ( ! iccProfileDefined() ) {\n const char* pad = \"\\x01\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x00\\x05\\x1cuuid\";\n uint32_t psize = 15;\n newlen = sizeof(newBox) + psize ;\n enforce(newlen <= output.size_ - outlen, Exiv2::kerCorruptedMetadata);\n ul2Data((byte*)&newBox.length,psize ,bigEndian);\n ul2Data((byte*)&newBox.type ,newBox.type,bigEndian);\n ::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox));\n ::memcpy(output.pData_+outlen+sizeof(newBox) ,pad ,psize );\n } else {\n const char* pad = \"\\x02\\x00\\x00\";\n uint32_t psize = 3;\n newlen = sizeof(newBox) + psize + iccProfile_.size_;\n enforce(newlen <= output.size_ - outlen, Exiv2::kerCorruptedMetadata);\n ul2Data((byte*)&newBox.length,newlen,bigEndian);\n ul2Data((byte*)&newBox.type,newBox.type,bigEndian);\n ::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox) );\n ::memcpy(output.pData_+outlen+sizeof(newBox) , pad ,psize );\n ::memcpy(output.pData_+outlen+sizeof(newBox)+psize,iccProfile_.pData_,iccProfile_.size_);\n }\n } else {\n enforce(newlen <= output.size_ - outlen, Exiv2::kerCorruptedMetadata);\n ::memcpy(output.pData_+outlen,boxBuf.pData_+inlen,subBox.length);\n }\n\n outlen += newlen;\n inlen += subBox.length;\n }\n\n // allocate the correct number of bytes, copy the data and update the box header\n outBuf.alloc(outlen);\n ::memcpy(outBuf.pData_,output.pData_,outlen);\n pBox = (Jp2BoxHeader*) outBuf.pData_;\n ul2Data((byte*)&pBox->type,kJp2BoxTypeJp2Header,bigEndian);\n ul2Data((byte*)&pBox->length,outlen,bigEndian);\n } // Jp2Image::encodeJp2Header", "project": "exiv2", "hash": 152635762460183118135898337348969828226, "size": 72, "commit_id": "f9308839198aca5e68a65194f151a1de92398f54", "message": "Better bounds checking in Jp2Image::encodeJp2Header()", "target": 0, "dataset": "other", "idx": 409137} {"func": "exif_mnote_data_canon_load (ExifMnoteData *ne,\n\tconst unsigned char *buf, unsigned int buf_size)\n{\n\tExifMnoteDataCanon *n = (ExifMnoteDataCanon *) ne;\n\tExifShort c;\n\tsize_t i, tcount, o, datao;\n\n\tif (!n || !buf || !buf_size) {\n\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteCanon\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\tdatao = 6 + n->offset;\n\tif (CHECKOVERFLOW(datao, buf_size, 2)) {\n\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteCanon\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\n\t/* Read the number of tags */\n\tc = exif_get_short (buf + datao, n->order);\n\tdatao += 2;\n\n\t/* Remove any old entries */\n\texif_mnote_data_canon_clear (n);\n\n\t/* Reserve enough space for all the possible MakerNote tags */\n\tn->entries = exif_mem_alloc (ne->mem, sizeof (MnoteCanonEntry) * c);\n\tif (!n->entries) {\n\t\tEXIF_LOG_NO_MEMORY(ne->log, \"ExifMnoteCanon\", sizeof (MnoteCanonEntry) * c);\n\t\treturn;\n\t}\n\n\t/* Parse the entries */\n\ttcount = 0;\n\tfor (i = c, o = datao; i; --i, o += 12) {\n\t\tsize_t s;\n\n\t\tmemset(&n->entries[tcount], 0, sizeof(MnoteCanonEntry));\n\t\tif (CHECKOVERFLOW(o,buf_size,12)) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t\"ExifMnoteCanon\", \"Short MakerNote\");\n\t\t\tbreak;\n\t\t}\n\n\t\tn->entries[tcount].tag = exif_get_short (buf + o, n->order);\n\t\tn->entries[tcount].format = exif_get_short (buf + o + 2, n->order);\n\t\tn->entries[tcount].components = exif_get_long (buf + o + 4, n->order);\n\t\tn->entries[tcount].order = n->order;\n\n\t\texif_log (ne->log, EXIF_LOG_CODE_DEBUG, \"ExifMnoteCanon\",\n\t\t\t\"Loading entry 0x%x ('%s')...\", n->entries[tcount].tag,\n\t\t\t mnote_canon_tag_get_name (n->entries[tcount].tag));\n\n\t\t/* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection,\n\t\t * we will check the buffer sizes closer later. */\n\t\tif (\texif_format_get_size (n->entries[tcount].format) &&\n\t\t\tbuf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components\n\t\t) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifMnoteCanon\", \"Tag size overflow detected (%u * %lu)\", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Size? If bigger than 4 bytes, the actual data is not\n\t\t * in the entry but somewhere else (offset).\n\t\t */\n\t\ts = exif_format_get_size (n->entries[tcount].format) * \n\t\t\t\t\t\t\t\t n->entries[tcount].components;\n\t\tn->entries[tcount].size = s;\n\t\tif (!s) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifMnoteCanon\",\n\t\t\t\t \"Invalid zero-length tag size\");\n\t\t\tcontinue;\n\n\t\t} else {\n\t\t\tsize_t dataofs = o + 8;\n\t\t\tif (s > 4) dataofs = exif_get_long (buf + dataofs, n->order) + 6;\n\n\t\t\tif (CHECKOVERFLOW(dataofs, buf_size, s)) {\n\t\t\t\texif_log (ne->log, EXIF_LOG_CODE_DEBUG,\n\t\t\t\t\t\"ExifMnoteCanon\",\n\t\t\t\t\t\"Tag data past end of buffer (%u > %u)\",\n\t\t\t\t\t(unsigned)(dataofs + s), buf_size);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tn->entries[tcount].data = exif_mem_alloc (ne->mem, s);\n\t\t\tif (!n->entries[tcount].data) {\n\t\t\t\tEXIF_LOG_NO_MEMORY(ne->log, \"ExifMnoteCanon\", s);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmemcpy (n->entries[tcount].data, buf + dataofs, s);\n\t\t}\n\n\t\t/* Tag was successfully parsed */\n\t\t++tcount;\n\t}\n\t/* Store the count of successfully parsed tags */\n\tn->count = tcount;\n}", "project": "libexif", "hash": 192830977113316409961824397562079867910, "size": 103, "commit_id": "e6a38a1a23ba94d139b1fa2cd4519fdcfe3c9bab", "message": "Add a failsafe on the maximum number of Canon MakerNote subtags.\n\nA malicious file could be crafted to cause extremely large values in some\ntags without tripping any buffer range checks. This is bad with the libexif\nrepresentation of Canon MakerNotes because some arrays are turned into\nindividual tags that the application must loop around.\n\nThe largest value I've seen for failsafe_size in a (very small) sample of valid\nCanon files is <5000. The limit is set two orders of magnitude larger to avoid\ntripping up falsely in case some models use much larger values.\n\nPatch from Google.\n\nCVE-2020-13114", "target": 1, "dataset": "other", "idx": 208385} {"func": "exif_mnote_data_canon_load (ExifMnoteData *ne,\n\tconst unsigned char *buf, unsigned int buf_size)\n{\n\tExifMnoteDataCanon *n = (ExifMnoteDataCanon *) ne;\n\tExifShort c;\n\tsize_t i, tcount, o, datao;\n\tlong failsafe_size = 0;\n\n\tif (!n || !buf || !buf_size) {\n\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteCanon\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\tdatao = 6 + n->offset;\n\tif (CHECKOVERFLOW(datao, buf_size, 2)) {\n\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t \"ExifMnoteCanon\", \"Short MakerNote\");\n\t\treturn;\n\t}\n\n\t/* Read the number of tags */\n\tc = exif_get_short (buf + datao, n->order);\n\tdatao += 2;\n\n\t/* Remove any old entries */\n\texif_mnote_data_canon_clear (n);\n\n\t/* Reserve enough space for all the possible MakerNote tags */\n\tn->entries = exif_mem_alloc (ne->mem, sizeof (MnoteCanonEntry) * c);\n\tif (!n->entries) {\n\t\tEXIF_LOG_NO_MEMORY(ne->log, \"ExifMnoteCanon\", sizeof (MnoteCanonEntry) * c);\n\t\treturn;\n\t}\n\n\t/* Parse the entries */\n\ttcount = 0;\n\tfor (i = c, o = datao; i; --i, o += 12) {\n\t\tsize_t s;\n\n\t\tmemset(&n->entries[tcount], 0, sizeof(MnoteCanonEntry));\n\t\tif (CHECKOVERFLOW(o,buf_size,12)) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t\"ExifMnoteCanon\", \"Short MakerNote\");\n\t\t\tbreak;\n\t\t}\n\n\t\tn->entries[tcount].tag = exif_get_short (buf + o, n->order);\n\t\tn->entries[tcount].format = exif_get_short (buf + o + 2, n->order);\n\t\tn->entries[tcount].components = exif_get_long (buf + o + 4, n->order);\n\t\tn->entries[tcount].order = n->order;\n\n\t\texif_log (ne->log, EXIF_LOG_CODE_DEBUG, \"ExifMnoteCanon\",\n\t\t\t\"Loading entry 0x%x ('%s')...\", n->entries[tcount].tag,\n\t\t\t mnote_canon_tag_get_name (n->entries[tcount].tag));\n\n\t\t/* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection,\n\t\t * we will check the buffer sizes closer later. */\n\t\tif (\texif_format_get_size (n->entries[tcount].format) &&\n\t\t\tbuf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components\n\t\t) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifMnoteCanon\", \"Tag size overflow detected (%u * %lu)\", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components);\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * Size? If bigger than 4 bytes, the actual data is not\n\t\t * in the entry but somewhere else (offset).\n\t\t */\n\t\ts = exif_format_get_size (n->entries[tcount].format) * \n\t\t\t\t\t\t\t\t n->entries[tcount].components;\n\t\tn->entries[tcount].size = s;\n\t\tif (!s) {\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t \"ExifMnoteCanon\",\n\t\t\t\t \"Invalid zero-length tag size\");\n\t\t\tcontinue;\n\n\t\t} else {\n\t\t\tsize_t dataofs = o + 8;\n\t\t\tif (s > 4) dataofs = exif_get_long (buf + dataofs, n->order) + 6;\n\n\t\t\tif (CHECKOVERFLOW(dataofs, buf_size, s)) {\n\t\t\t\texif_log (ne->log, EXIF_LOG_CODE_DEBUG,\n\t\t\t\t\t\"ExifMnoteCanon\",\n\t\t\t\t\t\"Tag data past end of buffer (%u > %u)\",\n\t\t\t\t\t(unsigned)(dataofs + s), buf_size);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tn->entries[tcount].data = exif_mem_alloc (ne->mem, s);\n\t\t\tif (!n->entries[tcount].data) {\n\t\t\t\tEXIF_LOG_NO_MEMORY(ne->log, \"ExifMnoteCanon\", s);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmemcpy (n->entries[tcount].data, buf + dataofs, s);\n\t\t}\n\n\t\t/* Track the size of decoded tag data. A malicious file could\n\t\t * be crafted to cause extremely large values here without\n\t\t * tripping any buffer range checks. This is especially bad\n\t\t * with the libexif representation of Canon MakerNotes because\n\t\t * some arrays are turned into individual tags that the\n\t\t * application must loop around. */\n\t\tfailsafe_size += mnote_canon_entry_count_values(&n->entries[tcount]);\n\n\t\tif (failsafe_size > FAILSAFE_SIZE_MAX) {\n\t\t\t/* Abort if the total size of the data in the tags extraordinarily large, */\n\t\t\texif_mem_free (ne->mem, n->entries[tcount].data);\n\t\t\texif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,\n\t\t\t\t\t \"ExifMnoteCanon\", \"Failsafe tag size overflow (%lu > %ld)\",\n\t\t\t\t\t failsafe_size, FAILSAFE_SIZE_MAX);\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Tag was successfully parsed */\n\t\t++tcount;\n\t}\n\t/* Store the count of successfully parsed tags */\n\tn->count = tcount;\n}", "project": "libexif", "hash": 215870267647801111255387237724645875655, "size": 121, "commit_id": "e6a38a1a23ba94d139b1fa2cd4519fdcfe3c9bab", "message": "Add a failsafe on the maximum number of Canon MakerNote subtags.\n\nA malicious file could be crafted to cause extremely large values in some\ntags without tripping any buffer range checks. This is bad with the libexif\nrepresentation of Canon MakerNotes because some arrays are turned into\nindividual tags that the application must loop around.\n\nThe largest value I've seen for failsafe_size in a (very small) sample of valid\nCanon files is <5000. The limit is set two orders of magnitude larger to avoid\ntripping up falsely in case some models use much larger values.\n\nPatch from Google.\n\nCVE-2020-13114", "target": 0, "dataset": "other", "idx": 409181} {"func": "Int32 BZ2_decompress ( DState* s )\n{\n UChar uc;\n Int32 retVal;\n Int32 minLen, maxLen;\n bz_stream* strm = s->strm;\n\n /* stuff that needs to be saved/restored */\n Int32 i;\n Int32 j;\n Int32 t;\n Int32 alphaSize;\n Int32 nGroups;\n Int32 nSelectors;\n Int32 EOB;\n Int32 groupNo;\n Int32 groupPos;\n Int32 nextSym;\n Int32 nblockMAX;\n Int32 nblock;\n Int32 es;\n Int32 N;\n Int32 curr;\n Int32 zt;\n Int32 zn; \n Int32 zvec;\n Int32 zj;\n Int32 gSel;\n Int32 gMinlen;\n Int32* gLimit;\n Int32* gBase;\n Int32* gPerm;\n\n if (s->state == BZ_X_MAGIC_1) {\n /*initialise the save area*/\n s->save_i = 0;\n s->save_j = 0;\n s->save_t = 0;\n s->save_alphaSize = 0;\n s->save_nGroups = 0;\n s->save_nSelectors = 0;\n s->save_EOB = 0;\n s->save_groupNo = 0;\n s->save_groupPos = 0;\n s->save_nextSym = 0;\n s->save_nblockMAX = 0;\n s->save_nblock = 0;\n s->save_es = 0;\n s->save_N = 0;\n s->save_curr = 0;\n s->save_zt = 0;\n s->save_zn = 0;\n s->save_zvec = 0;\n s->save_zj = 0;\n s->save_gSel = 0;\n s->save_gMinlen = 0;\n s->save_gLimit = NULL;\n s->save_gBase = NULL;\n s->save_gPerm = NULL;\n }\n\n /*restore from the save area*/\n i = s->save_i;\n j = s->save_j;\n t = s->save_t;\n alphaSize = s->save_alphaSize;\n nGroups = s->save_nGroups;\n nSelectors = s->save_nSelectors;\n EOB = s->save_EOB;\n groupNo = s->save_groupNo;\n groupPos = s->save_groupPos;\n nextSym = s->save_nextSym;\n nblockMAX = s->save_nblockMAX;\n nblock = s->save_nblock;\n es = s->save_es;\n N = s->save_N;\n curr = s->save_curr;\n zt = s->save_zt;\n zn = s->save_zn; \n zvec = s->save_zvec;\n zj = s->save_zj;\n gSel = s->save_gSel;\n gMinlen = s->save_gMinlen;\n gLimit = s->save_gLimit;\n gBase = s->save_gBase;\n gPerm = s->save_gPerm;\n\n retVal = BZ_OK;\n\n switch (s->state) {\n\n GET_UCHAR(BZ_X_MAGIC_1, uc);\n if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC);\n\n GET_UCHAR(BZ_X_MAGIC_2, uc);\n if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC);\n\n GET_UCHAR(BZ_X_MAGIC_3, uc)\n if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC);\n\n GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8)\n if (s->blockSize100k < (BZ_HDR_0 + 1) || \n s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC);\n s->blockSize100k -= BZ_HDR_0;\n\n if (s->smallDecompress) {\n s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) );\n s->ll4 = BZALLOC( \n ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) \n );\n if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR);\n } else {\n s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) );\n if (s->tt == NULL) RETURN(BZ_MEM_ERROR);\n }\n\n GET_UCHAR(BZ_X_BLKHDR_1, uc);\n\n if (uc == 0x17) goto endhdr_2;\n if (uc != 0x31) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_2, uc);\n if (uc != 0x41) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_3, uc);\n if (uc != 0x59) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_4, uc);\n if (uc != 0x26) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_5, uc);\n if (uc != 0x53) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_6, uc);\n if (uc != 0x59) RETURN(BZ_DATA_ERROR);\n\n s->currBlockNo++;\n if (s->verbosity >= 2)\n VPrintf1 ( \"\\n [%d: huff+mtf \", s->currBlockNo );\n \n s->storedBlockCRC = 0;\n GET_UCHAR(BZ_X_BCRC_1, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_BCRC_2, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_BCRC_3, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_BCRC_4, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n\n GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1);\n\n s->origPtr = 0;\n GET_UCHAR(BZ_X_ORIGPTR_1, uc);\n s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n GET_UCHAR(BZ_X_ORIGPTR_2, uc);\n s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n GET_UCHAR(BZ_X_ORIGPTR_3, uc);\n s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n\n if (s->origPtr < 0)\n RETURN(BZ_DATA_ERROR);\n if (s->origPtr > 10 + 100000*s->blockSize100k) \n RETURN(BZ_DATA_ERROR);\n\n /*--- Receive the mapping table ---*/\n for (i = 0; i < 16; i++) {\n GET_BIT(BZ_X_MAPPING_1, uc);\n if (uc == 1) \n s->inUse16[i] = True; else \n s->inUse16[i] = False;\n }\n\n for (i = 0; i < 256; i++) s->inUse[i] = False;\n\n for (i = 0; i < 16; i++)\n if (s->inUse16[i])\n for (j = 0; j < 16; j++) {\n GET_BIT(BZ_X_MAPPING_2, uc);\n if (uc == 1) s->inUse[i * 16 + j] = True;\n }\n makeMaps_d ( s );\n if (s->nInUse == 0) RETURN(BZ_DATA_ERROR);\n alphaSize = s->nInUse+2;\n\n /*--- Now the selectors ---*/\n GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);\n if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR);\n GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);\n if (nSelectors < 1) RETURN(BZ_DATA_ERROR);\n for (i = 0; i < nSelectors; i++) {\n j = 0;\n while (True) {\n GET_BIT(BZ_X_SELECTOR_3, uc);\n if (uc == 0) break;\n j++;\n if (j >= nGroups) RETURN(BZ_DATA_ERROR);\n }\n s->selectorMtf[i] = j;\n }\n\n /*--- Undo the MTF values for the selectors. ---*/\n {\n UChar pos[BZ_N_GROUPS], tmp, v;\n for (v = 0; v < nGroups; v++) pos[v] = v;\n \n for (i = 0; i < nSelectors; i++) {\n v = s->selectorMtf[i];\n tmp = pos[v];\n while (v > 0) { pos[v] = pos[v-1]; v--; }\n pos[0] = tmp;\n s->selector[i] = tmp;\n }\n }\n\n /*--- Now the coding tables ---*/\n for (t = 0; t < nGroups; t++) {\n GET_BITS(BZ_X_CODING_1, curr, 5);\n for (i = 0; i < alphaSize; i++) {\n while (True) {\n if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR);\n GET_BIT(BZ_X_CODING_2, uc);\n if (uc == 0) break;\n GET_BIT(BZ_X_CODING_3, uc);\n if (uc == 0) curr++; else curr--;\n }\n s->len[t][i] = curr;\n }\n }\n\n /*--- Create the Huffman decoding tables ---*/\n for (t = 0; t < nGroups; t++) {\n minLen = 32;\n maxLen = 0;\n for (i = 0; i < alphaSize; i++) {\n if (s->len[t][i] > maxLen) maxLen = s->len[t][i];\n if (s->len[t][i] < minLen) minLen = s->len[t][i];\n }\n BZ2_hbCreateDecodeTables ( \n &(s->limit[t][0]), \n &(s->base[t][0]), \n &(s->perm[t][0]), \n &(s->len[t][0]),\n minLen, maxLen, alphaSize\n );\n s->minLens[t] = minLen;\n }\n\n /*--- Now the MTF values ---*/\n\n EOB = s->nInUse+1;\n nblockMAX = 100000 * s->blockSize100k;\n groupNo = -1;\n groupPos = 0;\n\n for (i = 0; i <= 255; i++) s->unzftab[i] = 0;\n\n /*-- MTF init --*/\n {\n Int32 ii, jj, kk;\n kk = MTFA_SIZE-1;\n for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) {\n for (jj = MTFL_SIZE-1; jj >= 0; jj--) {\n s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj);\n kk--;\n }\n s->mtfbase[ii] = kk + 1;\n }\n }\n /*-- end MTF init --*/\n\n nblock = 0;\n GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym);\n\n while (True) {\n\n if (nextSym == EOB) break;\n\n if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) {\n\n es = -1;\n N = 1;\n do {\n /* Check that N doesn't get too big, so that es doesn't\n go negative. The maximum value that can be\n RUNA/RUNB encoded is equal to the block size (post\n the initial RLE), viz, 900k, so bounding N at 2\n million should guard against overflow without\n rejecting any legitimate inputs. */\n if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR);\n if (nextSym == BZ_RUNA) es = es + (0+1) * N; else\n if (nextSym == BZ_RUNB) es = es + (1+1) * N;\n N = N * 2;\n GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym);\n }\n while (nextSym == BZ_RUNA || nextSym == BZ_RUNB);\n\n es++;\n uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ];\n s->unzftab[uc] += es;\n\n if (s->smallDecompress)\n while (es > 0) {\n if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n s->ll16[nblock] = (UInt16)uc;\n nblock++;\n es--;\n }\n else\n while (es > 0) {\n if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n s->tt[nblock] = (UInt32)uc;\n nblock++;\n es--;\n };\n\n continue;\n\n } else {\n\n if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n\n /*-- uc = MTF ( nextSym-1 ) --*/\n {\n Int32 ii, jj, kk, pp, lno, off;\n UInt32 nn;\n nn = (UInt32)(nextSym - 1);\n\n if (nn < MTFL_SIZE) {\n /* avoid general-case expense */\n pp = s->mtfbase[0];\n uc = s->mtfa[pp+nn];\n while (nn > 3) {\n Int32 z = pp+nn;\n s->mtfa[(z) ] = s->mtfa[(z)-1];\n s->mtfa[(z)-1] = s->mtfa[(z)-2];\n s->mtfa[(z)-2] = s->mtfa[(z)-3];\n s->mtfa[(z)-3] = s->mtfa[(z)-4];\n nn -= 4;\n }\n while (nn > 0) { \n s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; \n };\n s->mtfa[pp] = uc;\n } else { \n /* general case */\n lno = nn / MTFL_SIZE;\n off = nn % MTFL_SIZE;\n pp = s->mtfbase[lno] + off;\n uc = s->mtfa[pp];\n while (pp > s->mtfbase[lno]) { \n s->mtfa[pp] = s->mtfa[pp-1]; pp--; \n };\n s->mtfbase[lno]++;\n while (lno > 0) {\n s->mtfbase[lno]--;\n s->mtfa[s->mtfbase[lno]] \n = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1];\n lno--;\n }\n s->mtfbase[0]--;\n s->mtfa[s->mtfbase[0]] = uc;\n if (s->mtfbase[0] == 0) {\n kk = MTFA_SIZE-1;\n for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) {\n for (jj = MTFL_SIZE-1; jj >= 0; jj--) {\n s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj];\n kk--;\n }\n s->mtfbase[ii] = kk + 1;\n }\n }\n }\n }\n /*-- end uc = MTF ( nextSym-1 ) --*/\n\n s->unzftab[s->seqToUnseq[uc]]++;\n if (s->smallDecompress)\n s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else\n s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]);\n nblock++;\n\n GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym);\n continue;\n }\n }\n\n /* Now we know what nblock is, we can do a better sanity\n check on s->origPtr.\n */\n if (s->origPtr < 0 || s->origPtr >= nblock)\n RETURN(BZ_DATA_ERROR);\n\n /*-- Set up cftab to facilitate generation of T^(-1) --*/\n /* Check: unzftab entries in range. */\n for (i = 0; i <= 255; i++) {\n if (s->unzftab[i] < 0 || s->unzftab[i] > nblock)\n RETURN(BZ_DATA_ERROR);\n }\n /* Actually generate cftab. */\n s->cftab[0] = 0;\n for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1];\n for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1];\n /* Check: cftab entries in range. */\n for (i = 0; i <= 256; i++) {\n if (s->cftab[i] < 0 || s->cftab[i] > nblock) {\n /* s->cftab[i] can legitimately be == nblock */\n RETURN(BZ_DATA_ERROR);\n }\n }\n /* Check: cftab entries non-descending. */\n for (i = 1; i <= 256; i++) {\n if (s->cftab[i-1] > s->cftab[i]) {\n RETURN(BZ_DATA_ERROR);\n }\n }\n\n s->state_out_len = 0;\n s->state_out_ch = 0;\n BZ_INITIALISE_CRC ( s->calculatedBlockCRC );\n s->state = BZ_X_OUTPUT;\n if (s->verbosity >= 2) VPrintf0 ( \"rt+rld\" );\n\n if (s->smallDecompress) {\n\n /*-- Make a copy of cftab, used in generation of T --*/\n for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i];\n\n /*-- compute the T vector --*/\n for (i = 0; i < nblock; i++) {\n uc = (UChar)(s->ll16[i]);\n SET_LL(i, s->cftabCopy[uc]);\n s->cftabCopy[uc]++;\n }\n\n /*-- Compute T^(-1) by pointer reversal on T --*/\n i = s->origPtr;\n j = GET_LL(i);\n do {\n Int32 tmp = GET_LL(j);\n SET_LL(j, i);\n i = j;\n j = tmp;\n }\n while (i != s->origPtr);\n\n s->tPos = s->origPtr;\n s->nblock_used = 0;\n if (s->blockRandomised) {\n BZ_RAND_INIT_MASK;\n BZ_GET_SMALL(s->k0); s->nblock_used++;\n BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; \n } else {\n BZ_GET_SMALL(s->k0); s->nblock_used++;\n }\n\n } else {\n\n /*-- compute the T^(-1) vector --*/\n for (i = 0; i < nblock; i++) {\n uc = (UChar)(s->tt[i] & 0xff);\n s->tt[s->cftab[uc]] |= (i << 8);\n s->cftab[uc]++;\n }\n\n s->tPos = s->tt[s->origPtr] >> 8;\n s->nblock_used = 0;\n if (s->blockRandomised) {\n BZ_RAND_INIT_MASK;\n BZ_GET_FAST(s->k0); s->nblock_used++;\n BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; \n } else {\n BZ_GET_FAST(s->k0); s->nblock_used++;\n }\n\n }\n\n RETURN(BZ_OK);\n\n\n\n endhdr_2:\n\n GET_UCHAR(BZ_X_ENDHDR_2, uc);\n if (uc != 0x72) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_3, uc);\n if (uc != 0x45) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_4, uc);\n if (uc != 0x38) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_5, uc);\n if (uc != 0x50) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_6, uc);\n if (uc != 0x90) RETURN(BZ_DATA_ERROR);\n\n s->storedCombinedCRC = 0;\n GET_UCHAR(BZ_X_CCRC_1, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_CCRC_2, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_CCRC_3, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_CCRC_4, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n\n s->state = BZ_X_IDLE;\n RETURN(BZ_STREAM_END);\n\n default: AssertH ( False, 4001 );\n }\n\n AssertH ( False, 4002 );\n\n save_state_and_return:\n\n s->save_i = i;\n s->save_j = j;\n s->save_t = t;\n s->save_alphaSize = alphaSize;\n s->save_nGroups = nGroups;\n s->save_nSelectors = nSelectors;\n s->save_EOB = EOB;\n s->save_groupNo = groupNo;\n s->save_groupPos = groupPos;\n s->save_nextSym = nextSym;\n s->save_nblockMAX = nblockMAX;\n s->save_nblock = nblock;\n s->save_es = es;\n s->save_N = N;\n s->save_curr = curr;\n s->save_zt = zt;\n s->save_zn = zn;\n s->save_zvec = zvec;\n s->save_zj = zj;\n s->save_gSel = gSel;\n s->save_gMinlen = gMinlen;\n s->save_gLimit = gLimit;\n s->save_gBase = gBase;\n s->save_gPerm = gPerm;\n\n return retVal; \n}", "project": "bzip2", "hash": 165979335088151361311447542269597699517, "size": 536, "commit_id": "74de1e2e6ffc9d51ef9824db71a8ffee5962cdbc", "message": "Make sure nSelectors is not out of range\n\nnSelectors is used in a loop from 0 to nSelectors to access selectorMtf\nwhich is\n\tUChar selectorMtf[BZ_MAX_SELECTORS];\nso if nSelectors is bigger than BZ_MAX_SELECTORS it'll do an invalid memory\naccess\n\nFixes out of bounds access discovered while fuzzying karchive", "target": 1, "dataset": "other", "idx": 208386} {"func": "Int32 BZ2_decompress ( DState* s )\n{\n UChar uc;\n Int32 retVal;\n Int32 minLen, maxLen;\n bz_stream* strm = s->strm;\n\n /* stuff that needs to be saved/restored */\n Int32 i;\n Int32 j;\n Int32 t;\n Int32 alphaSize;\n Int32 nGroups;\n Int32 nSelectors;\n Int32 EOB;\n Int32 groupNo;\n Int32 groupPos;\n Int32 nextSym;\n Int32 nblockMAX;\n Int32 nblock;\n Int32 es;\n Int32 N;\n Int32 curr;\n Int32 zt;\n Int32 zn; \n Int32 zvec;\n Int32 zj;\n Int32 gSel;\n Int32 gMinlen;\n Int32* gLimit;\n Int32* gBase;\n Int32* gPerm;\n\n if (s->state == BZ_X_MAGIC_1) {\n /*initialise the save area*/\n s->save_i = 0;\n s->save_j = 0;\n s->save_t = 0;\n s->save_alphaSize = 0;\n s->save_nGroups = 0;\n s->save_nSelectors = 0;\n s->save_EOB = 0;\n s->save_groupNo = 0;\n s->save_groupPos = 0;\n s->save_nextSym = 0;\n s->save_nblockMAX = 0;\n s->save_nblock = 0;\n s->save_es = 0;\n s->save_N = 0;\n s->save_curr = 0;\n s->save_zt = 0;\n s->save_zn = 0;\n s->save_zvec = 0;\n s->save_zj = 0;\n s->save_gSel = 0;\n s->save_gMinlen = 0;\n s->save_gLimit = NULL;\n s->save_gBase = NULL;\n s->save_gPerm = NULL;\n }\n\n /*restore from the save area*/\n i = s->save_i;\n j = s->save_j;\n t = s->save_t;\n alphaSize = s->save_alphaSize;\n nGroups = s->save_nGroups;\n nSelectors = s->save_nSelectors;\n EOB = s->save_EOB;\n groupNo = s->save_groupNo;\n groupPos = s->save_groupPos;\n nextSym = s->save_nextSym;\n nblockMAX = s->save_nblockMAX;\n nblock = s->save_nblock;\n es = s->save_es;\n N = s->save_N;\n curr = s->save_curr;\n zt = s->save_zt;\n zn = s->save_zn; \n zvec = s->save_zvec;\n zj = s->save_zj;\n gSel = s->save_gSel;\n gMinlen = s->save_gMinlen;\n gLimit = s->save_gLimit;\n gBase = s->save_gBase;\n gPerm = s->save_gPerm;\n\n retVal = BZ_OK;\n\n switch (s->state) {\n\n GET_UCHAR(BZ_X_MAGIC_1, uc);\n if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC);\n\n GET_UCHAR(BZ_X_MAGIC_2, uc);\n if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC);\n\n GET_UCHAR(BZ_X_MAGIC_3, uc)\n if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC);\n\n GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8)\n if (s->blockSize100k < (BZ_HDR_0 + 1) || \n s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC);\n s->blockSize100k -= BZ_HDR_0;\n\n if (s->smallDecompress) {\n s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) );\n s->ll4 = BZALLOC( \n ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) \n );\n if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR);\n } else {\n s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) );\n if (s->tt == NULL) RETURN(BZ_MEM_ERROR);\n }\n\n GET_UCHAR(BZ_X_BLKHDR_1, uc);\n\n if (uc == 0x17) goto endhdr_2;\n if (uc != 0x31) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_2, uc);\n if (uc != 0x41) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_3, uc);\n if (uc != 0x59) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_4, uc);\n if (uc != 0x26) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_5, uc);\n if (uc != 0x53) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_BLKHDR_6, uc);\n if (uc != 0x59) RETURN(BZ_DATA_ERROR);\n\n s->currBlockNo++;\n if (s->verbosity >= 2)\n VPrintf1 ( \"\\n [%d: huff+mtf \", s->currBlockNo );\n \n s->storedBlockCRC = 0;\n GET_UCHAR(BZ_X_BCRC_1, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_BCRC_2, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_BCRC_3, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_BCRC_4, uc);\n s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n\n GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1);\n\n s->origPtr = 0;\n GET_UCHAR(BZ_X_ORIGPTR_1, uc);\n s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n GET_UCHAR(BZ_X_ORIGPTR_2, uc);\n s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n GET_UCHAR(BZ_X_ORIGPTR_3, uc);\n s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n\n if (s->origPtr < 0)\n RETURN(BZ_DATA_ERROR);\n if (s->origPtr > 10 + 100000*s->blockSize100k) \n RETURN(BZ_DATA_ERROR);\n\n /*--- Receive the mapping table ---*/\n for (i = 0; i < 16; i++) {\n GET_BIT(BZ_X_MAPPING_1, uc);\n if (uc == 1) \n s->inUse16[i] = True; else \n s->inUse16[i] = False;\n }\n\n for (i = 0; i < 256; i++) s->inUse[i] = False;\n\n for (i = 0; i < 16; i++)\n if (s->inUse16[i])\n for (j = 0; j < 16; j++) {\n GET_BIT(BZ_X_MAPPING_2, uc);\n if (uc == 1) s->inUse[i * 16 + j] = True;\n }\n makeMaps_d ( s );\n if (s->nInUse == 0) RETURN(BZ_DATA_ERROR);\n alphaSize = s->nInUse+2;\n\n /*--- Now the selectors ---*/\n GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);\n if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR);\n GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);\n if (nSelectors < 1 || nSelectors > BZ_MAX_SELECTORS) RETURN(BZ_DATA_ERROR);\n for (i = 0; i < nSelectors; i++) {\n j = 0;\n while (True) {\n GET_BIT(BZ_X_SELECTOR_3, uc);\n if (uc == 0) break;\n j++;\n if (j >= nGroups) RETURN(BZ_DATA_ERROR);\n }\n s->selectorMtf[i] = j;\n }\n\n /*--- Undo the MTF values for the selectors. ---*/\n {\n UChar pos[BZ_N_GROUPS], tmp, v;\n for (v = 0; v < nGroups; v++) pos[v] = v;\n \n for (i = 0; i < nSelectors; i++) {\n v = s->selectorMtf[i];\n tmp = pos[v];\n while (v > 0) { pos[v] = pos[v-1]; v--; }\n pos[0] = tmp;\n s->selector[i] = tmp;\n }\n }\n\n /*--- Now the coding tables ---*/\n for (t = 0; t < nGroups; t++) {\n GET_BITS(BZ_X_CODING_1, curr, 5);\n for (i = 0; i < alphaSize; i++) {\n while (True) {\n if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR);\n GET_BIT(BZ_X_CODING_2, uc);\n if (uc == 0) break;\n GET_BIT(BZ_X_CODING_3, uc);\n if (uc == 0) curr++; else curr--;\n }\n s->len[t][i] = curr;\n }\n }\n\n /*--- Create the Huffman decoding tables ---*/\n for (t = 0; t < nGroups; t++) {\n minLen = 32;\n maxLen = 0;\n for (i = 0; i < alphaSize; i++) {\n if (s->len[t][i] > maxLen) maxLen = s->len[t][i];\n if (s->len[t][i] < minLen) minLen = s->len[t][i];\n }\n BZ2_hbCreateDecodeTables ( \n &(s->limit[t][0]), \n &(s->base[t][0]), \n &(s->perm[t][0]), \n &(s->len[t][0]),\n minLen, maxLen, alphaSize\n );\n s->minLens[t] = minLen;\n }\n\n /*--- Now the MTF values ---*/\n\n EOB = s->nInUse+1;\n nblockMAX = 100000 * s->blockSize100k;\n groupNo = -1;\n groupPos = 0;\n\n for (i = 0; i <= 255; i++) s->unzftab[i] = 0;\n\n /*-- MTF init --*/\n {\n Int32 ii, jj, kk;\n kk = MTFA_SIZE-1;\n for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) {\n for (jj = MTFL_SIZE-1; jj >= 0; jj--) {\n s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj);\n kk--;\n }\n s->mtfbase[ii] = kk + 1;\n }\n }\n /*-- end MTF init --*/\n\n nblock = 0;\n GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym);\n\n while (True) {\n\n if (nextSym == EOB) break;\n\n if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) {\n\n es = -1;\n N = 1;\n do {\n /* Check that N doesn't get too big, so that es doesn't\n go negative. The maximum value that can be\n RUNA/RUNB encoded is equal to the block size (post\n the initial RLE), viz, 900k, so bounding N at 2\n million should guard against overflow without\n rejecting any legitimate inputs. */\n if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR);\n if (nextSym == BZ_RUNA) es = es + (0+1) * N; else\n if (nextSym == BZ_RUNB) es = es + (1+1) * N;\n N = N * 2;\n GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym);\n }\n while (nextSym == BZ_RUNA || nextSym == BZ_RUNB);\n\n es++;\n uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ];\n s->unzftab[uc] += es;\n\n if (s->smallDecompress)\n while (es > 0) {\n if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n s->ll16[nblock] = (UInt16)uc;\n nblock++;\n es--;\n }\n else\n while (es > 0) {\n if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n s->tt[nblock] = (UInt32)uc;\n nblock++;\n es--;\n };\n\n continue;\n\n } else {\n\n if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n\n /*-- uc = MTF ( nextSym-1 ) --*/\n {\n Int32 ii, jj, kk, pp, lno, off;\n UInt32 nn;\n nn = (UInt32)(nextSym - 1);\n\n if (nn < MTFL_SIZE) {\n /* avoid general-case expense */\n pp = s->mtfbase[0];\n uc = s->mtfa[pp+nn];\n while (nn > 3) {\n Int32 z = pp+nn;\n s->mtfa[(z) ] = s->mtfa[(z)-1];\n s->mtfa[(z)-1] = s->mtfa[(z)-2];\n s->mtfa[(z)-2] = s->mtfa[(z)-3];\n s->mtfa[(z)-3] = s->mtfa[(z)-4];\n nn -= 4;\n }\n while (nn > 0) { \n s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; \n };\n s->mtfa[pp] = uc;\n } else { \n /* general case */\n lno = nn / MTFL_SIZE;\n off = nn % MTFL_SIZE;\n pp = s->mtfbase[lno] + off;\n uc = s->mtfa[pp];\n while (pp > s->mtfbase[lno]) { \n s->mtfa[pp] = s->mtfa[pp-1]; pp--; \n };\n s->mtfbase[lno]++;\n while (lno > 0) {\n s->mtfbase[lno]--;\n s->mtfa[s->mtfbase[lno]] \n = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1];\n lno--;\n }\n s->mtfbase[0]--;\n s->mtfa[s->mtfbase[0]] = uc;\n if (s->mtfbase[0] == 0) {\n kk = MTFA_SIZE-1;\n for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) {\n for (jj = MTFL_SIZE-1; jj >= 0; jj--) {\n s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj];\n kk--;\n }\n s->mtfbase[ii] = kk + 1;\n }\n }\n }\n }\n /*-- end uc = MTF ( nextSym-1 ) --*/\n\n s->unzftab[s->seqToUnseq[uc]]++;\n if (s->smallDecompress)\n s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else\n s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]);\n nblock++;\n\n GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym);\n continue;\n }\n }\n\n /* Now we know what nblock is, we can do a better sanity\n check on s->origPtr.\n */\n if (s->origPtr < 0 || s->origPtr >= nblock)\n RETURN(BZ_DATA_ERROR);\n\n /*-- Set up cftab to facilitate generation of T^(-1) --*/\n /* Check: unzftab entries in range. */\n for (i = 0; i <= 255; i++) {\n if (s->unzftab[i] < 0 || s->unzftab[i] > nblock)\n RETURN(BZ_DATA_ERROR);\n }\n /* Actually generate cftab. */\n s->cftab[0] = 0;\n for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1];\n for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1];\n /* Check: cftab entries in range. */\n for (i = 0; i <= 256; i++) {\n if (s->cftab[i] < 0 || s->cftab[i] > nblock) {\n /* s->cftab[i] can legitimately be == nblock */\n RETURN(BZ_DATA_ERROR);\n }\n }\n /* Check: cftab entries non-descending. */\n for (i = 1; i <= 256; i++) {\n if (s->cftab[i-1] > s->cftab[i]) {\n RETURN(BZ_DATA_ERROR);\n }\n }\n\n s->state_out_len = 0;\n s->state_out_ch = 0;\n BZ_INITIALISE_CRC ( s->calculatedBlockCRC );\n s->state = BZ_X_OUTPUT;\n if (s->verbosity >= 2) VPrintf0 ( \"rt+rld\" );\n\n if (s->smallDecompress) {\n\n /*-- Make a copy of cftab, used in generation of T --*/\n for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i];\n\n /*-- compute the T vector --*/\n for (i = 0; i < nblock; i++) {\n uc = (UChar)(s->ll16[i]);\n SET_LL(i, s->cftabCopy[uc]);\n s->cftabCopy[uc]++;\n }\n\n /*-- Compute T^(-1) by pointer reversal on T --*/\n i = s->origPtr;\n j = GET_LL(i);\n do {\n Int32 tmp = GET_LL(j);\n SET_LL(j, i);\n i = j;\n j = tmp;\n }\n while (i != s->origPtr);\n\n s->tPos = s->origPtr;\n s->nblock_used = 0;\n if (s->blockRandomised) {\n BZ_RAND_INIT_MASK;\n BZ_GET_SMALL(s->k0); s->nblock_used++;\n BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; \n } else {\n BZ_GET_SMALL(s->k0); s->nblock_used++;\n }\n\n } else {\n\n /*-- compute the T^(-1) vector --*/\n for (i = 0; i < nblock; i++) {\n uc = (UChar)(s->tt[i] & 0xff);\n s->tt[s->cftab[uc]] |= (i << 8);\n s->cftab[uc]++;\n }\n\n s->tPos = s->tt[s->origPtr] >> 8;\n s->nblock_used = 0;\n if (s->blockRandomised) {\n BZ_RAND_INIT_MASK;\n BZ_GET_FAST(s->k0); s->nblock_used++;\n BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; \n } else {\n BZ_GET_FAST(s->k0); s->nblock_used++;\n }\n\n }\n\n RETURN(BZ_OK);\n\n\n\n endhdr_2:\n\n GET_UCHAR(BZ_X_ENDHDR_2, uc);\n if (uc != 0x72) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_3, uc);\n if (uc != 0x45) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_4, uc);\n if (uc != 0x38) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_5, uc);\n if (uc != 0x50) RETURN(BZ_DATA_ERROR);\n GET_UCHAR(BZ_X_ENDHDR_6, uc);\n if (uc != 0x90) RETURN(BZ_DATA_ERROR);\n\n s->storedCombinedCRC = 0;\n GET_UCHAR(BZ_X_CCRC_1, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_CCRC_2, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_CCRC_3, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n GET_UCHAR(BZ_X_CCRC_4, uc);\n s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n\n s->state = BZ_X_IDLE;\n RETURN(BZ_STREAM_END);\n\n default: AssertH ( False, 4001 );\n }\n\n AssertH ( False, 4002 );\n\n save_state_and_return:\n\n s->save_i = i;\n s->save_j = j;\n s->save_t = t;\n s->save_alphaSize = alphaSize;\n s->save_nGroups = nGroups;\n s->save_nSelectors = nSelectors;\n s->save_EOB = EOB;\n s->save_groupNo = groupNo;\n s->save_groupPos = groupPos;\n s->save_nextSym = nextSym;\n s->save_nblockMAX = nblockMAX;\n s->save_nblock = nblock;\n s->save_es = es;\n s->save_N = N;\n s->save_curr = curr;\n s->save_zt = zt;\n s->save_zn = zn;\n s->save_zvec = zvec;\n s->save_zj = zj;\n s->save_gSel = gSel;\n s->save_gMinlen = gMinlen;\n s->save_gLimit = gLimit;\n s->save_gBase = gBase;\n s->save_gPerm = gPerm;\n\n return retVal; \n}", "project": "bzip2", "hash": 108046436633071473316758216167773719100, "size": 536, "commit_id": "74de1e2e6ffc9d51ef9824db71a8ffee5962cdbc", "message": "Make sure nSelectors is not out of range\n\nnSelectors is used in a loop from 0 to nSelectors to access selectorMtf\nwhich is\n\tUChar selectorMtf[BZ_MAX_SELECTORS];\nso if nSelectors is bigger than BZ_MAX_SELECTORS it'll do an invalid memory\naccess\n\nFixes out of bounds access discovered while fuzzying karchive", "target": 0, "dataset": "other", "idx": 409183} {"func": "static int uvc_scan_chain_forward(struct uvc_video_chain *chain,\n\tstruct uvc_entity *entity, struct uvc_entity *prev)\n{\n\tstruct uvc_entity *forward;\n\tint found;\n\n\t/* Forward scan */\n\tforward = NULL;\n\tfound = 0;\n\n\twhile (1) {\n\t\tforward = uvc_entity_by_reference(chain->dev, entity->id,\n\t\t\tforward);\n\t\tif (forward == NULL)\n\t\t\tbreak;\n\t\tif (forward == prev)\n\t\t\tcontinue;\n\n\t\tswitch (UVC_ENTITY_TYPE(forward)) {\n\t\tcase UVC_VC_EXTENSION_UNIT:\n\t\t\tif (forward->bNrInPins != 1) {\n\t\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Extension unit %d \"\n\t\t\t\t\t \"has more than 1 input pin.\\n\",\n\t\t\t\t\t entity->id);\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tlist_add_tail(&forward->chain, &chain->entities);\n\t\t\tif (uvc_trace_param & UVC_TRACE_PROBE) {\n\t\t\t\tif (!found)\n\t\t\t\t\tprintk(KERN_CONT \" (->\");\n\n\t\t\t\tprintk(KERN_CONT \" XU %d\", forward->id);\n\t\t\t\tfound = 1;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase UVC_OTT_VENDOR_SPECIFIC:\n\t\tcase UVC_OTT_DISPLAY:\n\t\tcase UVC_OTT_MEDIA_TRANSPORT_OUTPUT:\n\t\tcase UVC_TT_STREAMING:\n\t\t\tif (UVC_ENTITY_IS_ITERM(forward)) {\n\t\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Unsupported input \"\n\t\t\t\t\t\"terminal %u.\\n\", forward->id);\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tlist_add_tail(&forward->chain, &chain->entities);\n\t\t\tif (uvc_trace_param & UVC_TRACE_PROBE) {\n\t\t\t\tif (!found)\n\t\t\t\t\tprintk(KERN_CONT \" (->\");\n\n\t\t\t\tprintk(KERN_CONT \" OT %d\", forward->id);\n\t\t\t\tfound = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (found)\n\t\tprintk(KERN_CONT \")\");\n\n\treturn 0;\n}", "project": "linux", "hash": 40134444787400205515449543582828290804, "size": 63, "commit_id": "68035c80e129c4cfec659aac4180354530b26527", "message": "media: uvcvideo: Avoid cyclic entity chains due to malformed USB descriptors\n\nWay back in 2017, fuzzing the 4.14-rc2 USB stack with syzkaller kicked\nup the following WARNING from the UVC chain scanning code:\n\n | list_add double add: new=ffff880069084010, prev=ffff880069084010,\n | next=ffff880067d22298.\n | ------------[ cut here ]------------\n | WARNING: CPU: 1 PID: 1846 at lib/list_debug.c:31 __list_add_valid+0xbd/0xf0\n | Modules linked in:\n | CPU: 1 PID: 1846 Comm: kworker/1:2 Not tainted\n | 4.14.0-rc2-42613-g1488251d1a98 #238\n | Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\n | Workqueue: usb_hub_wq hub_event\n | task: ffff88006b01ca40 task.stack: ffff880064358000\n | RIP: 0010:__list_add_valid+0xbd/0xf0 lib/list_debug.c:29\n | RSP: 0018:ffff88006435ddd0 EFLAGS: 00010286\n | RAX: 0000000000000058 RBX: ffff880067d22298 RCX: 0000000000000000\n | RDX: 0000000000000058 RSI: ffffffff85a58800 RDI: ffffed000c86bbac\n | RBP: ffff88006435dde8 R08: 1ffff1000c86ba52 R09: 0000000000000000\n | R10: 0000000000000002 R11: 0000000000000000 R12: ffff880069084010\n | R13: ffff880067d22298 R14: ffff880069084010 R15: ffff880067d222a0\n | FS: 0000000000000000(0000) GS:ffff88006c900000(0000) knlGS:0000000000000000\n | CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\n | CR2: 0000000020004ff2 CR3: 000000006b447000 CR4: 00000000000006e0\n | Call Trace:\n | __list_add ./include/linux/list.h:59\n | list_add_tail+0x8c/0x1b0 ./include/linux/list.h:92\n | uvc_scan_chain_forward.isra.8+0x373/0x416\n | drivers/media/usb/uvc/uvc_driver.c:1471\n | uvc_scan_chain drivers/media/usb/uvc/uvc_driver.c:1585\n | uvc_scan_device drivers/media/usb/uvc/uvc_driver.c:1769\n | uvc_probe+0x77f2/0x8f00 drivers/media/usb/uvc/uvc_driver.c:2104\n\nLooking into the output from usbmon, the interesting part is the\nfollowing data packet:\n\n ffff880069c63e00 30710169 C Ci:1:002:0 0 143 = 09028f00 01030080\n 00090403 00000e01 00000924 03000103 7c003328 010204db\n\nIf we drop the lead configuration and interface descriptors, we're left\nwith an output terminal descriptor describing a generic display:\n\n /* Output terminal descriptor */\n buf[0]\t09\n buf[1]\t24\n buf[2]\t03\t/* UVC_VC_OUTPUT_TERMINAL */\n buf[3]\t00\t/* ID */\n buf[4]\t01\t/* type == 0x0301 (UVC_OTT_DISPLAY) */\n buf[5]\t03\n buf[6]\t7c\n buf[7]\t00\t/* source ID refers to self! */\n buf[8]\t33\n\nThe problem with this descriptor is that it is self-referential: the\nsource ID of 0 matches itself! This causes the 'struct uvc_entity'\nrepresenting the display to be added to its chain list twice during\n'uvc_scan_chain()': once via 'uvc_scan_chain_entity()' when it is\nprocessed directly from the 'dev->entities' list and then again\nimmediately afterwards when trying to follow the source ID in\n'uvc_scan_chain_forward()'\n\nAdd a check before adding an entity to a chain list to ensure that the\nentity is not already part of a chain.\n\nLink: https://lore.kernel.org/linux-media/CAAeHK+z+Si69jUR+N-SjN9q4O+o5KFiNManqEa-PjUta7EOb7A@mail.gmail.com/\n\nCc: \nFixes: c0efd232929c (\"V4L/DVB (8145a): USB Video Class driver\")\nReported-by: Andrey Konovalov \nSigned-off-by: Will Deacon \nSigned-off-by: Laurent Pinchart \nSigned-off-by: Mauro Carvalho Chehab ", "target": 1, "dataset": "other", "idx": 208387} {"func": "static int uvc_scan_chain_forward(struct uvc_video_chain *chain,\n\tstruct uvc_entity *entity, struct uvc_entity *prev)\n{\n\tstruct uvc_entity *forward;\n\tint found;\n\n\t/* Forward scan */\n\tforward = NULL;\n\tfound = 0;\n\n\twhile (1) {\n\t\tforward = uvc_entity_by_reference(chain->dev, entity->id,\n\t\t\tforward);\n\t\tif (forward == NULL)\n\t\t\tbreak;\n\t\tif (forward == prev)\n\t\t\tcontinue;\n\t\tif (forward->chain.next || forward->chain.prev) {\n\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Found reference to \"\n\t\t\t\t\"entity %d already in chain.\\n\", forward->id);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tswitch (UVC_ENTITY_TYPE(forward)) {\n\t\tcase UVC_VC_EXTENSION_UNIT:\n\t\t\tif (forward->bNrInPins != 1) {\n\t\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Extension unit %d \"\n\t\t\t\t\t \"has more than 1 input pin.\\n\",\n\t\t\t\t\t entity->id);\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tlist_add_tail(&forward->chain, &chain->entities);\n\t\t\tif (uvc_trace_param & UVC_TRACE_PROBE) {\n\t\t\t\tif (!found)\n\t\t\t\t\tprintk(KERN_CONT \" (->\");\n\n\t\t\t\tprintk(KERN_CONT \" XU %d\", forward->id);\n\t\t\t\tfound = 1;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase UVC_OTT_VENDOR_SPECIFIC:\n\t\tcase UVC_OTT_DISPLAY:\n\t\tcase UVC_OTT_MEDIA_TRANSPORT_OUTPUT:\n\t\tcase UVC_TT_STREAMING:\n\t\t\tif (UVC_ENTITY_IS_ITERM(forward)) {\n\t\t\t\tuvc_trace(UVC_TRACE_DESCR, \"Unsupported input \"\n\t\t\t\t\t\"terminal %u.\\n\", forward->id);\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tlist_add_tail(&forward->chain, &chain->entities);\n\t\t\tif (uvc_trace_param & UVC_TRACE_PROBE) {\n\t\t\t\tif (!found)\n\t\t\t\t\tprintk(KERN_CONT \" (->\");\n\n\t\t\t\tprintk(KERN_CONT \" OT %d\", forward->id);\n\t\t\t\tfound = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (found)\n\t\tprintk(KERN_CONT \")\");\n\n\treturn 0;\n}", "project": "linux", "hash": 295353061660172152390372845804699304944, "size": 68, "commit_id": "68035c80e129c4cfec659aac4180354530b26527", "message": "media: uvcvideo: Avoid cyclic entity chains due to malformed USB descriptors\n\nWay back in 2017, fuzzing the 4.14-rc2 USB stack with syzkaller kicked\nup the following WARNING from the UVC chain scanning code:\n\n | list_add double add: new=ffff880069084010, prev=ffff880069084010,\n | next=ffff880067d22298.\n | ------------[ cut here ]------------\n | WARNING: CPU: 1 PID: 1846 at lib/list_debug.c:31 __list_add_valid+0xbd/0xf0\n | Modules linked in:\n | CPU: 1 PID: 1846 Comm: kworker/1:2 Not tainted\n | 4.14.0-rc2-42613-g1488251d1a98 #238\n | Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\n | Workqueue: usb_hub_wq hub_event\n | task: ffff88006b01ca40 task.stack: ffff880064358000\n | RIP: 0010:__list_add_valid+0xbd/0xf0 lib/list_debug.c:29\n | RSP: 0018:ffff88006435ddd0 EFLAGS: 00010286\n | RAX: 0000000000000058 RBX: ffff880067d22298 RCX: 0000000000000000\n | RDX: 0000000000000058 RSI: ffffffff85a58800 RDI: ffffed000c86bbac\n | RBP: ffff88006435dde8 R08: 1ffff1000c86ba52 R09: 0000000000000000\n | R10: 0000000000000002 R11: 0000000000000000 R12: ffff880069084010\n | R13: ffff880067d22298 R14: ffff880069084010 R15: ffff880067d222a0\n | FS: 0000000000000000(0000) GS:ffff88006c900000(0000) knlGS:0000000000000000\n | CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\n | CR2: 0000000020004ff2 CR3: 000000006b447000 CR4: 00000000000006e0\n | Call Trace:\n | __list_add ./include/linux/list.h:59\n | list_add_tail+0x8c/0x1b0 ./include/linux/list.h:92\n | uvc_scan_chain_forward.isra.8+0x373/0x416\n | drivers/media/usb/uvc/uvc_driver.c:1471\n | uvc_scan_chain drivers/media/usb/uvc/uvc_driver.c:1585\n | uvc_scan_device drivers/media/usb/uvc/uvc_driver.c:1769\n | uvc_probe+0x77f2/0x8f00 drivers/media/usb/uvc/uvc_driver.c:2104\n\nLooking into the output from usbmon, the interesting part is the\nfollowing data packet:\n\n ffff880069c63e00 30710169 C Ci:1:002:0 0 143 = 09028f00 01030080\n 00090403 00000e01 00000924 03000103 7c003328 010204db\n\nIf we drop the lead configuration and interface descriptors, we're left\nwith an output terminal descriptor describing a generic display:\n\n /* Output terminal descriptor */\n buf[0]\t09\n buf[1]\t24\n buf[2]\t03\t/* UVC_VC_OUTPUT_TERMINAL */\n buf[3]\t00\t/* ID */\n buf[4]\t01\t/* type == 0x0301 (UVC_OTT_DISPLAY) */\n buf[5]\t03\n buf[6]\t7c\n buf[7]\t00\t/* source ID refers to self! */\n buf[8]\t33\n\nThe problem with this descriptor is that it is self-referential: the\nsource ID of 0 matches itself! This causes the 'struct uvc_entity'\nrepresenting the display to be added to its chain list twice during\n'uvc_scan_chain()': once via 'uvc_scan_chain_entity()' when it is\nprocessed directly from the 'dev->entities' list and then again\nimmediately afterwards when trying to follow the source ID in\n'uvc_scan_chain_forward()'\n\nAdd a check before adding an entity to a chain list to ensure that the\nentity is not already part of a chain.\n\nLink: https://lore.kernel.org/linux-media/CAAeHK+z+Si69jUR+N-SjN9q4O+o5KFiNManqEa-PjUta7EOb7A@mail.gmail.com/\n\nCc: \nFixes: c0efd232929c (\"V4L/DVB (8145a): USB Video Class driver\")\nReported-by: Andrey Konovalov \nSigned-off-by: Will Deacon \nSigned-off-by: Laurent Pinchart \nSigned-off-by: Mauro Carvalho Chehab ", "target": 0, "dataset": "other", "idx": 409209} {"func": "static BOOL rdp_read_font_capability_set(wStream* s, UINT16 length, rdpSettings* settings)\n{\n\tWINPR_UNUSED(settings);\n\tif (length > 4)\n\t\tStream_Seek_UINT16(s); /* fontSupportFlags (2 bytes) */\n\n\tif (length > 6)\n\t\tStream_Seek_UINT16(s); /* pad2Octets (2 bytes) */\n\n\treturn TRUE;\n}", "project": "FreeRDP", "hash": 63945765978373457675419959857261610616, "size": 11, "commit_id": "3627aaf7d289315b614a584afb388f04abfb5bbf", "message": "Fixed #6011: Bounds check in rdp_read_font_capability_set", "target": 1, "dataset": "other", "idx": 208417} {"func": "static BOOL rdp_read_font_capability_set(wStream* s, UINT16 length, rdpSettings* settings)\n{\n\tWINPR_UNUSED(settings);\n\tif (length > 5)\n\t\tStream_Seek_UINT16(s); /* fontSupportFlags (2 bytes) */\n\n\tif (length > 7)\n\t\tStream_Seek_UINT16(s); /* pad2Octets (2 bytes) */\n\n\treturn TRUE;\n}", "project": "FreeRDP", "hash": 92561895110037279576315503246460434637, "size": 11, "commit_id": "3627aaf7d289315b614a584afb388f04abfb5bbf", "message": "Fixed #6011: Bounds check in rdp_read_font_capability_set", "target": 0, "dataset": "other", "idx": 409646} {"func": "delete_buff_tail(buffheader_T *buf, int slen)\n{\n int len = (int)STRLEN(buf->bh_curr->b_str);\n\n if (len >= slen)\n {\n\tbuf->bh_curr->b_str[len - slen] = NUL;\n\tbuf->bh_space += slen;\n }\n}", "project": "vim", "hash": 320320646444324926020830996441995496926, "size": 10, "commit_id": "a4bc2dd7cccf5a4a9f78b58b6f35a45d17164323", "message": "patch 8.2.4233: crash when recording and using Select mode\n\nProblem: Crash when recording and using Select mode.\nSolution: When deleting the last recorded character check there is something\n to delete.", "target": 1, "dataset": "other", "idx": 208442} {"func": "delete_buff_tail(buffheader_T *buf, int slen)\n{\n int len;\n\n if (buf->bh_curr == NULL || buf->bh_curr->b_str == NULL)\n\treturn; // nothing to delete\n len = (int)STRLEN(buf->bh_curr->b_str);\n if (len >= slen)\n {\n\tbuf->bh_curr->b_str[len - slen] = NUL;\n\tbuf->bh_space += slen;\n }\n}", "project": "vim", "hash": 67321294593976323375988048434039618369, "size": 13, "commit_id": "a4bc2dd7cccf5a4a9f78b58b6f35a45d17164323", "message": "patch 8.2.4233: crash when recording and using Select mode\n\nProblem: Crash when recording and using Select mode.\nSolution: When deleting the last recorded character check there is something\n to delete.", "target": 0, "dataset": "other", "idx": 410380} {"func": "static int is_fuse_usermount(struct libmnt_context *cxt, int *errsv)\n{\n\tstruct libmnt_ns *ns_old;\n\tconst char *type = mnt_fs_get_fstype(cxt->fs);\n\tconst char *optstr;\n\tchar *user_id = NULL;\n\tsize_t sz;\n\tuid_t uid;\n\tchar uidstr[sizeof(stringify_value(ULONG_MAX))];\n\n\t*errsv = 0;\n\n\tif (!type)\n\t\treturn 0;\n\n\tif (strcmp(type, \"fuse\") != 0 &&\n\t strcmp(type, \"fuseblk\") != 0 &&\n\t strncmp(type, \"fuse.\", 5) != 0 &&\n\t strncmp(type, \"fuseblk.\", 8) != 0)\n\t\treturn 0;\n\n\t/* get user_id= from mount table */\n\toptstr = mnt_fs_get_fs_options(cxt->fs);\n\tif (!optstr)\n\t\treturn 0;\n\n\tif (mnt_optstr_get_option(optstr, \"user_id\", &user_id, &sz) != 0)\n\t\treturn 0;\n\n\tif (sz == 0 || user_id == NULL)\n\t\treturn 0;\n\n\t/* get current user */\n\tns_old = mnt_context_switch_origin_ns(cxt);\n\tif (!ns_old) {\n\t\t*errsv = -MNT_ERR_NAMESPACE;\n\t\treturn 0;\n\t}\n\n\tuid = getuid();\n\n\tif (!mnt_context_switch_ns(cxt, ns_old)) {\n\t\t*errsv = -MNT_ERR_NAMESPACE;\n\t\treturn 0;\n\t}\n\n\tsnprintf(uidstr, sizeof(uidstr), \"%lu\", (unsigned long) uid);\n\treturn strncmp(user_id, uidstr, sz) == 0;\n}", "project": "util-linux", "hash": 210310102417734751354249196559456080186, "size": 49, "commit_id": "57202f5713afa2af20ffbb6ab5331481d0396f8d", "message": "libmount: fix UID check for FUSE umount [CVE-2021-3995]\n\nImproper UID check allows an unprivileged user to unmount FUSE\nfilesystems of users with similar UID.\n\nSigned-off-by: Karel Zak ", "target": 1, "dataset": "other", "idx": 208443} {"func": "static int is_fuse_usermount(struct libmnt_context *cxt, int *errsv)\n{\n\tstruct libmnt_ns *ns_old;\n\tconst char *type = mnt_fs_get_fstype(cxt->fs);\n\tconst char *optstr;\n\tuid_t uid, entry_uid;\n\n\t*errsv = 0;\n\n\tif (!type)\n\t\treturn 0;\n\n\tif (strcmp(type, \"fuse\") != 0 &&\n\t strcmp(type, \"fuseblk\") != 0 &&\n\t strncmp(type, \"fuse.\", 5) != 0 &&\n\t strncmp(type, \"fuseblk.\", 8) != 0)\n\t\treturn 0;\n\n\t/* get user_id= from mount table */\n\toptstr = mnt_fs_get_fs_options(cxt->fs);\n\tif (!optstr)\n\t\treturn 0;\n\tif (mnt_optstr_get_uid(optstr, \"user_id\", &entry_uid) != 0)\n\t\treturn 0;\n\n\t/* get current user */\n\tns_old = mnt_context_switch_origin_ns(cxt);\n\tif (!ns_old) {\n\t\t*errsv = -MNT_ERR_NAMESPACE;\n\t\treturn 0;\n\t}\n\n\tuid = getuid();\n\n\tif (!mnt_context_switch_ns(cxt, ns_old)) {\n\t\t*errsv = -MNT_ERR_NAMESPACE;\n\t\treturn 0;\n\t}\n\n\treturn uid == entry_uid;\n}", "project": "util-linux", "hash": 183698717299577400492179801479311774546, "size": 41, "commit_id": "57202f5713afa2af20ffbb6ab5331481d0396f8d", "message": "libmount: fix UID check for FUSE umount [CVE-2021-3995]\n\nImproper UID check allows an unprivileged user to unmount FUSE\nfilesystems of users with similar UID.\n\nSigned-off-by: Karel Zak ", "target": 0, "dataset": "other", "idx": 410433} {"func": "static inline void tcp_check_send_head(struct sock *sk, struct sk_buff *skb_unlinked)\n{\n\tif (sk->sk_send_head == skb_unlinked)\n\t\tsk->sk_send_head = NULL;\n}", "project": "linux", "hash": 305735579556355500541582008604019854778, "size": 5, "commit_id": "bb1fceca22492109be12640d49f5ea5a544c6bb4", "message": "tcp: fix use after free in tcp_xmit_retransmit_queue()\n\nWhen tcp_sendmsg() allocates a fresh and empty skb, it puts it at the\ntail of the write queue using tcp_add_write_queue_tail()\n\nThen it attempts to copy user data into this fresh skb.\n\nIf the copy fails, we undo the work and remove the fresh skb.\n\nUnfortunately, this undo lacks the change done to tp->highest_sack and\nwe can leave a dangling pointer (to a freed skb)\n\nLater, tcp_xmit_retransmit_queue() can dereference this pointer and\naccess freed memory. For regular kernels where memory is not unmapped,\nthis might cause SACK bugs because tcp_highest_sack_seq() is buggy,\nreturning garbage instead of tp->snd_nxt, but with various debug\nfeatures like CONFIG_DEBUG_PAGEALLOC, this can crash the kernel.\n\nThis bug was found by Marco Grassi thanks to syzkaller.\n\nFixes: 6859d49475d4 (\"[TCP]: Abstract tp->highest_sack accessing & point to next skb\")\nReported-by: Marco Grassi \nSigned-off-by: Eric Dumazet \nCc: Ilpo J\u00e4rvinen \nCc: Yuchung Cheng \nCc: Neal Cardwell \nAcked-by: Neal Cardwell \nReviewed-by: Cong Wang \nSigned-off-by: David S. Miller ", "target": 1, "dataset": "other", "idx": 208465} {"func": "static inline void tcp_check_send_head(struct sock *sk, struct sk_buff *skb_unlinked)\n{\n\tif (sk->sk_send_head == skb_unlinked)\n\t\tsk->sk_send_head = NULL;\n\tif (tcp_sk(sk)->highest_sack == skb_unlinked)\n\t\ttcp_sk(sk)->highest_sack = NULL;\n}", "project": "linux", "hash": 5947355706701478126786824025705054068, "size": 7, "commit_id": "bb1fceca22492109be12640d49f5ea5a544c6bb4", "message": "tcp: fix use after free in tcp_xmit_retransmit_queue()\n\nWhen tcp_sendmsg() allocates a fresh and empty skb, it puts it at the\ntail of the write queue using tcp_add_write_queue_tail()\n\nThen it attempts to copy user data into this fresh skb.\n\nIf the copy fails, we undo the work and remove the fresh skb.\n\nUnfortunately, this undo lacks the change done to tp->highest_sack and\nwe can leave a dangling pointer (to a freed skb)\n\nLater, tcp_xmit_retransmit_queue() can dereference this pointer and\naccess freed memory. For regular kernels where memory is not unmapped,\nthis might cause SACK bugs because tcp_highest_sack_seq() is buggy,\nreturning garbage instead of tp->snd_nxt, but with various debug\nfeatures like CONFIG_DEBUG_PAGEALLOC, this can crash the kernel.\n\nThis bug was found by Marco Grassi thanks to syzkaller.\n\nFixes: 6859d49475d4 (\"[TCP]: Abstract tp->highest_sack accessing & point to next skb\")\nReported-by: Marco Grassi \nSigned-off-by: Eric Dumazet \nCc: Ilpo J\u00e4rvinen \nCc: Yuchung Cheng \nCc: Neal Cardwell \nAcked-by: Neal Cardwell \nReviewed-by: Cong Wang \nSigned-off-by: David S. Miller ", "target": 0, "dataset": "other", "idx": 410730} {"func": "static INLINE BOOL ensure_capacity(const BYTE* start, const BYTE* end, size_t size, size_t base)\n{\n\tconst size_t available = (uintptr_t)end - (uintptr_t)start;\n\tconst BOOL rc = available >= size * base;\n\treturn rc;\n}", "project": "FreeRDP", "hash": 203800133322701028714179275363172565549, "size": 6, "commit_id": "7b1d4b49391b4512402840431757703a96946820", "message": "Fix CVE-2020-11524: out of bounds access in interleaved\n\nThanks to Sunglin and HuanGMz from Knownsec 404", "target": 1, "dataset": "other", "idx": 208486} {"func": "static INLINE BOOL ensure_capacity(const BYTE* start, const BYTE* end, size_t size, size_t base)\n{\n\tconst size_t available = (uintptr_t)end - (uintptr_t)start;\n\tconst BOOL rc = available >= size * base;\n\treturn rc && (start <= end);\n}", "project": "FreeRDP", "hash": 224150333890835595116889465118463357527, "size": 6, "commit_id": "7b1d4b49391b4512402840431757703a96946820", "message": "Fix CVE-2020-11524: out of bounds access in interleaved\n\nThanks to Sunglin and HuanGMz from Knownsec 404", "target": 0, "dataset": "other", "idx": 411767} {"func": "parserule(struct scanner *s, struct environment *env)\n{\n\tstruct rule *r;\n\tchar *var;\n\tstruct evalstring *val;\n\tbool hascommand = false, hasrspfile = false, hasrspcontent = false;\n\n\tr = mkrule(scanname(s));\n\tscannewline(s);\n\twhile (scanindent(s)) {\n\t\tvar = scanname(s);\n\t\tparselet(s, &val);\n\t\truleaddvar(r, var, val);\n\t\tif (strcmp(var, \"command\") == 0)\n\t\t\thascommand = true;\n\t\telse if (strcmp(var, \"rspfile\") == 0)\n\t\t\thasrspfile = true;\n\t\telse if (strcmp(var, \"rspfile_content\") == 0)\n\t\t\thasrspcontent = true;\n\t}\n\tif (!hascommand)\n\t\tfatal(\"rule '%s' has no command\", r->name);\n\tif (hasrspfile != hasrspcontent)\n\t\tfatal(\"rule '%s' has rspfile and no rspfile_content or vice versa\", r->name);\n\tenvaddrule(env, r);\n}", "project": "samurai", "hash": 335382966921873606289133752083182751104, "size": 26, "commit_id": "d2af3bc375e2a77139c3a28d6128c60cd8d08655", "message": "parse: Check for non-empty command/rspfile/rspfile_content\n\nThis matches ninja behavior and prevents the possibility of a rule\nwith an empty (NULL) command string.\n\nFixes #68.", "target": 1, "dataset": "other", "idx": 208509} {"func": "parserule(struct scanner *s, struct environment *env)\n{\n\tstruct rule *r;\n\tchar *var;\n\tstruct evalstring *val;\n\tbool hascommand = false, hasrspfile = false, hasrspcontent = false;\n\n\tr = mkrule(scanname(s));\n\tscannewline(s);\n\twhile (scanindent(s)) {\n\t\tvar = scanname(s);\n\t\tparselet(s, &val);\n\t\truleaddvar(r, var, val);\n\t\tif (!val)\n\t\t\tcontinue;\n\t\tif (strcmp(var, \"command\") == 0)\n\t\t\thascommand = true;\n\t\telse if (strcmp(var, \"rspfile\") == 0)\n\t\t\thasrspfile = true;\n\t\telse if (strcmp(var, \"rspfile_content\") == 0)\n\t\t\thasrspcontent = true;\n\t}\n\tif (!hascommand)\n\t\tfatal(\"rule '%s' has no command\", r->name);\n\tif (hasrspfile != hasrspcontent)\n\t\tfatal(\"rule '%s' has rspfile and no rspfile_content or vice versa\", r->name);\n\tenvaddrule(env, r);\n}", "project": "samurai", "hash": 25964334636848040242473999480648310370, "size": 28, "commit_id": "d2af3bc375e2a77139c3a28d6128c60cd8d08655", "message": "parse: Check for non-empty command/rspfile/rspfile_content\n\nThis matches ninja behavior and prevents the possibility of a rule\nwith an empty (NULL) command string.\n\nFixes #68.", "target": 0, "dataset": "other", "idx": 411968} {"func": "handle_add_command(GraphicsManager *self, const GraphicsCommand *g, const uint8_t *payload, bool *is_dirty, uint32_t iid) {\n#define ABRT(code, ...) { set_add_response(#code, __VA_ARGS__); self->loading_image = 0; if (img) img->data_loaded = false; return NULL; }\n#define MAX_DATA_SZ (4u * 100000000u)\n has_add_respose = false;\n bool existing, init_img = true;\n Image *img = NULL;\n unsigned char tt = g->transmission_type ? g->transmission_type : 'd';\n enum FORMATS { RGB=24, RGBA=32, PNG=100 };\n uint32_t fmt = g->format ? g->format : RGBA;\n if (tt == 'd' && self->loading_image) init_img = false;\n if (init_img) {\n self->last_init_graphics_command = *g;\n self->last_init_graphics_command.id = iid;\n self->loading_image = 0;\n if (g->data_width > 10000 || g->data_height > 10000) ABRT(EINVAL, \"Image too large\");\n remove_images(self, add_trim_predicate, 0);\n img = find_or_create_image(self, iid, &existing);\n if (existing) {\n free_load_data(&img->load_data);\n img->data_loaded = false;\n free_refs_data(img);\n *is_dirty = true;\n self->layers_dirty = true;\n } else {\n img->internal_id = internal_id_counter++;\n img->client_id = iid;\n }\n img->atime = monotonic(); img->used_storage = 0;\n img->width = g->data_width; img->height = g->data_height;\n switch(fmt) {\n case PNG:\n if (g->data_sz > MAX_DATA_SZ) ABRT(EINVAL, \"PNG data size too large\");\n img->load_data.is_4byte_aligned = true;\n img->load_data.is_opaque = false;\n img->load_data.data_sz = g->data_sz ? g->data_sz : 1024 * 100;\n break;\n case RGB:\n case RGBA:\n img->load_data.data_sz = (size_t)g->data_width * g->data_height * (fmt / 8);\n if (!img->load_data.data_sz) ABRT(EINVAL, \"Zero width/height not allowed\");\n img->load_data.is_4byte_aligned = fmt == RGBA || (img->width % 4 == 0);\n img->load_data.is_opaque = fmt == RGB;\n break;\n default:\n ABRT(EINVAL, \"Unknown image format: %u\", fmt);\n }\n if (tt == 'd') {\n if (g->more) self->loading_image = img->internal_id;\n img->load_data.buf_capacity = img->load_data.data_sz + (g->compressed ? 1024 : 10); // compression header\n img->load_data.buf = malloc(img->load_data.buf_capacity);\n img->load_data.buf_used = 0;\n if (img->load_data.buf == NULL) {\n ABRT(ENOMEM, \"Out of memory\");\n img->load_data.buf_capacity = 0; img->load_data.buf_used = 0;\n }\n }\n } else {\n self->last_init_graphics_command.more = g->more;\n self->last_init_graphics_command.payload_sz = g->payload_sz;\n g = &self->last_init_graphics_command;\n tt = g->transmission_type ? g->transmission_type : 'd';\n fmt = g->format ? g->format : RGBA;\n img = img_by_internal_id(self, self->loading_image);\n if (img == NULL) {\n self->loading_image = 0;\n ABRT(EILSEQ, \"More payload loading refers to non-existent image\");\n }\n }\n int fd;\n static char fname[2056] = {0};\n switch(tt) {\n case 'd': // direct\n if (img->load_data.buf_capacity - img->load_data.buf_used < g->payload_sz) {\n if (img->load_data.buf_used + g->payload_sz > MAX_DATA_SZ || fmt != PNG) ABRT(EFBIG, \"Too much data\");\n img->load_data.buf_capacity = MIN(2 * img->load_data.buf_capacity, MAX_DATA_SZ);\n img->load_data.buf = realloc(img->load_data.buf, img->load_data.buf_capacity);\n if (img->load_data.buf == NULL) {\n ABRT(ENOMEM, \"Out of memory\");\n img->load_data.buf_capacity = 0; img->load_data.buf_used = 0;\n }\n }\n memcpy(img->load_data.buf + img->load_data.buf_used, payload, g->payload_sz);\n img->load_data.buf_used += g->payload_sz;\n if (!g->more) { img->data_loaded = true; self->loading_image = 0; }\n break;\n case 'f': // file\n case 't': // temporary file\n case 's': // POSIX shared memory\n if (g->payload_sz > 2048) ABRT(EINVAL, \"Filename too long\");\n snprintf(fname, sizeof(fname)/sizeof(fname[0]), \"%.*s\", (int)g->payload_sz, payload);\n if (tt == 's') fd = shm_open(fname, O_RDONLY, 0);\n else fd = open(fname, O_CLOEXEC | O_RDONLY);\n if (fd == -1) ABRT(EBADF, \"Failed to open file %s for graphics transmission with error: [%d] %s\", fname, errno, strerror(errno));\n img->data_loaded = mmap_img_file(self, img, fd, g->data_sz, g->data_offset);\n safe_close(fd, __FILE__, __LINE__);\n if (tt == 't') {\n if (global_state.boss) { call_boss(safe_delete_temp_file, \"s\", fname); }\n else unlink(fname);\n }\n else if (tt == 's') shm_unlink(fname);\n break;\n default:\n ABRT(EINVAL, \"Unknown transmission type: %c\", g->transmission_type);\n }\n if (!img->data_loaded) return NULL;\n self->loading_image = 0;\n bool needs_processing = g->compressed || fmt == PNG;\n if (needs_processing) {\n uint8_t *buf; size_t bufsz;\n#define IB { if (img->load_data.buf) { buf = img->load_data.buf; bufsz = img->load_data.buf_used; } else { buf = img->load_data.mapped_file; bufsz = img->load_data.mapped_file_sz; } }\n switch(g->compressed) {\n case 'z':\n IB;\n if (!inflate_zlib(self, img, buf, bufsz)) {\n img->data_loaded = false; return NULL;\n }\n break;\n case 0:\n break;\n default:\n ABRT(EINVAL, \"Unknown image compression: %c\", g->compressed);\n }\n switch(fmt) {\n case PNG:\n IB;\n if (!inflate_png(self, img, buf, bufsz)) {\n img->data_loaded = false; return NULL;\n }\n break;\n default: break;\n }\n#undef IB\n img->load_data.data = img->load_data.buf;\n if (img->load_data.buf_used < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.buf_used, img->load_data.data_sz);\n }\n if (img->load_data.mapped_file) {\n munmap(img->load_data.mapped_file, img->load_data.mapped_file_sz);\n img->load_data.mapped_file = NULL; img->load_data.mapped_file_sz = 0;\n }\n } else {\n if (tt == 'd') {\n if (img->load_data.buf_used < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.buf_used, img->load_data.data_sz);\n } else img->load_data.data = img->load_data.buf;\n } else {\n if (img->load_data.mapped_file_sz < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.mapped_file_sz, img->load_data.data_sz);\n } else img->load_data.data = img->load_data.mapped_file;\n }\n }\n size_t required_sz = (size_t)(img->load_data.is_opaque ? 3 : 4) * img->width * img->height;\n if (img->load_data.data_sz != required_sz) ABRT(EINVAL, \"Image dimensions: %ux%u do not match data size: %zu, expected size: %zu\", img->width, img->height, img->load_data.data_sz, required_sz);\n if (LIKELY(img->data_loaded && send_to_gpu)) {\n send_image_to_gpu(&img->texture_id, img->load_data.data, img->width, img->height, img->load_data.is_opaque, img->load_data.is_4byte_aligned, false, REPEAT_CLAMP);\n free_load_data(&img->load_data);\n self->used_storage += required_sz;\n img->used_storage = required_sz;\n }\n return img;\n#undef MAX_DATA_SZ\n#undef ABRT\n}", "project": "kitty", "hash": 193277586803458068601987516058015840256, "size": 163, "commit_id": "82c137878c2b99100a3cdc1c0f0efea069313901", "message": "Graphics protocol: Dont return filename in the error message when opening file fails, since filenames can contain control characters\n\nFixes #3128", "target": 1, "dataset": "other", "idx": 208514} {"func": "handle_add_command(GraphicsManager *self, const GraphicsCommand *g, const uint8_t *payload, bool *is_dirty, uint32_t iid) {\n#define ABRT(code, ...) { set_add_response(#code, __VA_ARGS__); self->loading_image = 0; if (img) img->data_loaded = false; return NULL; }\n#define MAX_DATA_SZ (4u * 100000000u)\n has_add_respose = false;\n bool existing, init_img = true;\n Image *img = NULL;\n unsigned char tt = g->transmission_type ? g->transmission_type : 'd';\n enum FORMATS { RGB=24, RGBA=32, PNG=100 };\n uint32_t fmt = g->format ? g->format : RGBA;\n if (tt == 'd' && self->loading_image) init_img = false;\n if (init_img) {\n self->last_init_graphics_command = *g;\n self->last_init_graphics_command.id = iid;\n self->loading_image = 0;\n if (g->data_width > 10000 || g->data_height > 10000) ABRT(EINVAL, \"Image too large\");\n remove_images(self, add_trim_predicate, 0);\n img = find_or_create_image(self, iid, &existing);\n if (existing) {\n free_load_data(&img->load_data);\n img->data_loaded = false;\n free_refs_data(img);\n *is_dirty = true;\n self->layers_dirty = true;\n } else {\n img->internal_id = internal_id_counter++;\n img->client_id = iid;\n }\n img->atime = monotonic(); img->used_storage = 0;\n img->width = g->data_width; img->height = g->data_height;\n switch(fmt) {\n case PNG:\n if (g->data_sz > MAX_DATA_SZ) ABRT(EINVAL, \"PNG data size too large\");\n img->load_data.is_4byte_aligned = true;\n img->load_data.is_opaque = false;\n img->load_data.data_sz = g->data_sz ? g->data_sz : 1024 * 100;\n break;\n case RGB:\n case RGBA:\n img->load_data.data_sz = (size_t)g->data_width * g->data_height * (fmt / 8);\n if (!img->load_data.data_sz) ABRT(EINVAL, \"Zero width/height not allowed\");\n img->load_data.is_4byte_aligned = fmt == RGBA || (img->width % 4 == 0);\n img->load_data.is_opaque = fmt == RGB;\n break;\n default:\n ABRT(EINVAL, \"Unknown image format: %u\", fmt);\n }\n if (tt == 'd') {\n if (g->more) self->loading_image = img->internal_id;\n img->load_data.buf_capacity = img->load_data.data_sz + (g->compressed ? 1024 : 10); // compression header\n img->load_data.buf = malloc(img->load_data.buf_capacity);\n img->load_data.buf_used = 0;\n if (img->load_data.buf == NULL) {\n ABRT(ENOMEM, \"Out of memory\");\n img->load_data.buf_capacity = 0; img->load_data.buf_used = 0;\n }\n }\n } else {\n self->last_init_graphics_command.more = g->more;\n self->last_init_graphics_command.payload_sz = g->payload_sz;\n g = &self->last_init_graphics_command;\n tt = g->transmission_type ? g->transmission_type : 'd';\n fmt = g->format ? g->format : RGBA;\n img = img_by_internal_id(self, self->loading_image);\n if (img == NULL) {\n self->loading_image = 0;\n ABRT(EILSEQ, \"More payload loading refers to non-existent image\");\n }\n }\n int fd;\n static char fname[2056] = {0};\n switch(tt) {\n case 'd': // direct\n if (img->load_data.buf_capacity - img->load_data.buf_used < g->payload_sz) {\n if (img->load_data.buf_used + g->payload_sz > MAX_DATA_SZ || fmt != PNG) ABRT(EFBIG, \"Too much data\");\n img->load_data.buf_capacity = MIN(2 * img->load_data.buf_capacity, MAX_DATA_SZ);\n img->load_data.buf = realloc(img->load_data.buf, img->load_data.buf_capacity);\n if (img->load_data.buf == NULL) {\n ABRT(ENOMEM, \"Out of memory\");\n img->load_data.buf_capacity = 0; img->load_data.buf_used = 0;\n }\n }\n memcpy(img->load_data.buf + img->load_data.buf_used, payload, g->payload_sz);\n img->load_data.buf_used += g->payload_sz;\n if (!g->more) { img->data_loaded = true; self->loading_image = 0; }\n break;\n case 'f': // file\n case 't': // temporary file\n case 's': // POSIX shared memory\n if (g->payload_sz > 2048) ABRT(EINVAL, \"Filename too long\");\n snprintf(fname, sizeof(fname)/sizeof(fname[0]), \"%.*s\", (int)g->payload_sz, payload);\n if (tt == 's') fd = shm_open(fname, O_RDONLY, 0);\n else fd = open(fname, O_CLOEXEC | O_RDONLY);\n if (fd == -1) ABRT(EBADF, \"Failed to open file for graphics transmission with error: [%d] %s\", errno, strerror(errno));\n img->data_loaded = mmap_img_file(self, img, fd, g->data_sz, g->data_offset);\n safe_close(fd, __FILE__, __LINE__);\n if (tt == 't') {\n if (global_state.boss) { call_boss(safe_delete_temp_file, \"s\", fname); }\n else unlink(fname);\n }\n else if (tt == 's') shm_unlink(fname);\n break;\n default:\n ABRT(EINVAL, \"Unknown transmission type: %c\", g->transmission_type);\n }\n if (!img->data_loaded) return NULL;\n self->loading_image = 0;\n bool needs_processing = g->compressed || fmt == PNG;\n if (needs_processing) {\n uint8_t *buf; size_t bufsz;\n#define IB { if (img->load_data.buf) { buf = img->load_data.buf; bufsz = img->load_data.buf_used; } else { buf = img->load_data.mapped_file; bufsz = img->load_data.mapped_file_sz; } }\n switch(g->compressed) {\n case 'z':\n IB;\n if (!inflate_zlib(self, img, buf, bufsz)) {\n img->data_loaded = false; return NULL;\n }\n break;\n case 0:\n break;\n default:\n ABRT(EINVAL, \"Unknown image compression: %c\", g->compressed);\n }\n switch(fmt) {\n case PNG:\n IB;\n if (!inflate_png(self, img, buf, bufsz)) {\n img->data_loaded = false; return NULL;\n }\n break;\n default: break;\n }\n#undef IB\n img->load_data.data = img->load_data.buf;\n if (img->load_data.buf_used < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.buf_used, img->load_data.data_sz);\n }\n if (img->load_data.mapped_file) {\n munmap(img->load_data.mapped_file, img->load_data.mapped_file_sz);\n img->load_data.mapped_file = NULL; img->load_data.mapped_file_sz = 0;\n }\n } else {\n if (tt == 'd') {\n if (img->load_data.buf_used < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.buf_used, img->load_data.data_sz);\n } else img->load_data.data = img->load_data.buf;\n } else {\n if (img->load_data.mapped_file_sz < img->load_data.data_sz) {\n ABRT(ENODATA, \"Insufficient image data: %zu < %zu\", img->load_data.mapped_file_sz, img->load_data.data_sz);\n } else img->load_data.data = img->load_data.mapped_file;\n }\n }\n size_t required_sz = (size_t)(img->load_data.is_opaque ? 3 : 4) * img->width * img->height;\n if (img->load_data.data_sz != required_sz) ABRT(EINVAL, \"Image dimensions: %ux%u do not match data size: %zu, expected size: %zu\", img->width, img->height, img->load_data.data_sz, required_sz);\n if (LIKELY(img->data_loaded && send_to_gpu)) {\n send_image_to_gpu(&img->texture_id, img->load_data.data, img->width, img->height, img->load_data.is_opaque, img->load_data.is_4byte_aligned, false, REPEAT_CLAMP);\n free_load_data(&img->load_data);\n self->used_storage += required_sz;\n img->used_storage = required_sz;\n }\n return img;\n#undef MAX_DATA_SZ\n#undef ABRT\n}", "project": "kitty", "hash": 62380342440080942581251333456874353665, "size": 163, "commit_id": "82c137878c2b99100a3cdc1c0f0efea069313901", "message": "Graphics protocol: Dont return filename in the error message when opening file fails, since filenames can contain control characters\n\nFixes #3128", "target": 0, "dataset": "other", "idx": 412024} {"func": "PHPAPI unsigned char *php_quot_print_encode(const unsigned char *str, size_t length, size_t *ret_length) /* {{{ */\n{\n\tunsigned long lp = 0;\n\tunsigned char c, *ret, *d;\n\tchar *hex = \"0123456789ABCDEF\";\n\n\tret = safe_emalloc(1, 3 * length + 3 * (((3 * length)/PHP_QPRINT_MAXL) + 1), 0);\n\td = ret;\n\n\twhile (length--) {\n\t\tif (((c = *str++) == '\\015') && (*str == '\\012') && length > 0) {\n\t\t\t*d++ = '\\015';\n\t\t\t*d++ = *str++;\n\t\t\tlength--;\n\t\t\tlp = 0;\n\t\t} else {\n\t\t\tif (iscntrl (c) || (c == 0x7f) || (c & 0x80) || (c == '=') || ((c == ' ') && (*str == '\\015'))) {\n\t\t\t\tif ((lp += 3) > PHP_QPRINT_MAXL) {\n\t\t\t\t\t*d++ = '=';\n\t\t\t\t\t*d++ = '\\015';\n\t\t\t\t\t*d++ = '\\012';\n\t\t\t\t\tlp = 3;\n\t\t\t\t}\n\t\t\t\t*d++ = '=';\n\t\t\t\t*d++ = hex[c >> 4];\n\t\t\t\t*d++ = hex[c & 0xf];\n\t\t\t} else {\n\t\t\t\tif ((++lp) > PHP_QPRINT_MAXL) {\n\t\t\t\t\t*d++ = '=';\n\t\t\t\t\t*d++ = '\\015';\n\t\t\t\t\t*d++ = '\\012';\n\t\t\t\t\tlp = 1;\n\t\t\t\t}\n\t\t\t\t*d++ = c;\n\t\t\t}\n\t\t}\n\t}\n\t*d = '\\0';\n\t*ret_length = d - ret;\n\n\tret = erealloc(ret, *ret_length + 1);\n\treturn ret;\n}", "project": "php-src", "hash": 201039805180297414263699867243035103127, "size": 43, "commit_id": "18bb426587d62f93c54c40bf8535eb8416603629", "message": "Bug 62462: Prevent multibyte characters from being split between the lines\n\nMerged from https://github.com/php/php-src/pull/120", "target": 1, "dataset": "other", "idx": 208542} {"func": "PHPAPI unsigned char *php_quot_print_encode(const unsigned char *str, size_t length, size_t *ret_length) /* {{{ */\n{\n\tunsigned long lp = 0;\n\tunsigned char c, *ret, *d;\n\tchar *hex = \"0123456789ABCDEF\";\n\n\tret = safe_emalloc(1, 3 * length + 3 * (((3 * length)/PHP_QPRINT_MAXL) + 1), 0);\n\td = ret;\n\n\twhile (length--) {\n\t\tif (((c = *str++) == '\\015') && (*str == '\\012') && length > 0) {\n\t\t\t*d++ = '\\015';\n\t\t\t*d++ = *str++;\n\t\t\tlength--;\n\t\t\tlp = 0;\n\t\t} else {\n\t\t\tif (iscntrl (c) || (c == 0x7f) || (c & 0x80) || (c == '=') || ((c == ' ') && (*str == '\\015'))) {\n\t\t\t\tif ((((lp+= 3) > PHP_QPRINT_MAXL) && (c <= 0x7f)) \n || ((c > 0x7f) && (c <= 0xdf) && ((lp + 3) > PHP_QPRINT_MAXL)) \n || ((c > 0xdf) && (c <= 0xef) && ((lp + 6) > PHP_QPRINT_MAXL)) \n || ((c > 0xef) && (c <= 0xf4) && ((lp + 9) > PHP_QPRINT_MAXL))) {\n\t\t\t\t\t*d++ = '=';\n\t\t\t\t\t*d++ = '\\015';\n\t\t\t\t\t*d++ = '\\012';\n\t\t\t\t\tlp = 3;\n\t\t\t\t}\n\t\t\t\t*d++ = '=';\n\t\t\t\t*d++ = hex[c >> 4];\n\t\t\t\t*d++ = hex[c & 0xf];\n\t\t\t} else {\n\t\t\t\tif ((++lp) > PHP_QPRINT_MAXL) {\n\t\t\t\t\t*d++ = '=';\n\t\t\t\t\t*d++ = '\\015';\n\t\t\t\t\t*d++ = '\\012';\n\t\t\t\t\tlp = 1;\n\t\t\t\t}\n\t\t\t\t*d++ = c;\n\t\t\t}\n\t\t}\n\t}\n\t*d = '\\0';\n\t*ret_length = d - ret;\n\n\tret = erealloc(ret, *ret_length + 1);\n\treturn ret;\n}", "project": "php-src", "hash": 194162703673769915280815161904119135108, "size": 46, "commit_id": "18bb426587d62f93c54c40bf8535eb8416603629", "message": "Bug 62462: Prevent multibyte characters from being split between the lines\n\nMerged from https://github.com/php/php-src/pull/120", "target": 0, "dataset": "other", "idx": 412529} {"func": "HRESULT Http::HrReadHeaders()\n{\n\tHRESULT hr;\n\tstd::string strBuffer;\n\tULONG n = 0;\n\tstd::map::iterator iHeader = mapHeaders.end();\n\n\tec_log_debug(\"Receiving headers:\");\n\tdo\n\t{\n\t\thr = m_lpChannel->HrReadLine(strBuffer);\n\t\tif (hr != hrSuccess)\n\t\t\treturn hr;\n\t\tif (strBuffer.empty())\n\t\t\tbreak;\n\n\t\tif (n == 0) {\n\t\t\tm_strAction = strBuffer;\n\t\t} else {\n\t\t\tauto pos = strBuffer.find(':');\n\t\t\tsize_t start = 0;\n\n\t\t\tif (strBuffer[0] == ' ' || strBuffer[0] == '\\t') {\n\t\t\t\tif (iHeader == mapHeaders.end())\n\t\t\t\t\tcontinue;\n\t\t\t\t// continue header\n\t\t\t\twhile (strBuffer[start] == ' ' || strBuffer[start] == '\\t')\n\t\t\t\t\t++start;\n\t\t\t\tiHeader->second += strBuffer.substr(start);\n\t\t\t} else {\n\t\t\t\t// new header\n\t\t\t\tauto r = mapHeaders.emplace(strBuffer.substr(0, pos), strBuffer.substr(pos + 2));\n\t\t\t\tiHeader = r.first;\n\t\t\t}\n\t\t}\n\n\t\tif (strBuffer.find(\"Authorization\") != std::string::npos)\n\t\t\tec_log_debug(\"< Authorization: